branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<repo_name>danielpattaro/PattaroDaniel_A_Verifica16<file_sep>/Verifica16.ino long numeroRandom; int r1=13; int g1= 11; int b1= 7; int v1=5; int ripetizioni=0; void setup() { // put your setup code here, to run once: pinMode (r1, OUTPUT); pinMode (g1, OUTPUT); pinMode (b1, OUTPUT); pinMode (v1, OUTPUT); Serial.begin(4800); Serial.println("Seriale attiva"); while(ripetizioni==0){ Serial.println("Numero ripetizioni: "); while(Serial.available()==0){}; ripetizioni=Serial.readString().toInt(); } } void accensione (){ numeroRandom = random(10000); int i=0; while (i<ripetizioni) { digitalWrite(r1, HIGH); delay(numeroRandom); digitalWrite(r1, LOW); digitalWrite(g1, HIGH); delay(numeroRandom); digitalWrite(g1, LOW); digitalWrite(b1, HIGH); delay(numeroRandom); digitalWrite(b1, LOW); digitalWrite(v1, HIGH); delay(numeroRandom); digitalWrite(v1, LOW); i++; } ripetizioni=0; setup(); } void loop() { // put your main code here, to run repeatedly: accensione(); } // ggg
b9a57fce02aef302c4fcee6a98d1e98dca606043
[ "C++" ]
1
C++
danielpattaro/PattaroDaniel_A_Verifica16
2d1eb279960c2c2b374299eea43d9c359ba6c3d2
7115dfcbf6d41a58a78727fa5d38f0709d76bc67
refs/heads/master
<repo_name>shawwn/unixpath<file_sep>/README.md # unixpath > unix-style path processing functions ## Why? My goal was to provide `posixpath` path processing functions in pure Python (e.g. `normpath`, `join`, `split`, etc) *minus* any functions that rely on any kind of "filesystem" concept (`stat`, etc). Basically, this is a "minimum viable unix path processing framework." Path processing functions are useful for e.g. ML libraries that want to use unix-style paths to refer to model variables. (Honestly `unixpath` is kind of pointless. Its functions are copy-pasted from `posixpath`, so why not just `import posixpath` and not worry about the extra dependency on `unixpath`? Answer: because I was curious how Python implemented their unix path processing functions, so I made this library as a learning exercise.) ## Install ``` python3 -m pip install -U unixpath ``` ## Usage ```py import unixpath unixpath.join('a', 'b') # 'a/b' unixpath.join('a', 'b', '..', 'c') # 'a/b/../c' unixpath.normpath('a/b/../c') # 'a/c' ``` ## License MIT ## Contact A library by [<NAME>](https://www.shawwn.com). If you found it useful, please consider [joining my patreon](https://www.patreon.com/shawwn)! My Twitter DMs are always open; you should [send me one](https://twitter.com/theshawwn)! It's the best way to reach me, and I'm always happy to hear from you. - Twitter: [@theshawwn](https://twitter.com/theshawwn) - Patreon: [https://www.patreon.com/shawwn](https://www.patreon.com/shawwn) - HN: [sillysaurusx](https://news.ycombinator.com/threads?id=sillysaurusx) - Website: [shawwn.com](https://www.shawwn.com) <file_sep>/tests/test_unixpath.py import unixpath import os.path def check(fn, *args, **kws): assert getattr(os.path, fn)(*args, **kws) == getattr(unixpath, fn)(*args, **kws) def test_path(): check('join', '.', '/foo') for fn in ['isabs', 'split', 'dirname', 'basename', 'normpath']: check(fn, '/') check(fn, '//') check(fn, '///') check(fn, '////') check(fn, './') check(fn, '/abc') check(fn, '/abc/') check(fn, '/abc//') assert '/' == unixpath.dirname('/') assert '//' == unixpath.dirname('//') assert '/' == unixpath.normpath('///') assert '/' == unixpath.normpath('////') assert '///' == unixpath.dirname('///') assert '////' == unixpath.dirname('////') assert 'a/b/../c' == unixpath.join('a', 'b', '..', 'c') assert 'a/c' == unixpath.normpath(unixpath.join('a', 'b', '..', 'c')) assert 'a/b' == unixpath.dirname('a/b/c') assert 'c' == unixpath.basename('a/b/c') assert '' == unixpath.basename('a/b/c/') assert '' == unixpath.basename('') assert '.' == unixpath.normpath('') assert unixpath.isabs('/foo') assert not unixpath.isabs('./foo') <file_sep>/unixpath/__init__.py __version__ = '0.1.1' import genericpath from typing import Union PathType = Union[str, bytes] # For testing purposes, make sure the function is available when the C # implementation exists. def _fspath(path): """Return the path representation of a path-like object. If str or bytes is passed in, it is returned unchanged. Otherwise the os.PathLike interface is used to get the path representation. If the path representation is not str or bytes, TypeError is raised. If the provided path is not str, bytes, or os.PathLike, TypeError is raised. """ if isinstance(path, (str, bytes)): return path # Work from the object's type to match method resolution of other magic # methods. path_type = type(path) try: path_repr = path_type.__fspath__(path) except AttributeError: if hasattr(path_type, '__fspath__'): raise else: raise TypeError("expected str, bytes or os.PathLike object, " "not " + path_type.__name__) if isinstance(path_repr, (str, bytes)): return path_repr else: raise TypeError("expected {}.__fspath__() to return str or bytes, " "not {}".format(path_type.__name__, type(path_repr).__name__)) def _get_sep(path: PathType) -> PathType: if isinstance(path, bytes): return b'/' else: return '/' # Return whether a path is absolute. # Trivial in Posix, harder on the Mac or MS-DOS. def isabs(s: PathType) -> bool: """Test whether a path is absolute""" s = _fspath(s) sep = _get_sep(s) return s.startswith(sep) # Join pathnames. # Ignore the previous parts if a part is absolute. # Insert a '/' unless the first part is empty or already ends in '/'. def join(a: PathType, *p: PathType) -> PathType: """Join two or more pathname components, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.""" a = _fspath(a) sep = _get_sep(a) path = a try: if not p: path[:0] + sep #23780: Ensure compatible data type even if p is null. for b in map(_fspath, p): if b.startswith(sep): path = b elif not path or path.endswith(sep): path += b else: path += sep + b except (TypeError, AttributeError, BytesWarning): genericpath._check_arg_types('join', a, *p) raise return path # Split a path in head (everything up to the last '/') and tail (the # rest). If the path ends in '/', tail will be empty. If there is no # '/' in the path, head will be empty. # Trailing '/'es are stripped from head unless it is the root. def split(p: PathType) -> (PathType, PathType): """Split a pathname. Returns tuple "(head, tail)" where "tail" is everything after the final slash. Either part may be empty.""" p = _fspath(p) sep = _get_sep(p) i = p.rfind(sep) + 1 head, tail = p[:i], p[i:] if head and head != sep*len(head): head = head.rstrip(sep) return head, tail # Normalize a path, e.g. A//B, A/./B and A/foo/../B all become A/B. # It should be understood that this may change the meaning of the path # if it contains symbolic links! def normpath(path: PathType) -> PathType: """Normalize path, eliminating double slashes, etc.""" path = _fspath(path) if isinstance(path, bytes): sep = b'/' empty = b'' dot = b'.' dotdot = b'..' else: sep = '/' empty = '' dot = '.' dotdot = '..' if path == empty: return dot initial_slashes = path.startswith(sep) # POSIX allows one or two initial slashes, but treats three or more # as single slash. if initial_slashes and path.startswith(sep * 2) and not path.startswith(sep * 3): initial_slashes = 2 comps = path.split(sep) new_comps = [] for comp in comps: if comp in (empty, dot): continue if comp != dotdot or \ (not initial_slashes and not new_comps) or \ (new_comps and new_comps[-1] == dotdot): new_comps.append(comp) elif new_comps: new_comps.pop() comps = new_comps path = sep.join(comps) if initial_slashes: path = sep*initial_slashes + path return path or dot # Return the tail (basename) part of a path, same as split(path)[1]. def basename(p: PathType) -> PathType: """Returns the final component of a pathname""" p = _fspath(p) sep = _get_sep(p) i = p.rfind(sep) + 1 return p[i:] # Return the head (dirname) part of a path, same as split(path)[0]. def dirname(p: PathType) -> PathType: """Returns the directory component of a pathname""" p = _fspath(p) sep = _get_sep(p) i = p.rfind(sep) + 1 head = p[:i] if head and head != sep*len(head): head = head.rstrip(sep) return head
88dde4d48e94dcfae7d909d395841f53692b4cc0
[ "Markdown", "Python" ]
3
Markdown
shawwn/unixpath
fda363ee9734189ea2a5bdd87a091b931b8dbe47
0e94e8c355d682935b48576a32f6474bcf98f606
refs/heads/master
<repo_name>Jspharmando/PBO2-10117077-Latihan35-ProgramTunjangan<file_sep>/src/com/company/Tunjangan.java package com.company; /** * * @author <NAME> */ public class Tunjangan { public double gajiAwal; public String status; public double tunjangan; public double hitungTunjangan(){ tunjangan = (status.equals("menikah"))? 0.35*gajiAwal:0; return tunjangan; } public double hitungTotalGaji(){ return gajiAwal + tunjangan; } }
15f6326a1d93665897d1c801b49d13ebc87d03d4
[ "Java" ]
1
Java
Jspharmando/PBO2-10117077-Latihan35-ProgramTunjangan
1748c3e65bbbe43409b764da83e1dd7be4855b66
456afda200e40f92af0be14739c6c6f07a246624
refs/heads/master
<repo_name>rnpatil/TM3<file_sep>/files/tm3.c #include <linux/kernel.h> #include <linux/module.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv4.h> #include <linux/netdevice.h> #include <linux/ip.h> #include <linux/tcp.h> #include <net/route.h> //#define DEBUG_DUMP #pragma GCC diagnostic ignored "-Wdeclaration-after-statement" MODULE_AUTHOR("<NAME>"); MODULE_LICENSE("TODO"); static struct nf_hook_ops netfilter_ops_in; static struct nf_hook_ops netfilter_ops_out; #define HOOK_UPLINK NF_INET_LOCAL_OUT #define HOOK_DOWNLINK NF_INET_LOCAL_IN typedef unsigned char BYTE; typedef unsigned int DWORD; typedef unsigned short WORD; #ifdef USE_TEST_SERVER static char * testServerIP = "172.16.31.10"; DWORD tIP; module_param(testServerIP, charp, 0000); MODULE_PARM_DESC(testServerIP, "Test Server IP"); #endif DWORD rIP; static char * remoteProxyIP = "0.0.0.0"; module_param(remoteProxyIP, charp, 0000); MODULE_PARM_DESC(remoteProxyIP, "Remote Proxy IP Address"); static char * fwdInterface = "eth0"; module_param(fwdInterface, charp, 0000); MODULE_PARM_DESC(fwdInterface, "Interface name"); static char * portList = "6001"; module_param(portList, charp, 0000); MODULE_PARM_DESC(portList, "Port list"); #define LOCAL_PROXY_IP "127.0.0.1" #define LOCAL_PROXY_PORT 1202 DWORD localHost; WORD localProxyPort; #define PROT_TCP 6 #define PROT_UDP 17 #define TCPFLAG_FIN 0x1 #define TCPFLAG_SYN 0x2 #define TCPFLAG_RST 0x4 #define TCPFLAG_ACK 0x10 #define MAGIC_MSS_VALUE 1459 typedef struct _IPv4_INFO { DWORD srcIP; DWORD dstIP; WORD protocol; WORD srcPort; WORD dstPort; int payloadLen; int ipHeaderLen; int tcpHeaderLen; BYTE tcpFlags; } IPv4_INFO; static int pktCount = 0; static WORD srcPort2serverPort[65536]; static DWORD srcPort2serverIP[65536]; //static BYTE srcPort2NoModify[65536]; static WORD forwardedPorts[65536]; void ReportError(const char * format, ...) { char dest[784]; va_list argptr; va_start(argptr, format); vsprintf(dest, format, argptr); va_end(argptr); printk("+++++ERROR+++++: %s\n", dest); } void Log(const char * format, ...) { char dest[784]; va_list argptr; va_start(argptr, format); vsprintf(dest, format, argptr); va_end(argptr); printk(KERN_INFO "[FENG] %s", dest); } static inline DWORD ReverseDWORD(DWORD x) { return (x & 0xFF) << 24 | (x & 0xFF00) << 8 | (x & 0xFF0000) >> 8 | (x & 0xFF000000) >> 24; } static inline WORD ReverseWORD(WORD x) { return (x & 0xFF) << 8 | (x & 0xFF00) >> 8; } static inline int ReverseINT(int x) { return (int)ReverseDWORD((DWORD)x); } const char * ConvertDWORDToIP(DWORD ip) { static char ipstr[5][128]; static int count = 0; int i = count++; if (count == 5) count = 0; sprintf(ipstr[i], "%d.%d.%d.%d", (ip & 0x000000FF), (ip & 0x0000FF00) >> 8, (ip & 0x00FF0000) >> 16, (ip & 0xFF000000) >> 24 ); return ipstr[i]; } DWORD ConvertIPToDWORD(const char * _ip) { char ip[128]; DWORD ipc[4]; strcpy(ip, _ip); int len = strlen(ip); ip[len++] = '.'; int i, j=0, k=0; for (i=0; i<len; i++) { if (ip[i] == '.') { ip[i] = 0; kstrtou32(ip + j, 10, &ipc[k++]); j = i+1; if (k == 4) break; } } return (ipc[0]) | (ipc[1] << 8) | (ipc[2] << 16) | (ipc[3] << 24); } void ParsePortList(void) { char pl[256]; strcpy(pl, portList); int len = strlen(pl); pl[len++] = ','; int i, j=0; DWORD p; for (i=0; i<len; i++) { if (pl[i] == ',') { pl[i] = 0; kstrtou32(pl + j, 10, &p); forwardedPorts[p] = 1; Log("Forward port = %u\n", p); j = i+1; } } } void DumpPayload(const struct sk_buff * skb) { } int IsIPv4(const struct sk_buff * skb, IPv4_INFO * pInfo) { const BYTE * pkt_data = skb->data; if (pkt_data == NULL) { ReportError("skb data empty"); return 0; } BYTE ipFlag = *pkt_data; if ((ipFlag & 0xF0) != 0x40) return 0; if ((ipFlag & 0x0F) < 5) { ReportError("IPv4 flag: %d", (int)ipFlag); DumpPayload(skb); return 0; } DWORD ipOptionLength = 4 * ((ipFlag & 0x0F) - 5); WORD ipLength = ReverseWORD(*((WORD *)(pkt_data + 2))); if (ipLength != skb->len) { ReportError("skb len (%d) != ipLen (%d)", (int)skb->len, (int)ipLength); DumpPayload(skb); return 0; } pInfo->srcIP = *((DWORD *)(pkt_data + 12)); pInfo->dstIP = *((DWORD *)(pkt_data + 16)); pInfo->protocol = *((BYTE *)(pkt_data + 9)); pInfo->ipHeaderLen = 20 + ipOptionLength; pkt_data += ipOptionLength; //***** Change offset if (pInfo->protocol == PROT_TCP) { if (ipLength < 20 + ipOptionLength + 20) { ReportError("Malformed TCP header"); DumpPayload(skb); return 0; } pInfo->srcPort = ReverseWORD(*((WORD *)(pkt_data + 20 + 0))); pInfo->dstPort = ReverseWORD(*((WORD *)(pkt_data + 20 + 2))); int tcpHeaderLen = (*((BYTE *)(pkt_data + 20 + 12)) & 0xF0) >> 2; pInfo->payloadLen = (int)ipLength - 20 - ipOptionLength - tcpHeaderLen; pInfo->tcpHeaderLen = tcpHeaderLen; pInfo->tcpFlags = *(pkt_data + 20 + 13); if (pInfo->payloadLen < 0) { ReportError("Malformed TCP packet"); DumpPayload(skb); return 0; } } else if (pInfo->protocol == PROT_UDP) { if (ipLength < 20 + ipOptionLength + 8) { ReportError("Malformed UDP header"); DumpPayload(skb); return 0; } pInfo->srcPort = ReverseWORD(*((WORD *)(pkt_data + 20 + 0))); pInfo->dstPort = ReverseWORD(*((WORD *)(pkt_data + 20 + 2))); pInfo->tcpHeaderLen = 0; pInfo->tcpFlags = 0; pInfo->payloadLen = (int)ipLength - 20 - ipOptionLength - 8; if (pInfo->payloadLen < 0) { ReportError("Malformed UDP packet"); DumpPayload(skb); return 0; } } else { pInfo->srcPort = 0; pInfo->dstPort = 0; pInfo->payloadLen = (int)ipLength - 20 - ipOptionLength; pInfo->tcpHeaderLen = 0; } return 1; } void AddIPOptionForSYN(struct sk_buff * skb, IPv4_INFO * pInfo) { //Use IP option (record route) to carry custom data static const int ipOptLen = 12; //must be a multiple of 4 if (skb->end - skb->tail < ipOptLen) { ReportError("Not enough space in SKB"); return; } //TODO: a case where there is already IP options skb_put(skb, ipOptLen); BYTE * p = skb->data + pInfo->ipHeaderLen; memmove(p+ipOptLen, p, pInfo->tcpHeaderLen + pInfo->payloadLen); *p = 7; *(p+1) = 11; *(p+2) = 12; *((DWORD *)(p+3)) = pInfo->dstIP; *((DWORD *)(p+8)) = 0; *((WORD *)(p+7)) = ReverseWORD(pInfo->dstPort); //Update IP len pInfo->ipHeaderLen += ipOptLen; WORD newIpLen = ReverseWORD((WORD)(pInfo->ipHeaderLen + pInfo->tcpHeaderLen + pInfo->payloadLen)); *((WORD *)(skb->data + 2)) = newIpLen; //ip len *skb->data = 0x40 | (BYTE)(5 + (ipOptLen >> 2)); } WORD IPChecksum(WORD *data, int len) { DWORD sum = 0; int i, j; for (i=0, j=0; i<len; i+=2, j++) { if (i == 10) continue; sum += data[j]; } while(sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16); return (WORD)(~sum); } WORD TCPChecksum(WORD * data, int len, DWORD srcIP, DWORD dstIP) { DWORD sum = 0; int i, j; for (i=0, j=0; i<len; i+=2, j++) { if (i == 16) continue; if (i == len - 1) sum += *((BYTE *)(data) + len - 1); else sum += data[j]; } sum += (WORD)((srcIP & 0xFFFF0000) >> 16); sum += (WORD)(srcIP & 0xFFFF); sum += (WORD)((dstIP & 0xFFFF0000) >> 16); sum += (WORD)(dstIP & 0xFFFF); sum += ReverseWORD(0x0006); sum += ReverseWORD((WORD)len); while(sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16); return (WORD)(~sum); } void UpdateTCPIPChecksum(int dir, const struct sk_buff * skb, const IPv4_INFO * pInfo/*, DWORD srcIP, DWORD dstIP*/) { WORD ipSum /*, tcpSum*/; if (dir == HOOK_UPLINK) { *(WORD *)(skb->data + 10) = ipSum = IPChecksum((WORD *)skb->data, pInfo->ipHeaderLen); /* *(WORD *)(skb->data + pInfo->ipHeaderLen + 16) = TCPChecksum((WORD *)(skb->data + pInfo->ipHeaderLen), pInfo->payloadLen + pInfo->tcpHeaderLen, srcIP, dstIP); */ } //Log("\t IP Checksum = %x TCP Checksum = %x\n", ipSum, tcpSum); } int ModifyPacket(unsigned int hooknum, struct sk_buff * skb, const struct net_device * in, const struct net_device * out) { #ifdef DEBUG_DUMP Log("*** #%d %c len=%d(%d) %s->%s ***\n", pktCount, hooknum == HOOK_UPLINK ? 'U' : 'D', (int)skb->len, (int)skb->len + 14, in==NULL ? "null" : in->name, out==NULL ? "null" : out->name ); #endif /* //(int)(skb->tail - skb->data) always equals to skb->len if (skb->tail - skb->data != skb->len) { ReportError("!!! SIZE NOT MATCH %d %d %d !!!", (int)skb->data_len, (int)skb->len, (int)(skb->tail - skb->data)); } */ IPv4_INFO info; if (!IsIPv4(skb, &info)) { //Log("\t(not IPv4 packet)\n"); return 0; } if (info.protocol == PROT_TCP || info.protocol == PROT_UDP) { #ifdef DEBUG_DUMP Log("\t%s %s:%d->%s:%d (%d B)\n", info.protocol == PROT_TCP ? "TCP" : "UDP", ConvertDWORDToIP(info.srcIP), (int)info.srcPort, ConvertDWORDToIP(info.dstIP), (int)info.dstPort, info.payloadLen ); #endif } else { #ifdef DEBUG_DUMP Log("\tProt=%d %s->%s (%d B)\n", (int)info.protocol, ConvertDWORDToIP(info.srcIP), ConvertDWORDToIP(info.dstIP), info.payloadLen ); #endif return 0; } //only handle TCP and UDP if (info.protocol == PROT_TCP) { if (hooknum == HOOK_UPLINK) { //UPLINK /* //option 1: only route traffic not destined to the middlebox to CMAT //if (info.dstIP == rIP && info.dstPort != 6001 && info.dstPort != 6002) return 0; //option 2: only route port 6001/6002 traffic destined to the middlebox to CMAT (used to evaluate HTTP/SPDY proxy in the paper) if (info.dstIP != rIP) return 0; if (info.dstPort != 6001 && info.dstPort != 443) return 0; //HTTP proxy */ if (!forwardedPorts[info.dstPort]) return 0; int bSYN; bSYN = info.tcpFlags & TCPFLAG_SYN; /* if (bSYN) { if (GetTCPMSS(skb, &info) == MAGIC_MSS_VALUE) { srcPort2NoModify[info.srcPort] = 1; } else { srcPort2NoModify[info.srcPort] = 0; } } if (srcPort2NoModify[info.srcPort]) return 0; */ #ifdef USE_TEST_SERVER if (info.dstIP == tIP) { #endif *(DWORD *)(skb->data + 16) = localHost; //dstIP *(WORD *)(skb->data + info.ipHeaderLen + 2) = localProxyPort; //dstPort if (bSYN) { AddIPOptionForSYN(skb, &info); if (srcPort2serverIP[info.srcPort] != 0) { Log("*** DUPLICATE PORT!!! ***\n"); } srcPort2serverPort[info.srcPort] = info.dstPort; srcPort2serverIP[info.srcPort] = info.dstIP; } UpdateTCPIPChecksum(hooknum, skb, &info); #ifdef DEBUG_DUMP Log("\t ### DstIP/Port changed to %s/%d\n", ConvertDWORDToIP(localHost), (int)LOCAL_PROXY_PORT); #endif return 1; #ifdef USE_TEST_SERVER } #endif } else { //DOWNLINK //if (srcPort2NoModify[info.dstPort]) return 0; /* if (info.srcIP != rIP) return 0; if (info.srcIP == rIP && info.srcPort != 6001 && info.srcPort != 6002) return 0; */ if (info.srcIP == localHost && info.srcPort == LOCAL_PROXY_PORT) { DWORD svrIP = srcPort2serverIP[info.dstPort]; WORD svrPort = srcPort2serverPort[info.dstPort]; *(DWORD *)(skb->data + 12) = svrIP; //srcIP *((WORD *)(skb->data + info.ipHeaderLen)) = ReverseWORD(svrPort); //srcPort UpdateTCPIPChecksum(hooknum, skb, &info); #ifdef DEBUG_DUMP Log("\t ### SrcIP/Port changed to %s/%d\n", ConvertDWORDToIP(svrIP), (int)svrPort); #endif return 1; } } } else { //UDP //TODO: currently do nothing for UDP } return 0; } /* Function prototype in <linux/netfilter> */ unsigned int main_hook(const struct nf_hook_ops *ops, struct sk_buff * skb, const struct net_device *in, const struct net_device *out, int (*okfn)(struct sk_buff*)) { unsigned hooknum = ops->hooknum; if (!skb) return NF_ACCEPT; if (skb->pkt_type != PACKET_HOST) return NF_ACCEPT; //TODO: serious performance issue /* if (skb_is_nonlinear(skb)) { if (skb_linearize(skb) != 0) return NF_DROP; } */ pktCount++; int bMod = 0; if (hooknum == HOOK_UPLINK && !strcmp(out->name, fwdInterface)) { bMod = ModifyPacket(hooknum, skb, in, out); } else if (hooknum == HOOK_DOWNLINK && !strcmp(in->name, "lo")) { bMod = ModifyPacket(hooknum, skb, in, out); } else { goto NO_MOD; } if (bMod) { if (hooknum == HOOK_UPLINK) { static struct net_device * pLO = NULL; if (pLO == NULL) pLO = dev_get_by_name(&init_net, "lo"); skb->dev = pLO; dev_hard_header(skb, skb->dev, ETH_P_IP, NULL //dest MAC addr , NULL //skb->dev->dev_addr //my MAC addr , skb->dev->addr_len ); //no TCP checksum skb->ip_summed = CHECKSUM_UNNECESSARY; //Important: force to update the routing info ip_route_me_harder(skb, RTN_LOCAL); /* ////////////////////////// Dumping dst_entry ////////////////////// struct rtable * rt = skb_rtable(skb); Log("RT: src=%s dst=%s, gateway=%s, spec_dst=%s\n", ConvertDWORDToIP(rt->rt_src), ConvertDWORDToIP(rt->rt_dst), ConvertDWORDToIP(rt->rt_gateway), ConvertDWORDToIP(rt->rt_spec_dst) ); ////////////////////////// Dumping dst_entry ////////////////////// */ int r = dev_queue_xmit(skb); //no need for kfree_skb(skb); if (r < 0) ReportError("dev_queue_xmit returns %d", r); return NF_STOLEN; } else { goto NO_MOD; } } NO_MOD: return NF_ACCEPT; } int init_module() { #ifdef USE_TEST_SERVER tIP = ConvertIPToDWORD(testServerIP); Log("Test Server IP = %s\n", ConvertDWORDToIP(tIP)); #endif rIP = ConvertIPToDWORD(remoteProxyIP); Log("Remote Proxy IP = %s\n", ConvertDWORDToIP(rIP)); localHost = ConvertIPToDWORD(LOCAL_PROXY_IP); localProxyPort = ReverseWORD(LOCAL_PROXY_PORT); Log("Interface name = %s\n", fwdInterface); int i; for (i=0; i<65535; i++) { srcPort2serverPort[i] = 0; srcPort2serverIP[i] = 0; forwardedPorts[i] = 0; //srcPort2NoModify[i] = 0; } ParsePortList(); netfilter_ops_in.hook = main_hook; netfilter_ops_in.pf = PF_INET; netfilter_ops_in.hooknum = HOOK_UPLINK; //out to interface netfilter_ops_in.priority = NF_IP_PRI_MANGLE; netfilter_ops_out.hook = main_hook; netfilter_ops_out.pf = PF_INET; netfilter_ops_out.hooknum = HOOK_DOWNLINK; //in from interface netfilter_ops_out.priority = NF_IP_PRI_MANGLE; nf_register_hook(&netfilter_ops_in); /* register NF_IP_PRE_ROUTING hook */ nf_register_hook(&netfilter_ops_out); /* register NF_IP_POST_ROUTING hook */ return 0; } void cleanup_module() { nf_unregister_hook(&netfilter_ops_in); nf_unregister_hook(&netfilter_ops_out); }
c7552ea1e1e922105c06dc1c3d689a1c36065347
[ "C" ]
1
C
rnpatil/TM3
e420d0d339f85f605b145e2e0be093a8ad7dfa1f
64d0a76b176d8683860cafb90d28b72b58fe6438
refs/heads/master
<repo_name>bailongmahaha/Study-C<file_sep>/1.c # include <stdio.h> int main(void) { int i = 33; printf("i = %#X\n", i);//%X是以十六进制打印,并且a到f打印出来的是大写的A,B,C,D,E,F //如果是%#X,则会在打印的十六进制结果前面加上0X。 return 0; } <file_sep>/README.md # Study-C 郝斌C程序 <file_sep>/andshiyong.c # include <stdio.h> int main(void) { int i = 10; int k = 20; int m; m = (1>2) || (k=5); //不含有分号的是表达式 含有分号的是语句 printf("m = %d, k = %d\n", m, k); return 0; }
4aef8c87af7fc6fa013092a7331308ad9e89e38d
[ "Markdown", "C" ]
3
C
bailongmahaha/Study-C
03c1d3383f6c42292ee891d0ec3b6c6837354937
13b97eb056cfd8f417bf3acd8fb3016014719ee7
refs/heads/master
<file_sep>using Microsoft.Owin; using Microsoft.Owin.Cors; using Microsoft.Owin.FileSystems; using Microsoft.Owin.StaticFiles; using Owin; using System.IO; using System.Reflection; using System.Web.Http; [assembly: OwinStartup(typeof(Cake23.Connection.Server.Cake23Startup))] namespace Cake23.Connection.Server { public class Cake23Startup { public void Configuration(IAppBuilder app) { #if DEBUG app.UseErrorPage(); #endif var staticWebContentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\WebStaticContent"; var physicalFileSystem = new PhysicalFileSystem(staticWebContentPath); var options = new FileServerOptions(); options.EnableDefaultFiles = true; options.FileSystem = physicalFileSystem; options.EnableDirectoryBrowsing = true; options.StaticFileOptions.FileSystem = physicalFileSystem; options.StaticFileOptions.ServeUnknownFileTypes = true; options.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" }; if (Cake23Host.GetInstance().AllowCORS) app.UseCors(CorsOptions.AllowAll); app.UseFileServer(options); app.MapSignalR(); HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute("Templates", "client/{templateName}", new { controller = "Template", templateName = "index" }); app.UseWebApi(config); } } } <file_sep>using Cake23.Connection.Clients; using Cake23.Util; using System.Collections.Generic; namespace Cake23.Connection.Server { public class Cake23HostConnection : Cake23Connection { public override string ClientName { get { return "Cake23"; } } public override string HubName { get { return typeof(Cake23Hub).Name; } } public override void Connect(object obj = null) { if (CanConnect()) { base.Connect(obj); On<UserClient>("Register", OnRegister); } } public override void Unconnect(object obj = null) { if (CanUnconnect()) { base.Unconnect(obj); } } private void OnRegister(UserClient uc) { if (!userClientsMap.ContainsKey(uc.UserName)) { userClientsMap.Add(uc.UserName, new List<string>()); this.Log("username " + uc.UserName + " registered"); } userClientsMap[uc.UserName].Add(uc.ClientName); this.Log(uc.ClientName + " registered for user " + uc.UserName); } private Dictionary<string, List<string>> userClientsMap = new Dictionary<string, List<string>>(); internal void Register(UserClient uc) { Invoke("Register", uc); } } }
bdf8306fc003780d544c89dea3aac3326b8d18ac
[ "C#" ]
2
C#
lUllLabs/Cake23
1f45d09aa4ac182464ff37d6aeaeafc7a6a0cad6
259db8b3f49b80740b25ae82ff6255da2577aa66
refs/heads/master
<repo_name>romanslex/callback-example<file_sep>/database/factories/WidgetFactory.php <?php use App\Models\Widget; use Carbon\Carbon; use Faker\Generator as Faker; use Webpatser\Uuid\Uuid; $factory->define(Widget::class, function (Faker $faker) { return [ "id" => Uuid::generate(4), "url" => $faker->domainName, "window_settings" => null, "btn_settings" => null, "mobile_btn_settings" => null, "mobile_window_settings" => null, "rate_expired_at" => Carbon::today()->addDays(7), "emails" => [["value" => $faker->email]], "phones" => [], "timezone" => "Europe/Moscow", "schedule" => Widget::$defaultSchedule, ]; }); <file_sep>/resources/js/components/Pages/Widgets/store.js const store = { namespaced: true, state: { widgets: [], isAlreadyInitialized: false }, mutations: { setWidgets(state, payload){ state.widgets = payload; state.isAlreadyInitialized = true; }, addWidget(state, widget){ state.widgets.push(widget) } }, actions: { setWidgets({commit}, payload){ commit("setWidgets", payload) }, addWidget({commit}, widget){ commit("addWidget", widget) } } }; export default store<file_sep>/resources/js/components/Shared/ColorDarkenPlugin.js import Color from "color" const ColorDarkenPlugin = { install(Vue, options) { Vue.prototype.$colorDarken = function (color, amt) { let colorObj = Color(color); let hex = colorObj.hex(); amt = amt || -20; let usePound = false; if (hex[0] === "#") { hex = hex.slice(1); usePound = true; } let num = parseInt(hex, 16); let r = (num >> 16) + amt; if (r > 255) r = 255; else if (r < 0) r = 0; let b = ((num >> 8) & 0x00FF) + amt; if (b > 255) b = 255; else if (b < 0) b = 0; let g = (num & 0x0000FF) + amt; if (g > 255) g = 255; else if (g < 0) g = 0; return Color((usePound?"#":"") + String("000000" + (g | (b << 8) | (r << 16)).toString(16)).slice(-6)) } } }; export default ColorDarkenPlugin<file_sep>/app/Http/Controllers/Data/AntispamController.php <?php namespace App\Http\Controllers\Data; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Validation\Rule; class AntispamController extends Controller { public function __construct() { $this->middleware('auth'); } public function index() { return [ "blackIps" => auth()->user()->blackIps->map(function ($ip) { return ["id" => $ip["id"], "ip" => $ip["ip"]]; }), "blackPhones" => auth()->user()->blackPhones->map(function ($phone) { return ["id" => $phone["id"], "number" => $phone["number"]]; }) ]; } public function storeIp(Request $request) { $validatedData = $request->validate([ "ip" => [ "required", "ip", Rule::unique('black_ips')->where(function ($query) { return $query->where('user_id', auth()->user()->id); }) ], ]); $ip = auth()->user()->blackIps()->create(["ip" => $validatedData["ip"]]); return $ip; } public function storePhone(Request $request) { $validatedData = $request->validate([ "number" => [ "required", Rule::unique('black_phones')->where(function ($query) { return $query->where('user_id', auth()->user()->id); }) ], ]); $phone = auth()->user()->blackPhones()->create(["number" => $validatedData["number"]]); return $phone; } public function deleteIp($id) { auth()->user()->blackIps()->findOrFail($id)->delete(); return []; } public function deletePhone($id) { auth()->user()->blackPhones()->findOrFail($id)->delete(); return []; } } <file_sep>/app/Http/Controllers/MobileAppearanceController.php <?php namespace App\Http\Controllers; use App\Http\Resources\MobileAppearanceSettings; use App\Structs\MobileBtnSettings; use App\Structs\MobileWindowSettings; use Illuminate\Http\Request; class MobileAppearanceController extends Controller { public function __construct() { $this->middleware("auth"); } public function index($id) { $widget = auth()->user()->widgets()->findOrFail($id); return view( "mobile-appearance", (new MobileAppearanceSettings($widget))->toArray() ); } public function updateBtn(Request $request, $id) { $widget = auth()->user()->widgets()->findOrFail($id); $mobileBtnSettings = new MobileBtnSettings(); $mobileBtnSettings->currentBtn = $request->get("currentBtn"); $mobileBtnSettings->buttons = $request->get("buttons"); $widget->mobile_btn_settings = $mobileBtnSettings; $widget->save(); return []; } public function updateWindow(Request $request, $id) { $widget = auth()->user()->widgets()->findOrFail($id); $mobileWindowSettings = new MobileWindowSettings(); $mobileWindowSettings->currentWindow = $request->get("currentWindow"); $mobileWindowSettings->windows = $request->get("windows"); $widget->mobile_window_settings = $mobileWindowSettings; $widget->save(); return []; } } <file_sep>/app/Models/Widget.php <?php namespace App\Models; use App\Structs\BtnSettings; use App\Structs\MobileBtnSettings; use App\Structs\MobileWindowSettings; use App\Structs\WindowSettings; use App\Traits\PhoneNumberFormatter; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; use Webpatser\Uuid\Uuid; class Widget extends Model { use PhoneNumberFormatter; public $incrementing = false; protected $guarded = ["id", "owner_id"]; protected $dates = [ 'created_at', 'updated_at', 'rate_expired_at' ]; /** * Setup model event hooks */ public static function boot() { parent::boot(); self::creating(function ($model) { $model->id = (string)Uuid::generate(4); }); } public function isExpired() { return Carbon::now()->gte($this->rate_expired_at); } public function owner() { return $this->belongsTo(User::class, "owner_id"); } public function regions() { return $this->hasMany(Region::class); } public function orders() { return $this->hasMany(Order::class); } public function getEmailsAttribute($value) { return json_decode($value, true); } public function setEmailsAttribute($value) { $this->attributes["emails"] = json_encode($value); } public function getPhonesAttribute($value) { return json_decode($value, true); } public function setPhonesAttribute($value) { if (empty($value)) { $this->attributes["phones"] = json_encode($value); return; } $value = collect($value)->map(function ($phone) { $string = $this->formatNumber($phone["value"]); return ["value" => $string]; }); $this->attributes["phones"] = json_encode($value); } public function getScheduleAttribute($value) { return json_decode($value, true); } public function setScheduleAttribute($value) { $this->attributes["schedule"] = json_encode($value); } /** * window_settings attribute * @param $value * @return WindowSettings */ public function getWindowSettingsAttribute($value): WindowSettings { return WindowSettings::makeFromJson($value); } public function setWindowSettingsAttribute(?WindowSettings $value) { $this->attributes["window_settings"] = (string)$value; } /** * btn_settings attribute * @param $value * @return BtnSettings */ public function getBtnSettingsAttribute($value): BtnSettings { return BtnSettings::makeFromJson($value); } public function setBtnSettingsAttribute(?BtnSettings $value) { $this->attributes["btn_settings"] = (string)$value; } /** * mobile_window_settings attribute * @param $value * @return MobileWindowSettings */ public function getMobileWindowSettingsAttribute($value): MobileWindowSettings { return MobileWindowSettings::makeFromJson($value); } public function setMobileWindowSettingsAttribute(?MobileWindowSettings $value) { $this->attributes["mobile_window_settings"] = (string)$value; } /** * mobile_btn_settings attribute * @param $value * @return MobileBtnSettings */ public function getMobileBtnSettingsAttribute($value): MobileBtnSettings { return MobileBtnSettings::makeFromJson($value); } public function setMobileBtnSettingsAttribute(?MobileBtnSettings $value) { $this->attributes["mobile_btn_settings"] = (string)$value; } public static $defaultSchedule = [ "is_weekdays_same_schedule" => true, "time_start" => ["08:00", "08:00", "08:00", "08:00", "08:00", "10:00", "10:00"], "time_end" => ["17:00", "17:00", "17:00", "17:00", "17:00", "16:00", "16:00"], "workdays" => [true, true, true, true, true, false, false], "weekdays_start" => "08:00", "weekdays_end" => "17:00", "weekdays_workdays" => true ]; /** * Вернуть дату конца тестового периода для домена с учетом его * истории использования * @param $url * @return Carbon */ public static function getRateExpiredAt($url) { $widget = Widget::where("url", $url)->first(); if (!$widget) { return Carbon::today()->addDays(7); } return $widget->rate_expired_at; } public function lastOrders() { $lastOrders = \DB::select(" select x.date, ifnull(count(o.created_at), 0) amount from ( select cast(now() as date) date union all select cast(now() - interval 1 day as date) date union all select cast(now() - interval 2 day as date) date union all select cast(now() - interval 3 day as date) date union all select cast(now() - interval 4 day as date) date union all select cast(now() - interval 5 day as date) date union all select cast(now() - interval 6 day as date) date union all select cast(now() - interval 7 day as date) date union all select cast(now() - interval 8 day as date) date union all select cast(now() - interval 9 day as date) date union all select cast(now() - interval 10 day as date) date union all select cast(now() - interval 11 day as date) date union all select cast(now() - interval 12 day as date) date union all select cast(now() - interval 13 day as date) date union all select cast(now() - interval 14 day as date) date union all select cast(now() - interval 15 day as date) date ) x left join orders o on x.date = cast(o.created_at as date) and o.widget_id = ? group by x.date order by x.date desc", [$this->id]); return collect($lastOrders)->pluck("amount")->toArray(); } public static $rates = [ ["interval" => 1, "price" => "300"], ["interval" => 3, "price" => "855"], ["interval" => 6, "price" => "1620"], ["interval" => 12, "price" => "2400"], ["interval" => 24, "price" => "4160"], ]; public function extend($rate) { if($this->owner->total < self::$rates[$rate]['price']) abort(400, "Не хватает денег на балансе"); $this->owner->total -= self::$rates[$rate]['price']; $this->owner->save(); $this->rate_expired_at = $this->rate_expired_at->addMonths(self::$rates[$rate]['interval']); Payment::createExtendPayment($this, self::$rates[$rate]['price']); $this->save(); } } <file_sep>/app/Http/Controllers/SpaController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SpaController extends Controller { public function __construct() { $this->middleware("auth"); } public function index() { $user = [ "name" => auth()->user()->name, "phone" => auth()->user()->phone, "email" => auth()->user()->email, "total" => auth()->user()->total, "isEmailNotificationEnabled" => auth()->user()->take_email_notifications ]; return view("spa", ["user" => $user]); } } <file_sep>/resources/js/router.js import Vue from "vue" import VueRouter from "vue-router" Vue.use(VueRouter); import Orders from "./components/Pages/Orders/Orders.vue" import Widgets from "./components/Pages/Widgets/Widgets.vue" import Faq from "./components/Pages/Faq.vue" import Antispam from "./components/Pages/Antispam/Antispam.vue"; import Feedback from "./components/Pages/Feedback.vue"; import Balance from "./components/Pages/Balance.vue"; import Settings from "./components/Pages/Settings.vue"; import WidgetEdit from "./components/Pages/WidgetEdit/Main.vue"; const router = new VueRouter({ mode: "history", routes: [ { path: "/home", redirect: "/home/orders" }, { path: '/home/orders', component: Orders, meta: { title: "Заявки | CallBackService" } }, { path: '/home/widgets', component: Widgets, meta: { title: "Виджеты | CallBackService" } }, { path: '/home/faq', component: Faq, meta: { title: "F.A.Q. | CallBackService" } }, { path: '/home/antispam', component: Antispam, meta: { title: "Антиспам | CallBackService" } }, { path: '/home/feedback', component: Feedback, meta: { title: "Обратная связь | CallBackService" } }, { path: '/home/balance', component: Balance, meta: { title: "Баланс | CallBackService" } }, { path: '/home/settings', component: Settings, meta: { title: "Настройки | CallBackService" } }, { path: '/home/widgets/:id/edit', component: WidgetEdit, meta: { title: "Редактирование виджета | CallBackService" } }, { path: "/home/*", redirect: "/home/orders" } ] }); router.beforeEach((to, from, next) => { document.title = to.meta.title; next() }); export default router;<file_sep>/app/Models/Payment.php <?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; class Payment extends Model { protected $guarded = []; protected $dates = [ 'created_at', 'updated_at', 'performed_at' ]; public function user() { return $this->belongsTo(User::class); } public function scopePerformedToday($query) { return $this->scopePerformed($query, Carbon::today()->format("d.m.Y"), Carbon::today()->format("d.m.Y")); } public function scopePerformed($query, $start, $end) { return $query ->whereDate("performed_at", ">=", Carbon::createFromFormat("d.m.Y", $start)->toDateString()) ->whereDate("performed_at", "<=", Carbon::createFromFormat("d.m.Y", $end)->toDateString()); } public static function createExtendPayment(Widget $widget, $sum) { return self::create([ "user_id" => $widget->owner->id, "info" => "Продление тарифа", "site" => $widget->url, "sum" => $sum, "is_replenishment" => false, "performed_at" => now() ]); } } <file_sep>/app/Models/WidgetDefaultSettings.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class WidgetDefaultSettings extends Model { protected $guarded = []; public function getSettingsAttribute($value) { return json_decode($value, true); } public function setSettingsAttribute($value) { $this->attributes["settings"] = json_encode($value); } public function scopeWindows($query) { return $query ->where("type", "window") ->get() ->mapWithKeys(function($window){ return [$window->name => $window->settings]; }); } public static function getCurrentWindow() { return self::where("type", "currentWindow")->firstOrFail()->name; } public function scopeButtons($query) { return $query ->where("type", "btn") ->get() ->mapWithKeys(function($btn){ return [$btn->name => $btn->settings]; }); } public static function getCurrentButton() { return self::where("type", "currentBtn")->firstOrFail()->name; } public function scopeMobileButtons($query) { return $query ->where("type", "mobileBtn") ->get() ->mapWithKeys(function($mobileBtn){ return [$mobileBtn->name => $mobileBtn->settings]; }); } public static function getCurrentMobileButton() { return self::where("type", "currentMobileBtn")->firstOrFail()->name; } public function scopeMobileWindows($query) { return $query ->where("type", "mobileWindow") ->get() ->mapWithKeys(function($mobileWindow){ return [$mobileWindow->name => $mobileWindow->settings]; }); } public static function getCurrentMobileWindow() { return self::where("type", "currentMobileWindow")->firstOrFail()->name; } } <file_sep>/app/Http/Controllers/Data/WidgetsController.php <?php namespace App\Http\Controllers\Data; use App\Mail\WidgetManual; use App\Models\Region; use App\Models\Widget; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Mail; use Illuminate\Validation\Rule; class WidgetsController extends Controller { public function __construct() { $this->middleware('auth'); } public function getWidgets() { return auth() ->user() ->widgets() ->orderBy("created_at") ->orderBy("url") ->get() ->map(function ($widget) { return [ "id" => $widget->id, "url" => $widget->url, "orders" => $widget->lastOrders(), "rateExpiredAt" => $widget->rate_expired_at->format("d.m.Y"), "isExpired" => $widget->isExpired(), ]; }); } public function getWidgetById($id) { return auth() ->user() ->widgets() ->with("regions") ->findOrFail($id); } public function update(Request $request, $id) { $request->validate([ "autodisplay_delay" => [ "numeric", function ($attribute, $value, $fail) { if ($value < 5 || $value > 60) { return $fail('Поле "Автоматически показывать окно" должно содержать значение в диапазоне от 5 до 60'); } }, ], "emails.*.value" => "email" ]); $widget = auth()->user()->widgets()->findOrFail($id); $widget->update($request->except([ "regions", "window_settings", "btn_settings", "mobile_btn_settings", "mobile_window_settings", ])); $widget->regions()->delete(); $regions = collect($request->get("regions"))->map(function ($region) { if (array_key_exists("id", $region)) { return Region::make([ "id" => $region["id"], "name" => $region['name'], "code" => $region["code"], "uid" => $region["uid"] ]); } return Region::make([ "name" => $region['name'], "code" => $region["code"], "uid" => $region["uid"] ]); }); $widget->regions()->saveMany($regions); return []; } public function store(Request $request) { $request->validate([ "url" => [ "required", "max:255", Rule::unique("widgets")->where(function ($query) { return $query->where("owner_id", auth()->user()->id); }) ] ]); $widget = auth()->user()->widgets()->create([ "url" => $request->get("url"), "emails" => [["value" => auth()->user()->email]], "phones" => [], "schedule" => Widget::$defaultSchedule, "window_settings" => null, "btn_settings" => null, "mobile_btn_settings" => null, "mobile_window_settings" => null, "rate_expired_at" => Widget::getRateExpiredAt($request->get('url')), "timezone" => "Europe/Moscow", ]); return [ "id" => $widget->id, "url" => $widget->url, "orders" => $widget->lastOrders(), "rateExpiredAt" => $widget->rate_expired_at->format("d.m.Y"), "isExpired" => $widget->isExpired(), ]; } public function destroy($id) { auth()->user()->widgets()->findOrFail($id)->delete(); } public function sendManual(Request $request, $id) { $validatedData = $request->validate([ "email" => "required|email" ]); $widget = auth()->user()->widgets()->findOrFail($id); // Mail::to($validatedData["email"]) // ->send(new WidgetManual($widget)); return []; } public function extend(Request $request, $id) { $this->validate($request, [ "rate" => 'digits_between:0,4' ]); $widget = auth()->user()->widgets()->findOrFail($id); $rate = $request->get("rate"); $widget->extend($rate); return [ "total" => auth()->user()->refresh()->total, "widgets" => $this->getWidgets() ]; } } <file_sep>/resources/js/components/Pages/WindowAppearance/store.js import Vue from "vue" import Vuex from "vuex" import w1Store from "./components/window1/store" import w2Store from "./components/window2/store" Vue.use(Vuex); const store = new Vuex.Store({ state: { currentWindow: "w1", site: "", wid: "" }, modules: { w1: w1Store, w2: w2Store, }, mutations: { changeCurrentWindow(state, payload){ state.currentWindow = payload; }, setWindowsSettings(state, payload){ for(let key in payload) if(key.match(/w[1-90].*/)) state[key].widget = payload[key]; console.log({state}) }, setSite(state, payload){ state.site = payload }, setWid(state, payload){ state.wid = payload }, }, actions: { changeCurrentWindow(context, payload){ context.commit("changeCurrentWindow", payload) }, initState(context){ let site = document.getElementById("content").dataset["url"]; context.commit("setSite", site); let settings = JSON.parse(document.getElementById("content").dataset["settings"]); context.commit("setWindowsSettings", settings); let currentWindow = document.getElementById("content").dataset["currentwindow"]; context.commit("changeCurrentWindow", currentWindow); let wid = document.getElementById("content").dataset["wid"]; context.commit("setWid", wid); } } }); export default store<file_sep>/app/Structs/MobileBtnSettings.php <?php namespace App\Structs; class MobileBtnSettings { public $currentBtn; public $buttons; public function __toString() { return json_encode([ "currentBtn" => $this->currentBtn, "buttons" => $this->buttons ]); } public static function makeFromJson($json) { $settings = json_decode($json, true); $btnSettings = new self; $btnSettings->currentBtn = $settings["currentBtn"] ?? null; $btnSettings->buttons = $settings["buttons"] ?? []; return $btnSettings; } }<file_sep>/resources/js/components/Pages/MobileAppearance/store.js import Vue from "vue" import Vuex from "vuex" import w1Store from "./components/window1/store" import b1Store from "./components/btn1/store" Vue.use(Vuex) const store = new Vuex.Store({ state: { currentWindow: "mw1", currentBtn: "mb1", wid: "" }, modules: { mw1: w1Store, mb1: b1Store, }, mutations: { changeCurrentWindow(state, payload){ state.currentWindow = payload }, changeCurrentBtn(state, payload){ state.currentBtn = payload }, setWid(state, payload){ state.wid = payload }, setBtnState(state, payload){ for(let key in payload) if(key.match(/mb[1-90].*/)) state[key].widget = payload[key] }, setWindowState(state, payload){ for(let key in payload) if(key.match(/mw[1-90].*/)) state[key].widget = payload[key] } }, actions: { initState(context){ let doc = document.getElementById("content"); let wid = doc.dataset["wid"]; context.commit("setWid", wid); let btnState = JSON.parse(doc.dataset["btnsettings"]); context.commit("setBtnState", btnState); let windowState = JSON.parse(doc.dataset["windowsettings"]); context.commit("setWindowState", windowState); let currentBtn = doc.dataset["currentbtn"]; context.commit("changeCurrentBtn", currentBtn); let currentWindow = doc.dataset["currentwindow"]; context.commit("changeCurrentWindow", currentWindow); }, changeCurrentWindow(context, payload){ context.commit("changeCurrentWindow", payload) }, changeCurrentBtn(context, payload){ context.commit("changeCurrentBtn", payload) } } }); export default store;<file_sep>/app/Http/Resources/OrdersResponseModel.php <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\ResourceCollection; class OrdersResponseModel extends ResourceCollection { /** * Transform the resource collection into an array. * * @param \Illuminate\Http\Request $request * @return array */ public function toArray($request) { return [ "data" => $this->collection->map(function ($order) { return [ "id" => $order->id, "created_at" => $order->created_at->format("d.m.Y в H:i"), "site" => $order->widget->url, "phone" => $order->phone ]; }) ]; } } <file_sep>/app/Http/Resources/WindowAppearanceSettings.php <?php namespace App\Http\Resources; use App\Models\WidgetDefaultSettings; class WindowAppearanceSettings { private $widget; public function __construct($widget) { $this->widget = $widget; } public function toArray() { $currentWindow = $this->widget->window_settings->currentWindow ?? WidgetDefaultSettings::getCurrentWindow(); $defaultWindows = WidgetDefaultSettings::windows(); $windows = collect($defaultWindows)->mapWithKeys(function($window, $key){ if(array_key_exists($key, $this->widget->window_settings->windows)) return [$key => $this->widget->window_settings->windows[$key]]; return [$key => $window]; }); return [ "wid" => $this->widget->id, "site" => $this->widget->url, "currentWindow" => $currentWindow, "settings" => $windows ]; } }<file_sep>/resources/js/store.js import Vue from "vue" import Vuex from "vuex"; Vue.use(Vuex) import OrdersPageStore from "./components/Pages/Orders/store" import WidgetsPageStore from "./components/Pages/Widgets/store" import WidgetEditPageStore from "./components/Pages/WidgetEdit/store" import AntispamPageStore from "./components/Pages/Antispam/store" const store = new Vuex.Store({ modules: { ordersPage: OrdersPageStore, widgetsPage: WidgetsPageStore, widgetEditPage: WidgetEditPageStore, antispamPage: AntispamPageStore, }, state: { user: { name: "", email: "", total: "", phone: "", isEmailNotificationEnabled: "" } }, mutations: { initUser(state, user){ state.user.name = user.name; state.user.email = user.email; state.user.total = user.total; state.user.phone = user.phone; state.user.isEmailNotificationEnabled = user.isEmailNotificationEnabled; }, updateUserSettings(state, user){ state.user.name = user.name; state.user.email = user.email; state.user.phone = user.phone; state.user.isEmailNotificationEnabled = user.isEmailNotificationEnabled; }, updateTotal(state, amount){ state.user.total = amount; } }, actions: { initUser({commit}){ let user = JSON.parse(document.getElementById("app").dataset["user"]); commit("initUser", user) } } }); export default store<file_sep>/database/factories/WidgetDefaultSettingsFactory.php <?php use Faker\Generator as Faker; $factory->define(\App\Models\WidgetDefaultSettings::class, function (Faker $faker) { return [ "type" => "window", "name" => "w1", "settings" => [] ]; }); <file_sep>/resources/js/components/Pages/BtnAppearance/components/btn1/store.js const store = { namespaced: true, state: {}, mutations: { changePosition(state, payload){ state.position = payload }, changeBtnColor(state, payload){ state.btnColor = payload; }, changeWaveColor(state, payload){ state.waveColor = payload; }, changeXPosition(state, payload){ state.xPosition = payload }, changeYPosition(state, payload){ state.yPosition = payload }, }, }; export default store;<file_sep>/database/migrations/2019_01_22_075600_create_widgets_table.php <?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateWidgetsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('widgets', function (Blueprint $table) { $table->uuid('id')->unique(); $table->integer("owner_id")->unsigned(); $table->string("url"); $table->datetime("rate_expired_at"); $table->boolean("is_email_notify_enabled")->default(true); $table->text("emails"); $table->boolean("is_sms_notify_enabled")->default(false); $table->text("phones"); $table->string("timezone"); $table->text("schedule"); $table->boolean("is_displayed_during_not_working_hours")->default(false); $table->boolean("is_catch_enabled")->default(false); $table->boolean("is_autodisplay_enabled")->default(false); $table->integer("autodisplay_delay")->default(5); $table->boolean("is_displayed_in_all_regions")->default(true); $table->text("window_settings"); $table->text("btn_settings"); $table->text("mobile_window_settings"); $table->text("mobile_btn_settings"); $table->timestamps(); $table->foreign('owner_id')->references('id')->on('users')->onDelete("cascade"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table("widgets", function($table){ $table->dropForeign(['owner_id']); }); Schema::dropIfExists('widgets'); } } <file_sep>/app/Http/Controllers/Data/FeedbackController.php <?php namespace App\Http\Controllers\Data; use App\Mail\Feedback; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Mail; class FeedbackController extends Controller { public function __construct() { $this->middleware('auth'); } public function SendComment(Request $request) { $validatedData = $request->validate([ 'title' => 'required|string|max:100', "msg" => "required|max:1000" ]); $title = $validatedData["title"]; $msg = $validatedData["msg"]; Mail::to("<EMAIL>") ->send(new Feedback($title, $msg)); return []; } } <file_sep>/app/Http/Resources/MobileAppearanceSettings.php <?php namespace App\Http\Resources; use App\Models\WidgetDefaultSettings; class MobileAppearanceSettings { private $widget; public function __construct($widget) { $this->widget = $widget; } public function toArray() { $settings = [ "wid" => $this->widget->id, ]; $btnSettings = $this->getBtnSettings(); $windowSettings = $this->getWindowSettings(); return array_merge($settings, $btnSettings, $windowSettings); } private function getBtnSettings() { $currentBtn = $this->widget->mobile_btn_settings->currentBtn ?? WidgetDefaultSettings::getCurrentMobileButton(); $defaultButtons = WidgetDefaultSettings::mobileButtons(); $buttons = collect($defaultButtons) ->mapWithKeys(function($btn, $key){ if(array_key_exists($key, $this->widget->mobile_btn_settings->buttons)) return [$key => $this->widget->mobile_btn_settings->buttons[$key]]; return [$key => $btn]; }); return [ "currentBtn" => $currentBtn, "btnSettings" => $buttons ]; } private function getWindowSettings() { $currentWindow = $this->widget->mobile_window_settings->currentWindow ?? WidgetDefaultSettings::getCurrentMobileWindow(); $defaultWindows = WidgetDefaultSettings::mobileWindows(); $windows = collect($defaultWindows)->mapWithKeys(function($window, $key){ if(array_key_exists($key, $this->widget->mobile_window_settings->windows)) return [$key => $this->widget->mobile_window_settings->windows[$key]]; return [$key => $window]; }); return [ "currentWindow" => $currentWindow, "windowSettings" => $windows ]; } }<file_sep>/app/Models/User.php <?php namespace App\Models; use Illuminate\Notifications\Notifiable; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; protected $guarded = []; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; public function widgets() { return $this->hasMany(Widget::class, "owner_id"); } public function blackIps() { return $this->hasMany(BlackIp::class); } public function blackPhones() { return $this->hasMany(BlackPhone::class); } public function payments() { return $this->hasMany(Payment::class); } public function orders() { return $this->hasManyThrough(Order::class, Widget::class, "owner_id"); } } <file_sep>/app/Structs/WindowSettings.php <?php namespace App\Structs; class WindowSettings { public $currentWindow; public $windows; public function __toString() { return json_encode([ "currentWindow" => $this->currentWindow, "windows" => $this->windows ]); } public static function makeFromJson($json) { $settings = json_decode($json, true); $windowSettings = new self; $windowSettings->currentWindow = $settings["currentWindow"] ?? null; $windowSettings->windows = $settings["windows"] ?? []; return $windowSettings; } }<file_sep>/app/Http/Controllers/Data/OrdersController.php <?php namespace App\Http\Controllers\Data; use App\Http\Controllers\Controller; use App\Http\Resources\OrdersResponseModel; use Illuminate\Http\Request; class OrdersController extends Controller { public function __construct() { $this->middleware('auth'); } public function getOrders(Request $request) { $validatedData = $request->validate([ "s" => "required|date_format:d.m.Y", "e" => "required|date_format:d.m.Y", ]); $start = $validatedData["s"]; $end = $validatedData["e"]; return new OrdersResponseModel( auth() ->user() ->orders() ->received($start, $end) ->orderBy("created_at", "desc") ->paginate(20) ); } } <file_sep>/app/Http/Resources/BtnAppearanceSettings.php <?php namespace App\Http\Resources; use App\Models\WidgetDefaultSettings; class BtnAppearanceSettings { private $widget; public function __construct($widget) { $this->widget = $widget; } public function toArray() { $currentBtn = $this->widget->btn_settings->currentBtn ?? WidgetDefaultSettings::getCurrentButton(); $defaultButtons = WidgetDefaultSettings::buttons(); $buttons = collect($defaultButtons) ->mapWithKeys(function($btn, $key){ if(array_key_exists($key, $this->widget->btn_settings->buttons)) return [$key => $this->widget->btn_settings->buttons[$key]]; return [$key => $btn]; }); return [ "wid" => $this->widget->id, "site" => $this->widget->url, "currentBtn" => $currentBtn, "settings" => $buttons ]; } }<file_sep>/app/Models/Order.php <?php namespace App\Models; use Carbon\Carbon; use Illuminate\Database\Eloquent\Model; class Order extends Model { protected $guarded = []; public function widget() { return $this->belongsTo(Widget::class); } public function scopeReceivedToday($query) { return $this->scopeReceived($query, Carbon::today()->format("d.m.Y"), Carbon::today()->format("d.m.Y")); } public function scopeReceived($query, $start, $end) { return $query ->whereDate("orders.created_at", ">=", Carbon::createFromFormat("d.m.Y", $start)->toDateString()) ->whereDate("orders.created_at", "<=", Carbon::createFromFormat("d.m.Y", $end)->toDateString()); } } <file_sep>/app/Http/Controllers/BtnAppearanceController.php <?php namespace App\Http\Controllers; use App\Http\Resources\BtnAppearanceSettings; use App\Structs\BtnSettings; use Illuminate\Http\Request; class BtnAppearanceController extends Controller { public function __construct() { $this->middleware('auth'); } public function index($id) { $widget = auth()->user()->widgets()->findOrFail($id); return view( 'btn-appearance', (new BtnAppearanceSettings($widget))->toArray() ); } public function update(Request $request, $id) { $widget = auth()->user()->widgets()->findOrFail($id); $btnSettings = new BtnSettings(); $btnSettings->currentBtn = $request->get("currentBtn"); $btnSettings->buttons = $request->get("buttons"); $widget->btn_settings = $btnSettings; $widget->save(); return []; } } <file_sep>/resources/js/components/Pages/WindowAppearance/index.js import Vue from 'vue' import App from './components/App.vue' import store from "./store" import NotifyPlugin from "../../Shared/NotifyPlugin/NotifyPlugin" import ColorDarkenPlugin from "../../Shared/ColorDarkenPlugin" Vue.use(NotifyPlugin); Vue.use(ColorDarkenPlugin); new Vue({ render: h => h(App), store, created: function(){ this.$store.dispatch("initState") } }).$mount("#content");<file_sep>/app/Http/Controllers/Data/SettingsController.php <?php namespace App\Http\Controllers\Data; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Hash; class SettingsController extends Controller { public function __construct() { $this->middleware('auth'); } public function update(Request $request) { $validatedData = $request->validate([ 'name' => 'required|max:255', "phone" => "max:255", "take_email_notifications" => "required|boolean" ]); auth()->user()->update( collect($validatedData)->only(['name', 'phone', 'take_email_notifications']) ->toArray() ); return []; } public function changePassword(Request $request) { $validatedData = $request->validate([ "current_password" => "<PASSWORD>", 'new_password' => '<PASSWORD>', ]); if (!Hash::check($validatedData["current_password"], auth()->user()->getAuthPassword())) { return response([ "errors" => ["current_password" => ["<PASSWORD>"]] ], 422); } // auth()->user()->fill([ // "password" => <PASSWORD>($validatedData["<PASSWORD>"]), // ])->save(); return []; } } <file_sep>/app/Http/Controllers/WindowAppearanceController.php <?php namespace App\Http\Controllers; use App\Http\Resources\WindowAppearanceSettings; use App\Structs\WindowSettings; use Illuminate\Http\Request; class WindowAppearanceController extends Controller { public function __construct() { $this->middleware('auth'); } public function index($id) { $widget = auth()->user()->widgets()->findOrFail($id); return view( 'window-appearance', (new WindowAppearanceSettings($widget))->toArray() ); } public function update(Request $request, $id) { $widget = auth()->user()->widgets()->findOrFail($id); $windowSettings = new WindowSettings(); $windowSettings->currentWindow = $request->get("currentWindow"); $windowSettings->windows = $request->get("windows"); $widget->window_settings = $windowSettings; $widget->save(); return []; } } <file_sep>/resources/js/components/Pages/MobileAppearance/components/window1/store.js const store = { namespaced: true, state: { widget: {}, system: { currentState: "general" } }, mutations: { changeBgColor(state, payload){ state.widget.bgColor = payload }, changeFontColor(state, payload){ state.widget.fontColor = payload }, changeCurrentState(state, payload){ state.system.currentState = payload }, changeGeneralHeader(state, payload){ state.widget.phrases.general.header = payload }, changeGeneralBtnText(state, payload){ state.widget.phrases.general.btnText = payload }, changeAfterSendingHeader(state, payload){ state.widget.phrases.afterSending.header = payload }, changeNotWorkingHoursHeader(state, payload){ state.widget.phrases.notWorkingHours.header = payload }, changeNotWorkingHoursBtnText(state, payload){ state.widget.phrases.notWorkingHours.btnText = payload }, } }; export default store<file_sep>/webpack.common.js const path = require('path'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const VueLoaderPlugin = require("vue-loader/lib/plugin"); module.exports = { entry: { "app": "./resources/js/app.js", "window-appearance": "./resources/js/components/Pages/WindowAppearance/index.js", "btn-appearance": "./resources/js/components/Pages/BtnAppearance/index.js", "mobile-appearance": "./resources/js/components/Pages/MobileAppearance/index.js" }, output: { filename: "js/[name].js", path: path.resolve(__dirname, "public") }, module: { rules: [ { test: /\.vue$/, loader: "vue-loader" }, { test: /\.styl(us)?$/, use: [ 'vue-style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'stylus-loader' ] }, { test: /\.pug$/, loader: 'pug-plain-loader' }, { test: /\.less$/, use: [ 'vue-style-loader', MiniCssExtractPlugin.loader, 'css-loader', 'less-loader' ] }, { test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/, use: [{ loader: 'file-loader', options: { name: '[name].[ext]', outputPath: '/fonts/' } }] }, { test: /\.(png|jpg|gif)$/, use: [{ loader: 'file-loader', options: { name: "[sha512:hash:base64:7].[ext]", outputPath: "/img/", } }] }, ] }, plugins: [ new VueLoaderPlugin(), new MiniCssExtractPlugin({ filename: 'css/[name].css' }) ] };<file_sep>/database/seeds/WidgetDefaultSettingsSeeder.php <?php use App\Models\WidgetDefaultSettings; use Illuminate\Database\Seeder; class WidgetDefaultSettingsSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->seedWindows(); $this->seedButtons(); $this->seedMobileButtons(); $this->seedMobileWindows(); } private function seedWindows() { factory(WidgetDefaultSettings::class)->create([ "type" => "window", "name" => "w1", "settings" => [ "bgColor" => "rgba(0, 0, 0, 0.8)", "fontColor" => "rgba(255, 255, 255, 1)", "btnBgColor" => "rgba(0, 144, 199, 1)", "btnFontColor" => "rgba(255, 255, 255, 1)", "phrases" => [ "general" => [ "header" => "Здравствуйте!", "text" => "Остались вопросы по ремонту? Оставьте ваш номер телефона, мы с Вами свяжемся и с радостью ответим на них.", "btnText" => "Жду звонка!" ], "onExit" => [ "header" => "Здравствуйте!", "text" => "Не нашли, что искали? Давайте мы вам перезвоним и ответим на все вопросы?", "btnText" => "Жду звонка!" ], "afterSending" => [ "header" => "Спасибо за заявку, ожидайте звонка!", ], "notWorkingHours" => [ "header" => "Я вас категорически приветствую", "text" => "Сейчас мы уже не работаем, но можем перезвонить вам завтра", "btnText" => "Жду звонка!" ] ] ] ]); factory(WidgetDefaultSettings::class)->create([ "type" => "window", "name" => "w2", "settings" => [ "overlayColor" => "rgba(0, 0, 0, 0.4)", "btnBgColor" => "rgba(233,87,63,1)", "btnShadowColor" => "rgba(186, 45, 21, 1)", "phrases" => [ "general" => [ "header" => "Здравствуйте!", "text" => "Остались вопросы по ремонту? Оставьте ваш номер телефона, мы с Вами свяжемся и с радостью ответим на них.", "btnText" => "Жду звонка!" ], "onExit" => [ "header" => "Здравствуйте!", "text" => "Не нашли, что искали? Давайте мы вам перезвоним и ответим на все вопросы?", "btnText" => "Жду звонка!" ], "afterSending" => [ "header" => "Спасибо за заявку, ожидайте звонка!", ], "notWorkingHours" => [ "header" => "Я вас категарически приветствую", "text" => "Сейчас мы уже не работаем, но можем перезвонить вам завтра", "btnText" => "Ага!" ] ] ] ]); factory(WidgetDefaultSettings::class)->create([ "type" => "currentWindow", "name" => "w1" ]); } private function seedButtons() { factory(WidgetDefaultSettings::class)->create([ "type" => "btn", "name" => "b1", "settings" => [ "position" => "rb", "btnColor" => "rgba(33, 153, 255, 1)", "waveColor" => "rgba(33, 153, 255, 1)", "xPosition" => 20, "yPosition" => 20 ] ]); factory(WidgetDefaultSettings::class)->create([ "type" => "currentBtn", "name" => "b1" ]); } private function seedMobileButtons() { factory(WidgetDefaultSettings::class)->create([ "type" => "mobileBtn", "name" => "mb1", "settings" => [ "color" => "rgba(39, 132, 221, 0.95)", "xPosition" => 50, "yPosition" => 94 ] ]); factory(WidgetDefaultSettings::class)->create([ "type" => "currentMobileBtn", "name" => "mb1" ]); } private function seedMobileWindows() { factory(WidgetDefaultSettings::class)->create([ "type" => "mobileWindow", "name" => "mw1", "settings" => [ "bgColor" => "rgba(32, 95, 78, 0.95)", "fontColor" => "rgba(255,255,255,1)", "phrases" => [ "general" => [ "header" => "Мы Вам перезвоним!", "btnText" => "Жду звонка!" ], "afterSending" => [ "header" => "Спасибо за заявку!" ], "notWorkingHours" => [ "header" => "Мы сейчас не работаем. Перезвоним завтра", "btnText" => "Ok!" ] ] ] ]); factory(WidgetDefaultSettings::class)->create([ "type" => "currentMobileWindow", "name" => "mw1" ]); } } <file_sep>/routes/web.php <?php Route::get("/data/orders/get-orders", "Data\OrdersController@getOrders"); Route::get("/data/widgets", "Data\WidgetsController@getWidgets"); Route::get("/data/widgets/{id}", "Data\WidgetsController@getWidgetById"); Route::put("/data/widgets/{id}", "Data\WidgetsController@update"); Route::post("/data/widgets", "Data\WidgetsController@store"); Route::delete("/data/widgets/{id}", "Data\WidgetsController@destroy"); Route::post("/data/widgets/send-manual/{id}", "Data\WidgetsController@sendManual"); Route::post("/data/widgets/{id}/extend", "Data\WidgetsController@extend"); Route::get("/data/payments", "Data\PaymentsController@index"); Route::post("/data/payments", "Data\PaymentsController@replenish"); Route::post("/data/black-ip", "Data\AntispamController@storeIp"); Route::delete("/data/black-ip/{id}", "Data\AntispamController@deleteIp"); Route::get("/data/antispam", "Data\AntispamController@index"); Route::post("/data/black-phones", "Data\AntispamController@storePhone"); Route::delete("/data/black-phones/{id}", "Data\AntispamController@deletePhone"); Route::post("/data/feedback/send-comment", "Data\FeedbackController@sendComment"); Route::get("home/window-appearance/{id}", "WindowAppearanceController@index"); Route::put("home/window-appearance/{id}", "WindowAppearanceController@update"); Route::get("home/btn-appearance/{id}", "BtnAppearanceController@index"); Route::put("home/btn-appearance/{id}", "BtnAppearanceController@update"); Route::get("home/mobile-appearance/{id}", "MobileAppearanceController@index"); Route::put("home/mobile-appearance/btn/{id}", "MobileAppearanceController@updateBtn"); Route::put("home/mobile-appearance/window/{id}", "MobileAppearanceController@updateWindow"); Route::put("data/settings", "Data\SettingsController@update"); Route::put("data/settings/change-password", "Data\SettingsController@changePassword"); Route::get('/home{any}', 'SpaController@index')->where('any', '.*'); Auth::routes(); Route::get("/", "Auth\LoginController@showLoginForm")->name("login"); Route::get('/home', 'HomeController@index')->name('home'); <file_sep>/resources/js/components/Shared/NotifyPlugin/NotifyPlugin.js import SuccessNotify from "./SuccessNotify.vue" import DangerNotify from "./DangerNotify.vue" const NotifyPlugin = { install(Vue, options) { let successNotifyCtor = Vue.extend(SuccessNotify); let successNotify = new successNotifyCtor(); let vm = successNotify.$mount(); document.querySelector('body').appendChild(vm.$el); let dnCtor = Vue.extend(DangerNotify); let dangerNotify = new dnCtor(); let dnVM = dangerNotify.$mount(); document.querySelector("body").appendChild(dnVM.$el); Vue.prototype.$notifySuccess = function(text){ successNotify.notify(text) }; Vue.prototype.$notifyDanger = function(text){ dangerNotify.notify(text); }; } }; export default NotifyPlugin;<file_sep>/app/Traits/PhoneNumberFormatter.php <?php namespace App\Traits; trait PhoneNumberFormatter { public function formatNumber($phone) { $string = preg_replace('/[^0-9]/u', '', $phone); $string = ltrim($string, "7"); return $string; } }<file_sep>/resources/js/components/Pages/Orders/store.js const store = { namespaced: true, state: { state: null }, mutations: { setState(state, payload){ state.state = payload; } }, }; export default store<file_sep>/database/factories/PaymentFactory.php <?php use Faker\Generator as Faker; $factory->define(\App\Models\Payment::class, function (Faker $faker) { return [ "info" => $faker->sentence(3), "site" => $faker->domainName, "sum" => $faker->numberBetween(0, 30000), "is_replenishment" => $faker->boolean, "performed_at" => $faker->dateTimeBetween("-4 month", "now") ]; }); <file_sep>/database/seeds/DatabaseSeeder.php <?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { // $this->call(UsersTableSeeder::class); factory(\App\Models\User::class) ->create(["email" => "<EMAIL>", "name" => "Admin"]) ->each(function ($user) { $user->widgets()->saveMany( factory(\App\Models\Widget::class, 2)->make()) ->each(function ($widget) { $widget->orders()->saveMany( factory(\App\Models\Order::class, 500)->make() ); }); $user->payments()->saveMany( factory(\App\Models\Payment::class, 500)->make() ); }); (new WidgetDefaultSettingsSeeder())->run(); } } <file_sep>/app/Http/Controllers/Data/PaymentsController.php <?php namespace App\Http\Controllers\Data; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PaymentsController extends Controller { public function __construct() { $this->middleware('auth'); } public function index(Request $request) { $validatedData = $request->validate([ "s" => "required|date_format:d.m.Y", "e" => "required|date_format:d.m.Y", ]); $start = $validatedData["s"]; $end = $validatedData["e"]; return auth() ->user() ->payments() ->performed($start, $end) ->orderBy("performed_at", "desc") ->get() ->map(function($payment){ return [ "performed_at" => $payment->performed_at->format("d.m.Y в H:i"), "info" => $payment->info, "sum" => $payment->sum, "site" => $payment->site, "is_replenishment" => $payment->is_replenishment ]; }); } public function replenish(Request $request) { $validatedData = $request->validate([ "replenish" => "required|numeric|min:100|max:100000", ]); auth()->user()->payments()->create([ "info" => "Пополнение баланса", "sum" => $validatedData["replenish"], "is_replenishment" => true, "performed_at" => now() ]); auth()->user()->total += $validatedData["replenish"]; auth()->user()->save(); return [ "total" => auth()->user()->total ]; } } <file_sep>/resources/js/components/Pages/WidgetEdit/store.js const store = { namespaced: true, string: true, state: { settings: {}, }, mutations: { initWidgetData(state, payload){ let newState = Object.assign({}, state.settings); newState[payload.id] = payload; state.settings = newState; }, toggleEmailNotify(state, payload){ state.settings[payload.widgetId].is_email_notify_enabled = payload.value; }, toggleSmsNotify(state, payload){ state.settings[payload.widgetId].is_sms_notify_enabled = payload.value; }, addEmail(state, widgetId){ state.settings[widgetId].emails.push({value: ""}); }, removeEmail(state, payload){ state.settings[payload.widgetId].emails.splice(payload.value, 1); }, addPhone(state, widgetId){ state.settings[widgetId].phones.push({value: ""}); }, removePhone(state, payload){ state.settings[payload.widgetId].phones.splice(payload.value, 1); }, setTimezone(state, payload){ state.settings[payload.widgetId].timezone = payload.value; }, setWeekdaysSameSchedule(state, payload){ state.settings[payload.widgetId].schedule.is_weekdays_same_schedule = payload.value; }, setWeekdaysWorkdays(state, payload){ state.settings[payload.widgetId].schedule.weekdays_workdays = payload.value; }, setWeekdaysStart(state, payload){ state.settings[payload.widgetId].schedule.weekdays_start = payload.value; }, setWeekdaysEnd(state, payload){ state.settings[payload.widgetId].schedule.weekdays_end = payload.value; }, setIsDisplayedDuringNotWorkingHours(state, payload){ state.settings[payload.widgetId].is_displayed_during_not_working_hours = payload.value; }, setIsCatchEnabled(state, payload){ state.settings[payload.widgetId].is_catch_enabled = payload.value; }, setAutodisplayEnabled(state, payload){ state.settings[payload.widgetId].is_autodisplay_enabled = payload.value; }, setAutodisplayDelay(state, payload){ state.settings[payload.widgetId].autodisplay_delay = payload.value; }, setIsDisplayedInAllRegions(state, payload){ state.settings[payload.widgetId].is_displayed_in_all_regions = payload.value; }, setRegions(state, payload){ state.settings[payload.widgetId].regions = payload.value; }, addRegion(state, payload){ let regions = state.settings[payload.widgetId].regions; regions.push(payload.value); state.settings[payload.widgetId].regions = regions; }, removeRegion(state, payload){ let regions = state.settings[payload.widgetId].regions; regions.splice(_.findIndex(regions, i => i.uid === payload.value.uid), 1) }, }, actions: { toggleEmailNotify({commit}, payload){ commit("toggleEmailNotify", payload) }, toggleSmsNotify({commit}, payload){ commit("toggleSmsNotify", payload) }, setTimezone({commit}, payload){ commit("setTimezone", payload) }, setWeekdaysSameSchedule({commit}, payload){ commit("setWeekdaysSameSchedule", payload) }, setWeekdaysWorkdays({commit}, payload){ commit("setWeekdaysWorkdays", payload) }, setWeekdaysStart({commit}, payload){ commit("setWeekdaysStart", payload) }, setWeekdaysEnd({commit}, payload){ commit("setWeekdaysEnd", payload) }, setIsDisplayedDuringNotWorkingHours({commit}, payload){ commit("setIsDisplayedDuringNotWorkingHours", payload) }, setIsCatchEnabled({commit}, payload){ commit("setIsCatchEnabled", payload) }, setAutodisplayEnabled({commit}, payload){ commit("setAutodisplayEnabled", payload) }, setAutodisplayDelay({commit}, payload){ commit("setAutodisplayDelay", payload) }, setIsDisplayedInAllRegions({commit}, payload){ commit("setIsDisplayedInAllRegions", payload) }, setRegions({commit}, payload){ commit("setRegions", payload) }, addRegion({commit}, payload){ commit("addRegion", payload) }, removeRegion({commit}, payload){ commit("removeRegion", payload) }, }, getters: { widgetData: state => widgetId => state.settings[widgetId], isInitStateReady: state => widgetId => widgetId in state.settings }, }; export default store
198473de965d70b1b0ed163b2db6f25d06ab696e
[ "JavaScript", "PHP" ]
42
PHP
romanslex/callback-example
2c2eb16f1460450f6db15a9e56c8df91b4dcf764
162a9d78d86ed961b509aeabbbd9d8f5e25a22cf
refs/heads/master
<repo_name>lankunyao/dictation<file_sep>/dictation/dataset.py # coding:utf-8 import pymysql import random host = "localhost" user = "" pwd = "" db = "words" class Dataset: def __init__(self): self.conn = pymysql.connect(host=host, user=user, password=pwd, database=db) self.cursor = self.conn.cursor() self.wrong_choice = [] self.word = "" self.right_choice = "" self.test() def __del__(self): self.cursor.close() self.conn.close() print("连接已断开!") def test(self): test_text = "select word from words where id = 1" self.cursor.execute(test_text) result = self.cursor.fetchone() if result[0] == 'A': print("成功建立连接!") def random_select(self): random_number = random.randint(1, 15328) select_text = "select word,meaning from words where id = %s" self.cursor.execute(select_text, random_number) select_result = self.cursor.fetchone() print(select_result[0]) print(select_result[1]) self.word = select_result[0] self.right_choice = select_result[1] def wrong_choice_select(self): self.wrong_choice.clear() for i in range(1, 4): random_number = random.randint(1, 15328) select_text = "select meaning from words where id = %s" self.cursor.execute(select_text, random_number) select_result = self.cursor.fetchone() print(select_result[0]) self.wrong_choice.append(select_result[0]) def word_search(self, string): pass if __name__ == '__main__': dataset = Dataset() dataset.random_select() dataset.choice_select() <file_sep>/dictation/DIY.py # coding:utf-8 import sys import qtawesome from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * allAttributes = ['colorOnBegin', 'colorOnEnd', 'colorOffBegin', 'colorOffEnd', 'colorBorderIn', 'colorBorderOut', 'radiusBorderOut', 'radiusBorderIn', 'radiusCircle'] allDefaultVal = [QColor(0, 240, 0), QColor(0, 160, 0), QColor(0, 68, 0), QColor(0, 28, 0), QColor(140, 140, 140), QColor(100, 100, 100), 500, 450, 400] allLabelNames = [u'灯亮圆心颜色:', u'灯亮边缘颜色:', u'灯灭圆心颜色:', u'灯灭边缘颜色:', u'边框内测颜色:', u'边框外侧颜色:', u'边框外侧半径:', u'边框内侧半径:', u'中间圆灯半径:'] class QPushButton_circle(QAbstractButton): def __init__(self): super().__init__() self.scaledSize = 1000.0 # 为方便计算,将窗口短边值映射为1000 self.initUI() def initUI(self): self.setMinimumSize(24, 24) self.setCheckable(True) self.setButtonDefaultOption() def setButtonDefaultOption(self): for attr, val in zip(allAttributes, allDefaultVal): setattr(self, attr, val) self.update() def setButtonOption(self, opt='colorOnBegin', val=QColor(0, 240, 0)): if hasattr(self, opt): setattr(self, opt, val) self.update() def resizeEvent(self, evt): self.update() def paintEvent(self, evt): painter = QPainter(self) painter.setRenderHint(QPainter.Antialiasing, True) painter.setPen(QPen(Qt.black, 1)) realSize = min(self.width(), self.height()) # 窗口的短边 painter.translate(self.width() / 2.0, self.height() / 2.0) # 原点平移到窗口中心 painter.scale(realSize / self.scaledSize, realSize / self.scaledSize) # 缩放,窗口的短边值映射为self.scaledSize gradient = QRadialGradient(QPointF(0, 0), self.scaledSize / 2.0, QPointF(0, 0)) # 辐射渐变 # 画边框外圈和内圈 for color, radius in [(self.colorBorderOut, self.radiusBorderOut), # 边框外圈 57(self.colorBorderIn, self.radiusBorderIn)]: # 边框内圈 gradient.setColorAt(1, color) painter.setBrush(QBrush(gradient)) painter.drawEllipse(QPointF(0, 0), radius, radius) # 画内圆 gradient.setColorAt(0, self.colorOnBegin if self.isChecked() else self.colorOffBegin) gradient.setColorAt(1, self.colorOnEnd if self.isChecked() else self.colorOffEnd) painter.setBrush(QBrush(gradient)) painter.drawEllipse(QPointF(0, 0), self.radiusCircle, self.radiusCircle) <file_sep>/README.md # dictation My project about a dictation app. <file_sep>/dictation/GUI.py # coding:utf-8 import sys import qtawesome from PyQt5 import QtGui, QtCore, QtWidgets import dataset import random class MainUI(QtWidgets.QMainWindow): def __init__(self): super().__init__() self.database = dataset.Dataset() self.main_widget = QtWidgets.QWidget() # 创建窗口主部件 self.main_layout = QtWidgets.QGridLayout() # 创建主部件的网格布局 self.left_widget = QtWidgets.QWidget() # 创建左侧部件 self.left_layout = QtWidgets.QGridLayout() # 创建左侧部件的网格布局层 self.right_widget = QtWidgets.QWidget() # 创建右侧部件 self.right_layout = QtWidgets.QGridLayout() self.right_widget_2 = QtWidgets.QWidget() self.right_layout_2 = QtWidgets.QGridLayout() self.right_widget_3 = QtWidgets.QWidget() self.right_layout_3 = QtWidgets.QGridLayout() self.right_widget_4 = QtWidgets.QWidget() self.right_layout_4 = QtWidgets.QGridLayout() self.left_button_1 = QtWidgets.QPushButton(qtawesome.icon('fa.book', color='white'), "单词本") self.left_button_2 = QtWidgets.QPushButton(qtawesome.icon('fa.search', color='white'), "查询单词") self.left_button_3 = QtWidgets.QPushButton(qtawesome.icon('fa.bookmark', color='white'), "收藏夹") self.left_close = QtWidgets.QPushButton("") # 关闭按钮 self.left_mini = QtWidgets.QPushButton("") # 最小化按钮 self.right_button_start = QtWidgets.QPushButton("开始") self.right_label = QtWidgets.QLabel("") self.right_button_1 = QtWidgets.QPushButton("") self.right_button_2 = QtWidgets.QPushButton("") self.right_button_3 = QtWidgets.QPushButton("") self.right_button_4 = QtWidgets.QPushButton("") self.right_label_2 = QtWidgets.QLabel("") self.right_label_3 = QtWidgets.QLabel("") self.right_button_5 = QtWidgets.QPushButton(qtawesome.icon('fa.chevron-right'), "下一个") self.right_number = 0 self.init_ui() def init_ui(self): self.setFixedSize(400, 420) self.main_widget.setLayout(self.main_layout) # 设置窗口主部件布局为网格布局 self.left_widget.setObjectName('left_widget') self.left_widget.setLayout(self.left_layout) # 设置左侧部件布局为网格 self.right_widget.setObjectName('right_widget') self.right_widget.setLayout(self.right_layout) # 设置右侧部件布局为网格 self.right_widget_2.setObjectName('right_widget_2') self.right_widget_2.setLayout(self.right_layout_2) self.right_widget_3.setObjectName('right_widget_3') self.right_widget_3.setLayout(self.right_layout_3) self.right_widget_4.setObjectName('right_widget_4') self.right_widget_4.setLayout(self.right_layout_4) self.main_layout.addWidget(self.left_widget, 0, 0, 8, 3) self.main_layout.addWidget(self.right_widget, 0, 3, 8, 9) self.main_layout.addWidget(self.right_widget_2, 0, 3, 8, 9) self.main_layout.addWidget(self.right_widget_3, 0, 3, 8, 9) self.main_layout.addWidget(self.right_widget_4, 0, 3, 8, 9) self.setCentralWidget(self.main_widget) # 设置窗口主部件 self.right_widget.show() self.right_widget_2.hide() self.right_widget_3.hide() self.right_widget_4.hide() self.left_button_1.setObjectName('left_button') self.left_button_2.setObjectName('left_button') self.left_button_3.setObjectName('left_button') self.right_button_start.setObjectName('right_start') self.left_layout.addWidget(self.left_close, 0, 2, 1, 1) self.left_layout.addWidget(self.left_mini, 0, 0, 1, 1) self.left_layout.addWidget(self.left_button_1, 2, 0, 2, 3) self.left_layout.addWidget(self.left_button_2, 4, 0, 2, 3) self.left_layout.addWidget(self.left_button_3, 6, 0, 2, 3) self.right_layout.addWidget(self.right_button_start) self.right_button_start.setFixedSize(200, 200) self.left_close.setFixedSize(30, 30) self.left_mini.setFixedSize(30, 30) self.setWindowOpacity(0.9) self.setAttribute(QtCore.Qt.WA_TranslucentBackground) self.setWindowFlag(QtCore.Qt.FramelessWindowHint) self.main_layout.setSpacing(0) self.left_close.clicked.connect(self.close) self.left_mini.clicked.connect(self.showMinimized) self.right_button_start.clicked.connect(self.dictation) self.right_label.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) self.right_label_2.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) self.right_label_3.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter) self.right_button_5.clicked.connect(self.dictation) self.right_label.adjustSize() self.right_label_2.adjustSize() self.right_label_2.adjustSize() self.left_button_1.clicked.connect(self.show_words) self.left_button_2.clicked.connect(self.search_words) self.left_button_3.clicked.connect(self.favorite_words) self.QSS() def dictation(self): self.right_widget.hide() self.right_widget_2.show() self.right_widget_3.hide() self.right_widget_4.hide() self.right_button_1.setObjectName('right_button') self.right_button_2.setObjectName('right_button') self.right_button_3.setObjectName('right_button') self.right_button_4.setObjectName('right_button') self.right_label.setObjectName('right_label') self.right_label_2.setObjectName('right_label_2') self.right_label_2.setObjectName('right_label_3') self.right_layout_2.addWidget(self.right_label) self.right_layout_2.addWidget(self.right_button_1) self.right_layout_2.addWidget(self.right_button_2) self.right_layout_2.addWidget(self.right_button_3) self.right_layout_2.addWidget(self.right_button_4) self.choose_right_choice() def choose_right_choice(self): self.database.random_select() self.database.wrong_choice_select() self.right_label.setText(self.database.word) self.right_number = random.randint(1, 4) print(self.right_number) if self.right_number == 1: self.right_button_1.setText(self.database.right_choice) self.right_button_2.setText(self.database.wrong_choice[0]) self.right_button_3.setText(self.database.wrong_choice[1]) self.right_button_4.setText(self.database.wrong_choice[2]) self.right_button_1.clicked.connect(self.right_answer) self.right_button_2.clicked.connect(self.wrong_answer) self.right_button_3.clicked.connect(self.wrong_answer) self.right_button_4.clicked.connect(self.wrong_answer) elif self.right_number == 2: self.right_button_2.setText(self.database.right_choice) self.right_button_1.setText(self.database.wrong_choice[0]) self.right_button_3.setText(self.database.wrong_choice[1]) self.right_button_4.setText(self.database.wrong_choice[2]) self.right_button_2.clicked.connect(self.right_answer) self.right_button_1.clicked.connect(self.wrong_answer) self.right_button_3.clicked.connect(self.wrong_answer) self.right_button_4.clicked.connect(self.wrong_answer) elif self.right_number == 3: self.right_button_3.setText(self.database.right_choice) self.right_button_2.setText(self.database.wrong_choice[0]) self.right_button_1.setText(self.database.wrong_choice[1]) self.right_button_4.setText(self.database.wrong_choice[2]) self.right_button_3.clicked.connect(self.right_answer) self.right_button_2.clicked.connect(self.wrong_answer) self.right_button_1.clicked.connect(self.wrong_answer) self.right_button_4.clicked.connect(self.wrong_answer) elif self.right_number == 4: self.right_button_4.setText(self.database.right_choice) self.right_button_2.setText(self.database.wrong_choice[0]) self.right_button_3.setText(self.database.wrong_choice[1]) self.right_button_1.setText(self.database.wrong_choice[2]) self.right_button_4.clicked.connect(self.right_answer) self.right_button_2.clicked.connect(self.wrong_answer) self.right_button_3.clicked.connect(self.wrong_answer) self.right_button_1.clicked.connect(self.wrong_answer) def right_answer(self): if self.right_number == 1: self.right_button_1.clicked.disconnect(self.right_answer) self.right_button_2.clicked.disconnect(self.wrong_answer) self.right_button_3.clicked.disconnect(self.wrong_answer) self.right_button_4.clicked.disconnect(self.wrong_answer) elif self.right_number == 2: self.right_button_2.clicked.disconnect(self.right_answer) self.right_button_1.clicked.disconnect(self.wrong_answer) self.right_button_3.clicked.disconnect(self.wrong_answer) self.right_button_4.clicked.disconnect(self.wrong_answer) elif self.right_number == 3: self.right_button_3.clicked.disconnect(self.right_answer) self.right_button_1.clicked.disconnect(self.wrong_answer) self.right_button_2.clicked.disconnect(self.wrong_answer) self.right_button_4.clicked.disconnect(self.wrong_answer) elif self.right_number == 4: self.right_button_4.clicked.disconnect(self.right_answer) self.right_button_1.clicked.disconnect(self.wrong_answer) self.right_button_3.clicked.disconnect(self.wrong_answer) self.right_button_2.clicked.disconnect(self.wrong_answer) print("right!") self.right_widget.hide() self.right_widget_2.hide() self.right_widget_3.show() self.right_widget_4.hide() self.right_layout_3.addWidget(self.right_label) self.right_label_2.setText(self.database.right_choice) self.right_layout_3.addWidget(self.right_label_2) self.right_layout_3.addWidget(self.right_button_5) def wrong_answer(self): if self.right_number == 1: self.right_button_1.clicked.disconnect(self.right_answer) self.right_button_2.clicked.disconnect(self.wrong_answer) self.right_button_3.clicked.disconnect(self.wrong_answer) self.right_button_4.clicked.disconnect(self.wrong_answer) elif self.right_number == 2: self.right_button_2.clicked.disconnect(self.right_answer) self.right_button_1.clicked.disconnect(self.wrong_answer) self.right_button_3.clicked.disconnect(self.wrong_answer) self.right_button_4.clicked.disconnect(self.wrong_answer) elif self.right_number == 3: self.right_button_3.clicked.disconnect(self.right_answer) self.right_button_1.clicked.disconnect(self.wrong_answer) self.right_button_2.clicked.disconnect(self.wrong_answer) self.right_button_4.clicked.disconnect(self.wrong_answer) elif self.right_number == 4: self.right_button_4.clicked.disconnect(self.right_answer) self.right_button_1.clicked.disconnect(self.wrong_answer) self.right_button_3.clicked.disconnect(self.wrong_answer) self.right_button_2.clicked.disconnect(self.wrong_answer) print("wrong!") self.right_widget.hide() self.right_widget_2.hide() self.right_widget_3.show() self.right_widget_4.show() self.right_layout_4.addWidget(self.right_label) self.right_label_3.setText(self.database.right_choice) self.right_layout_4.addWidget(self.right_label_3) self.right_layout_4.addWidget(self.right_button_5) def show_words(self): pass def search_words(self): pass def favorite_words(self): pass def QSS(self): self.left_close.setStyleSheet(''' QPushButton{ background:#F76677; border-radius:15px; } QPushButton:hover{ background:red; image:url(resource/close.png); } ''') self.left_mini.setStyleSheet(''' QPushButton{ background:#6DDF6D; border-radius:15px; } QPushButton:hover{ background:green; image:url(resource/mini.png); } ''') self.left_widget.setStyleSheet(''' QPushButton{ color: rgb(137, 221, 255); background-color: rgb(37, 121, 255); border-style:none; border:1px solid rgb(37, 121, 255); padding:5px; min-height:20px; border-radius:15px; } QPushButton:hover{ background:blue; } QWidget#left_widget{ background:#ebe6e6; border-top:1px solid white; border-bottom:1px solid white; border-left:1px solid white; border-top-left-radius:10px; border-bottom-left-radius:10px; } ''') self.right_widget.setStyleSheet(''' QPushButton{ font-family: "KaiTi"; font-weight: bold; font-size: 60px; color: rgb(39, 72, 98); background-color: rgb(147, 224, 255); border-style:none; border:1px solid rgb(147, 224, 255); padding:5px; min-height:30px; border-radius:100px; } QPushButton:hover{ background:#00bcd4; } QWidget#right_widget{ background:#f3f3f3; border-top:1px solid white; border-bottom:1px solid white; border-right:1px solid white; border-top-right-radius:10px; border-bottom-right-radius:10px; } ''') self.right_widget_2.setStyleSheet(''' QWidget#right_widget_2{ background:#f3f3f3; border-top:1px solid white; border-bottom:1px solid white; border-right:1px solid white; border-top-right-radius:10px; border-bottom-right-radius:10px; } QPushButton{ background-color:#a6e3e9; border-style:none; border:1px solid #a6e3e9; padding:5px; min-height:30px; border-radius:15px; } QPushButton:hover{ background:#71c9ce; } QLabel{ font-family: "Times New Roman"; font-weight: bold; font-size: 30px; background-color:#a6e3e9; border-style:none; border:1px solid #a6e3e9; border-radius:15px; } ''') self.right_widget_3.setStyleSheet(''' QWidget#right_widget_3{ background:#f3f3f3; border-top:1px solid white; border-bottom:1px solid white; border-right:1px solid white; border-top-right-radius:10px; border-bottom-right-radius:10px; } QLabel{ background-color:#30e3ca; border-style:none; border:1px solid #30e3ca; border-radius:15px; } QLabel#right_label{ font-family: "Times New Roman"; font-weight: bold; font-size: 30px; } QLabel#right_label_3{ font-family: "KaiTi"; font-size: 20px; } ''') self.right_widget_4.setStyleSheet(''' QWidget#right_widget_4{ background:#f3f3f3; border-top:1px solid white; border-bottom:1px solid white; border-right:1px solid white; border-top-right-radius:10px; border-bottom-right-radius:10px; } QLabel{ background-color:#ff2e63; border-style:none; border:1px solid #ff2e63; border-radius:15px; } QLabel#right_label{ font-family: "Times New Roman"; font-weight: bold; font-size: 30px; } QLabel#right_label_4{ font-family: "KaiTi"; font-size: 20px; } ''') def main(): app = QtWidgets.QApplication(sys.argv) gui = MainUI() gui.show() sys.exit(app.exec_()) if __name__ == '__main__': main() <file_sep>/dictation/operation.py # coding:utf-8 import GUI import sys from PyQt5 import QtWidgets import dataset class Operate(GUI.MainUI, dataset.Dataset): def __init__(self): super.__init__() def get_question(self): print("") def main(): app = QtWidgets.QApplication(sys.argv) gui = GUI.MainUI() gui.show() sys.exit(app.exec_()) if __name__ == '__main__': main() <file_sep>/dictation/dictation.py # coding:utf-8 import GUI import dataset from PyQt5 import QtGui, QtCore, QtWidgets import sys import operation def main(): app = QtWidgets.QApplication(sys.argv) gui = GUI.MainUI() gui.show() words = dataset.Dataset() sys.exit(app.exec_()) if __name__ == '__main__': main()
cc6e3df46b6ac96a42828f88bbbcfe6328f11c5c
[ "Markdown", "Python" ]
6
Python
lankunyao/dictation
be287902be5bc5cdb5fc1db6757f8528e2ae0c4a
3a0b0d4a396b30a8f565cb3f0f53f1e2b5b8a4ee
refs/heads/master
<repo_name>kavyamithra14/assignment<file_sep>/src/comments.js import React from 'react'; import Home from './home.js'; import PostItem from './postItem.js'; /* On view comments button click,data received is displayed in Comments component*/ const fulldata=(props)=>{ console.log(props); if(props.length()>0){ console.log("props inside function",props); } else { console.log("no value"); } /*return item.map((comments)=> { return comments.name[0]; } )*/ } const Comments=(props)=>{ return( <div> {console.log('inside comment component', props)} <p>{fulldata()} </p> </div> ); } export default Comments;<file_sep>/src/update.js import React, { Component } from 'react'; import PostItem from './postItem.js'; let pStyle = { fontSize: '15px', textAlign: 'center', color: '#00a3cc' }; let divStyle = { backgroundColor: "grey", textAlign: "center", float: "left", width: "200px", height: "400px", margin: "20px" } class Update extends Component { constructor(props) { super(props); this.state = { data: [], buttonVisible:false }; } buttonClick = () => { this.setState({buttonVisible:true}) fetch('https://jsonplaceholder.typicode.com/posts?userId=1') .then(response => response.json()) .then(data => { console.log(data); this.setState({ data:data}); }) .catch(error => console.log("error", error)); } componentDidMount() { fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => { console.log(data); this.setState({ data:data}); }) .catch(error => console.log("error", error)); } onDelete=(e)=>{ let array=this.state.data; console.log(array); var deleteid=e.target.id; console.log(deleteid); var newarray=array.filter((del)=> { if(del.id==deleteid) { return(del.id===deleteid); } else { return(del.id!==deleteid); } }); console.log(newarray); this.setState({data: newarray}); //const newarray=array.find((id) //array.id!==id; //); //console.log(newarray); } render() { return ( <div> <h1>ALL POSTS</h1> {this.state.data.map((item)=>{ return <PostItem details={item} deleteInfo={this.onDelete} /> })} <button type="submit" onClick={this.buttonClick} >MYPOSTS</button> </div> ); } } export default Update;<file_sep>/src/postItem.js import React from 'react'; import Home from './home.js'; import Comments from './comments.js'; let divStyle={ backgroundColor:"grey", textAlign:"center", float:"left", width:"200px", height:"400px", margin:"20px" } class PostItem extends React.Component{ constructor(props){ super(props); this.state={ comments:[], commentvalue:false }; } render(){ return( <div> {/*Display data passed from map function in home*/} <div key={this.props.details.id} style={divStyle}> <p>{this.props.details.title}</p> <p>{this.props.details.body}</p> {/*Only displaying delete for user with id=1*/} {this.props.details.userId===1? <button onClick={this.props.deleteInfo} id={this.props.details.id} >DELETE</button>:null } <br/> {/* Displaying viewcomments for user with id=1*/} {this.props.details.userId===1?<button onClick={this.props.viewcomments} id={this.props.details.id}>VIEW COMMENTS</button>:null} <br/> </div> </div> ); } } export default PostItem;<file_sep>/src/delete.js import React, { Component } from 'react'; let pStyle = { fontSize: '15px', textAlign: 'center', color:'#00a3cc' }; let divStyle={ backgroundColor:"grey", textAlign:"center", float:"left", width:"200px", height:"400px", margin:"20px" } class Delete extends Component { constructor(props) { super(props); this.state = { data:[], }; } buttonClick=(i)=>{ //}fetch('https://jsonplaceholder.typicode.com/posts?userId=1') //} .then(response => response.json()) //}.then(data =>{ //} console.log(data); //}let info=data.filter((item)=>{ //}if(item.id!==i){ //} return ( //} <div key={item.id} style={divStyle}> //} <p>title:{item.title}</p> //} <p>body:{item.body}</p> //} </div> //} ) //} } //}this.setState({data:info}); //} }) //} }) //} .catch(error=>console.log("error",error)); let userdata=this.state.data; //const result=userdata.filter((i.id)=>{ //return (i.id!== userdata.id); //}); console.log("hello"); let result = userdata.filter((i)=> { return (i.id!== userdata.id); }); console.log(result); return ( <div key={userdata.id} style={divStyle}> <p>title:{userdata.title}</p> <p>body:{userdata.body}</p> </div> ) } componentDidMount() { fetch('https://jsonplaceholder.typicode.com/posts?userId=1') .then(response => response.json()) .then(data =>{ let info=data.map((item)=>{ let postid= item.id; this.state.data=item; return ( <div key={item.id} style={divStyle}> <p>{item.title}</p> <p>{item.body}</p> <button onClick={this.buttonClick(item)}>DELETE</button> </div> ) }) this.setState({data:info}); }) .catch(error=>console.log("error",error)); } render() { return ( <div> {this.state.data} </div> ); } } export default Delete;
0761bd6972c8e8520d62df157205760a5945e20c
[ "JavaScript" ]
4
JavaScript
kavyamithra14/assignment
84e01ce7179d582db774368ddf34efdcc09c88c3
e72196b89d41032cee6d5e22f8732eb280cbb489
refs/heads/master
<file_sep>package com.besttocode.serverproductmanagement.model; import lombok.Data; @Data public class StringResponse { private String response; }<file_sep># Spring Boot Server Product Management Project Backend of Server Product Management Project Using Spring Boot and MySql <file_sep>#docker image build -t product-management-server-spring . FROM openjdk:15 EXPOSE 8080 ADD build/libs/server-product-management-0.0.1-SNAPSHOT.jar server-product-management-0.0.1-SNAPSHOT.jar ENTRYPOINT ["java","-jar","/server-product-management-0.0.1-SNAPSHOT.jar"]
adb208304a04bd4f784cacf93cb26f2723eaac22
[ "Markdown", "Java", "Dockerfile" ]
3
Java
yacinebest/server-product-management-project-backend-spring-boot
1511e39729e3e2c16de4106863f48915ad0e3d79
5e1a87340e7356ef585139f98227a60aba6abc1e
refs/heads/main
<repo_name>pallavi980/pro28<file_sep>/sketch.js const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; var shinchan,stone,tree,mango; var m1,m2,m3,m4,m5,m6,m7,m8; function preload() { shinchanImg=loadImage("shinchan.jpg") stoneImg=loadImage("stone.jpg") treeImg=loadImage("th.jpg") mangoImg=loadImage("mango.jpg") } function setup() { createCanvas(800, 700); engine = Engine.create(); world = engine.world; rectMode(CENTER) shinchan=createSprite(200,400,10,10) shinchan.addImage(shinchanImg) shinchan.scale=0.1 stone=createSprite(150,400,80,70) stone.addImage(stoneImg) stone.scale=0.1 tree=createSprite(500,300,50,50) tree.addImage(treeImg) tree.scale=2 m1=new Mango(100,100,10,10) Engine.run(engine); } function draw() { rectMode(CENTER); background("white"); m1.display(); drawSprites(); }
e7d5cd546be597c320fdd10e671914bcd07d509f
[ "JavaScript" ]
1
JavaScript
pallavi980/pro28
76502bdbec5e39a625f93ba810336f7fef23e15c
3f6bf88fac90fb9f818b0b064452e1c8bddf648b
refs/heads/master
<repo_name>paulopilotti/Scripts<file_sep>/qrcode.sh #!/bin/bash # AUTOR: <NAME> # DATA: Seg 02 Mai 2011 BRT # SCRIPT qrcode.sh v1.0 # DESCRICAO: Sript que utiliza Google Chart Tools para gerar uma imagem #com um QR code. # # Script feito com base em outras dicas do site http://www.dicas-l.com.br # # ------ ------ ------ ------ ----------- VARIAVEIS ------ ------ ------ ------ -------- dimension="250x250" text="My QR code" xtmp=/tmp/x$$.1 # ------ ------ ------ ------ ------ ------ FUNCOES ------ ------ ------ ------ --------- getText(){ echo " Digite texto para o QRcode:" read text } getDimension(){ echo " Digite dimenão para o QRcode (ex.:250):" read dimension } makeImage(){ url="https://chart.googleapis.com/chart?cht=qr&chs=$dimension&chl=$text " wget "$url" -O $xtmp.jpg 2>/dev/null visualizador="display" clear echo "QR code gerado !" [ -f $xtmp.jpg ] && $visualizador $xtmp.jpg || echo "Nao gerou o QR code!" } # ------ ------ ------ ---------- INICIO PROGRAMA ------ ------ ------ ------ --------- getText getDimension clear echo "Gerando imagem QR code ..." makeImage exit 0 <file_sep>/omnislash_2.sh #!/bin/bash echo "-------------------------------------------------------------------------------------------------------------------" echo "Baixando os arquivos para o novo kernel" echo "-------------------------------------------------------------------------------------------------------------------" sudo wget http://kernel-omnislash.googlecode.com/files/linux-image-2.6.34-omnislash1.4.4_x86-64_amd64.deb sudo wget http://kernel-omnislash.googlecode.com/files/linux-headers-2.6.34-omnislash1.4.4_x86-64_amd64.deb echo "-------------------------------------------------------------------------------------------------------------------" echo "Instalando o novo kernel" echo "-------------------------------------------------------------------------------------------------------------------" sudo dpkg -i linux-headers-2.6.34-omnislash1.4.4_x86-64_amd64.deb linux-image-2.6.34-omnislash1.4.4_x86-64_amd64.deb sudo mkinitramfs -o /boot/initrd.img-2.6.34-omnislash1.4.4 /lib/modules/2.6.34-omnislash1.4.4 echo "-------------------------------------------------------------------------------------------------------------------" echo "Dando update no GRUB para que o novo kernel apareca na inicializacao" echo "-------------------------------------------------------------------------------------------------------------------" sudo update-grub echo "-------------------------------------------------------------------------------------------------------------------" echo "Dando reboot no sistema para testar o novo kernel" echo "-------------------------------------------------------------------------------------------------------------------" sudo reboot <file_sep>/cgroup_patch #!/bin/bash #credits: superpiwi #http://ubuntulife.wordpress.com/2010/11/22/el-parche-milagro-de-linux-ahora-con-script-de-instalacion/ #in English and with 3 small fixes by Andrew @ http://www.webupd8.org YELLOW="\033[1;33m" RED="\033[0;31m" ENDCOLOR="\033[0m" #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: # PARCHEAR # # Aplica las mejoras del kernel (parche de 200 lineas) # pero en 4 lineas de bash. # #:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: function PARCHEAR () { FICHERO="$HOME/.bashrc" echo "" echo -e $YELLOW"Patching [${FICHERO}]..."$ENDCOLOR echo "" # Añadiendo cadenas a .bashrc # Primero buscamos una cadena "base" para ver si esta o no ya añadido LINEAS=`cat $FICHERO | grep "/dev/cgroup/cpu/user" | wc -l` if [ "$LINEAS" == "0" ]; then echo "Adding the patch..." echo "if [ \"\$PS1\" ] ; then" | tee -a $FICHERO echo "mkdir -p -m 0700 /dev/cgroup/cpu/user/\$\$ > /dev/null 2>&1" | tee -a $FICHERO echo "echo \$\$ > /dev/cgroup/cpu/user/\$\$/tasks" | tee -a $FICHERO echo "echo \"1\" > /dev/cgroup/cpu/user/\$\$/notify_on_release" | tee -a $FICHERO echo "fi" | tee -a $FICHERO else echo "It seems the patch is already included in $FICHERO" fi FICHERO="/etc/rc.local" echo "" echo -e $YELLOW"Patching [${FICHERO}]..."$ENDCOLOR echo "" # Añadiendo cadenas a /etc/rc.local # Primero buscamos una cadena "base" para ver si esta o no ya añadido LINEAS=`cat $FICHERO | grep "/dev/cgroup/cpu/release_agent" | wc -l` if [ "$LINEAS" == "0" ]; then echo "Adding the patch..." POSI=`cat $FICHERO | grep -n "exit 0" | sort -nr | head -n 1 | awk -F: '{print $1}'` #echo "Posi es [$POSI]" echo "Making backup of $FICHERO in /etc/rc.local.backup.txt" cp /etc/rc.local /etc/rc.local.backup.txt sed "${POSI}imkdir -p /dev/cgroup/cpu\nmount -t cgroup cgroup /dev/cgroup/cpu -o cpu\nmkdir -m 0777 /dev/cgroup/cpu/user\necho \"/usr/local/sbin/cgroup_clean\" > /dev/cgroup/cpu/release_agent" /etc/rc.local | tee /etc/rc.new.local mv /etc/rc.new.local /etc/rc.local #echo "#========== 200 lines kernel patch alternative ============" | tee -a $FICHERO #echo "mkdir -p /dev/cgroup/cpu" | tee -a $FICHERO #echo "mount -t cgroup cgroup /dev/cgroup/cpu -o cpu" | tee -a $FICHERO #echo "mkdir -m 0777 /dev/cgroup/cpu/user" | tee -a $FICHERO #echo "echo \"/usr/local/sbin/cgroup_clean\" > /dev/cgroup/cpu/release_agent" | tee -a $FICHERO #echo "#====================================" | tee -a $FICHERO else echo "It seems the patch is already included in $FICHERO" fi echo "" echo -e $YELLOW"Making [${FICHERO}] executable"$ENDCOLOR echo "" sudo chmod +x $FICHERO FICHERO="/usr/local/sbin/cgroup_clean" echo "" echo -e $YELLOW"Creating [${FICHERO}]..."$ENDCOLOR echo "" if [ ! -e $FICHERO ]; then echo "#!/bin/sh" | tee $FICHERO echo "if [ \"\$*\" != \"/user\" ]; then" | tee -a $FICHERO echo "rmdir /dev/cgroup/cpu/\$*" | tee -a $FICHERO echo "fi" | tee -a $FICHERO else echo "File $FICHERO already exists." fi; echo "" echo -e $YELLOW"Making [${FICHERO}] executable"$ENDCOLOR echo "" sudo chmod +x $FICHERO echo "DONE. The patch has been applied. Restart your computer..." } #----------------------------------------------------------------------------- # Comprobar que eres usuario root if [ $USER != root ]; then echo -e $RED"Error: you need to run this script as root." echo -e $YELLOW"Exiting..."$ENDCOLOR exit 0 fi # Parchear el Sistema PARCHEAR # end of parche.sh <file_sep>/omnislash.sh #!/bin/bash echo "-------------------------------------------------------------" echo "Instalando o novo kernel: Omnislash" echo "-------------------------------------------------------------" echo "Instalando as dependências para o novo kernel >>>" sudo apt-get install build-essential bin86 kernel-package libqt3-headers libqt3-mt-dev wget libncurses5 libncurses5-dev echo "Baixando os pacotes necessários >>>" mkdir ~/omni_kernel/ cd ~/omni_kernel/ wget http://www.kernel.org/pub/linux/kernel/v2.6/linux-2.6.30.tar.bz2 wget http://dl.dropbox.com/u/1612719/configx86 wget http://dl.dropbox.com/u/1612719/configx86-64 wget http://dl.dropbox.com/u/1612719/omnislash.bz2 echo "Copiando os arquivos para /usr/src >>>" sudo cp linux-2.6.30.tar.bz2 omnislash.bz2 configx86 configx86-64 /usr/src echo "desconpctando e criando links >>>" cd /usr/src sudo tar -xvjf linux-2.6.30.tar.bz2 sudo chmod -R a-s /usr/src/linux-2.6.30 sudo rm -rf linux && ln -s /usr/src/linux-2.6.30 linux sudo cp omnislash.bz2 linux/ sudo cp configx86 linux/ sudo cp configx86-64 linux/ echo "Colocando o patch em si >>>" sudo bzcat omnislash.bz2 |patch -p1 echo "Otimizacoes do kernel, faca as alteracoes, salve e saia >>>" sudo cp /usr/src/linux-2.6.30/configx86-64 .config && make xconfig echo "Compilando o novo kernel com base nas informacoes (tempo estimado de 45 minutos) >>>" sudo make-kpkg clean sudo CONCURRENCY_LEVEL=2 make-kpkg –-initrd –-revision=x86 kernel_image kernel_headers modules_image kernel_source echo "Instalando o DEB gerado para o novo kernel >>>" sudo cd .. && dpkg -i linux*2.6.30*.deb echo "Configuracoes extra para o Sysctl.conf >>>" echo "vm.dirty_ratio = 20" >> /etc/sysctl.conf echo "vm.dirty_background_ratio = 20" >> /etc/sysctl.conf sudo sysctl -p echo "Ativando o ramzswap >>>" sudo echo "ramzswap" >> /etc/modules && echo "/dev/ramzswap0 none swap sw,pri=100 0 0" >> /etc/fstab echo "Fim ... agora reinicie e usufrua o seu novo kernel" <file_sep>/aptget.sh #!/bin/bash add-apt-repository ppa:ubuntu-mozilla-security/ppa add-apt-repository ppa:glasen/intel-driver add-apt-repository ppa:transmissionbt/ppa add-apt-repository ppa:pidgin-developers/ppa add-apt-repository ppa:ubuntu-mozilla-daily/ppa add-apt-repository ppa:tldm217/tahutek.net add-apt-repository ppa:hotot-team add-apt-repository ppa:kernel-ppa/ppa add-apt-repository ppa:sevenmachines/flash add-apt-repository ppa:webupd8team/unstable add-apt-repository ppa:libreoffice/ppa add-apt-repository ppa:jfi/ppa add-apt-repository ppa:banshee-team/ppa add-apt-repository ppa:webkit-team/ppa add-apt-repository ppa:mozillateam/firefox-next add-apt-repository ppa:emesene-team/emesene-stable add-apt-repository ppa:atareao/atareao add-apt-repository ppa:alexeftimie/ppa sh -c 'echo "deb http://ppa.launchpad.net/xorg-edgers/ppa/ubuntu jaunty main" >> /etc/apt/sources.list' sh -c 'echo "deb http://dl.google.com/linux/talkplugin/deb/ stable main" >> /etc/apt/sources.list.d/google.list' sh -c 'echo "deb http://dl.google.com/linux/deb/ stable non-free main" >> /etc/apt/sources.list.d/google.list' sh -c 'echo "deb http://download.virtualbox.org/virtualbox/debian natty contrib" >> /etc/apt/sources.list' wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add - wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add - apt-key adv --recv-keys --keyserver keyserver.ubuntu.com 4F191A5A8844C542 <file_sep>/image_google.sh #!/bin/bash # http://imagecharteditor.appspot.com/ # <NAME> discos=$(df -P| sed -n '/^[/]/p' | awk '{print $1"+-+"$6"+-+"$5}' | paste -s -d'|') usagem=$(for i in $(df -P| sed -n '/^[/]/p' | awk '{print $1}');do df -P|grep $i|awk '{print $5}';done| paste -s -d','| tr -d '%') echo "http://chart.apis.google.com/chart?chs=700x240&cht=p&chd=t:"$usagem"&chl="$discos"&chtt=Uso+dos+discos+montados" <file_sep>/webos.sh #!/bin/bash echo "Iniciando instalacao do WebOS" echo "Criando diretorio padrao" mkdir webos cd webos echo"Iniciando download das dependecias" wget -q http://download.virtualbox.org/virtualbox/debian/oracle_vbox.asc -O- | sudo apt-key add - sudo apt-get update sudo apt-get install virtualbox-4.1 sudo apt-get install ia32-libs sudo apt-get install sun-java6-jre echo "Iniciando download dos arquivos do WebOS" wget https://cdn.downloads.palm.com/sdkdownloads/3.0.2.652/sdkBinaries/palm-novacom_1.0.76_amd64.deb wget https://cdn.downloads.palm.com/sdkdownloads/3.0.2.652/sdkBinaries/palm-sdk_3.0.2-svn499310-pho652_i386.deb sudo dpkg -i --force-architecture palm-sdk_3.0.2-svn499310-pho652_i386.deb sudo dpkg -i --force-architecture palm-novacom_1.0.76_amd64.deb echo "Instalacao concluida." echo "Para rodar o webos diretamente digite: <palm-emulator> no terminal." <file_sep>/ppc.sh #!/bin/bash echo "Iniciando ..." cd /home/guilherme/Downloads/PPC java -jar APE.jar <file_sep>/frd.sh #!/bin/bash cd /home/guilherme/frd/ java -jar frd.jar <file_sep>/nokia.sh #!/bin/bash sudo obextool --obexcmd "obexftp -u 1" <file_sep>/stacks.sh #!/bin/bash # install requires libraries sudo add-apt-repository ppa:docky-core/ppa sudo apt-get update -qq sudo apt-get install -y bzr libgio2.0-cil-dev automake bzr mono-gmcs libmono-cairo2.0-cil gtk-sharp2 libndesk-dbus-glib1.0-cil libndesk-dbus1.0-cil libgtk2.0-dev libnotify0.4-cil libgio2.0-cil-dev libtool intltool ca-certificates gnome-desktop-sharp2 libgconf2-dev monodevelop-nunit sudo apt-get build-dep -y docky # fix link in maverick (test) if [ "$(lsb_release -c -s)" == "maverick" ]; then sudo touch /var/lib/apt/lists/ppa.launchpad.net_savoirfairelinux_ppa_ubuntu_dists_maverick_main_source_Sources fi # build docky stacks cd /tmp bzr branch lp:~docky-core/docky/stacks cd stacks ./autogen.sh ./configure --prefix=/usr make sudo make install killall docky nohup docky > /dev/null &
9a3237a93daaa3cce924c0e6eeb2af69e36d962d
[ "Shell" ]
11
Shell
paulopilotti/Scripts
31e0c520f210475e6d79b0757ebbc9f63155c989
2aeac6755a83ed7b57f93ff4bac8dce749046845
refs/heads/master
<repo_name>devious/wiconfig<file_sep>/README.md #wiconfig Simplified wifi on OpenBSD ##EXAMPLE Manually configure a wireless interface `# sh /etc/wiconfig iwi0` Automatically scan for wireless networks and, using previous manual configurations, configure the wireless interface based on the strongest wireless signal (for use with hostname.if(5) files) ``` $ cat /etc/hostname.iwi0 !/bin/sh /etc/wiconfig -q \$if ``` With the above /etc/hostname.iwi0 in place, iwi0 will be configured upon startup or whenever /etc/netstart iwi0 is invoked. wiconfig can also be used in conjunction with apmd. In the following example, upon resume, it'll check the status of the wireless connection and, if there is no network connection, it'll automatically scan for wireless networks and, using previous manual configurations, configure the wireless interface based on the strongest wireless signal. ``` $ cat /etc/apmd/resume #!/bin/sh /bin/sh /etc/wiconfig -qs iwi0 ``` <file_sep>/wiconfig #!/bin/sh # # v.9.5 2/7/2012 17:30 # # Copyright (c) 2012 <NAME> <<EMAIL>> # # Permission to use, copy, modify and distribute this software for any purpose # with or without fee is hereby granted, provided that the above copyright # notice and this permission notice appear in all copies. # # This software is provided by the regents and contributors "as is" and any # express or implied warranties, including, but not limited to, the implied # warranties of merchantability and fitness for a particular purpose are # disclaimed. In no event shall the regents or contributors be liable for any # direct, indirect, incidental, special, exemplary or consequential damages # (including, but not limited to, procurement of substitute goods or services; # loss of use, data or profits; or business interruption) however caused and on # any theory of liability, whether in contract, strict liability or tort # (including negligence or otherwise) arising in any way out of the use of this # software even if advised of the possibility of such damage. # # NAME # wiconfig - simplifies the configuration of wireless interfaces # # SYNOPSIS # wiconfig [-dnqs] interface # # EXAMPLE # Manually configure a wireless interface # # # sh /etc/wiconfig iwi0 # # Automatically scan for wireless networks and, using previous manual # configurations, configure the wireless interface based on the strongest # wireless signal (for use with hostname.if(5) files) # # $ cat /etc/hostname.iwi0 # !/bin/sh /etc/wiconfig -q \$if # # With the above /etc/hostname.iwi0 in place, iwi0 will be configured # upon startup or whenever /etc/netstart iwi0 is invoked. # # wiconfig can also be used in conjunction with apmd(8). In the # following example, upon resume, it'll check the status of the wireless # connection and, if there is no network connection, it'll automatically # scan for wireless networks and, using previous manual configurations, # configure the wireless interface based on the strongest wireless # signal. # # $ cat /etc/apmd/resume # #!/bin/sh # /bin/sh /etc/wiconfig -qs iwi0 # # apmd will need this file to be executable so you'll want to do this as # well # # # chmod 0744 /etc/apm/resume # # FILES # /etc/wiconfig.db Wireless network database # # CAVEATS # 1) Only DHCP is supported # 2) No user-defined nwid prioritization--the nwid with the strongest # signal will always be preferred # 3) Only the first 20 nwids with the strongest signals are used # 4) When used within a hostname.if(5), host startup will be delayed # slightly while a wireless network scan is performed # 5) Database records are never purged--existing entries will be updated, # but unwanted entries need to be removed manually # 6) Hidden nwids are not supported # set -x # Save default IFS oIFS=$IFS myname=$0 max=20 # Number of seconds to wait before checking interface status seconds=3 wiconfigdb="/etc/wiconfig.db" function usage { echo "usage: $myname [-dnqs] interface" exit 1 } # Determine network status and name function review { # Assume we are not connected to a network typeset _i=1 _status=false _ifconfig _nwid _yn # We are being called from apmd $quiet && sleep 2 # Need to use a co-process here to handle _status (and _nwid?) ifconfig "$if" |& while read -p _ifconfig; do case $_i in # Sixth line/status 6) active $_ifconfig && _status=true;; # Seventh line/nwid 7) # Connected to an active network if $_status; then set $_ifconfig _nwid=${3#\"} # nwid begins with a quote if [ ${#3} -gt ${#_nwid} ]; then # nwid is not hidden if [ ${#3} -gt 2 ]; then IFS='"' set $_ifconfig _nwid="$2" IFS=$oIFS else unset _nwid fi fi fi break;; esac _i=$(($_i+1)) done if $_status; then if $quiet; then exit else different "$_nwid" fi else start fi } # Determine if the network is active function active { typeset _status=$* typeset _length=${#_status} _status=${_status%active} # Network is active if [ ${#_status} -lt $_length ]; then return fi return 1 } function different { typeset _yn echo "Currently connected to $*." read _yn?"Would you like to connect to a different network (y/n)? " case $_yn in y) start;; n) exit;; *) different "$*";; esac } function start { readdb scan createarray match # Position of nwid in db typeset _n=$? # Automatically configuring interface if $quiet; then # Found an nwid match if [ $_n -ne 0 ]; then echo "connecting to wireless network ${r[$_n]}" configure "${r[$_n]}" "${r[$_n+2]}" else exit 1 fi else if [ $_n -ne 0 ]; then # Reconnection desired if $(reconnect $_n); then configure "${r[$_n]}" "${r[$_n+2]}" exit fi fi menu fi } function readdb { # If db exists and is readable if [ -r $wiconfigdb ]; then typeset _i=1 while read r[$_i]; do _i=$((_i+1)) done < $wiconfigdb # Remove newline from array as it's counted in ${#r[@]} unset r[$_i] fi } # Parse and sort ifconfig nwid output function scan { # Need to include a quote to account for nwids with spaces # IFS=' "' # IFS=$oIFS echo -n > "$output" typeset _nwids _args _nwid ! $quiet && echo "Performing wireless scan..." # Parse ifconfig nwid output for sorting ifconfig $if scan | grep ^[[:space:]]*nwid | while read _nwids; do # nwid name chan channel bssid mac db speed options # Required to set positional parameters set $_nwids _args=$# # Remove possible leading double quote _nwid=${2#\"} # nwid begins with a quote if [ ${#2} -gt ${#_nwid} ]; then # nwid is not hidden if [ ${#2} -gt 2 ]; then IFS='"' set $_nwids _nwid=$2 shift 2 _nwids=$* IFS=$oIFS set $_nwids else continue fi else shift 2 fi # shift # nwid has one or more spaces # if [ $_args -gt 9 ]; then # # Remove possible leading double quote # _nwid=${1#\"} # shift # _args=$(($_args-1)) # while [ $_args -gt 9 ]; do # _nwid=$_nwid $1 # # _nwid=$_nwid\ $1 # shift # _args=$(($_args-1)) # done # # Append and remove trailing double quote # _nwid=$_nwid\ ${1%\"} # else # _nwid=$1 # fi # shift # unset _nwid # nwid might contain one or more spaces # while [ $_args -ge 9 ]; do # _nwid="${_nwid:-$1} ${_nwid:+$1}" # shift # _args=$(($_args-1)) # done # nwid is hidden? # [[ X$4 = X00:00:00:00:00:00 ]] && continue echo -n "$_nwid" >> $output # Channel echo -n "|$2" >> $output # MAC echo -n "|$4" >> $output # Signal quality printf "|%02d" ${5%dBm} >> $output # Speed echo -n "|$6" >> $output # Options echo "|$7" >> $output # echo $name $number $chan $mac $db $speed $options done IFS=$oIFS # Wireless network(s) found if [ -s "$output" ]; then # Sort nwids by greatest signal quality sort -rk 4 -o "$input" -t "|" "$output" else if ! $quiet; then rescan else exit 1 fi fi } function rescan { typeset _rq read _rq?"No wireless networks found. Enter r to rescan or q to quit: " case $_rq in r) scan;; q) exit;; *) rescan;; esac } # Create sorted array of top $max nwids function createarray { IFS='|' typeset _i=1 _length # If the array exists [[ -n ${index[1]} ]] && \ unset nwid chan mac db speed options index access while read nwid[$_i] chan[$_i] mac[$_i] db[$_i] speed[$_i] options[$_i] && [ $_i -le $max ]; do index[$_i]=$_i # Determine if access is secure _length=${#options[$_i]} options=${options[$_i]#privacy} # Access is secure if [ ${#options} -lt $_length ]; then access[$_i]="Secured" else access[$_i]="Unsecured" fi _i=$(($_i+1)) done < "$input" IFS=$oIFS } # Linear search for best nwid match function match { typeset _i _m # Start with the nwid with the strongest signal for _i in ${index[@]}; do matchdb "${nwid[$_i]}" "${mac[$_i]}" _m=$? # Match found [[ $_m -ne 0 ]] && return $_m done return 0 } # Return match in the db function matchdb { # Start with last MAC in db typeset _i=$((${#r[@]}-1)) # More records in the db while [ $_i -gt 0 ]; do # MAC and nwid matches if [ "X$2" = "X${r[$_i]}" ] && \ [ "X$1" = "X${r[$_i-1]}" ]; then # Return position of nwid in db return $(($_i-1)) fi # Move to previous MAC (and network) in db _i=$(($_i-3)) done } # Configure interface function configure { ifconfig $if -nwid -nwkey -wpakey down > /dev/null 2>&1 # Apparently we need to use eval and single quotes to handle nwids with # spaces eval ifconfig $if nwid \'$1\' $2 up > /dev/null 2>&1 if [ ! $nodhcp ]; then dhclient $if fi } function reconnect { typeset _yn read _yn?"${r[$1]} found. Would you like to reconnect (y/n)? " case $_yn in y) return;; n) return 1;; *) reconnect;; esac } function menu { typeset _i echo printf " %-40s %-6s %-10s\n" "Network Name" "Signal" "Access" echo for _i in ${index[@]}; do printf "%3d) %-40s %-6s %-10s\n" \ $_i "${nwid[$_i]}" "${db[$_i]}dB" "${access[$_i]}" done echo read choice?"Enter the number of the network to connect to (or r to rescan or q to quit): " if [ $choice -ge 1 ] && [ $choice -le ${#index[@]} ]; then if [ "X${access[$choice]}" = XSecured ]; then password determine else configure "${nwid[$choice]}" update fi elif [ "X$choice" = "Xr" ]; then start elif [ "X$choice" = "Xq" ]; then exit else echo "Invalid choice" sleep 1 menu fi } function password { stty -echo read -r pass1?"Enter the password for ${nwid[$choice]} (will not echo): " echo read -r pass2?"Enter the password for ${nwid[$choice]} (again): " echo stty echo # If passwords do not match or are blank if [ "X$pass1" != "X$pass2" ] || [ "X$pass1" = X ]; then echo "Passwords do not match or are invalid" sleep 1 password fi } # Determine if we are using WPA or WEP function determine { echo "Connecting to wireless network ${nwid[$choice]}..." ifconfig "$if" -nwid -nwkey -wpakey down > /dev/null 2>&1 # Must bring interface up for status to become active ifconfig "$if" nwid "${nwid[$choice]}" wpakey "$pass1" up > /dev/null 2>&1 typeset _status=$? # Lackluster workaround for athn taking a while to become active [[ $if = athn? ]] && seconds=11 sleep $seconds # Network is active if [ $_status -eq 0 ] && active $(ifconfig "$if" | fgrep status); then update wpa else ifconfig "$if" -nwid -wpakey down > /dev/null 2>&1 ifconfig "$if" nwid "${nwid[$choice]}" nwkey "$pass1" up > /dev/null 2>&1 _status=$? sleep $seconds if [ $_status -eq 0 ] && \ active $(ifconfig "$if" | fgrep status); then update wep else echo "Unable to connect" exit 1 fi fi if [ ! $nodhcp ]; then dhclient $if fi } # Update existing db record, if it exists, or create a new one function update { # Number of entries in db typeset _i=${#r[@]} _m # db is not empty if [ $_i -gt 0 ]; then matchdb "${nwid[$choice]}" "${mac[$choice]}" _m=$? # Match found if [ $_m -ne 0 ]; then secure $(($_m+2)) $1 createdb return fi fi r[$_i+1]="${nwid[$choice]}" r[$_i+2]="${mac[$choice]}" secure $(($_i+3)) $1 createdb } # Set nwid access parameters for db record function secure { case $2 in wpa) r[$1]="wpakey \"$<PASSWORD>1\"";; wep) r[$1]="nwkey $pass1";; # Open nwid *) r[$1]="";; esac } function createdb { # If the db does not exist, create and secure it if [ ! -a "$wiconfigdb" ]; then touch "$wiconfigdb" chmod 640 "$wiconfigdb" fi echo -n > "$wiconfigdb" typeset _i=1 while [ $_i -le ${#r[@]} ]; do echo "${r[$_i]}" >> "$wiconfigdb" _i=$(($_i+1)) done } function end { rm -f "$output" "$input" } trap end EXIT ERR INT KILL TERM # Debugging for functions (must be specified after the function declaration) # typeset -ft review # typeset -ft active # typeset -ft different # typeset -ft start # typeset -ft readdb # typeset -ft scan # typeset -ft rescan # typeset -ft createarray # typeset -ft match # typeset -ft matchdb # typeset -ft configure # typeset -ft reconnect # typeset -ft menu # typeset -ft password # typeset -ft determine # typeset -ft update # typeset -ft secure # typeset -ft createdb debug=false # Assume we are being used interactively quiet=false # Do not check the wireless network status before configuring the interface # (expected in the hostname.if(5) case) status=false if [ "X$(whoami)" != Xroot ]; then echo "$myname must be run as root" exit 1 fi while getopts dnqs opt; do case $opt in d) debug=true;; n) nodhcp=true;; q) quiet=true;; s) status=true;; ?) usage;; esac done if $debug; then set -x typeset -ft review active different start readdb \ scan rescan createarray match matchdb configure reconnect menu \ password determine update secure createdb fi shift $(($OPTIND-1)) # No interface specified [[ -z "$1" ]] && usage if="$1" ifconfig "$if" > /dev/null 2>&1 # Interface does not exist if [ $? -ne 0 ]; then # Manually configuring interface if ! $quiet; then echo "Interface $if does not exist" fi exit 1 fi output=$(mktemp) input=$(mktemp) # Running from hostname.if if $quiet && ! $status; then start else review fi
b747c3ce922d4bb2d8c33be17f87a09d4ca36007
[ "Markdown", "Shell" ]
2
Markdown
devious/wiconfig
969b97afe4bf828443a00a896b8f4cc16b963fd8
771bc868bf8665121443404366102aa3992d505d
refs/heads/master
<file_sep>import tkinter def employee_reg(): rootE = tkinter.Tk() rootE.title('EMPLOYEES REGISTRATION FORM:') rootE.geometry('400x400') var = tkinter.StringVar(master=rootE) head = tkinter.Label(rootE, text='REGISTER EMPLOYEES:', fg='grey', font='arial 10 bold') head.place(x=50, y=20) l1 = tkinter.Label(rootE, text='EMPLOYEES ID:', fg='green', font='arial 8 bold') l1.place(x=50, y=50) t1 = tkinter.Entry(rootE) t1.place(x=170, y=50) l2 = tkinter.Label(rootE, text='EMPLOYEE NAME:', fg='green', font='arial 8 bold') l2.place(x=50, y=80) t2 = tkinter.Entry(rootE) t2.place(x=170, y=80) l3 = tkinter.Label(rootE, text='SEX:', fg='green', font='arial 8 bold') l3.place(x=50, y=110) # we have to create an variable r1 = tkinter.Radiobutton(rootE, text='MALE', value='male') r1.place(x=80, y=110) r2 = tkinter.Radiobutton(rootE, text='FEMALE', value='female') r2.place(x=150, y=110) l4 = tkinter.Label(rootE, text='AGE:', fg='green', font='arial 8 bold') l4.place(x=50, y=140) t3 = tkinter.Entry(rootE) t3.place(x=80, y=140) l5 = tkinter.Label(rootE, text='EMPLOYEE POSITION:', fg='green', font='arial 8 bold') l5.place(x=50, y=170) scrollbar = tkinter.Scrollbar(rootE, width=15) scrollbar.place(x=310, y=155) lb = tkinter.Listbox(rootE, selectmode='SINGLE', exportselection=0, height=1, width=21) lb.insert(tkinter.END, 'DOCTOR') lb.insert(tkinter.END, 'NURSE') lb.insert(tkinter.END, 'NURSING TECHNICIAN') lb.place(x=170, y=170) lb.config(yscrollcommand=scrollbar.set) scrollbar.configure(command=lb.yview) l6 = tkinter.Label(rootE, text='SALARY:', fg='green', font='arial 8 bold') l6.place(x=50, y=200) t4 = tkinter.Entry(rootE) t4.place(x=110, y=200) l7 = tkinter.Label(rootE, text='EXPERIENCE:', fg='green', font='arial 8 bold') l7.place(x=50, y=230) t5 = tkinter.Entry(rootE) t5.place(x=140, y=200) l8 = tkinter.Label(rootE, text='TELEPHONE:', fg='green', font='arial 8 bold') l8.place(x=50, y=260) t6 = tkinter.Entry(rootE) t6.place(x=140, y=260) l9 = tkinter.Label(rootE, text='E-MAIL:', fg='green', font='arial 8 bold') l9.place(x=50, y=290) t7 = tkinter.Entry(rootE) t7.place(x=90, y=290) rootE.mainloop() <file_sep>import tkinter import sqlite3 import tkinter.messagebox from patient_reg import patient_reg from employee_reg import employee_reg from patient_bill import patient_bill from room_finder import room_finder from reservation import reservation root1 = None def menu(): global root1, button1, button2, button3, button4, button5, button6 root1 = tkinter.Tk() root1.geometry('280x350') root1.title('Hospital System : MENU :') head = tkinter.Label(root1, text='MENU', font='Times 16 bold ' 'italic', fg='grey') button1 = tkinter.Button(root1, text='REGISTER PACIENT:', bg='light blue', fg='black', command=patient_reg) button2 = tkinter.Button(root1, text='FIND ROOM:', bg='light green', fg='black', command=room_finder) button3 = tkinter.Button(root1, text='EMPLOYEE REGISTRATION:', bg='light blue', fg='black', command=employee_reg) button4 = tkinter.Button(root1, text='RESERVATIONS:', bg='light green', fg='black', command=reservation) button5 = tkinter.Button(root1, text='PATIENT BILLING:', bg='light blue', fg='black', command=patient_bill) button6 = tkinter.Button(root1, text='EXIT:', bg='light green', fg='black') head.place(x=75, y=5) button1.pack(side=tkinter.TOP) button1.place(x=80, y=50) button2.pack(side=tkinter.TOP) button2.place(x=80, y=100) button3.pack(side=tkinter.TOP) button3.place(x=80, y=150) button4.pack(side=tkinter.TOP) button4.place(x=80, y=200) button5.pack(side=tkinter.TOP) button5.place(x=80, y=250) button6.pack(side=tkinter.TOP) button6.place(x=80, y=300) root1.mainloop() <file_sep>import tkinter def reservation(): rootR = tkinter.Tk() rootR.geometry('500x550') rootR.title('Reservation') head = tkinter.Label(rootR, text='Reservation', fg='blue', font='arial 10 bold') head.place(x=55, y=5) p_id = tkinter.Label(rootR, text='Patient ID', fg='blue', font='arial 8 bold') p_id.place(x=20, y=30) patient_id = tkinter.Entry(rootR) patient_id.place(x=100, y=30) d_id = tkinter.Label(rootR, text='Doctor ID', fg='blue', font='arial 8 bold') d_id.place(x=20, y=60) doctor_id = tkinter.Entry(rootR) doctor_id.place(x=110, y=60) r_id = tkinter.Label(rootR, text='Reservation Nº', fg='blue', font='arial 8 bold') r_id.place(x=20, y=90) r_time = tkinter.Label(rootR, text='Reservation Time (HH:MM:SS)', fg='blue', font='arial 8 bold') r_time.place(x=20, y=120) re_time = tkinter.Entry(rootR) re_time.place(x=20, y=145) r_date = tkinter.Label(rootR, text='Reservation Date (YYYY-MM-DD)', fg='blue', font='arial 8 bold') r_date.place(x=20, y=170) re_date = tkinter.Entry(rootR) re_date.place(x=20, y=195) description = tkinter.Label(rootR, text='Description', fg='blue', font='arial 8 bold') description.place(x=20, y=220) description_e = tkinter.Text(rootR, width=20, height=3) description_e.place(x=20, y=245) reserve = tkinter.Button(rootR, text='Generate', fg='blue', font='arial 8 bold') reserve.place(x=20, y=310) delete = tkinter.Button(rootR, text='Delete', fg='blue', font='arial 8 bold') delete.place(x=180, y=310) reservations = tkinter.Button(rootR, text='Reservations', fg='blue', font='arial 8 bold') reservations.place(x=320, y=310) rootR.mainloop() <file_sep>import tkinter from menu import menu root = None userbox = None passbox = None topframe = None bottomframe = None frame3 = None login = None def get_login(): global userbox, passbox, error usertest = userbox.get() passwordtest = passbox.get() if (usertest == 'master' and passwordtest == 'master'): root.destroy() menu() else: error = tkinter.Label(bottomframe, text='PLEASE ENTER A VALID USERNAME AND PASSWORD!', fg='red', font='bold') error.pack() def entry(): global root, userbox, passbox, login, topframe, bottomframe, image_1 root = tkinter.Tk() root.geometry('440x480') topframe = tkinter.Frame(root) topframe.pack() bottomframe = tkinter.Frame(root) bottomframe.pack() head = tkinter.Label(topframe, width=45, text='Hospital System', bg='#135823', fg='grey', font='Times 16 bold ' 'italic') username = tkinter.Label(topframe, text='User:') userbox = tkinter.Entry(topframe) password = tkinter.Label(bottomframe, text='Password:') passbox = tkinter.Entry(bottomframe) login = tkinter.Button(bottomframe, text='LOGIN', font='arial 8 bold', command=get_login) root.wm_iconbitmap(r'D:\\DataScience\\Hospital-System-Using-Python\\icons\\password.ico') image = tkinter.PhotoImage(file='D:\\DataScience\\Hospital-System-Using-Python\\img\\login.png') image = image.subsample(1,1) labelimg = tkinter.Label(image=image, height='380', width='300') labelimg.pack() head.pack() username.pack() userbox.pack() password.pack() passbox.pack() login.pack() root.title('Hospital System : LOGIN :') root.mainloop() entry() <file_sep>import tkinter def room_details(): rootRD = tkinter.Tk() rootRD.geometry('280x280') rootRD.title('ROOM INFORMATION') head = tkinter.Label(rootRD, text='Patient ID', font='Times 13 bold', fg='orange') head.place(x=20, y=20) patient_id = tkinter.Entry(rootRD) patient_id.place(x=50, y=50) search = tkinter.Button(rootRD, text='Search', font='Times 8 bold', fg='orange') search.place(x=70, y=80) exit = tkinter.Button(rootRD, text='Exit', font='Times 8 bold', fg='orange') exit.place(x=150, y=80) rootRD.mainloop() def room_finder(): rootR = tkinter.Tk() rootR.geometry('400x400') rootR.title('FIND ROOM:') head = tkinter.Label(rootR, text='FIND ROOM:', font='Times 13 bold', fg='orange') head.place(x=75, y=10) id = tkinter.Label(rootR, text='PATIENT ID:', font='Times 8 bold', fg='orange') id.place(x=30, y=60) patient_id = tkinter.Entry(rootR) patient_id.place(x=100, y=60) room_tl = tkinter.Label(rootR, text='ROOM TYPE:', font='Times 8 bold', fg='orange') room_tl.place(x=30, y=100) rate_l = tkinter.Label(rootR, text='ROOM RATE:', font='Times 8 bold', fg='orange') rate_l.place(x=30, y=220) rate = tkinter.Entry(rootR) rate.place(x=130, y=220) ed_l = tkinter.Label(rootR, text='ENTRY DATE:', font='Times 8 bold', fg='orange') ed_l.place(x=30, y=260) ed = tkinter.Entry(rootR) ed.place(x=140, y=260) dd_l = tkinter.Label(rootR, text='DEPARTURE DATE:', font='Times 8 bold', fg='orange') dd_l.place(x=30, y=300) dd = tkinter.Entry(rootR) dd.place(x=155, y=300) submit = tkinter.Button(rootR, text='Submit', font='Times 8 bold', fg='orange') submit.place(x=30, y=340) update = tkinter.Button(rootR, text='Update', font='Times 8 bold', fg='orange') update.place(x=130, y=340) room_d = tkinter.Button(rootR, text='Room Details', font='Times 8 bold', fg='orange', command=room_details) room_d.place(x=220, y=340) exit = tkinter.Button(rootR, text='Exit', font='Times 8 bold', fg='orange') exit.place(x=330, y=340) rootR.mainloop() <file_sep>import tkinter import _sqlite3 import tkinter.messagebox def patient_update(): rootP = tkinter.Tk() rootP.geometry('340x460') rootP.title('PATIENT UPDATE FORM:') head = tkinter.Label(rootP, text='PATIENT UPDATE FORM:', font='arial 16 bold') id = tkinter.Label(rootP, text='PATIENT ID:', font='arial 8 bold', fg='blue') patient_id = tkinter.Entry(rootP) name = tkinter.Label(rootP, text='PATIENT FULL NAME:', font='arial 8 bold', fg='blue') patient_name = tkinter.Entry(rootP) sex = tkinter.Label(rootP, text='SEX:', font='arial 8 bold', fg='blue') patient_sex = tkinter.Entry(rootP) dof = tkinter.Label(rootP, text='DATE OF BIRTH (YYYY-MM-DD):', font='arial 8 bold', fg='blue') patient_dof = tkinter.Entry(rootP) blood_g = tkinter.Label(rootP, text='BLOOD GROUP:', font='arial 8 bold', fg='blue') patient_blood_g = tkinter.Entry(rootP) contact1 = tkinter.Label(rootP, text='TELEPHONE:', font='arial 8 bold', fg='blue') patient_contact1 = tkinter.Entry(rootP) contact2 = tkinter.Label(rootP, text='CONTACT:', font='arial 8 bold', fg='blue') patient_contact2 = tkinter.Entry(rootP) email = tkinter.Label(rootP, text='E-MAIL:', font='arial 8 bold', fg='blue') patient_email = tkinter.Entry(rootP) ct = tkinter.Label(rootP, text='CONSULTANT TEAM DOCTOR:', font='arial 8 bold', fg='blue') patient_ct = tkinter.Entry(rootP) address = tkinter.Label(rootP, text='ADDRESS:', font='arial 8 bold', fg='blue') patient_address = tkinter.Entry(rootP) # back = tkinter.Button(rootP, text='Back', fg='blue', font='arial 8 bold', bg='orange') # search = tkinter.Button(rootP, text='Search', fg='blue', font='arial 8 bold', bg='darkorange') # delete = tkinter.Button(rootP, text='Delete', fg='blue', font='arial 8 bold', bg='sienna') update = tkinter.Button(rootP, text='Update', fg='blue', font='arial 8 bold', bg='darkmagenta') # submit = tkinter.Button(rootP, text='Submit', fg='blue', font='arial 8 bold', bg='darkcyan') head.pack() id.pack() patient_id.pack() name.pack() patient_name.pack() sex.pack() patient_sex.pack() dof.pack() patient_dof.pack() blood_g.pack() patient_blood_g.pack() contact1.pack() patient_contact1.pack() contact2.pack() patient_contact2.pack() email.pack() patient_email.pack() ct.pack() patient_ct.pack() address.pack() patient_address.pack() #submit.pack() #back.pack(side=tkinter.LEFT) update.pack() #delete.pack(side=tkinter.LEFT) #search.pack(side=tkinter.LEFT) rootP.mainloop() def patient_delete(): rootP = tkinter.Tk() rootP.geometry('290x150') rootP.title('PATIENT DELETE FORM:') head = tkinter.Label(rootP, text='INSERT PATIENT ID TO DELETE:', font='arial 8 bold') patient_id = tkinter.Entry(rootP) delete = tkinter.Button(rootP, text='Delete', font='arial 8 bold', bg='red') head.pack() patient_id.pack() delete.pack() rootP.mainloop() def patient_search(): rootP = tkinter.Tk() rootP.geometry('400x150') rootP.title('PATIENT SEARCH FORM:') head = tkinter.Label(rootP, text='INSERT PATIENT TO SEARCH:', font='arial 8 bold') patient_id = tkinter.Entry(rootP) search = tkinter.Button(rootP, text='Search', font='arial 8 bold', bg='red') head.pack() patient_id.pack() search.pack() rootP.mainloop() <file_sep># Hospital-System-Using-Python <file_sep>import tkinter def patient_bill(): rootB = tkinter.Tk() rootB.geometry('450x350') rootB.title('BILLING FORM') head = tkinter.Label(rootB, text='PATIENT BILLS', font='arial 16 bold italic', fg='orange') head.place(x=100, y=10) id = tkinter.Label(rootB, text='PATIENT ID:') id.place(x=20, y=60) patient_id =tkinter.Entry(rootB) patient_id.place(x=100, y=60) date_l = tkinter.Label(rootB, text='DATE:') date_l.place(x=20, y=100) dd =tkinter.Entry(rootB) dd.place(x=135, y=100) dd_update = tkinter.Button(rootB, text='UPDATE DATE') dd_update.place(x=270, y=100) treat = tkinter.Label(rootB, text='TYPE OF TREATMENT') treat.place(x=20, y=140) # We must create a lisbox here! cost_l = tkinter.Label(rootB, text='COST:') cost_l.place(x=315, y=140) cost_t = tkinter.Entry(rootB, width=5) cost_t.place(x=350, y=140) med_l = tkinter.Label(rootB, text='SELECT MEDICINE:') med_l.place(x=20, y=180) med_ql = tkinter.Label(rootB, text='AMOUNT:') med_ql.place(x=20, y=180) price_l = tkinter.Label(rootB, text='PRICE:') price_l.place(x=315, y=180) price = tkinter.Entry(rootB, width=5) price.place(x=360, y=180)
e1b810bba889302b185b2c9431e114c2daa9f8c9
[ "Markdown", "Python" ]
8
Python
Collumbus/Hospital-System-Using-Python
c5b1cdf51f2cd44f30603e89e7ad8a20cdd2506d
463d9ac42de641d5cc3599920990d4b14dd4dcbd
refs/heads/master
<file_sep>CREATE TABLE STATE_TAX_BRACKET(STATE CHAR(50), RATE REAL, STATUS CHAR(50), MIN REAL, MAX REAL);<file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Test Redirect!</title> </head> <form action="addCustomerDetail" method="post" id="formid" class="transbox" style="width:700px;"> <div align="center"> <h2>Thank you! Your order has been placed successfully <br> Your order number is {{ customerid }}.</h2> </div> </form> </body> </html><file_sep>CREATE TABLE FEDERAL_TAX_BRACKET(RATE REAL, STATUS CHAR(50), MIN REAL, MAX REAL);<file_sep>-- MySQL Workbench Forward Engineering SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0; SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0; SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES'; -- ----------------------------------------------------- -- Schema mydb -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema paycheck_calculator -- ----------------------------------------------------- -- ----------------------------------------------------- -- Schema paycheck_calculator -- ----------------------------------------------------- CREATE SCHEMA IF NOT EXISTS `paycheck_calculator` DEFAULT CHARACTER SET utf8 ; USE `paycheck_calculator` ; -- ----------------------------------------------------- -- Table `paycheck_calculator`.`federal_tax_bracket` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `paycheck_calculator`.`federal_tax_bracket` ( `RATE` DOUBLE NULL DEFAULT NULL, `STATUS` CHAR(50) NULL DEFAULT NULL, `MIN` DOUBLE NULL DEFAULT NULL, `MAX` DOUBLE NULL DEFAULT NULL) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; -- ----------------------------------------------------- -- Table `paycheck_calculator`.`state_tax_bracket` -- ----------------------------------------------------- CREATE TABLE IF NOT EXISTS `paycheck_calculator`.`state_tax_bracket` ( `STATE` CHAR(50) NULL DEFAULT NULL, `RATE` DOUBLE NULL DEFAULT NULL, `STATUS` CHAR(50) NULL DEFAULT NULL, `MIN` DOUBLE NULL DEFAULT NULL, `MAX` DOUBLE NULL DEFAULT NULL) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8; SET SQL_MODE=@OLD_SQL_MODE; SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS; SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS; <file_sep>INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(10, 'Single', 0, 9275); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(10, 'Joint', 0, 18550); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(15, 'Single', 9275, 37650); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(15, 'Joint', 18550, 75300); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(25, 'Single', 37650, 91150); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(25, 'Joint', 75300, 151900); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(28, 'Single', 91150, 190150); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(28, 'Joint', 151900, 231450); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(33, 'Single', 190150, 413350); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(33, 'Joint', 231450, 413350); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(35, 'Single', 413350, 466950); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(35, 'Joint', 413350, 441000); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(39.6, 'Single', 466950, 10000000); INSERT INTO FEDERAL_TAX_BRACKET(RATE, STATUS, MIN, MAX) VALUES(39.6, 'Joint', 441000, 10000000);<file_sep># All Imports from flask import Flask, render_template, request import pymysql from datetime import datetime, date, time import numpy as np app = Flask(__name__) # Configurations conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='<PASSWORD>', db='paycheck_calculator') cursor = conn.cursor() # The Home Page @app.route('/') def main(): return render_template('index.html') @app.route('/test', methods=['GET', 'POST']) def test(): return render_template("test.html", customerid=100) # To Show the List of Restaurants @app.route('/payCheckCalculator', methods=['GET', 'POST']) def payCheckCalculator(): selected_state = request.form['states'] selected_grosspay = request.form['grosspay'] selected_payfrequency = request.form['pay_frequency'] selected_status = request.form['filing_status'] select_allowances = request.form['allowances'] selected_withholding = request.form['withholding'] selected_exempt_tax = request.form.getlist('exemption') selected_statewithhold = request.form['withhold'] selected_exemptstate_yes_no = request.form.getlist('exempt') # Number of weekdays in current year now = datetime.now() workingdays_in_year = np.busday_count(str(now.year), str(now.year + 1)) # total number of weeks in current year weeks_in_year = int(datetime(now.year, 12, 31).strftime("%W")) selected_grosspay = int(selected_grosspay) if selected_payfrequency == "Daily": paycheckGrossPay = selected_grosspay / workingdays_in_year elif selected_payfrequency == "Weekly": paycheckGrossPay = selected_grosspay / weeks_in_year elif selected_payfrequency == "Bi-Weekly" or selected_payfrequency == "Semi-Monthly": paycheckGrossPay = selected_grosspay / weeks_in_year paycheckGrossPay = paycheckGrossPay * 2 elif selected_payfrequency == "Monthly": paycheckGrossPay = selected_grosspay / 12 elif selected_payfrequency == "Quarterly": paycheckGrossPay = selected_grosspay / 12 paycheckGrossPay = paycheckGrossPay * 3 elif selected_payfrequency == "Semi-Annually": paycheckGrossPay = selected_grosspay / 6 elif selected_payfrequency == "Annually": paycheckGrossPay = selected_grosspay # Calculate Federal tax if 'Federal' in selected_exempt_tax or 'yes' in selected_exemptstate_yes_no: fedtax_rate = 0 else: sql = "SELECT RATE FROM FEDERAL_TAX_BRACKET WHERE MIN<=' + selected_grosspay + ' AND MAX>=' + selected_grosspay + ' AND STATUS = '" + selected_status + "'" cursor.execute(sql) row = cursor.fetchone() fedtax_rate = row[0] federaltax_deduction = paycheckGrossPay * fedtax_rate / 100 # Calculate State tax sql1 = "SELECT RATE FROM STATE_TAX_BRACKET WHERE STATE = '" + selected_state + "' AND STATUS = '" + selected_status + "' AND MIN<=' + selected_grosspay + ' AND MAX>=' + selected_grosspay + '" cursor.execute(sql1) row = cursor.fetchone() statetax_rate = row[0] statetax_deduction = paycheckGrossPay * statetax_rate / 100 # Medicare tax = 3.8% when Single -> 200k or Married ->250k, otherwise 1.45% if 'Medicare' in selected_exempt_tax: medicaretax_percent = 0 elif (selected_grosspay > 200000 and selected_status == "Single") or ( selected_grosspay > 250000 and selected_status == "Married"): medicaretax_percent = 3.8 else: medicaretax_percent = 1.45 medicaretax_deduction = paycheckGrossPay * medicaretax_percent / 100 # SDI / SUI tax for the year 2016 is 0.9 % sditax_deduction = paycheckGrossPay * 0.9 / 100 # Social security tax for the year 2016 is 6.2% if 'Fica' in selected_exempt_tax: socialsecuritytax_percent = 0 else: socialsecuritytax_percent = 6.2 socialsecuritytax_deduction = paycheckGrossPay * socialsecuritytax_percent / 100 # Calculate net pay netpay = paycheckGrossPay - federaltax_deduction - statetax_deduction - socialsecuritytax_deduction - medicaretax_deduction - sditax_deduction return render_template("paychk.html", state=selected_state, grosspay=paycheckGrossPay, netpay=netpay, payfrequency=selected_payfrequency, filing_status=selected_status, federal_tax=federaltax_deduction, state_tax=statetax_deduction, sstax=socialsecuritytax_deduction, medicare_tax=medicaretax_deduction, sdi_sui=sditax_deduction) # Application starting point. if __name__ == '__main__': app.run()
2d21d978b5e8b7e3f3ec80f86e0b2c129a171ca6
[ "SQL", "Python", "HTML" ]
6
SQL
varshareddydvr/Pay_Check_Calculator_Python
4298f80c708d41f83baf3fc0b2e3807dd344b2f9
bfdf0e55306a044703d553e652868b7997b3470c
refs/heads/master
<file_sep>#bin/sh # Search for a ".sh" function in the current directory and the subdirectories find . -name "*.sh" | cut -d . -f 2 | rev | cut -d / -f 1 | rev <file_sep>#bin/sh/ ifconfig | grep "HWaddr" | cut -d "H" -f 2 | cut -d " " -f 2 <file_sep># fonction-sh print_groups.sh "Search for a .sh function in the current directory and the subdirectories" <file_sep>#bin/sh/ #Search the current directory and all its subdirectories all files find . \( -name '*.sh' \) -print | sed 's/\(.*\)\///g' | sed 's/\.sh//g' <file_sep>#bin/sh/ cat /etc/passwd | cut -d ":" -f 1 | sed -n 2~2p | rev | sort -r | tr "\n" "," | sed "s/,/, /g" | sed "s/\(.*\), /\1.\n/" <file_sep>#bin/sh/ #View the number of regular files and directories in the current directory and all its subdirectories find * | find . | wc -l
5fc1ab7f26432acbf79d4748063abf551451b576
[ "Markdown", "Shell" ]
6
Shell
himuraxp/fonction-sh
f140660174b34d9fc4048719eee445b219fba5d2
696927884fedf151ef96818127a080ca29c41749
refs/heads/master
<file_sep>import entobn #a = entobn.googel_translate('do') translet = entobn.translate_bengali('What are you doing now?') # Translate To Bengali From Google, Bing, Yandex, Baidu. tobangla = entobn.en_bn('What are you doing now?') # Translate To Bengali From English. toenglish = entobn.bn_en('তুমি এখন কি করছো?') # Translate To English From Bengali. print (tobangla) <file_sep>import entobn #a = entobn.googel_translate('do') translet = entobn.translate_bengali('How are you?') # Translate To Bengali From Google, Bing, Yandex, Baidu. tobangla = entobn.en_bn('How are you?') # Translate To Bengali From English. toenglish = entobn.bn_en('তুমি কেমন আছো?') # Translate To English From Bengali. print (translet) <file_sep># Project description. Englishtobengali is a web based Bangla to English and reverse translator. - Translating From English To Bangali. - Translating From Bangali To English. It uses Google, Bing, Yandex, Baidu translation servies . ### Installation. Install ```englishtobengali``` through pip using Python 3. ``` $ pip install englishtobengali $ pip3 install englishtobengali ``` ### Usages/Example. To translate Bengali to English and reverse. ``` import entobn translet = entobn.translate_bengali('How are you?') # Translate To Bengali From Google, Bing, Yandex, Baidu. tobangla = entobn.en_bn('How are you?') # Translate To Bengali From English. toenglish = entobn.bn_en('তুমি কেমন আছো?') # Translate To English From Bengali. print (toenglish) ``` It can be run from command line/cmd creating a bat file. Need to download/clone the app from GITHUB. Paste the below code in bat file and place bat file and downloaded/cloned app at same directory. ``` @echo off ``` ### Contribute. Create Github Pull Request. For any suggestion : Facebook : [<NAME>](https://www.facebook.com/paradox.jabed) Else GitHub issue system : GitHub : [Md Jabed Ali](https://github.com/jabedparadox) PYPI : [Md Jabed Ali](https://pypi.org/project/englishtobengali/) ### Thanks. <file_sep>#!/usr/bin/python #!/usr/bin/python3 #!/usr/bin/env python #!/usr/bin/env python3 # -*- coding: utf8 -*- import setuptools with open('README.md', encoding='utf8', errors='ignore') as rd: long_description = rd.read() setuptools.setup( name = 'englishtobengali', version = '0.0.2', author = '<NAME> (Jabed)', author_email = '<EMAIL>', description = '+8801670105219', long_description = 'Python Web Based English To Bangla Translator.', #long_description_content_type=textmarkdown, url = 'https://github.com/jabedparadox', packages = setuptools.find_packages(), classifiers = [ 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Development Status :: 5 - Production/Stable', 'Topic :: Software Development :: Libraries :: Python Modules' ], license = 'MIT', setup_requires=['wheel'], keywords = 'python bangla english translator python english to bangla translator python bangla' ) <file_sep>#!/usr/bin/python #!/usr/bin/python3 #!/usr/bin/env python #!/usr/bin/env python3 # -*- coding: utf8 -*- # Python Web Based English To Bangla Translator. # date :- # author :- <NAME>(jabed) import entobn as bn_trnslt bn_trnslt.googel_translate()
d5b91b91c29fa33c77a3a47b7273a53aa806b768
[ "Markdown", "Python" ]
5
Python
jabedparadox/englishtobengali
bd28fca3583d297f114364450a8f1d5c100b8a27
991c9036661749886d0513b6931fe5a23815d74b
refs/heads/main
<repo_name>rtequida/Paramiko<file_sep>/Dead_Ports/findDeadPorts.py import paramiko import sys import time import xlrd import xlsxwriter def main(): loc = ("switches.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) switches = getSwitches(sheet) info = getInfo(switches) writeData(info) writeDateText(info) def getSwitches(sheet): data = [] for i in range(sheet.nrows): data.append(sheet.cell_value(i, 0)) return data def getInfo(switches_list): nbytes = 4096 username = "***Enter username here***" password = "***<PASSWORD>***" info = [] output = "" switches = {} for switch in switches_list: print("Working on " + switch) port = 22 switches[switch] = {} hostname = switch ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(hostname, port = port, username = username, password = <PASSWORD>) except paramiko.ssh_exception.AuthenticationException: print("Could not authenticate to host " + hostname) continue except paramiko.ssh_exception.NoValidConnectionsError: print("Could not connect to host " + hostname) continue except: print("Unknown Error with host " + hostname) continue time.sleep(2) print ("Successfully connected to " + hostname) shell = ssh.invoke_shell() time.sleep(2) output = shell.recv(2000) print("Running commands...") shell.send("terminal length 0\n") time.sleep(1) print("Getting port info...") shell.send("sh int status\n") time.sleep(2) if shell.recv_ready(): output = shell.recv(16000) info = output.decode("ascii") ports = getPorts(info) for port in ports: print("Reading port", port) command = "sh int " + port + " | i Last input" shell.send(command + "\n") time.sleep(.2)0\ if shell.recv_ready(): output = shell.recv(2000) status = output.decode("ascii") status = status.split("\n") print(status) ports[port] = status[1].strip() switches[switch] = ports shell.send("terminal length 48\n") time.sleep(1) shell.close() ssh.close() print("Finished with switch " + hostname) return switches def getPorts(info): ports = {} info = info.split("\n")[4:-1] for item in info: temp = item.split(" ") ports[temp[0]] = "" return ports def writeData(switches): wb = xlsxwriter.Workbook("Port Usage Info.xlsx") ws = wb.add_worksheet() row = 0 col = 0 ws.set_column('C:C', 50) for switch in switches: ws.write(row, col, switch) row += 1 col = 1 for port in switches[switch]: ws.write(row, col, port) col = 2 ws.write(row, col, switches[switch][port]) col = 1 row += 1 col = 0 wb.close() def writeDateText(switches): for switch in switches: file = open(switch + " Port Usage Info.txt", "w") for port in switches[switch]: file.write(port + " : " + switches[switch][port] + "\n") file.close() main() <file_sep>/nslookup.py import socket import xlrd def main(): loc = ("UnreachableDevices.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) device_IPs = getData(sheet) displayFQDN(device_IPs) def getData(sheet): data = [] for i in range(sheet.nrows): data.append(sheet.cell_value(i, 0)) return data def displayFQDN(ips): for ip in ips: print(socket.getfqdn(ip)) main() <file_sep>/UnreachableNodesDetective.py import paramiko import sys import time import xlrd import csv import subprocess import os def main(): loc = ("UnreachableDevices.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) device_IPs = getData(sheet) info = pingable(device_IPs) info = conclusion = findAnswers(info) for key in info: print(key, ":", info[key]) def getData(sheet): data = [] for i in range(sheet.nrows): data.append(sheet.cell_value(i, 0)) return data def pingable(ips): info = {} nos = 0 yes = 0 length = len(ips) count = 0 with open(os.devnull, "wb") as limbo: for ip in ips: count += 1 result = subprocess.Popen(["ping", "-n", "1", "-w", "200", ip], stdout=limbo, stderr=limbo).wait() if result: print(ip, "\t: failed", " (", count, "/", length, ")") info[ip] = "NO" nos += 1 else: print(ip, "\t: passed", " (", count, "/", length, ")") info[ip] = "YES" yes += 1 print("Failed: ", nos, "\nPassed: ", yes) return info def findAnswers(info): nbytes = 4096 port = 22 username = "" password = "" command = "ls" output = "" for ip in info: if info[ip] == "YES": hostname = ip ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) print("Testing: ", hostname) try: ssh.connect(hostname, port = port, username = username, password = <PASSWORD>) except paramiko.ssh_exception.AuthenticationException: print("Could not authenticate to host " + hostname) info[ip] = "Could not authenticate to host" continue except paramiko.ssh_exception.NoValidConnectionsError: print("Could not connect to host " + hostname) info[ip] = "Could not connect to host" continue except paramiko.ssh_exception.SSHException: print("Failures in SSH2 protocol") info[ip] = "Failed to establish SSH connection" continue except: print("Unknown Error") info[ip] = "Unknown Error" continue time.sleep(2) print ("Successfully connceted to " + hostname) info[ip] = "Success" ssh.close() return info main() <file_sep>/wipe.py import paramiko import sys import time from tkinter import * from tkinter.font import * COLOR = "gray5" def main(): root = Tk() root.config(bg = COLOR) nbytes = 4096 hostname = "" port = 22 password = "" first = 17 last = 23 run = 0 root.mainloop() if run != 0: for i in range(first, last + 1): print ("Working on port " + str(i)) username = "netadmin:port" + str(i) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(hostname, port = port, username = username, password = <PASSWORD>) except paramiko.ssh_exception.AuthenticationException: print ("Couldn't connect") continue except: print ("Unknown Error") continue shell = ssh.invoke_shell() time.sleep(3) shell.send("\r\n") time.sleep(3) shell.send("***Enter user name here***\n") time.sleep(.5) shell.send("***Enter password here***\n") time.sleep(.5) shell.send("en\n") time.sleep(.5) shell.send("***Enter password here***\n") time.sleep(.5) print ("Destroying Data!!!") shell.send("write erase\n") time.sleep(.5) shell.send("\r\n") time.sleep(3) shell.send("delete flash:vlan.dat\n") time.sleep(.5) shell.send("\r\n") time.sleep(.5) shell.send("\r\n") time.sleep(.5) shell.send("reload\n") time.sleep(.5) shell.send("\r\n") time.sleep(.5) shell.send("no\n") time.sleep(.5) shell.send("\r\n") ssh.close() shell.close() main() <file_sep>/PingStuff.py import paramiko import sys import time import xlrd import csv import subprocess import os def main(): loc = ("UnreachableDevices.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) device_IPs = getData(sheet) info = pingable(device_IPs) def getData(sheet): data = [] for i in range(sheet.nrows): data.append(sheet.cell_value(i, 0)) return data def pingable(ips): info = {} nos = 0 yes = 0 length = len(ips) count = 1 with open(os.devnull, "wb") as limbo: for ip in ips: result = subprocess.Popen(["ping", "-n", "1", "-w", "200", ip], stdout=limbo, stderr=limbo).wait() if result: print(ip, "\t: failed") info[ip] = "NO" nos += 1 else: print(ip, "\t: passed") info[ip] = "YES" yes += 1 print("Failed: ", nos, "\nPassed: ", yes, " (", count, "/", length, ")") return info main() <file_sep>/device_names.py import paramiko import sys import time import xlrd import csv def main(): loc = ("All Switches.xlsx") wb = xlrd.open_workbook(loc) sheet = wb.sheet_by_index(0) all_switches = getData(sheet) info = pullInfo(all_switches) info = parseInfo(info) writeData(info) def pullInfo(all_switches): info = [] nbytes = 4096 port = 22 username = "" password = "" command = "ls" output = "" for sw in all_switches: hostname = sw ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: ssh.connect(hostname, port = port, username = username, password = <PASSWORD>) except paramiko.ssh_exception.AuthenticationException: print("Could not authenticate to host " + hostname) info.append("Couldn't connect to " + hostname) continue except paramiko.ssh_exception.NoValidConnectionsError: print("Could not connect to host " + hostname) info.append("Couldn't connect to " + hostname) continue except: print("Unknown Error") info.append("Couldn't connect to " + hostname) continue time.sleep(2) print ("Successfully connected to " + hostname) shell = ssh.invoke_shell() time.sleep(2) output = shell.recv(2000) shell.send("sh inven\n") time.sleep(2) if shell.recv_ready(): output = shell.recv(1000) if "missing mandatory parameter" in (str(output)): shell.send("sh inven 1\n") time.sleep(2) if shell.recv_ready(): output = shell.recv(1000) info.append(str(output)) ssh.close() return info def getData(sheet): data = [] for i in range(sheet.nrows): data.append(sheet.cell_value(i, 0)) return data def parseInfo(info): for num in range(len(info)): if not info[num].startswith("Couldn't"): text = info[num].partition("DESCR: \"")[2].partition("\"")[0] if text.endswith("Stack"): text = info[num].partition("DESCR: \"")[2].partition("DESCR: \"")[2].partition("\"")[0] info[num] = text return info def writeData(info): with open("Switch Types 3.csv", 'w', newline="") as myfile: wr = csv.writer(myfile, delimiter = "\n", quoting=csv.QUOTE_ALL) wr.writerow(info) main() <file_sep>/CDPPulls.py import paramiko import sys import time nbytes = 4096 hostname = "" port = 22 username = "***Enter username here***" password = "***<PASSWORD>***" command = "ls" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname, port = port, username = username, password = <PASSWORD>) time.sleep(2) print ("here") stdin, stdout, stderr = ssh.exec_command("sh inven") output = stdout.readlines() for line in output: print (line) <file_sep>/README.md # Paramiko
e2c988e6cf20d07244a29335d9e022ef25ec5c5c
[ "Markdown", "Python" ]
8
Python
rtequida/Paramiko
27a34b49267ac5b56c06f195bb27a59109a22055
2d1b84c5e380923ea28d2eec02dc27dc4274a8e5
refs/heads/master
<file_sep><?php namespace App\Repositories; use App\User; class IndexRepository { public function getFirstUserName() { return User::cursor()->first()->name; } } <file_sep><?php use Illuminate\Database\Seeder; use App\User; class UserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i=0; $i < 10; $i++) { $attributes = [ 'name' => 'User'.$i, 'email' => '<EMAIL>', 'email_verified_at' => date('Y-m-d H:i:s'), 'password' => hash('sha256', '<PASSWORD>') ]; User::create($attributes); } } } <file_sep># laravel61Demo # copy for .env file - $ cp .env.example .env # install vender - $ composer install # set app key - $ php artisan key:generate # change for your db - $ Set .env file DB setting # migrate db table - $ php artisan migrate # Seed Testing data - $ php artisan db:seed # Set Up - $ php artisan serve (default at 127.0.0.1:8000) # Use - http://127.0.0.1:8000/ (will see welcome) - http://127.0.0.1:8000/sayHello (will see Hello User) # Test - $ vendor/phpunit/phpunit/phpunit <file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Services\IndexService; use App\User; class IndexController extends Controller { // public function __construct(IndexService $service) { $this->service = $service; } public function index(Request $request) { $say = $this->service->sayHello(); return view('test', compact('say')); } } <file_sep><?php namespace App\Services; use App\Repositories\IndexRepository; class IndexService { public function __construct(IndexRepository $repository) { $this->repository = $repository; } public function sayHello() { return $this->repository->getFirstUserName(); } }
c28a0a87c89e9d136db9b3b13de4d1be92a14bfb
[ "Markdown", "PHP" ]
5
PHP
leoku7020/laravel61Demo
ca6e22a60835cf803bc1f02e9da3f5044d5fd9e7
77c53180f3bf16708b8884a52368654ecd38a132
refs/heads/master
<file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); if( $_GET ){ $pay_id = $_GET['pay_id']; $sql=$conn->query("CALL delete_payment('$pay_id',@p_msg)"); if ($sql){ echo show_p_o_msg(); } else{ echo 'Something Wrong'; } } ?><file_sep><style type="text/css"> #exceptional{ display:none; } </style> <div class="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="cnf.php">Home</a> </li> <li class="breadcrumb-item active">Add New Particular</li> </ol> <div class="col-md-2 pull-left"></div> <form class="form-inline form-custom col-md-8" action="" method="POST" autocomplete="on"> <center> <center><h2>Enter Particuler Field</h2></center> <hr /> <div class="form-group"> <label for="particuler">Particular Field:</label>&nbsp;&nbsp; <input type="text" class="form-control" name="particuler" placeholder="Enter a particuler field" required /> </div> <br /> <div class="form-group"> <label for="port">For Port:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <select class="form-control" name="port" id="select_port" onchange="portOption()" required> <option value="">Select port:</option> <?php query_table('port'); ?> </select> </div> <br /> <div class="form-group" id="exceptional"> <label for="particular_type">Type:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <select class="form-control" name="particular_type" id=""> <option value="">Select Type: </option> <option value="customs">Customs</option> <option value="port_jetty"> Port&jetty &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</option> <option value="Others">Others</option> </select> </div> <br /> <input style="" type="submit" class="btn submit_btn" value="submit" name="particuler_add" /> <?php insert_particuler('particular'); ?> </center> </form> </div> <script type="text/javascript"> function portOption(){ var x = document.getElementById("select_port").value; //consol.log(x); if ( x == 2){ document.getElementById("exceptional").style.display= "block"; //$("exceptional").show(); } else{ //$("exceptional").hide(); document.getElementById("exceptional").style.display= "none"; } } </script> <file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); echo '<option value="">Select Customer:</option>'; query_table('customer_option_view'); ?> <file_sep><?php include('../db/dbconfig.php'); function query_table($table_name){ global $conn; $sql=$conn->query("SELECT * FROM $table_name "); $count=$sql->field_count; while($getrow=$sql->fetch_array()){ $i=0; while($i<=$count){ echo $getrow[$i].'<br />'; $i++; } } } query_table('particular'); echo $count; ?><file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); subtotal_bill_view(); ?> <file_sep>-- job_id function DROP FUNCTION IF EXISTS job_f; DELIMITER $$ CREATE FUNCTION job_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_job_id int(10); SELECT MAX(job.job_id) INTO v_job_id FROM job; IF v_job_id is NULL THEN SET v_job_id=1; ELSE SET v_job_id=v_job_id+1; END IF; RETURN v_job_id; END$$ DELIMITER ; -- customer_id function DROP FUNCTION IF EXISTS customer_f; DELIMITER $$ CREATE FUNCTION customer_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_customer_id int(10); SELECT MAX(customer.customer_id) INTO v_customer_id FROM customer; IF v_customer_id is NULL THEN SET v_customer_id=1; ELSE SET v_customer_id=v_customer_id+1; END IF; RETURN v_customer_id; END$$ DELIMITER ; -- port_id function DROP FUNCTION IF EXISTS port_f; DELIMITER $$ CREATE FUNCTION port_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_port_id int(10); SELECT MAX(port.port_id) INTO v_port_id FROM port; IF v_port_id is NULL THEN SET v_port_id=1; ELSE SET v_port_id=v_port_id+1; END IF; RETURN v_port_id; END$$ DELIMITER ; -- ed_id(encloser) function DROP FUNCTION IF EXISTS encloser_doc_f; DELIMITER $$ CREATE FUNCTION encloser_doc_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_ed_id int(10); SELECT MAX(encloser_doc.ed_id) INTO v_ed_id FROM encloser_doc; IF v_ed_id is NULL THEN SET v_ed_id=1; ELSE SET v_ed_id=v_ed_id+1; END IF; RETURN v_ed_id; END$$ DELIMITER ; -- edd_id(encloser_doc_d) function DROP FUNCTION IF EXISTS encloser_doc_d_f; DELIMITER $$ CREATE FUNCTION encloser_doc_d_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_edd_id int(10); SELECT MAX(encloser_doc_d.edd_id) INTO v_edd_id FROM encloser_doc_d; IF v_edd_id is NULL THEN SET v_edd_id=1; ELSE SET v_edd_id=v_edd_id+1; END IF; RETURN v_edd_id; END$$ DELIMITER ; -- temp edd_id(encloser_doc_d) function DROP FUNCTION IF EXISTS temp_encloser_doc_d_f; DELIMITER $$ CREATE FUNCTION temp_encloser_doc_d_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_edd_id int(10); DECLARE v_temp_edd_id int(10); SELECT MAX(temp_encloser_doc_d.edd_id) INTO v_temp_edd_id FROM temp_encloser_doc_d; IF v_temp_edd_id IS NULL THEN SELECT MAX(encloser_doc_d.edd_id) INTO v_edd_id FROM encloser_doc_d; IF v_edd_id is NULL THEN SET v_edd_id=1; ELSE SET v_edd_id=v_edd_id+1; END IF; ELSE SET v_edd_id=v_temp_edd_id+1; END IF; RETURN v_edd_id; END$$ DELIMITER ; -- particular_id function DROP FUNCTION IF EXISTS particular_f; DELIMITER $$ CREATE FUNCTION particular_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_particular_id int(10); SELECT MAX(particular.particular_id) INTO v_particular_id FROM particular; IF v_particular_id is NULL THEN SET v_particular_id=1; ELSE SET v_particular_id=v_particular_id+1; END IF; RETURN v_particular_id; END$$ DELIMITER ; -- pd_id function DROP FUNCTION IF EXISTS particular_d_f; DELIMITER $$ CREATE FUNCTION particular_d_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_particular_d_id int(10); SELECT MAX(particular_d.pd_id) INTO v_particular_d_id FROM particular_d; IF v_particular_d_id is NULL THEN SET v_particular_d_id=1; ELSE SET v_particular_d_id=v_particular_d_id+1; END IF; RETURN v_particular_d_id; END$$ DELIMITER ; -- temp_pd_id function DROP FUNCTION IF EXISTS temp_particular_d_f; DELIMITER $$ CREATE FUNCTION temp_particular_d_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_temp_pd_id int(10); DECLARE v_null_pd_id int(10); SELECT MAX(temp_particular_d.pd_id) INTO v_null_pd_id FROM temp_particular_d; IF v_null_pd_id IS NULL THEN SELECT MAX(particular_d.pd_id) INTO v_temp_pd_id FROM particular_d; IF v_temp_pd_id is NULL THEN SET v_temp_pd_id=1; ELSE SET v_temp_pd_id=v_temp_pd_id+1; END IF; ELSE SET v_temp_pd_id=v_null_pd_id+1; END IF; RETURN v_temp_pd_id; END$$ DELIMITER ; -- bill function DROP FUNCTION IF EXISTS bill_f; DELIMITER $$ CREATE FUNCTION bill_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE p_bill_id int(10); SELECT MAX(bill.bill_id) INTO p_bill_id FROM bill; IF p_bill_id is NULL THEN SET p_bill_id=1; ELSE SET p_bill_id=p_bill_id+1; END IF; RETURN p_bill_id; END$$ DELIMITER ; -- bill payment function DROP FUNCTION IF EXISTS payment_f; DELIMITER $$ CREATE FUNCTION payment_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE p_pay_id int(10); SELECT MAX(payment.pay_id) INTO p_pay_id FROM payment; IF p_pay_id is NULL THEN SET p_pay_id=1; ELSE SET p_pay_id=p_pay_id+1; END IF; RETURN p_pay_id; END$$ DELIMITER ; -- temp bill function DROP FUNCTION IF EXISTS temp_bill_f; DELIMITER $$ CREATE FUNCTION temp_bill_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE p_bill_id int(10); DECLARE p_temp_bill_id int(10); SELECT MAX(temp_bill.bill_id) INTO p_temp_bill_id FROM temp_bill; IF p_temp_bill_id IS NULL THEN SELECT MAX(bill.bill_id) INTO p_bill_id FROM bill; IF p_bill_id is NULL THEN SET p_bill_id=1; ELSE SET p_bill_id=p_bill_id+1; END IF; ELSE SET p_bill_id = p_temp_bill_id+1; END IF; RETURN p_bill_id; END$$ DELIMITER ; -- bank_id function DROP FUNCTION IF EXISTS bank_info_f; DELIMITER $$ CREATE FUNCTION bank_info_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_bank_id int(10); SELECT MAX(bank_info.bank_id) INTO v_bank_id FROM bank_info; IF v_bank_id is NULL THEN SET v_bank_id=1; ELSE SET v_bank_id=v_bank_id+1; END IF; RETURN v_bank_id; END$$ DELIMITER ; -- bank_trans function DROP FUNCTION IF EXISTS bank_trans_f; DELIMITER $$ CREATE FUNCTION bank_trans_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE v_bank_trans int(10); SELECT MAX(bank_trans.bt_id) INTO v_bank_trans FROM bank_trans; IF v_bank_trans is NULL THEN SET v_bank_trans=1; ELSE SET v_bank_trans=v_bank_trans+1; END IF; RETURN v_bank_trans; END$$ DELIMITER ; -- total_bill_am DROP FUNCTION IF EXISTS total_bill_am; DELIMITER $$ CREATE FUNCTION total_bill_am(p_bill_id int(255)) RETURNS float(15,2) DETERMINISTIC BEGIN DECLARE v_bill float(15,2); DECLARE v_acc float(15,2); SELECT SUM(particular_d.amount*particular_d.qty) INTO v_bill FROM particular_d WHERE particular_d.bill_id=p_bill_id; IF v_bill is NULL THEN SET v_bill=0; END IF; SELECT (bill.accesable_value*bill.comission_acc)/100 INTO v_acc FROM bill WHERE bill.bill_id=p_bill_id; SET v_bill= v_bill+v_acc; RETURN v_bill; END$$ DELIMITER ; -- temp total_bill_am DROP FUNCTION IF EXISTS total_temp_bill_am; DELIMITER $$ CREATE FUNCTION total_temp_bill_am(p_bill_id int(255)) RETURNS float(15,2) DETERMINISTIC BEGIN DECLARE v_bill float(15,2); DECLARE v_acc float(15,2); SELECT SUM(temp_particular_d.amount*temp_particular_d.qty) INTO v_bill FROM temp_particular_d WHERE temp_particular_d.bill_id=p_bill_id; IF v_bill is NULL THEN SET v_bill=0; END IF; SELECT (temp_bill.accesable_value*temp_bill.comission_acc)/100 INTO v_acc FROM temp_bill WHERE temp_bill.bill_id=p_bill_id; SET v_bill= v_bill+v_acc; RETURN v_bill; END$$ DELIMITER ; -- bill_to_lc DROP FUNCTION IF EXISTS bill_to_lc; DELIMITER $$ CREATE FUNCTION bill_to_lc(p_bill_id int(255)) RETURNS varchar(255) DETERMINISTIC BEGIN DECLARE v_lc varchar(255); SELECT customer.lc_no INTO v_lc FROM customer , job , bill WHERE customer.customer_id = job.customer_id AND job.job_id = bill.job_id AND bill.bill_id=p_bill_id; RETURN v_lc; END$$ DELIMITER ; -- customer messers to bill DROP FUNCTION IF EXISTS messers_to_bill; DELIMITER $$ CREATE FUNCTION messers_to_bill(p_bill_id int(255)) RETURNS varchar(255) DETERMINISTIC BEGIN DECLARE v_messers varchar(255); SELECT customer.messers INTO v_messers FROM customer , job , bill WHERE customer.customer_id = job.customer_id AND job.job_id = bill.job_id AND bill.bill_id=p_bill_id; RETURN v_messers; END$$ DELIMITER ; -- customer address to bill DROP FUNCTION IF EXISTS address_to_bill; DELIMITER $$ CREATE FUNCTION address_to_bill(p_bill_id int(255)) RETURNS varchar(255) DETERMINISTIC BEGIN DECLARE v_address varchar(255); SELECT customer.address INTO v_address FROM customer , job , bill WHERE customer.customer_id = job.customer_id AND job.job_id = bill.job_id AND bill.bill_id=p_bill_id; RETURN v_address; END$$ DELIMITER ; -- bill to goods DROP FUNCTION IF EXISTS bill_to_goods; DELIMITER $$ CREATE FUNCTION bill_to_goods(p_bill_id int(255)) RETURNS varchar(255) DETERMINISTIC BEGIN DECLARE v_dec varchar(255); SELECT job.disc_goods INTO v_dec FROM job , bill WHERE job.job_id = bill.job_id AND bill.bill_id=p_bill_id; RETURN v_dec; END$$ DELIMITER ; DROP FUNCTION IF EXISTS bill_incomplete_status; DELIMITER $$ CREATE FUNCTION bill_incomplete_status(p_bill_id int(255)) RETURNS varchar(255) DETERMINISTIC BEGIN DECLARE v_temp_pd_id int(255); DECLARE v_pd_id int(255); DECLARE v_msg varchar(255); SELECT MAX(temp_particular_d.pd_id) INTO v_temp_pd_id FROM temp_particular_d WHERE temp_particular_d.bill_id=p_bill_id; SELECT MAX(particular_d.pd_id) INTO v_pd_id FROM particular_d WHERE particular_d.bill_id=p_bill_id; IF v_temp_pd_id IS NOT NULL THEN SET v_msg= 'Incomplete'; ELSE IF v_pd_id IS NULL THEN SET v_msg='empty'; ELSE SET v_msg='Complete'; END IF; END IF; RETURN v_msg; END$$ DELIMITER ; DROP FUNCTION IF EXISTS particular_amount_f; DELIMITER $$ CREATE FUNCTION particular_amount_f(p_particular_id int(255)) RETURNS varchar(255) DETERMINISTIC BEGIN DECLARE v_particular_id int(255); DECLARE v_pd_id int(255); DECLARE v_amount int(255); SELECT particular.particular_id INTO v_particular_id FROM particular WHERE particular.particular_id=p_particular_id; SELECT particular_d.particular_id INTO v_pd_id FROM particular_d WHERE particular_d.particular_id=p_particular_id; IF v_particular_id=v_pd_id THEN SELECT particular_d.amount INTO v_amount FROM particular_d WHERE particular_d.particular_id=v_particular_id; ELSE SET v_amount = NULL; END IF; RETURN v_amount; END$$ DELIMITER ; <file_sep><?php include('../db/dbconfig.php'); if($_GET){ $customer_id=$_GET['customer_name']; $bill_id = $_GET['bill_id']; if(empty($customer_id) and !empty($bill_id)){ $sql2=$conn->query("SELECT * FROM bill_view WHERE bill_id='$bill_id' "); $getrow2=$sql2->fetch_array(); $customer_id=$getrow2['customer_id']; } ?> <div class="table-responsive"> <table class="table table-bordered form-custom"> <thead> <tr> <th>SL No.</th> <th>Bill No.</th> <th>LC No.</th> <th>Total Bill</th> <th>Paid Amount</th> <th>Due</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql=$conn->query("SELECT * FROM bill_view WHERE customer_id='$customer_id' "); $count = $sql->num_rows; if($count > 0){ while($getrow=$sql->fetch_array()){ echo '<tr>'; echo '<td>'. $getrow['bill_id'] .'</td>'; echo '<td>'. $getrow['bill_no'] .'</td>'; echo '<td>'. $getrow['bill_lc'] .'</td>'; echo '<td>'. $getrow['sub_total'] .'</td>'; echo '<td>'. $getrow['paid_am'] .'</td>'; echo '<td>'. $getrow['due'] .'</td>'; echo '<td><button class="btn btn-success btn-sm view_btn" value="'.$getrow['bill_id'].'">View</button></td>'; echo'</tr>'; } } else{ echo '<tr>'; echo '<td colspan="7" class="text-center">No Billing Info Found.</td>'; echo'</tr>'; } ?> </tbody> </table> </div> <?php } ?> <script type="text/javascript"> $(document).ready(function(){ // code to get all records from table via select box $(".view_btn").click(function() { $.ajax({ type: "GET", url: 'extarnel_pages/payment_info.php', dataType: "html", data: {bill_id:$(this).val()}, cache: false, success: function(response) { $("#show_pay_data").html(response); } }); }); }); </script><file_sep>-- PORT TABLE CREATE TABLE port( port_id int(255), port_name varchar(100) NOT NULL ); -- CUSTOMER TABLE CREATE TABLE customer( customer_id int(255), messers varchar(255) NOT NULL, address varchar(255) NOT NULL, lc_no varchar(255) NOT NULL, lc_date date ); -- JOB TABLE CREATE TABLE job( job_id int(10), job_no varchar(255) NOT NULL, ac varchar(255) NOT NULL, bill_of_entry int(255) NOT NULL, date_of_bill date, disc_goods varchar(255) NOT NULL, quantity varchar(255) NOT NULL, weight float(30,2) NOT NULL, ex_ss varchar(255) NOT NULL, rot_no varchar(255) NOT NULL, lin_no varchar(255) NOT NULL, arrived_on date, track_recipt varchar(255), tr_description varchar(255), exporter varchar(255) NOT NULL, depot varchar(255) NOT NULL, cnf_value float(30,2) NOT NULL, clearence_date date, customer_id int(255) NOT NULL, port_id int(255) ); -- ENCLOSER TABLE CREATE TABLE encloser_doc( ed_id int(255), ed_name varchar(255), port_id int(255) ); -- PARTICULAR TABLE CREATE TABLE particular( particular_id int(255), particular_name varchar(255), port_id int(255) ); -- BILL TABLE CREATE TABLE bill( bill_id int(255), bill_no varchar(255), bill_date date, accesable_value float(30,2), comission_acc float(30,2), discount float(30,2), paid_am float(30,2), job_id int(255) ); -- BILL PAYMENT CREATE TABLE payment( pay_id int(255), bill_id int(255), amount float(15,2), pay_date date ); -- TEMP BILL TABLE CREATE TABLE temp_bill( bill_id int(255), bill_no varchar(255), bill_date date, accesable_value float(30,2), comission_acc float(30,2), discount float(30,2), paid_am float(30,2), job_id int(255) ); -- ENCLOSER DETAILS TABLE CREATE TABLE encloser_doc_d( edd_id int(255), ed_id int(255), ed_image varchar(2000), bill_id int(255) ); -- TEMP ENCLOSER DETAILS TABLE CREATE TABLE temp_encloser_doc_d( edd_id int(255), ed_id int(255), ed_image varchar(2000), bill_id int(255) ); -- PARTICULAR DETAILS TABLE CREATE TABLE particular_d( pd_id int(255), particular_id int(255), amount float(15,2), qty float(15,2), bill_id int(255) ); -- TEMP PARTICULAR DETAILS TABLE CREATE TABLE temp_particular_d( pd_id int(255), particular_id int(255), amount float(15,2), qty float(15,2), bill_id int(255) ); -- BANK INFO TABLE CREATE TABLE bank_info( bank_id int(255), bank_name varchar(255) NOT NULL, bank_branch varchar(255) NOT NULL, bank_district varchar(255) NOT NULL, bank_balance float(30,2) NOT NULL, opening_date date ); -- BANK TRANSACTION TABLE CREATE TABLE bank_trans( bt_id int(255), bt_date varchar(255) NOT NULL, bt_amount float(30,2) NOT NULL, bt_status varchar(255) NOT NULL, payment_type varchar(30) NOT NULL, bank_id int(255) );<file_sep>-- port table------------------------------------------------- ALTER TABLE port ADD PRIMARY KEY (port_id); ALTER TABLE port ADD CONSTRAINT uk_port_port_name UNIQUE (port_name); -- customer table-------------------------------------------- ALTER TABLE customer ADD PRIMARY KEY (customer_id); -- job table ----------------------------------------------- ALTER TABLE job ADD PRIMARY KEY (job_id); ALTER TABLE job ADD CONSTRAINT uk_job_bill_of_entry UNIQUE (bill_of_entry); ALTER TABLE job ADD CONSTRAINT fk_job_customer_id FOREIGN KEY (customer_id) REFERENCES customer(customer_id); ALTER TABLE job ADD CONSTRAINT fk_job_port_id FOREIGN KEY (port_id) REFERENCES port(port_id); -- encloser_doc table----------------------------------------------- ALTER TABLE encloser_doc ADD PRIMARY KEY (ed_id); ALTER TABLE encloser_doc ADD CONSTRAINT uk_encloser_doc_name UNIQUE (ed_name); ALTER TABLE encloser_doc ADD CONSTRAINT fk_port_id FOREIGN KEY (port_id) REFERENCES port(port_id); -- particular table---------------------------------------------- ALTER TABLE particular ADD PRIMARY KEY (particular_id); ALTER TABLE particular ADD CONSTRAINT uk_particular_name UNIQUE (particular_name); ALTER TABLE particular ADD CONSTRAINT fk_particular_port_id FOREIGN KEY (port_id) REFERENCES port(port_id); -- bill table-------------------------------------------- ALTER TABLE bill ADD PRIMARY KEY (bill_id); ALTER TABLE bill ADD CONSTRAINT uk_bill_no UNIQUE (bill_no); ALTER TABLE bill ADD CONSTRAINT fk_bill_job_id FOREIGN KEY (job_id) REFERENCES job(job_id); -- payment table -------------------------------------------- ALTER TABLE payment ADD PRIMARY KEY (pay_id); ALTER TABLE payment ADD CONSTRAINT fk_payment_bill_id FOREIGN KEY (bill_id) REFERENCES bill(bill_id); -- encloser_doc details table----------------------------------------------- ALTER TABLE encloser_doc_d ADD PRIMARY KEY (edd_id); ALTER TABLE encloser_doc_d ADD CONSTRAINT fk_encd_bill_id FOREIGN KEY (bill_id) REFERENCES bill(bill_id); ALTER TABLE encloser_doc_d ADD CONSTRAINT fk_encd_ed_id FOREIGN KEY (ed_id) REFERENCES encloser_doc(ed_id); ALTER TABLE encloser_doc_d ADD CONSTRAINT uk_encd_bill_id UNIQUE (bill_id,ed_id); -- temp encloser_doc details table----------------------------------------------- ALTER TABLE temp_encloser_doc_d ADD PRIMARY KEY (edd_id); ALTER TABLE temp_encloser_doc_d ADD CONSTRAINT fk_temp_encd_bill_id FOREIGN KEY (bill_id) REFERENCES temp_bill(bill_id); ALTER TABLE temp_encloser_doc_d ADD CONSTRAINT fk_temp_encd_ed_id FOREIGN KEY (ed_id) REFERENCES encloser_doc(ed_id); ALTER TABLE temp_encloser_doc_d ADD CONSTRAINT uk_temp_encd_bill_id UNIQUE (bill_id,ed_id); -- particular details table---------------------------------------------- ALTER TABLE particular_d ADD PRIMARY KEY (pd_id); ALTER TABLE particular_d ADD CONSTRAINT fk_pd_bill_id FOREIGN KEY (bill_id) REFERENCES bill(bill_id); ALTER TABLE particular_d ADD CONSTRAINT fk_particular_id FOREIGN KEY (particular_id) REFERENCES particular(particular_id); ALTER TABLE particular_d ADD CONSTRAINT uk_particular_d_name_bill UNIQUE (bill_id,pd_id); -- temp particular details table---------------------------------------------- ALTER TABLE temp_particular_d ADD PRIMARY KEY (pd_id); ALTER TABLE temp_particular_d ADD CONSTRAINT fk_temp_pd_bill_id FOREIGN KEY (bill_id) REFERENCES temp_bill(bill_id); ALTER TABLE temp_particular_d ADD CONSTRAINT fk_temp_particular_id FOREIGN KEY (particular_id) REFERENCES particular(particular_id); ALTER TABLE temp_particular_d ADD CONSTRAINT uk_temp_particular_id UNIQUE (particular_id); ALTER TABLE temp_particular_d ADD CONSTRAINT uk_temp_particular_d_name_bill UNIQUE (bill_id,pd_id); -- bank info table-------------------------------------------- ALTER TABLE bank_info ADD PRIMARY KEY (bank_id); ALTER TABLE bank_info ADD CONSTRAINT uk_bank UNIQUE (bank_name,bank_branch,bank_district); -- bank trans table-------------------------------------------- ALTER TABLE bank_trans ADD PRIMARY KEY (bt_id);<file_sep><!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> <?php include('db/dbconfig.php'); ?> <style type="text/css"> .fixed-table-body { overflow-x: auto; overflow-y: auto; height: auto !important; } </style> <?php include('inc/easy_table.php'); ?> <!--<div id="toolbar"> <select class="form-control"> <option value="">Export Basic</option> <option value="all">Export All</option> <option value="selected">Export Selected</option> </select> </div>--> </head> <body> <table id="table" data-toggle="table" data-search="true" data-filter-control="true" data-show-export="false" data-click-to-select="false" data-show-header="true" data-pagination="true" data-id-field="name" data-page-list="[5, 10, 25, 50, 100, ALL]" data-page-size="5" data-escape="false" > <thead> <tr> <th data-field="state" data-checkbox="true"></th> <th data-field="sl_no" data-sortable="true">SL. No.</th> <th data-field="bill_no" data-filter-control="input" data-sortable="true">Bill No.</th> <th data-field="bill_date" data-filter-control="select" data-sortable="true">Bill Date</th> <th data-field="messers" data-filter-control="select" data-sortable="true">Messers</th> <th data-field="address" data-filter-control="input" data-sortable="true">Address</th> <th data-field="lc_no" data-filter-control="input" data-sortable="true">L/C No.</th> <th data-field="desc" data-filter-control="input" data-sortable="true">Goods Description</th> <th data-field="total_bill" data-filter-control="input" data-sortable="true">Total Bill</th> <th data-field="paid_am" data-filter-control="input" data-sortable="true">Paid Amount</th> <th data-field="due_am" data-filter-control="input" data-sortable="true">Due Amount</th> <th >View Bill</th> </tr> </thead> <tbody> <?php $sql=$conn->query("SELECT * FROM bill_view "); while($getrow=$sql->fetch_array()){ echo '<tr>'; echo '<td class="bs-checkbox "><input data-index="'. $getrow['bill_id'] .'" name="btSelectItem" type="checkbox"></td>'; echo '<td>'. $getrow['bill_id'] .'</td>'; echo '<td>'. $getrow['bill_no'] .'</td>'; echo '<td>'. $getrow['bill_date'] .'</td>'; echo '<td>'. $getrow['messers'] .'</td>'; echo '<td>'. $getrow['address'] .'</td>'; echo '<td>'. $getrow['bill_lc'] .'</td>'; echo '<td>'. $getrow['desc'] .'</td>'; echo '<td>'. $getrow['sub_total'] .'</td>'; echo '<td>'. $getrow['paid_am'] .'</td>'; echo '<td>'. $getrow['due'] .'</td>'; echo '<td><a href="final'.$getrow['port_id'].'.php?bill_id='.$getrow['bill_id'] .'" class="btn btn-link">View Bill</a></td>'; echo '</tr>'; } ?> </tbody> </table> </body> </html> <file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); if( $_POST ){ $customer_id = test_input($_POST['customer_id']); $port = "1"; $job_no = test_input($_POST['job_no']); $ac = test_input($_POST['ac']); $bill_of_entry = test_input($_POST['bill_of_entry']); $bill_date = test_input($_POST['bill_date']); $desc_good = test_input($_POST['desc_good']); $qty = test_input($_POST['qty']); $weight = test_input($_POST['weight']); $ex_ss = ""; $rot_no = ""; $lin_no = ""; $arrived_on = ""; $track_recipt = test_input($_POST['track_recipt']); $tr_description = test_input($_POST['tr_description']); $exporter = test_input($_POST['exporter']); $depot = ""; $cnf_value = test_input($_POST['cnf_value']); $clearence_date = test_input($_POST['clearence_date']); if(empty($customer_id)){ $customer_id = last_customer(); } $sql = $conn->query("CALL insert_job('$job_no','$ac','$bill_of_entry','$bill_date','$desc_good','$qty','$weight','$ex_ss','$rot_no','$lin_no','$arrived_on','$track_recipt','$tr_description','$exporter','$depot','$cnf_value','$clearence_date','$customer_id','$port',@p_msg)"); $sql2=$conn->query('SELECT @p_msg'); $getmsg=$sql2->fetch_array(); $msg=$getmsg['@p_msg']; if($sql){ ?> <table class="table table-striped" border="0"> <tr> <td colspan="2"> <div class="alert alert-info"> <strong>Success</strong>, Job Details Successfully Added... </div> </td> </tr> <tr> <td>Customer Id</td> <td><?php echo $customer_id ?></td> </tr> <tr> <td>Ref. No.</td> <td><?php echo $job_no; ?></td> </tr> <tr> <td>A/c.</td> <td><?php echo $ac; ?></td> </tr> <tr> <td>Bill Of entry</td> <td><?php echo $bill_of_entry; ?></td> </tr> <tr> <td>Bill Date</td> <td><?php echo $bill_date; ?></td> </tr> <tr> <td>Description Of Goods</td> <td><?php echo $desc_good; ?></td> </tr> <tr> <td>Quantity</td> <td><?php echo $qty; ?></td> </tr> <tr> <td>Weight</td> <td><?php echo $weight; ?></td> </tr> <tr> <td>Track Recipt</td> <td><?php echo $track_recipt; ?></td> </tr> <tr> <td>Track Recipt Description</td> <td><?php echo $tr_description; ?></td> </tr> <tr> <td>Exporter</td> <td><?php echo $exporter; ?></td> </tr> <tr> <td>C & F Value</td> <td><?php echo $cnf_value; ?></td> </tr> <tr> <td>Clearence Date</td> <td><?php echo $clearence_date; ?></td> </tr> </table> <?php echo $msg; ?> <?php } else{ echo 'Something Wrong'; } } ?><file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); total_bill_view(); ?> <file_sep><?php //include('header.php'); include('inc/function.php'); if ($_GET['bill_id']){ $bill_id = $_GET['bill_id']; //$job_id = $_GET['job_id']; ?> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <style type="text/css" media="print"> #printLink , .navbar-brand {display : none} @page { size: auto; /* auto is the initial value */ margin: 0mm; /* this affects the margin in the printer settings */ } html { background-color: #FFFFFF; margin: 10px; /* this affects the margin on the html before sending to printer */ } body { /* border: solid 1px blue ; margin: 10mm 15mm 10mm 15mm; margin you want for the content */ margin-top:0px; } .job_discription>h6>span{ margin-right:100px; padding:10px; floa:right; } </style> <style type="text/css"> body{ background-color:#000; } .main_part{ background-color:#fff; } #printLink{ cursor:pointer; } .job_discription>h6{ padding:0px !important; margin:0px !important; } .cardss{ border:0.5px solid #000; border-radius:5px; } .brand_heading>h1,h5,h6{ padding:0px !important; margin:0px !important; } table{ width:100%; } table, thead, th ,tr , td{ border:1px solid; } </style> <div style="margin-bottom:10px;" class="col-md-8 offset-md-2 main_part"> <center class="brand_heading"> <h6><u>BILL</u></h6> <h1>Sourobh Enterprise</h1> <h5>Govt. Authorized Customs Clearing & Forwarding Agent</h5> </center> <div class="row"> <div class="floa-left job_discription col-md-12"> <h6>Job No. <strong><?php echo reterve_job_comp($bill_id)['job_no']; ?></strong><span style="margin-right:50px;padding:10px;" class="cardss float-right"><?php echo reterve_intable_from_bill_view($bill_id)['bill_no']; ?></span></h6> <h6>Messers: <strong><?php echo last_customer_comp($bill_id)['messers']; ?></strong></h6> <h6>Address: <strong><?php echo last_customer_comp($bill_id)['address']; ?></strong></h6> <h6>A/C: <strong><?php echo reterve_job_comp($bill_id)['ac']; ?></strong><span style="margin-right:10px;" class="float-right">Date:- <?php echo reterve_intable_from_bill_view($bill_id)['bill_date']; ?></span></h6> <h6>Bill Of Entry No. <strong><?php echo reterve_job_comp($bill_id)['bill_of_entry']; ?></strong> Dt. <strong><?php echo reterve_job_comp($bill_id)['date_of_bill']; ?></strong> L/C No. <strong><?php echo last_customer_comp($bill_id)['lc_no']; ?></strong> Dt. <strong><?php echo last_customer_comp($bill_id)['lc_date']; ?></strong></h6> <h6>Discription Of Goods: <strong><?php echo reterve_job_comp($bill_id)['disc_goods']; ?></strong> Quantity: <strong><?php echo reterve_job_comp($bill_id)['quantity']; ?></strong></h6> </div> </div> <br /> <table > <thead> <tr class="text-center"> <th>Enclosures of Documents</th> <th>Particular</th> <th> &nbsp; Amount &nbsp; </th> <th>Ps.</th> </tr> </thead> <tbody> <tr> <td rowspan="4" style="vertical-align: text-top;height:10px;"><?php reterve_intable_data_encloser_doc(); ?></td> <td style="height:10px;"> <center><strong>Custom</center></strong></td> <td style="border-bottom: 1px solid #fff;"></td> <td rowspan="13"></td> </tr> <tr> <td rowspan="" style="vertical-align: text-top;height:10px;"> <?php reterve_intable_data_particular('2','customs'); ?> </td> <td style="border-bottom: 1px solid #fff;vertical-align: text-top;height:10px;" class="text-right" rowspan="2"> <?php $sql=$conn->query("SELECT * FROM particular WHERE port_id = '2' and particular_type = 'customs' "); while($getres=$sql->fetch_array()){ $id = $getres[0] ; $sql2=$conn->query("SELECT * FROM particular_d WHERE particular_id= '$id' and bill_id='$bill_id' "); $getres2=$sql2->fetch_array(); $amount = $getres2['amount']; $space = "-" ; if($amount == NULL OR $amount == 0){ echo '<h6 style="padding:0px;margin:0px;font-size:14px;">'. $space .'</h6>'; } else{ echo '<h6 style="padding:0px;margin:0px;font-size:14px;">'.$amount.'</h6>'; } } ?> </td> </tr> <tr> </tr> <tr> <td style="height:10px;"> <center><strong>Port & Jettys </strong></center> </td> </tr> <tr> <td><strong>Ex. S.S:</strong> &nbsp;<?php echo reterve_job_comp($bill_id)['ex_ss']; ?></td> <td rowspan="6" style="vertical-align: text-top;height:10px;"> <?php reterve_intable_data_particular('2','port_jetty'); ?> </td> <td style="border-color: #fff;" class="text-right" rowspan="6"> <?php $sql=$conn->query("SELECT * FROM particular WHERE port_id = '2' and particular_type = 'port_jetty' "); while($getres=$sql->fetch_array()){ $id = $getres[0] ; $sql2=$conn->query("SELECT * FROM particular_d WHERE particular_id= '$id' and bill_id='$bill_id' "); $getres2=$sql2->fetch_array(); $amount = $getres2['amount']; $space = "-" ; if($amount == NULL OR $amount == 0){ echo '<h6 style="padding:0px;margin:0px;font-size:14px;">'. $space .'</h6>'; } else{ echo '<h6 style="padding:0px;margin:0px;font-size:14px;">'.$amount.'</h6>'; } } ?> </td> </tr> <tr> <td> <strong>Rot No.:</strong> &nbsp;<?php echo reterve_job_comp($bill_id)['rot_no']; ?></td> </tr> <tr> <td><strong>Lin No.:</strong> &nbsp;<?php echo reterve_job_comp($bill_id)['lin_no']; ?></td> </tr> <tr> <td><strong>Arraived On.:</strong> &nbsp;<?php echo reterve_job_comp($bill_id)['arrived_on']; ?></td> </tr> <tr> <td><strong>Exporter:</strong> &nbsp;<?php echo reterve_job_comp($bill_id)['exporter']; ?></td> </tr> <tr> <td><strong>Depot:</strong> &nbsp;<?php echo reterve_job_comp($bill_id)['depot']; ?></td> </tr> <tr> <td><strong>C&F Value:</strong> &nbsp;<?php echo reterve_job_comp($bill_id)['cnf_value']; ?></td> <td style="height:10px;"> <center><strong>Others</strong></center> </td> <td style="border-color:#fff;"> </td> </tr> <tr> <td style="height:1px;"><strong>Date Of Clearance:</strong> &nbsp;<?php echo reterve_job_comp($bill_id)['clearence_date']; ?></td> <td rowspan="2" style="vertical-align: text-top;height:10px;"> <?php reterve_intable_data_particular('2','others'); ?> <h6 style="padding:0px;margin:0px;font-size:14px;">Commission C&F on Assessable Value Tk. <?php echo reterve_intable_from_bill_view($bill_id)['accesable_value']; ?> @ <?php echo reterve_intable_from_bill_view($bill_id)['comission_acc']; ?>%</h6> </td> <td rowspan="2" style="vertical-align:text-top;height:10px;"class="text-right"><?php $sql=$conn->query("SELECT * FROM particular WHERE port_id = '2' and particular_type = 'others' "); while($getres=$sql->fetch_array()){ $id = $getres[0] ; $sql2=$conn->query("SELECT * FROM particular_d WHERE particular_id= '$id' and bill_id='$bill_id' "); $getres2=$sql2->fetch_array(); $amount = $getres2['amount']; $space = "-" ; if($amount == NULL OR $amount == 0){ echo '<h6 style="padding:0px;margin:0px;font-size:14px;">'. $space .'</h6>'; } else{ echo '<h6 style="padding:0px;margin:0px;font-size:14px;">'.$amount.'</h6>'; } } ?> <h6 style="padding:0px;margin:0px;font-size:14px;"><?php echo reterve_intable_from_bill_view($bill_id)['net_comission_am']; ?></h6> </td> </tr> <tr> <td rowspan="6"><center><strong>Remarks: </strong> <br /><u>CTG</u><br /><?php echo reterve_job_comp($bill_id)['ac']; ?></center></td> </tr> <tr> <td style="border-bottom-color: #fff;" class="text-right">Total Tk.</td> <td class="text-center"><h6><?php echo reterve_intable_from_bill_view($bill_id)['total_bill']; ?></h6></td> <td></td> </tr> <tr> <td style="border-bottom-color: #fff;" class="text-right">Add Old/New Balance Tk.</td> <td class="text-center"></td> <td></td> </tr> <tr> <td style="border-bottom-color: #fff;" class="text-right">Grand Total</td> <td class="text-center"><h6><?php echo reterve_intable_from_bill_view($bill_id)['total_bill']; ?></h6></td> <td></td> </tr> <tr> <td style="border-bottom-color: #fff;" class="text-right">Less Advance Cash/Cheque/DD/TT on Date...</td> <td class="text-center"><h6><?php echo reterve_intable_from_bill_view($bill_id)['discount']; ?></h6></td> <td></td> </tr> <tr> <td style="" class="text-right">Net B/F Tk.</td> <td class="text-center"><h6><?php echo reterve_intable_from_bill_view($bill_id)['sub_total']; ?></h6></td> <td></td> </tr> </tbody> </table> <h6>Total Tk.(In Words): <?php $total_am=reterve_intable_from_bill_view($bill_id)['total_bill']; echo numberTowords($total_am); ?></h6> <br /> <!--<div class="v_l" style="height:200px;width:2px;background-color:#000;"></div>--> <span style="margin-right: 10px;" class="float-right">Authorization Signature</span> <h4><strong>Tk.</strong> &nbsp;&nbsp;&nbsp;<span style="display: inline-block; padding: 7px 27px 12px 12px;" class="cardss" >=<?php echo $total_am; ?></span></h4> <br /> <center><button style="padding:5px;border-radius:5px" onclick="window.print()" id='printLink'>PRINT THIS BILL</button></center> </div> <?php } ?> <file_sep>CREATE OR REPLACE VIEW customer_option_view AS SELECT customer.customer_id as 'customer_id' , customer.messers as 'messers' FROM customer; CREATE OR REPLACE VIEW job_option_view AS SELECT job.job_id as 'job_id' , job.job_no as 'job_no' FROM job; CREATE OR REPLACE VIEW bill_view as SELECT bill.bill_id as 'bill_id', bill.bill_no as 'bill_no' , bill.bill_date as 'bill_date', job.job_no as 'job_no',job.customer_id as 'customer_id' ,messers_to_bill(bill.bill_id) as 'messers',address_to_bill(bill.bill_id) as 'address', bill_to_lc(bill.bill_id) as 'bill_lc' ,job.ac as 'ac',bill.accesable_value as 'accesable_value' , bill.comission_acc as 'comission_acc' , round(((bill.accesable_value*bill.comission_acc)/100),2) as 'net_comission_am' ,total_bill_am(bill.bill_id) as 'total_bill' , bill.discount as 'discount' , (total_bill_am(bill.bill_id)-bill.discount) as 'sub_total', bill.paid_am as 'paid_am' ,((total_bill_am(bill.bill_id)-bill.discount)-bill.paid_am) as 'due' , bill_incomplete_status(bill.bill_id) as 'status' , bill_to_goods(bill.bill_id) as 'desc', job.port_id as 'port_id' FROM bill , job WHERE bill.job_id=job.job_id; -- temp_bill view CREATE OR REPLACE VIEW temp_bill_view as SELECT temp_bill.bill_id as 'bill_id', temp_bill.bill_no as 'bill_no' , temp_bill.bill_date as 'bill_date' , temp_bill.accesable_value as 'accesable_value' , temp_bill.comission_acc as 'comission_acc',total_temp_bill_am(temp_bill.bill_id) as 'total_bill',temp_bill.discount as 'discount' ,(total_temp_bill_am(temp_bill.bill_id)-temp_bill.discount) as 'sub_total', temp_bill.paid_am as 'paid_am' FROM temp_bill; CREATE OR REPLACE VIEW particular_with_amount as SELECT particular.particular_id as 'particular_id', particular.particular_name as 'particular_name' ,particular_amount_f(particular.particular_id) as 'amount' FROM particular; <file_sep>-- <<------END INSERT PROCEDURE-------->> -- -- <<------START UPDATE PROCEDURE-------->> -- -- port update---------------------------------- DROP PROCEDURE IF EXISTS update_port; DELIMITER $$ CREATE PROCEDURE update_port (IN p_port_id int(255), IN p_port_name varchar(100), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO @p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO @p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO @p_msg; START TRANSACTION; UPDATE port SET port_name=p_port_name WHERE port_id=p_port_id; COMMIT; SET p_msg='Successful Updated'; END$$ DELIMITER ; /* CALL update_port('ctg',1,@p_msg);SELECT @p_msg; */ -- customer update---------------------------------- DROP PROCEDURE IF EXISTS update_customer; DELIMITER $$ CREATE PROCEDURE update_customer (IN p_customer_id int(255), IN p_messers varchar(255), IN p_address varchar(255), IN p_lc_no int(255), IN p_lc_date date, OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO @p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO @p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO @p_msg; START TRANSACTION; UPDATE customer SET customer.messers=p_messers, customer.address=p_address, customer.lc_no=p_lc_no, customer.lc_date=p_lc_date WHERE customer.customer_id=p_customer_id; COMMIT; SET p_msg='Successful Updated'; END$$ DELIMITER ; /* CALL update_customer(1,'suvo shop','jessore','38479238',curdate(),@p_msg); SELECT @p_msg; */ -- Job Update procedure ---------------------------- DROP PROCEDURE IF EXISTS update_job; DELIMITER $$ CREATE PROCEDURE update_job ( IN p_job_id int(10), IN p_job_no int(255), IN p_ac varchar(255), IN p_bill_of_entry int(255), IN p_date_of_bill date, IN p_disc_goods varchar(255), IN p_quantity varchar(255), IN p_weight float(30,2), IN p_ex_ss varchar(255), IN p_rot_no int(255), IN p_lin_no int(255), IN p_arrived_on date, IN p_track_recipt varchar(255), IN p_tr_description varchar(255), IN p_exporter varchar(255), IN p_depot varchar(255), IN p_cnf_value float(30,2), IN p_clearence_date date OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; UPDATE job SET job.job_no=p_job_no, job.ac=p_ac, job.bill_of_entry=p_bill_of_entry, job.date_of_bill=p_date_of_bill, job.disc_goods=p_disc_goods, job.quantity=p_quantity, job.weight=p_weight, job.ex_ss=p_ex_ss, job.rot_no=p_rot_no, job.lin_no=p_lin_no, job.arrived_on=p_arrived_on, job.track_recipt=p_track_recipt, job.tr_description=p_tr_description, job.exporter=p_exporter, job.depot=p_depot, job.cnf_value=p_cnf_value, job.clearence_date=p_clearence_date WHERE job_id=p_job_id ; COMMIT; SET p_msg='Successfully Updated'; END$$ DELIMITER ; /* CALL update_job(1,2,2222,44444,curdate(),'oil',900,40,'x.p padma','8989','766',curdate(),'343h343u','something','cc','port',49000.00,curdate(),1,1,@p_msg); SELECT @p_msg; */ -- encloser_doc update---------------------------------- DROP PROCEDURE IF EXISTS update_encloser_doc; DELIMITER $$ CREATE PROCEDURE update_encloser_doc (IN ed_id int(255), IN p_ed_name varchar(255), IN p_status boolean, OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO @p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO @p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO @p_msg; START TRANSACTION; UPDATE encloser_doc SET encloser_doc.ed_name=p_ed_name, encloser_doc.status=p_status WHERE encloser_doc.ed_id=ed_id; COMMIT; SET p_msg='Successful Updated'; END$$ DELIMITER ; /* CALL update_encloser_doc(1,'Landing Charg',0,1,@p_msg); SELECT @p_msg; */ -- particular update---------------------------------- DROP PROCEDURE IF EXISTS update_particular; DELIMITER $$ CREATE PROCEDURE update_particular (IN p_particular_id int(255), IN p_particular_name varchar(255), IN p_amount varchar(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO @p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO @p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO @p_msg; START TRANSACTION; UPDATE particular SET particular.particular_name=p_particular_name, particular.amount=p_amount WHERE particular.particular_id=p_particular_id; COMMIT; SET p_msg='Successful Updated'; END$$ DELIMITER ; /* CALL update_particular(1,'customer duty',900,@p_msg);SELECT @P_msg; */ -- bill update---------------------------------- -- DROP PROCEDURE IF EXISTS update_bill; -- DELIMITER $$ -- CREATE PROCEDURE update_bill -- (IN p_bill_id int(255), -- IN p_bill_no varchar(255), -- IN p_bill_date date, -- IN p_commision_am float(30,2), -- IN p_total_am float(30,2), -- IN p_add_on_balance float(30,2), -- IN p_grand_total float(30,2), -- IN p_less_ad_date date, -- IN p_net_bf float(30,2), -- OUT p_msg varchar(100) -- ) -- BEGIN -- DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO @p_msg; -- DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO @p_msg; -- DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO @p_msg; -- START TRANSACTION; -- UPDATE bill -- SET -- bill.bill_no=p_bill_no, -- bill.bill_date=p_bill_date, -- bill.commision_am=p_commision_am, -- bill.total_am=p_total_am, -- bill.add_on_balance=p_add_on_balance, -- bill.grand_total=p_grand_total, -- bill.less_ad_date=p_less_ad_date, -- bill.net_bf=p_net_bf -- WHERE bill_id=p_bill_id; -- COMMIT; -- SET p_msg='Successful Updated'; -- END$$ -- DELIMITER ; /* CALL update_bill(2,444,curdate(),44444.56,55555,7777,9999,curdate(),23555,@p_msg); SELECT @p_msg; */ DROP PROCEDURE IF EXISTS update_bill_accesable_value; DELIMITER $$ CREATE PROCEDURE update_bill_accesable_value (IN p_bill_id int(255), IN p_accesable_value float(15,2), IN p_commision_am float(3,2), OUT p_msg varchar(255) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; UPDATE bill SET bill.accesable_value = p_accesable_value, bill.comission_acc = p_commision_am WHERE bill.bill_id=p_bill_id; COMMIT; SET p_msg="Accesable value added"; END$$ DELIMITER ; /* CALL update_bill_accesable_value(1,450000.00,0.20,@p_msg); SELECT @p_msg; */ -- update_temp_bill_accesable_value DROP PROCEDURE IF EXISTS update_temp_bill_accesable_value; DELIMITER $$ CREATE PROCEDURE update_temp_bill_accesable_value (IN p_bill_id int(255), IN p_accesable_value float(15,2), IN p_commision_am float(3,2), OUT p_msg varchar(255) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; UPDATE temp_bill SET temp_bill.accesable_value = p_accesable_value, temp_bill.comission_acc = p_commision_am WHERE temp_bill.bill_id=p_bill_id; COMMIT; SET p_msg="Accesable value added"; END$$ DELIMITER ; /* CALL update_bill_accesable_value(1,450000.00,0.20,@p_msg); SELECT @p_msg; */ DROP PROCEDURE IF EXISTS update_bill_discount; DELIMITER $$ CREATE PROCEDURE update_bill_discount (IN p_bill_id int(255), IN p_discount float(15,2), OUT p_msg varchar(255) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; UPDATE bill SET bill.discount = p_discount WHERE bill.bill_id=p_bill_id; COMMIT; SET p_msg="Discount amount added"; END$$ DELIMITER ; /* CALL update_bill_discount(1,3000,@p_msg); SELECT @p_msg; */ -- update_temp_bill_discount DROP PROCEDURE IF EXISTS update_temp_bill_discount; DELIMITER $$ CREATE PROCEDURE update_temp_bill_discount (IN p_bill_id int(255), IN p_discount float(15,2), OUT p_msg varchar(255) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; UPDATE temp_bill SET temp_bill.discount = p_discount WHERE temp_bill.bill_id=p_bill_id; COMMIT; SET p_msg="Discount amount added"; END$$ DELIMITER ; /* CALL update_temp_bill_discount(1,3000,@p_msg); SELECT @p_msg; */ -- update bill paid DROP PROCEDURE IF EXISTS update_bill_paid; DELIMITER $$ CREATE PROCEDURE update_bill_paid (IN p_bill_id int(255), IN p_paid_am float(15,2), OUT p_msg varchar(255) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; UPDATE bill SET bill.paid_am = p_paid_am WHERE bill.bill_id=p_bill_id; COMMIT; SET p_msg="Paid amount added"; END$$ DELIMITER ; /* CALL update_bill_paid(1,20000,@p_msg); SELECT @p_msg; */ -- update_temp_bill_paid DROP PROCEDURE IF EXISTS update_temp_bill_paid; DELIMITER $$ CREATE PROCEDURE update_temp_bill_paid (IN p_bill_id int(255), IN p_paid_am float(15,2), OUT p_msg varchar(255) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; UPDATE temp_bill SET temp_bill.paid_am = p_paid_am WHERE temp_bill.bill_id=p_bill_id; COMMIT; SET p_msg="Paid amount added"; END$$ DELIMITER ; /* CALL update_bill_paid(1,20000,@p_msg); SELECT @p_msg; */ /*-----------Bank Info------------------*/ DROP PROCEDURE IF EXISTS update_bank_info; DELIMITER $$ CREATE PROCEDURE update_bank_info (IN p_bank_id int(255), IN p_bank_name varchar(255), IN p_bank_branch varchar(255), IN p_bank_district varchar(255), IN p_bank_balance float(30,2), IN p_openning_date date, OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; UPDATE bank_info SET bank_info.bank_name=p_bank_name, bank_info.bank_branch=p_bank_branch, bank_info.bank_district=p_bank_district, bank_info.bank_balance=p_bank_balance, bank_info.openning_date=p_openning_date WHERE bank_info.bank_id=p_bank_id; COMMIT; SET p_msg="Bank Info Successfully Updated"; END$$ DELIMITER ; /* CALL update_bank_info(1,'Agrani','Newmarket','Jessore',900000.00,curdate(),@p_msg); SELECT @p_msg; */ /*-----------Bank Trans------------------*/ DROP PROCEDURE IF EXISTS update_bank_trans; DELIMITER $$ CREATE PROCEDURE update_bank_trans (IN p_bt_id int(10), IN p_bt_amount float(15,2), IN p_bt_status enum('deposit', 'withdraw'), IN p_payment_type varchar(30), OUT p_msg varchar(100) ) BEGIN DECLARE v_status varchar(30); DECLARE b_amount float(15,2); DECLARE n_amount float(15,2); DECLARE bt_n_amount float(15,2); DECLARE f_amount float(15,2); DECLARE v_bank_id int(10); DECLARE v_amount float(15,2); DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' as msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered'; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000'; START TRANSACTION; SELECT bank_trans.bank_id,bank_trans.bt_status,bank_trans.bt_amount INTO v_bank_id,v_status,v_amount FROM bank_trans WHERE bank_trans.bt_id=p_bt_id; SELECT bank_info.bank_balance INTO b_amount FROM bank_info WHERE bank_info.bank_id=v_bank_id; IF v_status='withdraw' THEN SET n_amount=b_amount+v_amount; ELSE SET n_amount=b_amount-v_amount; END IF; IF p_bt_status='withdraw' THEN SET f_amount=n_amount-p_bt_amount; ELSE SET f_amount=n_amount+p_bt_amount; END IF; UPDATE bank_info SET bank_info.bank_balance=f_amount WHERE bank_info.bank_id=v_bank_id; UPDATE bank_trans SET bank_trans.bt_amount=p_bt_amount,bank_trans.bt_status=p_bt_status,bank_trans.payment_type=p_payment_type WHERE bank_trans.bt_id=p_bt_id; SET p_msg='Bank Transaction successfully Updated'; COMMIT; END$$ DELIMITER ; /* CALL update_bank_trans(1,'100000','withdraw','cash',@p_msg); SELECT @p_msg; */ -- <<------END UPDATE PROCEDURE-------->> --<file_sep><div class="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="cnf.php">Home</a> </li> <li class="breadcrumb-item active">Benapole-Bhomra</li> </ol> <div id="demo"> <div class="step-app"> <ul class="step-steps"> <li><a href="#step1">Customer Info</a></li> <li><a href="#step2">Job Info</a></li> <li><a href="#step3">Bill Info</a></li> <li><a href="#step4">Particular</a></li> <li><a href="#step5">Enclosur</a></li> </ul> <div class="step-content"> <!-- first Step start--> <div style="overflow:hidden;" class="step-tab-panel" id="step1"> <div class="container"> <div class="row"> <div class="col-md-12"> <div id="futt" style="margin-top:20px;margin-bottom:20px;" class="alert alert-warning"> <center><strong>Existing Customer.</strong> Skip this page if customer is existed.</center> </div> <div style="clear:both"></div> <div id="new" class="col-md-6 offset-md-3"> <button style="width:100%" class="btn btn-default"> Register a New customer </button> </div> <div style="clear:both"></div> <!-- new customer start --> <div id="open_new"> <div id="form-content"> <form method="post" class="col-md-8 offset-md-2 form-custom2 reg-form" autocomplete="on"> <center><h1> New Customer Info </h1></center> <hr /> <div class="form-group"> <label for="messers">Messers :</label> <input type="text" class="form-control" id="messers" name="messers" placeholder="Enter Messers" onBlur="job_custom" required /> </div> <div class="form-group"> <label for="address">Address :</label> <input type="text" class="form-control" id="address" name="address" placeholder="Enter Address" required /> </div> <div class="form-group"> <label for="lc_no">LC Number:</label> <input type="number" class="form-control" id="lc_no" name="lc_no" placeholder="Enter LC Number" required /> </div> <div class="form-group"> <label for="lc_date">LC Date:</label> <input type="date" class="form-control" id="lc_date" name="lc_date" required /> </div> <button style="width:100%; margin-bottom: 20px;" class="btn btn-primary" name="insert-data" id="insert-data" onclick="insertData()">Add Customer</button> <div style="clear:both"></div> </form> </div> </div><!-- .new customer end --> <div style="clear:both"></div> <!-- existing customer star --> </div> </div> </div> </div> <!-- .first Step end--> <!-- second Step start--> <div class="step-tab-panel" id="step2"> <div id="form-content2"> <form style="padding-top:20px;padding-bottom:20px;margin-top:10px;" class="col-md-12 form-custom2" method="post" id="reg-form2" autocomplete="on"> <h1><center>Insert Job Info</center></h1> <hr /> <div class="form-group"> <label for="particuler">Select Customer: (<span style="color:red;font-size:12px;">Leave it blank for new customer.</span>) </label> <select class="form-control" name="customer_id" id="customer_id"> <option value="">Select Customer:</option> <?php query_table('customer_option_view'); ?> </select> </div> <div class="col-md-6 pull-left"> <div class="form-group"> <label for="job_no">Ref. No:</label>&nbsp;&nbsp; <input type="text" class="form-control" name="job_no" placeholder="Enter Job No" required /> </div> <div class="form-group"> <label for="ac">A/c :</label>&nbsp;&nbsp; <input type="text" class="form-control" name="ac" placeholder="Enter A/c Info" required /> </div> <div class="form-group"> <label for="bill_of_entry">Bill Of Entery No. :</label>&nbsp;&nbsp; <input type="text" class="form-control" name="bill_of_entry" placeholder="Enter Bill Of Entery No." required /> </div> <div class="form-group"> <label for="bill_date">Date Of Bill:</label>&nbsp;&nbsp; <input type="date" class="form-control" name="bill_date" required /> </div> <div class="form-group"> <label for="desc_good">Description Of Goods :</label>&nbsp;&nbsp; <input type="text" class="form-control" name="desc_good" placeholder="Enter Description Of Goods" required /> </div> <div class="form-group"> <label for="qty">Quantity :</label>&nbsp;&nbsp; <input type="text" class="form-control" name="qty" placeholder="Enter Quantity" required /> </div> </div> <div class="col-md-6 pull-right"> <div class="form-group"> <label for="weight">Weight :</label>&nbsp;&nbsp; <input type="text" class="form-control" name="weight" placeholder="Enter Weight" required /> </div> <div class="form-group"> <label for="track_recipt">Track Recipt RR/SR No. :</label>&nbsp; <input type="text" class="form-control" name="track_recipt" id="track_recipt" placeholder="Enter Track Recipt RR/SR No." value="" /> </div> <div class="form-group"> <label for="tr_description">Track Recipt Description:</label>&nbsp;&nbsp; <input type="text" class="form-control" name="tr_description" id="tr_description" placeholder="Enter Track Recipt Description" value="" /> </div> <div class="form-group"> <label for="exporter">Exporter:</label>&nbsp;&nbsp; <input type="text" class="form-control" name="exporter" placeholder="Enter exporter" required /> </div> <div class="form-group"> <label for="cnf_value">CNF Value:</label>&nbsp;&nbsp; <input type="text" class="form-control" name="cnf_value" placeholder="Enter CNF Value" required /> </div> <div class="form-group"> <label for="particuler">Clearence Date :</label>&nbsp;&nbsp; <input type="date" class="form-control" name="clearence_date" placeholder="Enter Clearence Date " required /> </div> </div> <input style="" type="submit" class="btn submit_btn" value="Submit" name="port_add" /> </form> </div> </div><!-- .second Step end--> <!-- Tirhd Step start--> <div class="step-tab-panel" id="step3"> <div id="show_succ"> <form style="padding-top:10px;padding-bottom:10px;margin-top:10px;" class="col-md-8 offset-md-2 form-custom2" method="POST" id="bill_form" > <center><h1>Bill Info</h1></center> <hr /> <div class="form-group"> <label for="bill_number">Bill Number :</label> <input type="text" class="form-control" name="bill_number" placeholder="Enter Bill Number " required /> </div> <div class="form-group"> <label for="bill_date">Bill Date:</label> <input type="date" class="form-control" name="bill_date" required /> </div> <input style="" type="submit" class="btn submit_btn" value="Submit" name="bill_add" /> </form> </div> </div><!-- .Tirhd Step start--> <!-- Fourth Step start--> <div class="step-tab-panel" id="step4"> <div style="padding-top:10px;padding-bottom:10px;margin-top:10px;" class="col-md-12 form-custom2" > <div id="msg_prt" class="msg_prt"></div> <h1><center>Insert Particular Info</center></h1> <hr /> <table id="bvp" style="" class="table table-bordered text-center"> <?php reterve_data_particular_bv() ?> <tr style="background-color: #fff;border-left: 2px solid #fff;border-right: 2px solid #ffff;"> <td colspan="4"> </td> </tr> <tr> <form class="com_add_form" method="POST"> <td> Clearing Commission A/Value Tk </td> <td > <input type="number" id="com_val" class="form-control" name="assessable_value" placeholder="Enter Commission C&F on assessable Value Tk " required /> </td> <td> <input style="width:50%;" type="number" id="com_per" class="form-control pull-left" name="comission_ass" placeholder="Enter comission parcentage" pattern="[0-9]+([\.,][0-9]+)?" step="0.01" onkeydown="com_func()" onkeyup="com_func()" required /> <span style="margin-top: 3px;margin-left: 7px;font-size:21px;" class="pull-left">%</span> </td> <td> <input type="submit" class="btn btn-info btn-sm part_ind_add" value="ADD"> </td> </form> </tr> <tr style="border-color:#000"> <td>Total C&F Commission Amount</td> <td colspan="3"><span id="total_comission"> 0 </span> </td> </tr> <tr style="border-color:#000"> <td><strong>Total Amount</strong></td> <td colspan="3"><strong><span class="total_am"> 0 </span></strong></td> </tr> <tr> <form class="disc_form" method="POST"> <td> Discount Amount </td> <td> <input type="number" id="disc_am" class="form-control pull-left" name="disc_am" placeholder="Enter comission parcentage" pattern="[0-9]+([\.,][0-9]+)?" step="0.01" required /> </td> <td colspan="2"> <input type="submit" class="btn btn-info btn-sm part_ind_add" value="ADD"> </td> </form> </tr> </table> <div class="card"> <div class="card-block"> <div class="container "> <div style="margin: 10px 0px;" class="row"> <div class="col-md-6 text-center"><h3><strong>Sub Total</strong></h3></div> <div style="padding-top:4px;" class="col-md-6 text-center"><h4><span id="sub_total_am"></span></h4></div> </div> </div> </div> </div> <!--<table style="margin-top:10px;" class="table table-bordered text-center"> <tr> <form id="paid_form" method="POST"> <td> Paid Amount </td> <td> <input type="number" id="paid_am" class="form-control text-center pull-left" name="paid_am" placeholder="Enter Paid Amount" pattern="[0-9]+([\.,][0-9]+)?" step="0.01" value="0" required /> </td> <td colspan="2"> <input type="submit" class="btn btn-info btn-sm part_ind_add" value="ADD"> </td> </form> </tr> </table>--> </div> </div><!-- .Fourth Step start--> <!-- Fifth Step start--> <div class="step-tab-panel" id="step5"> <div style="padding-top:10px;padding-bottom:10px;margin-top:10px;" class="col-md-12 form-custom2" > <div id="msg_prt2" class="msg_prt"></div> <h1><center>Insert Enclosur Document Info</center></h1> <hr /> <table class="table table-bordered text-center"> <?php reterve_data_encloser_doc(); ?> </table> </div> </div><!-- .Fifth Step start--> </div> </div> <div class="step-footer pull-right"> <button data-direction="prev" class="btn btn-info"><i class="fa fa-angle-double-left btn-lg" aria-hidden="true"></i></button> <button data-direction="next" class="btn btn-info btn-lg" id="nexts"><i class="fa fa-angle-double-right" aria-hidden="true"></i></button> <button data-direction="finish" class="btn btn-success btn-lg">FINISH</button> </div> </div> </div> </div> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="js/jquery-steps.js"></script> <script> $('#demo').steps({ onFinish: function () { window.location.href='cnf.php?page=finish'; } }); </script> <script> $(document).ready(function(){ $("#new").click(function(){ $("#open_new").toggle("slow"); $("#futt").toggle("slow"); }); }); </script> <script src="https://code.jquery.com/jquery-2.2.4.js" integrity="<KEY> crossorigin="anonymous"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { // submit form using $.ajax() method $('.reg-form').submit(function(e){ e.preventDefault(); // Prevent Default Submission $.ajax({ url: 'extarnel_pages/submit_customer.php', type: 'POST', data: $(this).serialize() // it will serialize the form data }) .done(function(data){ $('#form-content').fadeOut('slow', function(){ $('#form-content').fadeIn('slow').html(data); }); }) .fail(function(){ alert('Ajax Submit Failed ...'); }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { // submit form using $.ajax() method $('#reg-form2').submit(function(e){ e.preventDefault(); // Prevent Default Submission $.ajax({ url: 'extarnel_pages/submit_job_bv.php', type: 'POST', data: $(this).serialize() // it will serialize the form data }) .done(function(data){ $('#form-content2').fadeOut('slow', function(){ $('#form-content2').fadeIn('slow').html(data); }); }) .fail(function(){ alert('Ajax Submit Failed ...'); }); }); }); </script> <script> $(document).ready(function(){ $("span.add").hide(); $("center.addit").click(function(){ $("span.add").hide(); //hide all ul.menu $(this).prev().show("fast"); }); }); </script> <script type="text/javascript"> $(document).ready(function() { // submit form using $.ajax() method $('.parti_ind').submit(function(e){ e.preventDefault(); // Prevent Default Submission $.ajax({ url: 'extarnel_pages/particuler_form.php', type: 'POST', data: $(this).serialize() // it will serialize the form data }) .done(function(data){ $('#msg_prt').fadeIn('slow').html(data); //$('#myModal').modal({ show: false}); //alert('success to add amount on particuler field'); }) .fail(function(){ alert('Ajax Submit Failed ...'); }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { // submit form using $.ajax() method $('#bill_form').submit(function(e){ e.preventDefault(); // Prevent Default Submission $.ajax({ url: 'extarnel_pages/submit_bill.php', type: 'POST', data: $(this).serialize() // it will serialize the form data }) .done(function(data){ $('#show_succ').fadeOut('slow', function(){ $('#show_succ').fadeIn('slow').html(data); }); }) .fail(function(){ alert('Ajax Submit Failed ...'); }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { // submit form using $.ajax() method $('.com_add_form').submit(function(e){ e.preventDefault(); // Prevent Default Submission $.ajax({ url: 'extarnel_pages/com_add_form.php', type: 'POST', data: $(this).serialize() // it will serialize the form data }) .done(function(data){ $('#msg_prt').fadeIn('slow').html(data); }) .fail(function(){ alert('Ajax Submit Failed ...'); }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { // submit form using $.ajax() method $('.disc_form').submit(function(e){ e.preventDefault(); // Prevent Default Submission $.ajax({ url: 'extarnel_pages/disc_form.php', type: 'POST', data: $(this).serialize() // it will serialize the form data }) .done(function(data){ $('#msg_prt').fadeIn('slow').html(data); }) .fail(function(){ alert('Ajax Submit Failed ...'); }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $('#paid_form').submit(function(e){ e.preventDefault(); // Prevent Default Submission $.ajax({ url: 'extarnel_pages/paid_form.php', type: 'POST', data: $(this).serialize() // it will serialize the form data }) .done(function(data){ $('#msg_prt').fadeIn('slow').html(data); }) .fail(function(){ alert('Ajax Submit Failed ...'); }); }); }); </script> <script type="text/javascript"> $(document).ready(function() { setInterval(function(){ $.ajax({ //create an ajax request to display.php type: "GET", url: "extarnel_pages/sub_total_am.php", dataType: "html", //expect html to be returned success: function(response){ $("#sub_total_am").html(response); } }); $.ajax({ //create an ajax request to display.php type: "GET", url: "extarnel_pages/total_am.php", dataType: "html", //expect html to be returned success: function(response){ $(".total_am").html(response); } }); }, 500); }); </script> <script type="text/javascript"> $(document).ready(function (e) { $(".form_enc").on('submit',(function(e) { e.preventDefault(); $.ajax({ url: "extarnel_pages/submit_enc_doc.php", type: "POST", data: new FormData(this), contentType: false, cache: false, processData:false, beforeSend : function() { //$("#preview").fadeOut(); $("#err").fadeOut(); }, success: function(data) { if(data=='invalid') { // invalid file format. $("#err").html("Invalid File !").fadeIn(); } else { $("#msg_prt2").html(data).fadeIn(); } }, error: function(e) { $("#err").html(e).fadeIn(); } }); })); }); </script> <script type="text/javascript"> function com_func(){ var x = document.getElementById("com_val").value; var y = document.getElementById("com_per").value; var z = (x * y)/100 ; document.getElementById("total_comission").innerHTML = (Number(z).toFixed(2)) ; } function com_func2(){ var x = document.getElementById("com_val2").value; var y = document.getElementById("com_per2").value; var z = (x * y)/100 ; document.getElementById("total_comission2").innerHTML = (Number(z).toFixed(2)); } </script> <file_sep><?php include('db/dbconfig.php'); /*============Universal Function Start=========*/ //---- number to word function start----------- function numberTowords($num) { $number = $num; $no = round($number); $point = round($number - $no, 2) * 100; $hundred = null; $digits_1 = strlen($no); $i = 0; $str = array(); $words = array('0' => '', '1' => 'one', '2' => 'two', '3' => 'three', '4' => 'four', '5' => 'five', '6' => 'six', '7' => 'seven', '8' => 'eight', '9' => 'nine', '10' => 'ten', '11' => 'eleven', '12' => 'twelve', '13' => 'thirteen', '14' => 'fourteen', '15' => 'fifteen', '16' => 'sixteen', '17' => 'seventeen', '18' => 'eighteen', '19' =>'nineteen', '20' => 'twenty', '30' => 'thirty', '40' => 'forty', '50' => 'fifty', '60' => 'sixty', '70' => 'seventy', '80' => 'eighty', '90' => 'ninety'); $digits = array('', 'hundred', 'thousand', 'lakh', 'crore'); while ($i < $digits_1) { $divider = ($i == 2) ? 10 : 100; $number = floor($no % $divider); $no = floor($no / $divider); $i += ($divider == 10) ? 1 : 2; if ($number) { $plural = (($counter = count($str)) && $number > 9) ? 's' : null; $hundred = ($counter == 1 && $str[0]) ? ' and ' : null; $str [] = ($number < 21) ? $words[$number] . " " . $digits[$counter] . $plural . " " . $hundred : $words[floor($number / 10) * 10] . " " . $words[$number % 10] . " " . $digits[$counter] . $plural . " " . $hundred; } else $str[] = null; } $str = array_reverse($str); $result = implode('', $str); $points = ($point) ? "." . $words[$point / 10] . " " . $words[$point = $point % 10] : ''; return $result . "Taka " . $points . " Paisa"; } //---- number to word function end----------- //------ input sequrity start----// function test_input($data) { global $conn; $data = trim($data); $data=$conn->escape_string($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } //----- input sequrity end-----// //----- reterve port---// function query_table($table_name){ global $conn; $sql=$conn->query("SELECT * FROM $table_name "); $count=$sql->field_count; while($getrow=$sql->fetch_array()){ $i=1; while($i<$count){ $j=0; while($j<$i){ echo '<option value=" '. $getrow[$j] .' ">'. $getrow[$i] .'</option>'; $j++; } $i++; } } } //-----Output message showing start-----// function show_p_msg($redirect){ global $conn; $sqlp=$conn->query("SELECT @p_msg"); $getmsg=$sqlp->fetch_array(); $msg=$getmsg['@p_msg']; echo '<script type="text/javascript"> alert(" '. $msg .' "); window.location.href="cnf.php?page='. $redirect.'"; </script>'; } //--- only output message without pop up alert ------- function show_p_o_msg(){ global $conn; $sqlp=$conn->query("SELECT @p_msg"); $getmsg=$sqlp->fetch_array(); $msg=$getmsg['@p_msg']; return $msg; } //------start move particuler and encloser_doc details from temp------- function finalze_cnf(){ global $conn; $last_bill=last_bill(); $sql=$conn->query("CALL finalze_cnf('$last_bill',@p_msg)"); } // end move particuler and encloser_doc details from temp----- /* ==========Universal Function End============*/ /* ======function for insert data star========== */ /*start insert into port*/ function insert_port($portred){ global $conn; //submit from encoles insert interface by super admin if(isset($_POST['port_add'])){ $port=test_input($_POST['port']); $port_id=test_input($_POST['port']); $sql=$conn->query("CALL insert_port('$port',@p_msg)"); if($sql){ show_p_msg($portred); } } } /*end insert into port*/ /*start insert into particilar*/ function insert_particuler($particular){ global $conn; //submit from encoles insert interface by super admin if(isset($_POST['particuler_add'])){ $particuler=test_input($_POST['particuler']); $port_id=test_input($_POST['port']); $particuler_type=test_input($_POST['particuler_type']); if (empty($particuler_type)){ $particuler_type = NULL ; } $sql=$conn->query("CALL insert_particular('$particuler','$particuler_type','$port_id',@p_msg)"); if($sql){ show_p_msg($particular); } } } /*end insert into particilar*/ /*start insert into enclosur doc*/ function insert_encloser_doc($enc){ global $conn; //submit from encoles insert interface by super admin if(isset($_POST['enc_doc_add'])){ $enc_doc=test_input($_POST['enc_doc']); $port_id=test_input($_POST['port']); $sql=$conn->query("CALL insert_encloser_doc('$enc_doc','$port_id',@p_msg)"); if($sql){ show_p_msg($enc); } } } // function insert_encloser_doc(){ // global $conn; // //submit from encoles insert interface by super admin // if(isset($_POST['add_particular'])){ // $particular_name=test_input($_POST['particilar']); // $qyt=test_input($_POST['qyt']); // $sql=$conn->query("CALL insert_encloser_doc('$enc_doc','$port_id',@p_msg)"); // if($sql){ // show_p_msg($enc); // } // } // } /* ======function for insert data star========== */ /* ======function for reterve data star======== */ //------- last Bill id ---------- function last_bill(){ global $conn; $sql=$conn->query("SELECT * FROM temp_bill GROUP BY bill_id DESC LIMIT 1"); $getrow=$sql->fetch_array(); $last_bill_id=$getrow['bill_id']; return $last_bill_id; } //--------total bill view-------------- //------- last customer view ---------- function last_customer(){ global $conn; $sql=$conn->query("SELECT * FROM customer GROUP BY customer_id DESC LIMIT 1"); $getrow=$sql->fetch_array(); $last_customer_id = $getrow['customer_id']; return $last_customer_id; } function last_customer_comp($bill_id){ global $conn; $cust_id=reterve_job_comp($bill_id)['customer_id']; $sql=$conn->query("SELECT * FROM customer WHERE customer_id='$cust_id' "); $getrow=$sql->fetch_array(); return $getrow; } //--------last customer view-------------- //------- last job view ---------- function last_job(){ global $conn; $sql=$conn->query("SELECT * FROM job GROUP BY job_id DESC LIMIT 1"); $getrow=$sql->fetch_array(); $last_job_id=$getrow['job_id']; return $last_job_id; } function last_job_port(){ global $conn; $sql=$conn->query("SELECT * FROM job GROUP BY job_id DESC LIMIT 1"); $getrow=$sql->fetch_array(); $last_port_id=$getrow['port_id']; return $last_port_id; } //--------last job view End-------------- function total_bill_view(){ global $conn; $sql=$conn->query("SELECT * FROM temp_bill_view GROUP BY bill_id DESC LIMIT 1"); $getrow=$sql->fetch_array(); $total_am=$getrow['total_bill']; echo $total_am; } function subtotal_bill_view(){ global $conn; $sql=$conn->query("SELECT * FROM temp_bill_view GROUP BY bill_id DESC LIMIT 1"); $getrow=$sql->fetch_array(); $total_am=$getrow['sub_total']; echo $total_am; } //reterve particuler data function reterve_data_particular(){ global $conn; $sql=$conn->query("SELECT * FROM particular "); while($getres=$sql->fetch_array()){ ?> <tr> <form class="parti_ind" method="POST" > <td> <?php echo $getres[1] ?> </td> <td> <input type="text" value="<?php echo $getres[0] ?>" name="id" hidden /> <input type="text" class="form-control" name="particilar" placeholder="Enter <?php echo $getres[1] ?> " required /> </td> <td> <span class="add"><input style="width:51%;margin-bottom:10px;margin-left: 24%;" class="form-control" type="text" placeholder="Add Quantity" name="qty" value="1" /></span> <center style="margin-left: 25%;" class="addit"><input type="button" class="btn btn-info btn-sm pull-left" value="Add Quantity"></center> </td> <td> <input type="submit" class="btn btn-info btn-sm part_ind_add" value="ADD"> </td> </form> </tr> <?php } } function reterve_data_particular_bv(){ global $conn; $sql=$conn->query("SELECT * FROM particular WHERE port_id = 1 "); while($getres=$sql->fetch_array()){ ?> <tr> <form class="parti_ind" method="POST" > <td> <?php echo $getres[1] ?> </td> <td> <input type="text" value="<?php echo $getres[0] ?>" name="id" hidden /> <input type="text" class="form-control" name="particilar" placeholder="Enter <?php echo $getres[1] ?> " required /> </td> <td> <span class="add"><input style="width:51%;margin-bottom:10px;margin-left: 24%;" class="form-control" type="text" placeholder="Add Quantity" name="qty" value="1" /></span> <center style="margin-left: 25%;" class="addit"><input type="button" class="btn btn-info btn-sm pull-left" value="Add Quantity"></center> </td> <td> <input type="submit" class="btn btn-info btn-sm part_ind_add" value="ADD"> </td> </form> </tr> <?php } } function reterve_data_particular_ctg(){ global $conn; $sql=$conn->query("SELECT * FROM particular WHERE port_id = 2 "); while($getres=$sql->fetch_array()){ ?> <tr> <form class="parti_ind" method="POST" > <td> <?php echo $getres[1] ?> </td> <td> <input type="text" value="<?php echo $getres[0] ?>" name="id" hidden /> <input type="text" class="form-control" name="particilar" placeholder="Enter <?php echo $getres[1] ?> " required /> </td> <td> <span class="add"><input style="width:51%;margin-bottom:10px;margin-left: 24%;" class="form-control" type="text" placeholder="Add Quantity" name="qty" value="1" /></span> <center style="margin-left: 25%;" class="addit"><input type="button" class="btn btn-info btn-sm pull-left" value="Add Quantity"></center> </td> <td> <input type="submit" class="btn btn-info btn-sm part_ind_add" value="ADD"> </td> </form> </tr> <?php } } function reterve_job_comp($bill_id){ global $conn; $sql=$conn->query("SELECT * FROM bill WHERE bill_id = '$bill_id' "); $getres=$sql->fetch_array(); $job_id = $getres['job_id']; $sql2=$conn->query("SELECT * FROM job WHERE job_id = '$job_id' "); $getres2=$sql2->fetch_array(); return $getres2; } function reterve_intable_data_particular($port,$particular_type){ global $conn; $sql=$conn->query("SELECT * FROM particular WHERE port_id = '$port' and particular_type = '$particular_type' "); while($getres=$sql->fetch_array()){ echo '<h6 style="padding:0px;margin:0px;font-size:14px;">'. $getres[1] .'...........................</h6>'; } } function reterve_intable_data_particular_id($port){ global $conn; $sql=$conn->query("SELECT * FROM particular WHERE port_id = '$port' "); $getres=$sql->fetch_array(); $particular_id=$getres['particular_id']; return $particular_id; } function reterve_intable_data_particular_am($bill_id){ global $conn; $sql=$conn->query("SELECT * FROM particular_d WHERE bill_id= $bill_id"); while($getres=$sql->fetch_array()){ echo '<h6>'. $getres['amount'] .'</h6>'; } } //reterve enclosur_doc data function reterve_data_encloser_doc(){ global $conn; $sql=$conn->query("SELECT * FROM encloser_doc "); while($getres=$sql->fetch_array()){ ?> <tr> <form action="ajaxupload.php" enctype="multipart/form-data" class="enc_doc_ind form_enc" method="POST" > <td> <?php echo $getres[1] ?> <input type="text" value="<?php echo $getres[0] ?>"name="encloser_doc" hidden /> </td> <td> <input id="uploadImage" type="file" accept="image/*" name="file" /> </td> <td> <input type="submit" class="btn btn-info" value="ADD"> </td> </form> </tr> <?php } } function reterve_intable_data_encloser_doc(){ global $conn; $sql=$conn->query("SELECT * FROM encloser_doc "); while($getres=$sql->fetch_array()){ echo '<h6 style="padding:0px;margin:0px;font-size:14px;">'. $getres[1] .'</h6>'; } } function reterve_intable_from_bill_view($bill_id){ global $conn; $sql=$conn->query("SELECT * FROM bill_view WHERE bill_id = '$bill_id' "); $getres=$sql->fetch_array(); return $getres; } ?> <file_sep>-- <<---------START INSERT PROCEDURE---------->> -- -- PORT---------------------------- DROP PROCEDURE IF EXISTS insert_port; DELIMITER $$ CREATE PROCEDURE insert_port (IN p_port_name varchar(30), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO port VALUES (port_f() , p_port_name); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /* CALL insert_port('benapol',@p_msg); SELECT @p_msg; */ -- CUSTOMER---------------------------- DROP PROCEDURE IF EXISTS insert_customer; DELIMITER $$ CREATE PROCEDURE insert_customer (IN p_messers varchar(255), IN p_address varchar(255), IN p_lc_no varchar(255), IN p_lc_date date, OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO customer VALUES (customer_f(), p_messers, p_address, p_lc_no, p_lc_date ); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /* CALL insert_customer('janata shop ltd.','jessore','3829382',curdate(),@p_msg);SELECT @p_msg; */ -- JOB TABLE------------------------------- DROP PROCEDURE IF EXISTS insert_job; DELIMITER $$ CREATE PROCEDURE insert_job ( IN p_job_no varchar(255), IN p_ac varchar(255), IN p_bill_of_entry int(255), IN p_date_of_bill date, IN p_disc_goods varchar(255), IN p_quantity varchar(255), IN p_weight float(30,2), IN p_ex_ss varchar(255), IN p_rot_no varchar(255), IN p_lin_no varchar(255), IN p_arrived_on date, IN p_track_recipt varchar(255), IN p_tr_description varchar(255), IN p_exporter varchar(255), IN p_depot varchar(255), IN p_cnf_value float(30,2), IN p_clearence_date date, IN p_customer_id int(255), IN p_port_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO job VALUES (job_f(), p_job_no, p_ac, p_bill_of_entry, p_date_of_bill, p_disc_goods, p_quantity, p_weight, p_ex_ss, p_rot_no, p_lin_no, p_arrived_on, p_track_recipt, p_tr_description, p_exporter, p_depot, p_cnf_value, p_clearence_date, p_customer_id, p_port_id ); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /* CALL insert_job('120/45',1999,2333,curdate(),'oil',900,40,'x.p padma','8989','992',curdate(),'343h343u','something','cc','port',49000.00,curdate(),10,1,@p_msg);SELECT @p_msg; */ -- ENCLOSER---------------------------- DROP PROCEDURE IF EXISTS insert_encloser_doc; DELIMITER $$ CREATE PROCEDURE insert_encloser_doc (IN p_ed_name varchar(255), IN p_port_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO encloser_doc VALUES (encloser_doc_f(), p_ed_name, p_port_id ); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /*CALL insert_encloser_doc('TP/IP/GP',1,@p_msg); SELECT @p_msg; */ -- PARTICULER---------------------------- DROP PROCEDURE IF EXISTS insert_particular; DELIMITER $$ CREATE PROCEDURE insert_particular (IN p_particular_name varchar(255), IN p_particular_type varchar(255), IN p_port_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO particular VALUES (particular_f(), p_particular_name, p_particular_type, p_port_id ); SET p_msg='Successful'; COMMIT; END$$ DELIMITER ; /* CALL insert_particular('Bill of entry Charge /Final Assesment. ','others',2,@p_msg); SELECT @p_msg; */ -- BILL---------------------------- DROP PROCEDURE IF EXISTS insert_bill; DELIMITER $$ CREATE PROCEDURE insert_bill (IN p_bill_no varchar(255), IN p_bill_date date, IN p_accesable_value float(30,2), IN p_comission_acc float(30,2), IN p_discount float(30,2), IN p_paid_am float(30,2), IN p_job_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO bill VALUES (bill_f(), p_bill_no, p_bill_date, p_accesable_value, p_comission_acc, p_discount, p_paid_am, p_job_id ); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /* CALL insert_bill(337,curdate(),450000.56,33330000,8900,389000234,1,@p_msg); SELECT @p_msg; */ -- PAYMENT---------------------------- DROP PROCEDURE IF EXISTS insert_payment; DELIMITER $$ CREATE PROCEDURE insert_payment (IN p_bill_id int(255), IN p_amount float(15,2), IN p_pay_date date, OUT p_msg varchar(100) ) BEGIN DECLARE v_total_pay_am float(15,2); DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO payment VALUES (payment_f(), p_bill_id, p_amount, p_pay_date ); SELECT SUM(payment.amount) INTO v_total_pay_am FROM payment WHERE bill_id=p_bill_id; UPDATE bill SET bill.paid_am = v_total_pay_am WHERE bill.bill_id=p_bill_id; COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /* CALL insert_payment(1,3000.89,curdate(),@p_msg);SELECT @p_msg; */ -- TEMP BILL---------------------------- DROP PROCEDURE IF EXISTS insert_temp_bill; DELIMITER $$ CREATE PROCEDURE insert_temp_bill (IN p_bill_no varchar(255), IN p_bill_date date, IN p_accesable_value float(30,2), IN p_comission_acc float(30,2), IN p_discount float(30,2), IN p_paid_am float(30,2), IN p_job_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO temp_bill VALUES (temp_bill_f(), p_bill_no, p_bill_date, p_accesable_value, p_comission_acc, p_discount, p_paid_am, p_job_id ); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /* CALL insert_temp_bill(337,curdate(),450000.56,33330000,8900,389000234,1,@p_msg); SELECT @p_msg; */ -- ENCLOSER DETAILS---------------------------- DROP PROCEDURE IF EXISTS insert_encloser_doc_d; DELIMITER $$ CREATE PROCEDURE insert_encloser_doc_d (IN p_ed_id int(255), IN p_ed_image varchar(2000), IN p_bill_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO encloser_doc_d VALUES (encloser_doc_d_f(), p_ed_id, p_ed_image, p_bill_id ); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /* CALL insert_encloser_doc_d(1,'dghjkhgjkg76r687fuygu.jpg',1,@p_msg); SELECT @p_msg; */ -- TEMP ENCLOSER DETAILS---------------------------- DROP PROCEDURE IF EXISTS insert_temp_encloser_doc_d; DELIMITER $$ CREATE PROCEDURE insert_temp_encloser_doc_d (IN p_ed_id int(255), IN p_ed_image varchar(2000), IN p_bill_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO temp_encloser_doc_d VALUES (temp_encloser_doc_d_f(), p_ed_id, p_ed_image, p_bill_id ); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; /* CALL insert_temp_encloser_doc_d(1,'dghjkhgjkg76r687fuygu.jpg',1,@p_msg); SELECT @p_msg; */ -- PARTICULER DETAILS---------------------------- DROP PROCEDURE IF EXISTS insert_particular_d; DELIMITER $$ CREATE PROCEDURE insert_particular_d (IN p_particular_id int(255), IN p_amount float(15,2), IN p_qty float(15,2), IN p_bill_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO particular_d VALUES (particular_d_f(), p_particular_id, p_amount, p_qty, p_bill_id ); SET p_msg='Successful'; COMMIT; END$$ DELIMITER ; /* CALL insert_particular_d(1,9000.89,1,1,@p_msg); SELECT @p_msg; */ -- TEMP PARTICULER DETAILS---------------------------- DROP PROCEDURE IF EXISTS insert_temp_particular_d; DELIMITER $$ CREATE PROCEDURE insert_temp_particular_d (IN p_particular_id int(255), IN p_amount float(15,2), IN p_qty float(15,2), IN p_bill_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO temp_particular_d VALUES (temp_particular_d_f(), p_particular_id, p_amount, p_qty, p_bill_id ); SET p_msg=CONCAT('Successful ',p_amount*p_qty,' Taka Added'); COMMIT; END$$ DELIMITER ; /* CALL insert_temp_particular_d(1,9000.89,1,1,@p_msg); SELECT @p_msg; */ /*-----------Bank Info------------------*/ DROP PROCEDURE IF EXISTS insert_bank_info; DELIMITER $$ CREATE PROCEDURE insert_bank_info (IN p_bank_name varchar(255), IN p_bank_branch varchar(255), IN p_bank_district varchar(255), IN p_bank_balance float(30,2), IN p_openning_date date, OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO bank_info VALUES (bank_info_f(),p_bank_name,p_bank_branch,p_bank_district,p_bank_balance,p_openning_date); COMMIT; SET p_msg='Bank Info Successful Added'; END$$ DELIMITER ; /*CALL insert_bank_info('DBBL','Jessore','Jessore',100000.00,curdate());*/ /*----------- Bank Trans------------------*/ DROP PROCEDURE IF EXISTS insert_bank_trans; DELIMITER $$ CREATE PROCEDURE insert_bank_trans (IN p_bank_id int(10), IN p_bt_date date, IN p_bt_amount float(15,2), IN p_bt_status enum('deposit', 'withdraw'), IN p_payment_type varchar(30), OUT p_msg varchar(100) ) BEGIN DECLARE v_bank_balance float(15,3); DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; SELECT bank_info.bank_balance INTO v_bank_balance FROM bank_info WHERE bank_info.bank_id = p_bank_id; IF p_bt_status = 'withdraw' THEN IF (v_bank_balance = 0 OR v_bank_balance < p_bt_amount ) THEN SELECT 'Not Enough Balance'; ELSE INSERT INTO bank_trans VALUES (bank_trans_f(),p_bank_id,p_bt_date,p_bt_amount,p_bt_status,p_payment_type); SET v_bank_balance=v_bank_balance-p_bt_amount; UPDATE bank_info SET bank_balance=v_bank_balance WHERE bank_info.bank_id = p_bank_id; SET p_msg='Successfully Withdrawn'; END IF; ELSE INSERT INTO bank_trans VALUES (bank_trans_f(),p_bank_id,p_bt_date,p_bt_amount,p_bt_status,p_payment_type); SET v_bank_balance=v_bank_balance+p_bt_amount; UPDATE bank_info SET bank_balance=v_bank_balance WHERE bank_info.bank_id = p_bank_id; SET p_msg='Successfully Deposited'; END IF; COMMIT; END$$ DELIMITER ; /*CALL insert_bank_trans(1,curdate(),2300.00,'withdraw','Check'); */ -- move to final procedure DROP PROCEDURE IF EXISTS finalze_cnf; DELIMITER $$ CREATE PROCEDURE finalze_cnf( IN p_last_bill_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO bill SELECT * FROM temp_bill WHERE bill_id = p_last_bill_id; INSERT INTO encloser_doc_d SELECT * FROM temp_encloser_doc_d WHERE bill_id = p_last_bill_id; INSERT INTO particular_d SELECT * FROM temp_particular_d WHERE bill_id = p_last_bill_id; DELETE FROM temp_encloser_doc_d WHERE bill_id = p_last_bill_id; DELETE FROM temp_particular_d WHERE bill_id = p_last_bill_id; DELETE FROM temp_bill WHERE bill_id = p_last_bill_id; COMMIT; SET p_msg='A CNF successfully created'; END$$ DELIMITER ; /* CALL finalze_cnf(1,@p_msg); SELECT @p_msg; */ <file_sep><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <style type="text/css"> #show_data{ border-right: 3px solid #ddd; } .modal-backdrop.show{ display:none; } </style> <div class="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="">Home</a> </li> <li class="breadcrumb-item active">Individual Bills And Payment</li> </ol> <div class="row"> <div class="col-12"> <form class="form-custom" action=""> <div class="form-group"> <select name="customer_name" class="form-control" id="customer_name"> <option value="">Select a Customer...</option> <?php query_table('customer_option_view'); ?> </select> </div> </form> </div> </div> <div class="row"> <div class="col-md-7" id="show_data"></div> <div class="col-md-5" id="show_pay_data"></div> </div> </div> </div> <script type="text/javascript"> $(document).ready(function(){ // code to get all records from table via select box $("#customer_name").change(function() { $("#show_pay_data").html(' '); $.ajax({ type: "GET", url: 'extarnel_pages/ind_bill_data.php', dataType: "html", data: {customer_name:$(this).find(":selected").val()}, cache: false, success: function(response) { $("#show_data").html(response); } }); }); }); </script> <file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); if( $_POST ){ $messers = test_input($_POST['messers']); $address = test_input($_POST['address']); $lc_no = test_input($_POST['lc_no']); $lc_date = test_input($_POST['lc_date']); $sql = $conn->query("CALL insert_customer('$messers','$address','$lc_no','$lc_date',@p_msg)"); if($sql){ ?> <table class="table table-striped" border="0"> <tr> <td colspan="2"> <div class="alert alert-info"> <strong>Success</strong>, New Customr Added Successfully... </div> </td> </tr> <tr> <td>Messers</td> <td><?php echo $messers ?></td> </tr> <tr> <td>Address</td> <td><?php echo $address ?></td> </tr> <tr> <td>LC Number</td> <td><?php echo $lc_no; ?></td> </tr> <tr> <td>LC Date</td> <td><?php echo $lc_date; ?></td> </tr> </table> <?php } } ?><file_sep><div class="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="cnf.php">Home</a> </li> <li class="breadcrumb-item active">Add New Encclosures of Documents Fields</li> </ol> <div class="col-md-2 pull-left"></div> <form class="form-inline form-custom col-md-8" action="" method="POST" autocomplete="on"> <center> <center><h2>Enter Enclosures Documents Field</h2></center> <hr /> <div class="form-group"> <label for="particuler">Enc. Doc. Field:</label>&nbsp;&nbsp; <input type="text" class="form-control" name="enc_doc" placeholder="Enclosures Documents Field" required /> </div> <br /> <div class="form-group"> <label for="port">For Port:</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <select class="form-control" name="port" id="" required> <option value="">Select port:</option> <?php query_table('port'); ?> </select> </div> <br /> <input style="" type="submit" class="btn submit_btn" value="submit" name="enc_doc_add" /> <?php insert_encloser_doc('enc_doc'); ?> </center> </form> </div> <file_sep># CNF Clear&amp;Forwarding Managment <file_sep><?php include('../db/dbconfig.php'); if( $_GET ){ $bill_id = $_GET['bill_id']; ?> <style type="text/css"> .none{ display:none; } .modal-backdrop.show{ display:none; } </style> <div class="table-responsive"> <table class="table "> <thead> <tr> <th>SL No.</th> <th>Payment Date</th> <th>Amount</th> <th>Action</th> </tr> </thead> <tbody> <?php $sql=$conn->query("SELECT * FROM payment WHERE bill_id='$bill_id' "); $count = $sql->num_rows; if( $count > 0 ){ $i=1; while($getrow=$sql->fetch_array()){ echo '<tr>'; echo '<td>'. $i .'</td>'; echo '<td>'. $getrow['pay_date'] .'</td>'; echo '<td>'. $getrow['amount'] .'</td>'; echo '<td><button class="btn btn-danger btn-sm delete_btn" value="'.$getrow['pay_id'] .'"><i class="fa fa-trash"></i></button></td>'; echo'</tr>'; $i++; } } else{ echo '<tr>'; echo '<td colspan="4" class="text-center">Not Payment Yet.</td>'; echo'</tr>'; } ?> <tr> <td colspan="2" class="text-center">Total Payment Amount</td> <td><?php $sql2=$conn->query("SELECT SUM(amount) FROM payment WHERE bill_id='$bill_id' "); $getrow2=$sql2->fetch_array(); echo $getrow2['SUM(amount)']; ?> </td> <td></td> </tr> <tr> <td colspan="4" class="text-center"><button style="width:100%" class="btn btn-info" data-toggle="modal" data-target="#myModal">Add Paymet</button></td> </tr> </tbody> </table> </div> <button style="opacity:0;" id="btn2" value="<?php echo $bill_id ?>" >make it</button> </div> <div style="background-color: #00000038;" class="modal fade" id="myModal"> <div class="modal-dialog"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Add Payment</h4> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <!-- Modal body --> <div class="modal-body"> <form id="add_payment" action="" method="POST"> <input type="text" name="bill_id" value="<?php echo $bill_id; ?>" hidden /> <div class="form-group "> <label for="pay_date">Payment Date:</label> <input type="date" class="form-control" name="pay_date" required /> </div> <div class="form-group "> <label for="pay_amount">Amount:</label> <input type="number" class="form-control" name="pay_amount" placeholder="Enter Amount" required /> </div> <button type="submit" style="width:100%" value="<?php echo $bill_id ?>" class="btn btn-success" >ADD</button> </form> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Cansel</button> </div> </div> </div> </div> <?php } ?> <script type="text/javascript"> $(document).ready(function() { $('#add_payment').submit(function(e){ e.preventDefault(); // Prevent Default Submission $.ajax({ url: 'extarnel_pages/add_payment.php', type: 'POST', data: $(this).serialize(), // it will serialize the form data cache: false, success: function(response) { if (confirm(response)){ document.getElementById("myModal").style.className = "none"; } $("#btn2").click(); } }); // .done(function(data){ // //$("respm").html(data); // //jQuery("#myModal2").modal('show'); // alert(data); // //$("#myModal2").show(); // //$("#myModal").css('display:none'); // }) // .fail(function(){ // alert('Ajax Submit Failed ...'); // }); }); }); </script> <script type="text/javascript"> $(document).ready(function(){ // code to get all records from table via select box $(".delete_btn").click(function() { $.ajax({ type: "GET", url: 'extarnel_pages/delete_paid_amount.php', dataType: "html", data: {pay_id:$(this).val()}, cache: false, success: function(response) { alert(response); $("#btn2").click(); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function(){ // code to get all records from table via select box $("#btn2").click(function() { $.ajax({ type: "GET", url: 'extarnel_pages/payment_info.php', dataType: "html", data: {bill_id:$(this).val()}, cache: false, success: function(response) { $("#show_pay_data").html(response); } }); }); }); </script> <script type="text/javascript"> $(document).ready(function(){ // code to get all records from table via select box $("#btn2").click(function() { $.ajax({ type: "GET", url: 'extarnel_pages/ind_bill_data.php', dataType: "html", data: {bill_id:$(this).val()}, cache: false, success: function(response) { $("#show_data").html(response); } }); }); }); </script> <file_sep>-- <<------START DELETE PROCEDURE------->> -- -- port delete DROP PROCEDURE IF EXISTS delete_port; DELIMITER $$ CREATE PROCEDURE delete_port ( IN p_port_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'Delete not possible' INTO p_msg; START TRANSACTION; DELETE FROM port WHERE port.port_id=p_port_id; SET p_msg='Deleted successfully'; COMMIT; END$$ DELIMITER ; -- customer delete DROP PROCEDURE IF EXISTS delete_customer; DELIMITER $$ CREATE PROCEDURE delete_customer ( IN p_customer_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'Delete not possible' INTO p_msg; START TRANSACTION; DELETE FROM customer WHERE customer.customer_id=p_customer_id; SET p_msg='Deleted successfully'; COMMIT; END$$ DELIMITER ; -- job delete DROP PROCEDURE IF EXISTS delete_job; DELIMITER $$ CREATE PROCEDURE delete_job ( IN p_job_id int(10), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'Delete not possible' INTO p_msg; START TRANSACTION; DELETE FROM job WHERE job.job_id=p_job_id; SET p_msg='Deleted successfully'; COMMIT; END$$ DELIMITER ; -- encloser_doc delete DROP PROCEDURE IF EXISTS delete_encloser_doc; DELIMITER $$ CREATE PROCEDURE delete_encloser_doc ( IN p_ed_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'Delete not possible' INTO p_msg; START TRANSACTION; DELETE FROM encloser_doc WHERE encloser_doc.ed_id=p_ed_id; SET p_msg='Deleted successfully'; COMMIT; END$$ DELIMITER ; -- particular delete DROP PROCEDURE IF EXISTS delete_particular; DELIMITER $$ CREATE PROCEDURE delete_particular ( IN p_particular_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'Delete not possible' INTO p_msg; START TRANSACTION; DELETE FROM particular WHERE particular.particular_id=p_particular_id; SET p_msg='Deleted successfully'; COMMIT; END$$ DELIMITER ; -- bill delete DROP PROCEDURE IF EXISTS delete_bill; DELIMITER $$ CREATE PROCEDURE delete_bill ( IN p_bill_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'Delete not possible' INTO p_msg; START TRANSACTION; DELETE FROM bill WHERE bill.bill_id=p_bill_id; SET p_msg='Deleted successfully'; COMMIT; END$$ DELIMITER ; -- delete_payment DROP PROCEDURE IF EXISTS delete_payment; DELIMITER $$ CREATE PROCEDURE delete_payment ( IN p_pay_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE v_pay_amount float(15,2); DECLARE v_old_paid_amount float(15,2); DECLARE v_bill_id int(255); DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'Delete not possible' INTO p_msg; START TRANSACTION; SELECT payment.amount INTO v_pay_amount FROM payment WHERE payment.pay_id=p_pay_id; SELECT payment.bill_id INTO v_bill_id FROM payment WHERE payment.pay_id=p_pay_id; SELECT bill.paid_am INTO v_old_paid_amount FROM bill WHERE bill.bill_id=v_bill_id; SET v_old_paid_amount = v_old_paid_amount-v_pay_amount; UPDATE bill SET bill.paid_am = v_old_paid_amount WHERE bill.bill_id=v_bill_id; DELETE FROM payment WHERE payment.pay_id=p_pay_id; SET p_msg='Deleted successfully'; COMMIT; END$$ DELIMITER ; /* */ -- bank_info delete DROP PROCEDURE IF EXISTS delete_bank_info; DELIMITER $$ CREATE PROCEDURE delete_bank_info ( IN p_bank_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'Delete not possible' INTO p_msg; START TRANSACTION; DELETE FROM bank_info WHERE bank_info.bank_id=p_bank_id; SET p_msg='Deleted successfully'; COMMIT; END$$ DELIMITER ; -- bank_trans delete DROP PROCEDURE IF EXISTS delete_bank_trans; DELIMITER $$ CREATE PROCEDURE delete_bank_trans ( IN p_bt_id int(10), OUT p_msg varchar(100) ) BEGIN DECLARE v_amount float(15,2); DECLARE n_amount float(15,2); DECLARE b_amount float(15,2); DECLARE v_bank_id int(10); DECLARE v_status varchar(20); DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate keys error encountered' as msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered'; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000'; START TRANSACTION; SELECT bank_trans.bt_amount,bank_trans.bank_id,bank_trans.bt_status INTO v_amount,v_bank_id,v_status FROM bank_trans WHERE bank_trans.bt_id=p_bt_id; SELECT bank_info.bank_balance INTO b_amount FROM bank_info WHERE bank_info.bank_id=v_bank_id; IF v_status='withdraw' THEN SET n_amount=b_amount+v_amount; UPDATE bank_info SET bank_info.bank_balance=n_amount WHERE bank_info.bank_id=v_bank_id; SET p_msg='A Bank Transaction record successfully delete and added to Bank Balance'; ELSE SET n_amount=b_amount-v_amount; UPDATE bank_info SET bank_info.bank_balance=n_amount WHERE bank_info.bank_id=v_bank_id; SET p_msg='A Bank Transaction record successfully delete and substract from Bank Balance'; END IF; DELETE FROM bank_trans WHERE bank_trans.bt_id=p_bt_id; COMMIT; END$$ DELIMITER ; /* CALL delete_bank_trans(1,@p_msg); SELECT @p_msg; */ -- <<------END DELETE PROCEDURE------->> -- <file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); $encloser_doc=$_POST['encloser_doc']; $last_bill_id=last_bill(); /*------------------------- Image resizer Start -------------*/ $upload_image = $_FILES["file"]["name"]; $folder = "/xampp/htdocs/cnf/CNF/uploads/"; move_uploaded_file($_FILES["file"]["tmp_name"], "$folder".$_FILES["file"]["name"]); $file = '/xampp/htdocs/inex_tracking/uploads/'.$_FILES["file"][" name"]; $uploadimage = $folder.$_FILES["file"]["name"]; $newname = $_FILES["file"]["name"]; // Set the resize_image name $resize_image = $folder.$newname; $actual_image = $folder.$newname; // It gets the size of the image list( $width,$height ) = getimagesize( $uploadimage ); // It makes the new image width of 250 $newwidth = 250; // It makes the new image height of 250 $newheight = 250; // It loads the images we use jpeg function you can use any function like imagecreatefromjpeg $thumb = imagecreatetruecolor( $newwidth, $newheight ); $source = imagecreatefromjpeg( $resize_image ); // Resize the $thumb image. imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height); // It then save the new image to the location specified by $resize_image variable imagejpeg( $thumb, $resize_image, 60 ); // 100 Represents the quality of an image you can set and ant number in place of 100. $out_image=addslashes(file_get_contents($resize_image)); /*------------------------- Image resizer End-------------*/ $sql=$conn->query("CALL insert_temp_encloser_doc_d('$encloser_doc','$upload_image','$last_bill_id',@p_msg)"); $msg = show_p_o_msg(); if($sql){ ?> <div class="alert alert-info"> <strong>Success,</strong> <?php echo $msg; ?> </div> <?php } else{ echo 'something wrong'; } ?> <file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); if( $_POST ){ $assessable_value = test_input($_POST['assessable_value']); $comission_ass = test_input($_POST['comission_ass']); $last_bill_id=last_bill(); $sql = $conn->query("CALL update_temp_bill_accesable_value('$last_bill_id','$assessable_value','$comission_ass',@p_msg)"); if($sql){ ?> <div class="alert alert-info"> <strong>Success</strong> <?php echo show_p_o_msg();?> </div> <?php } } ?><file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); if( $_POST ){ $disc_am = test_input($_POST['disc_am']); $last_bill_id=last_bill(); $sql = $conn->query("CALL update_temp_bill_discount('$last_bill_id','$disc_am',@p_msg)"); $msg=show_p_o_msg(); if($sql){ ?> <div class="alert alert-info"> <strong>Success</strong> <?php echo $msg; ?> </div> <?php } } ?><file_sep>-- TEMP BILL TABLE CREATE TABLE temp_bill( bill_id int(255), bill_no varchar(255), bill_date date, accesable_value float(30,2), comission_acc float(30,2), discount float(30,2), paid_am float(30,2), job_id date ); ALTER TABLE temp_bill ADD PRIMARY KEY (bill_id); ALTER TABLE temp_bill ADD CONSTRAINT uk_temp_bill_no UNIQUE (bill_no); ALTER TABLE temp_bill ADD CONSTRAINT fk_temp_bill_job_id FOREIGN KEY (job_id) REFERENCES job(job_id); -- temp bill function DROP FUNCTION IF EXISTS temp_bill_f; DELIMITER $$ CREATE FUNCTION temp_bill_f() RETURNS int(10) DETERMINISTIC BEGIN DECLARE p_bill_id int(10); SELECT MAX(bill.bill_id) INTO p_bill_id FROM bill; IF p_bill_id is NULL THEN SET p_bill_id=1; ELSE SET p_bill_id=p_bill_id+1; END IF; RETURN p_bill_id; END$$ DELIMITER ; -- TEMP BILL---------------------------- DROP PROCEDURE IF EXISTS insert_temp_bill; DELIMITER $$ CREATE PROCEDURE insert_temp_bill (IN p_bill_no varchar(255), IN p_bill_date date, IN p_accesable_value float(30,2), IN p_comission_acc float(30,2), IN p_discount float(30,2), IN p_paid_am float(30,2), IN p_job_id int(255), OUT p_msg varchar(100) ) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT 'Duplicate entry is not allowd' INTO p_msg; DECLARE EXIT HANDLER FOR SQLEXCEPTION SELECT 'SQLException encountered' INTO p_msg; DECLARE EXIT HANDLER FOR SQLSTATE '23000' SELECT 'SQLSTATE 23000' INTO p_msg; START TRANSACTION; INSERT INTO temp_bill VALUES (temp_bill_f(), p_bill_no, p_bill_date, p_accesable_value, p_comission_acc, p_discount, p_paid_am, p_job_id ); COMMIT; SET p_msg='Successful'; END$$ DELIMITER ; -- temp total_bill_am DROP FUNCTION IF EXISTS total_temp_bill_am; DELIMITER $$ CREATE FUNCTION total_temp_bill_am(p_bill_id int(255)) RETURNS float(15,2) DETERMINISTIC BEGIN DECLARE v_bill float(15,2); DECLARE v_acc float(15,2); SELECT SUM(temp_particular_d.amount*temp_particular_d.qty) INTO v_bill FROM temp_particular_d WHERE temp_particular_d.bill_id=p_bill_id; IF v_bill is NULL THEN SET v_bill=0; END IF; SELECT (temp_bill.accesable_value*temp_bill.comission_acc)/100 INTO v_acc FROM temp_bill WHERE temp_bill.bill_id=p_bill_id; SET v_bill= v_bill+v_acc; RETURN v_bill; END$$ DELIMITER ; -- temp_bill view CREATE OR REPLACE VIEW temp_bill_view as SELECT temp_bill.bill_id as 'bill_id', temp_bill.bill_no as 'bill_no' , temp_bill.bill_date as 'bill_date' , temp_bill.accesable_value as 'accesable_value' , temp_bill.comission_acc as 'comission_acc',total_bill_am(temp_bill.bill_id) as 'total_bill',temp_bill.discount as 'discount' ,(total_bill_am(temp_bill.bill_id)-temp_bill.discount) as 'sub_total', temp_bill.paid_am as 'paid_am' FROM temp_bill; <file_sep><?php $last_bill=last_bill(); $sql=$conn->query("CALL finalze_cnf('$last_bill',@p_msg)"); $msg=show_p_o_msg(); $last_port=last_job_port(); $last_job = last_job(); $sql=$conn->query("SELECT * FROM bill GROUP BY bill_id DESC LIMIT 1"); $getrow=$sql->fetch_array(); $last_bill_id=$getrow['bill_id']; if($sql){ if ($last_port == 2){ echo '<script type="text/javascript"> if(confirm("'.$msg.'")){ window.open("final2.php?bill_id='. $last_bill_id .'&job_id='. $last_job .'", "_blank"); window.location.href="cnf.php?page=register_cnf"; } </script>'; } else{ echo '<script type="text/javascript"> if(confirm("'.$msg.'")){ window.open("final1.php?bill_id='. $last_bill_id .'&job_id='. $last_job .'", "_blank"); window.location.href="cnf.php?page=register_cnf"; } </script>'; } } else{ echo 'something wrong'; } ?><file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); if( $_POST ){ $bill_number = test_input($_POST['bill_number']); $bill_date = test_input($_POST['bill_date']); $job_number = last_job(); $accesable_value= null ; $comission_acc= null ; $discount= null ; $paid_am= null ; $sql = $conn->query("CALL insert_temp_bill('$bill_number','$bill_date','$accesable_value','$comission_acc','$discount','$paid_am','$job_number',@p_msg)"); $sql2=$conn->query('SELECT @p_msg'); $getmsg=$sql2->fetch_array(); $msg=$getmsg['@p_msg']; if($sql){ ?> <table class="table table-striped" border="0"> <tr> <td colspan="2"> <div class="alert alert-info"> <strong>Success</strong>, <?php echo $msg; ?> </div> </td> </tr> <tr> <td>Bill Number</td> <td><?php echo $bill_number ?></td> </tr> <tr> <td>Bill Date</td> <td><?php echo $bill_date ?></td> </tr> <tr> <td>Job No.</td> <td><?php echo $job_number; ?></td> </tr> </table> <?php } else{ echo 'Something Wrong'; } } ?><file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); if($_POST ){ $id=$_POST['id']; $particilar=$_POST['particilar']; $qty=$_POST['qty']; $last_bill_id=last_bill(); $sql=$conn->query("CALL insert_temp_particular_d('$id','$particilar','$qty','$last_bill_id',@p_msg)"); $msg=show_p_o_msg(); if($sql){ ?> <div class="alert alert-success alert-dismissable "> <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a> <center><strong>Success!</strong> </center> <center><h6> <?php echo $msg; ?> </h6></center> </div> <?php } } ?> <file_sep><?php include('../db/dbconfig.php'); include('../inc/function.php'); if( $_POST ){ $bill_id = test_input($_POST['bill_id']); $pay_date = test_input($_POST['pay_date']); $pay_amount = test_input($_POST['pay_amount']); $sql = $conn->query("CALL insert_payment('$bill_id','$pay_amount','$pay_date',@p_msg)"); if($sql){ echo show_p_o_msg(); } else{ echo 'Something wrong'; } } ?><file_sep><div class="content-wrapper"> <div class="container-fluid"> <!-- Breadcrumbs--> <ol class="breadcrumb"> <li class="breadcrumb-item"> <a href="cnf.php">Home</a> </li> <li class="breadcrumb-item active">Add New Port</li> </ol> <div class="col-md-2 pull-left"></div> <form class="form-inline form-custom col-md-8" action=" " method="POST" autocomplete="on"> <center> <center><h2>Enter Port</h2></center> <hr /> <div class="form-group"> <label for="particuler">New Port:</label>&nbsp;&nbsp; <input type="text" class="form-control" name="port" placeholder="Enter a particuler field" required /> </div> <br /> <input style="" type="submit" class="btn submit_btn" value="submit" name="port_add" /> </center> </form> </div> <?php insert_port('port');?>
2a72dd759ea6b4d1cd23857534a210df7ce91459
[ "Markdown", "SQL", "PHP" ]
33
PHP
sabbir268/CNF
6e3cb6503471d38ae8a98a48e146c5d51ae3e453
73620a4c75a9b2fbda39741cf74be31e6ef6d663
refs/heads/master
<file_sep><?php $pages = [ "Template:Test" => "Template/Test.mediawiki", "Category:Test Category" => "Category/Test_Category.mediawiki", ]; <file_sep>Page Importer ============= [![Build Status](https://travis-ci.org/enterprisemediawiki/PageImporter.svg?branch=master)](https://travis-ci.org/enterprisemediawiki/PageImporter) Extension to provide the ability to have extension-defined pages. Extensions can define directories of files which map to wiki pages, and will be synced with the files anytime `php extensions/PageImporter/importPages.php` is run. Additionally, the current state of the wiki's pages (that are tracked by an extension) can be exported to the extension by doing `php extensions/PageImporter/importPages.php --export`. ## Loading in MediaWiki PageImporter should be loaded using `wfLoadExtension`: ```php wfLoadExtension('PageImporter'); ``` It is still possible to load PageImporter with the legacy method, but this is deprecated: ```php require_once "$IP/extensions/PageImporter/PageImporter.php"; ``` Either way loads Page Importer into MediaWiki, however *PageImporter* does basically nothing on its own. It is expected to be used by other extensions. See below. ## Usage by extensions Extensions can register pages to be imported by registering a hook handler to their `extension.json`: ```json "Hooks": { "PageImporterRegisterPageLists": "MyExtension::onPageImporterRegisterPageLists" } ``` Then create a hook handling function: ```php public static function onPageImporterRegisterPageLists( array &$pageLists ) { // The array key (here 'MyExtension') should be a unique name, generally // your extension's name $pageLists['MyExtension'] = [ // list of pages to create and the corresponding files to use as content "pages" => [ "Template:Meeting" => "Template/Meeting.mediawiki", "Category:Meeting" => "Category/Meeting.mediawiki", "Form:Meeting" => "Form/Meeting.mediawiki", "Property:Related article" => "Property/Related article.mediawiki", ], // the directory where all paths in your list of pages are based from "root" => __DIR__ . '/pages', // edit summary used when PageImporter edits pages "comment" => "Updated with content from Extension:MyExtension version 1.0.0" ]; } ``` Note that here the `pages` key has an array of pages. Alternatively, `pages` can be a string representing the path to a file containing a list of pages. For example: ```php $pageLists['MyExtension'] = [ // ... 'pages' => __DIR__ . '/pages.php', // ... ]; ``` However, the method of having a separate file is not preferred because it prevents other extensions from being able to alter which pages are imported/exported (see section below). As such, this method may be removed in a future version. ## Altering other extension's pages Sometimes pages from one extension may conflict with another. One possible method to avoid this is for an extension to detect if another extension is present and unset the page from that extension. This can be done with another hook, `PageImporterBeforeImportOrExport`. ```json "Hooks": { "PageImporterBeforeImportOrExport": "MyExtension::onPageImporterBeforeImportOrExport" } ``` ```php public static function onPageImporterBeforeImportOrExport( array &$pageLists ) { // Remove the "Property:Related article" page from another extension if ( isset( $pageLists['SemanticMeetingMinutes'] ) ) { unset( $pageLists['SemanticMeetingMinutes']['pages']['Property:Related article'] ); } } ``` ## Deprecated method of registering pages ```php PageImporter::registerPageList( "MyExtension", // a unique name, generally your extension's name __DIR__ . "/pages.php", // a php file that maps MediaWiki wikitext files to wiki pages __DIR__ . "/pages", // the directory where all paths in your pages.php file are based from "Updated with content from Extension:MyExtension version 1.0.0" // edit summary ); ``` ## Pages file format The PHP file should be in the following format. Essentially you need to map page names with file paths. The file paths are based from the directory mentioned above. ```php { <?php $pages = array( "Template:Meeting" => "Template/Meeting.mediawiki", "Template:Meeting minutes" => "Template/Meeting minutes.mediawiki", "Form:Meeting" => "Form/Meeting.mediawiki", "Form:Meeting Minutes" => "Form/Meeting Minutes.mediawiki", "Category:Meeting" => "Category/Meeting.mediawiki", "Category:Meeting Minutes" => "Category/Meeting Minutes.mediawiki", "Property:Related article" => "Property/Related article.mediawiki", "Property:Synopsis" => "Property/Synopsis.mediawiki", ); } ``` ## Directory structure Whether putting pages in a separate files or not, the directory structure of the examples in this README looks like: ``` MyExtension MyExtension.php pages.php pages Template Meeting.mediawiki Meeting Minutes.mediawiki Form Meeting.mediawiki Meeting Minutes.mediawiki Category Meeting.mediawiki Meeting Minutes.mediawiki Property Related article.mediawiki Synopsis.mediawiki ``` <file_sep><?php /** * This script updates the extensions managed by the it * * Usage: * no parameters * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @author <NAME> * @ingroup Maintenance */ // @todo: does this always work if extensions are not in $IP/extensions ?? // this was what was done by SMW $basePath = getenv( 'MW_INSTALL_PATH' ) !== false ? getenv( 'MW_INSTALL_PATH' ) : __DIR__ . '/../..'; require_once $basePath . '/maintenance/Maintenance.php'; class PageImporterImportPages extends Maintenance { // phpcs:ignore MediaWiki.Files.ClassMatchesFilename.NotMatch public function __construct() { parent::__construct(); $this->mDescription = "Imports pages defined by this and other extensions."; // addOption ($name, $description, $required=false, $withArg=false, $shortName=false) $this->addOption( 'limit-to-groups', 'Specify which groups of pages to import' ); $this->addOption( 'dry-run', 'See what would be changed without making changes', false, false ); $this->addOption( 'export', 'Export pages to files rather than import', false, false ); } public function execute() { $groupsString = $this->getOption( 'limit-to-groups' ); if ( $groupsString ) { $limitToGroups = explode( ',', $groupsString ); foreach ( $limitToGroups as $i => $g ) { $limitToGroups[$i] = trim( $g ); } } else { $limitToGroups = false; } $pageImporter = new PageImporter(); // export pages if ( $this->getOption( 'export' ) ) { $pageImporter->exportPagesToFiles( $this, $limitToGroups ); $this->output( "\n## Finished exporting pages.\n" ); } // import pages else { $pageImporter->import( $this, $limitToGroups ); $this->output( "\n## Finished importing pages.\n" ); } } /** * just a wrapper on output() because output() is protected and the * PageImporter class needs to call it directly. * * @param string $output Text to print */ public function showOutput( $output ) { $this->output( $output ); } } $maintClass = "PageImporterImportPages"; require_once RUN_MAINTENANCE_IF_MAIN; <file_sep>#!/bin/bash # # Shameless stolen from SMW set -ex cd .. ## Use sha (master@5cc1f1d) to download a particular commit to avoid breakages ## introduced by MediaWiki core if [[ "$MW" == *@* ]] then arrMw=(${MW//@/ }) MW=${arrMw[0]} SOURCE=${arrMw[1]} else MW=$MW SOURCE=$MW fi wget https://github.com/wikimedia/mediawiki/archive/$SOURCE.tar.gz -O $MW.tar.gz tar -zxf $MW.tar.gz mv mediawiki-* mw cd mw ## MW 1.25 requires Psr\Logger if [ -f composer.json ] then composer install fi if [ "$DB" == "postgres" ] then # See #458 sudo /etc/init.d/postgresql stop # Travis@support: Try adding a sleep of a few seconds between starting PostgreSQL # and the first command that accesses PostgreSQL sleep 3 sudo /etc/init.d/postgresql start sleep 3 psql -c 'create database its_a_mw;' -U postgres php maintenance/install.php --dbtype $DB --dbuser postgres --dbname its_a_mw --pass nyan TravisWiki admin --scriptpath /TravisWiki else mysql -e 'create database its_a_mw;' php maintenance/install.php --dbtype $DB --dbuser root --dbname its_a_mw --dbpath $(pwd) --pass nyan TravisWiki admin --scriptpath /TravisWiki fi <file_sep>#! /bin/bash set -ex BASE_PATH=$(pwd) cd .. MW_INSTALL_PATH=$(pwd)/mw cd $MW_INSTALL_PATH/extensions/PageImporter php importPages.php RED='\033[0;31m' GREEN='\033[0;32m' BLUE='\033[0;34m' NC='\033[0m' # No Color fn_compare_file_with_page () { PAGE_NAME="$1" FILE_NAME="$2" INTEND_MATCH="$3" PAGE_VALUE=$(php $MW_INSTALL_PATH/maintenance/getText.php "$PAGE_NAME") FILE_VALUE=$(cat $MW_INSTALL_PATH/extensions/ExampleExtension/ImportFiles/$FILE_NAME) if [ "$INTEND_MATCH" = "no" ]; then if [ "$PAGE_VALUE" = "$FILE_VALUE" ]; then echo -e "$RED$PAGE_NAME matches $FILE_NAME and it should not$NC" && false else echo -e "$GREEN$PAGE_NAME does not match $FILE_NAME and it should not$NC" fi else if [ "$PAGE_VALUE" = "$FILE_VALUE" ]; then echo -e "$GREEN$PAGE_NAME matches $FILE_NAME$NC" else echo -e "$RED$PAGE_NAME does not match $FILE_NAME$NC" && false fi fi } fn_compare_file_with_page "Template:Test" "Template/Test.mediawiki" fn_compare_file_with_page "Category:Test_Category" "Category/Test_Category.mediawiki" # Edit pages echo "New template text" | php $MW_INSTALL_PATH/maintenance/edit.php "Template:Test" echo "New category text" | php $MW_INSTALL_PATH/maintenance/edit.php "Category:Test_Category" fn_compare_file_with_page "Template:Test" "Template/Test.mediawiki" "no" fn_compare_file_with_page "Category:Test_Category" "Category/Test_Category.mediawiki" "no" # Push the changes from the wiki back to the extension's files php importPages.php --export fn_compare_file_with_page "Template:Test" "Template/Test.mediawiki" fn_compare_file_with_page "Category:Test_Category" "Category/Test_Category.mediawiki" <file_sep><?php /** * Class enabling page import and export * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @author <NAME> */ class PageImporter { // phpcs:ignore MediaWiki.Files.ClassMatchesFilename.NotMatch /** * @var array */ protected static $pageLists = []; /** * Add description * * @param string $dryRun add description * @return null */ public function __construct( $dryRun = false ) { $this->dryRun = $dryRun; $pageLists = []; Hooks::run( 'PageImporterRegisterPageLists', [ &$pageLists ] ); self::$pageLists = array_merge( self::$pageLists, $pageLists ); } /** * Register a list of pages to be imported * * @param string $groupName an identifying string for a group of pages * @param string $pages the path to the file defining the pages to be imported * @param string $root the path to the root of the files * @param string $comment comment to be added to each file import * @return null */ public static function registerPageList( $groupName, $pages, $root, $comment ) { self::$pageLists[$groupName] = [ "pages" => $pages, "root" => $root, "comment" => $comment ]; } /** * Perform import of pages from files * * @param mixed $outputHandler How to output text. Use maintenance->output() * if possible. * @param string $limitToGroups Which groups of pages to import * @return null */ public function import( $outputHandler = false, $limitToGroups = false ) { if ( ! $outputHandler ) { $outputHandler = $this; } $pageLists = self::$pageLists; Hooks::run( 'PageImporterBeforeImportOrExport', [ &$pageLists ] ); $groupsToImport = []; if ( $limitToGroups ) { foreach ( $limitToGroups as $group ) { $groupsToImport[$group] = $pageLists[$group]; } } else { $groupsToImport = $pageLists; } foreach ( $groupsToImport as $groupName => $groupInfo ) { $outputHandler->showOutput( "\nStarting import from $groupName.\n\n" ); $root = $groupInfo["root"]; $comment = $groupInfo["comment"]; $pages = $this->getPages( $groupInfo['pages'] ); global $wgUser; $wgUser = User::newSystemUser( 'Maintenance script', [ 'steal' => true ] ); foreach ( $pages as $pageTitleText => $filePath ) { $wikiPage = WikiPage::factory( Title::newFromText( $pageTitleText ) ); $wikiPageContent = $wikiPage->getContent(); if ( $wikiPageContent ) { $wikiPageText = $wikiPageContent->getNativeData(); } else { $wikiPageText = ''; } $filePageContent = file_get_contents( $root . "/$filePath" ); if ( trim( $filePageContent ) !== trim( $wikiPageText ) ) { if ( $this->dryRun ) { $outputHandler->showOutput( "$pageTitleText would be changed.\n" ); // @todo: show diff? } else { $outputHandler->showOutput( "$pageTitleText changed.\n" ); $wikiPage->doEditContent( new WikitextContent( $filePageContent ), $comment ); } } else { $outputHandler->showOutput( "No change for $pageTitleText\n" ); } } } } /** * Take pages on wiki and push their contents to files within the extension * * @param mixed $outputHandler How to output text. Use maintenance->output() * if possible. * @param string $limitToGroups Which groups of pages to import * @return null */ public function exportPagesToFiles( $outputHandler = false, $limitToGroups = false ) { if ( ! $outputHandler ) { $outputHandler = $this; } $pageLists = self::$pageLists; Hooks::run( 'PageImporterBeforeImportOrExport', [ &$pageLists ] ); $groupsToImport = []; if ( $limitToGroups ) { foreach ( $limitToGroups as $group ) { $groupsToImport[$group] = $pageLists[$group]; } } else { $groupsToImport = $pageLists; } foreach ( $groupsToImport as $groupName => $groupInfo ) { $outputHandler->showOutput( "\nStarting export from $groupName.\n\n" ); $root = $groupInfo["root"]; $comment = $groupInfo["comment"]; $pages = $this->getPages( $groupInfo['pages'] ); foreach ( $pages as $pageTitleText => $filePath ) { $wikiPage = WikiPage::factory( Title::newFromText( $pageTitleText ) ); $wikiPageContent = $wikiPage->getContent(); if ( $wikiPageContent ) { $wikiPageText = $wikiPageContent->getNativeData(); } else { $wikiPageText = ''; } $filePageContent = file_get_contents( $root . "/$filePath" ); if ( trim( $filePageContent ) !== trim( $wikiPageText ) ) { if ( $this->dryRun ) { $outputHandler->showOutput( "$pageTitleText would be exported.\n" ); // @todo: show diff? } else { $outputHandler->showOutput( "$pageTitleText exported.\n" ); file_put_contents( $root . "/$filePath", $wikiPageText ); } } else { $outputHandler->showOutput( "No change for $pageTitleText\n" ); } } } } /** * Function used if a maintenance class is not provided * * @param string $output Text to output * @return null */ public function showOutput( $output ) { echo $output; } /** * Function used to extract a PHP array from a file or just return an array * if an array passed in. * * @param string|array $filepathOrArray is either a file path to file * containing a variable called '$pages' or is an array * of pages. * @return array */ public function getPages( $filepathOrArray ) { if ( is_string( $filepathOrArray ) ) { // if string, it's a path to a file containing the pages require $filepathOrArray; // return $pages variable defined in file return $pages; } else { // if not a string, assume array of pages return $filepathOrArray; } } } <file_sep><?php class ExampleExtension { // phpcs:ignore MediaWiki.Files.ClassMatchesFilename.NotMatch /** * Hook handler for PageImporter::PageImporterRegisterPageLists * * @param array &$pageLists Array of page import definitions supplied by * extensions * @return null */ public static function onPageImporterRegisterPageLists( array &$pageLists ) { // The array key (here 'MyExtension') should be a unique name, generally // your extension's name $pageLists['ExampleExtension'] = [ // list of pages to create and the corresponding files to use as content "pages" => [ "Template:Test" => "Template/Test.mediawiki", "Category:Test Category" => "Category/Test_Category.mediawiki", ], // the directory where all paths in your list of pages are based from "root" => __DIR__ . '/ImportFiles', // edit summary used when PageImporter edits pages "comment" => "Updated with content from Extension:ExampleExtension version 1.0.0" ]; } } <file_sep><?php # Not a valid entry point, skip unless MEDIAWIKI is defined if ( ! defined( 'MEDIAWIKI' ) ) { die( 'MeetingMinutes extension' ); } $GLOBALS['wgExtensionCredits']['other'][] = [ 'path' => __FILE__, 'name' => 'Example Extension', 'url' => 'http://github.com/enterprisemediawiki', 'author' => '<NAME>', 'descriptionmsg' => 'example-extension-desc', 'version' => '0.0.0' ]; $GLOBALS['wgMessagesDirs']['ExampleExtension'] = __DIR__ . '/i18n'; // Dependency: Extension:PageImporter. PageImporter::registerPageList( "ExampleExtension", __DIR__ . "/ImportFiles/pages.php", __DIR__ . "/ImportFiles", "Updated with content from Extension:ExampleExtension version 0.0.0" ); <file_sep><?php /** * Extension to provide the ability to have extension-defined pages * * Documentation: https://github.com/enterprisemediawiki/PageImporter * Support: https://github.com/enterprisemediawiki/PageImporter * Source code: https://github.com/enterprisemediawiki/PageImporter * * @file PageImporter.php * @addtogroup Extensions * @author <NAME> * @copyright © 2014 by <NAME> * @license GPL-3.0-or-later */ # Not a valid entry point, skip unless MEDIAWIKI is defined if ( ! defined( 'MEDIAWIKI' ) ) { die( 'PageImporter extension' ); } $GLOBALS['wgExtensionCredits']['other'][] = [ 'path' => __FILE__, 'name' => 'Page Importer', 'url' => 'http://github.com/enterprisemediawiki/PageImporter', 'author' => '<NAME>', 'descriptionmsg' => 'pageimporter-desc', 'version' => '0.1.0' ]; $GLOBALS['wgMessagesDirs']['PageImporter'] = __DIR__ . '/i18n'; // Autoload setup class (location of parser function definitions) // $GLOBALS['wgAutoloadClasses']['PageImporter'] = __DIR__ . '/PageImporter.class.php'; // PageImporter needs to be loaded immediately so other extensions can use the // PageImporter::registerPageList() static method require_once __DIR__ . '/PageImporter.class.php'; <file_sep>#!/bin/bash # # Adapted from SMW set -ex BASE_PATH=$(pwd) cd .. MW_INSTALL_PATH=$(pwd)/mw echo "base path:" ls $BASE_PATH echo "mw install path:" ls $MW_INSTALL_PATH cp -r $BASE_PATH $MW_INSTALL_PATH/extensions/PageImporter cd $MW_INSTALL_PATH echo "" >> LocalSettings.php echo "\$wgShowExceptionDetails = true;" >> LocalSettings.php echo "" >> LocalSettings.php if [ "$LOAD_TYPE" = "extension.json" ]; then echo "wfLoadExtension('PageImporter');" >> LocalSettings.php else echo "require_once \"$MW_INSTALL_PATH/extensions/PageImporter/PageImporter.php\";" >> LocalSettings.php fi echo "" >> LocalSettings.php cp -r $MW_INSTALL_PATH/extensions/PageImporter/tests/ExampleExtension $MW_INSTALL_PATH/extensions/ExampleExtension echo "" >> LocalSettings.php if [ "$LOAD_TYPE" = "extension.json" ]; then echo "wfLoadExtension('ExampleExtension');" >> LocalSettings.php else echo "require_once \"$MW_INSTALL_PATH/extensions/ExampleExtension/ExampleExtension.php\";" >> LocalSettings.php fi echo "" >> LocalSettings.php
f8f1db99322ffd69a46e51cc261e43ce4e0b00e6
[ "Markdown", "PHP", "Shell" ]
10
PHP
enterprisemediawiki/PageImporter
ab90aab31e94ec8d404160d66e951ae08851b43f
665ebe9fc30d43077136795d781a9a77c4e0ff2b
refs/heads/main
<file_sep>#!/bin/bash cd backend-datasource-plugin yarn install yarn dev cd ../ cd datasource-plugin yarn install yarn dev cd ../ cd panel-plugin yarn install yarn dev cd ../ <file_sep>version: "3.5" services: grafana: image: grafana/grafana:7.2.1 restart: always ports: - 3010:3000 volumes: - ./plugins/:/var/lib/grafana/plugins/ environment: GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_admin_password secrets: - grafana_admin_password secrets: grafana_admin_password: file: ./secrets/.grafana_admin_password <file_sep># grafana-plugins ## 作り方 ```bash $ npx @grafana/toolkit plugin:create my-grafana-plugin ? Select plugin type ❯ Panel Plugin Datasource Plugin Backend Datasource Plugin $ cd my-grafana-plugin $ yarn install $ yarn dev ``` <https://grafana.com/docs/grafana/latest/developers/plugins/> ## Build a panel plugin 1. Introduction 2. Set up your environment 1. Grafana pluginフォルダをマウント。 2. Grafana を再起動。 3. Create a new plugin 1. `作り方`に従ってpluginを生成。 4. Anatomy of a plugin 1. `dist/plugins.json`の`type, name, id`に適切な値を設定する。 2. `module.ts`を作成する。これはエントリポイントを記述するもの。 5. Panel plugins 1. Grafana 6.0はAngularJSベースだったが、現時点はReactJSベースにすべき。 2. `src/SimplePanel.tsx`で`props` 3. 開発の流れは以下の通り。 1. まずパネルをダッシュボードに追加する。 1. Grafanaをブラウザで開く。 2. 新しいダッシュボードとパネルを作成する。 3. 可視化タイプのリストからあなたのパネルを選択する。 4. ダッシュボードを保存する。 2. 次に手順を実施する。 1. `SimplePanel.tsx`を適当に変更する。 2. `yarn dev`を実行する。 3. ブラウザでGrafanaを再表示する。 6. Add panel options 7. Create dynamic panels using data frames 8. Configurations ## Build a source plugin 1. Introduction 2. Set up your environment 1. Grafana pluginフォルダをマウント。 2. Grafana を再起動。 3. Create a new plugin 1. `作り方`に従ってpluginを生成。 4. Anatomy of a plugin 1. `dist/plugins.json`の`type, name, id`に適切な値を設定する。 2. `module.ts`を作成する。これはエントリポイントを記述するもの。 5. Data source plugins 1. query メソッドは、外部DBからデータを取得し、Grafanaが認識できる形式でデータを返す。 2. testDatasource メソッドは、動作確認用のデートを読み込む。 6. Data frames 1. `const query = defaults(target, defaultQuery);`でqueryのデフォルトクエリを読み込む。 2. data frameを作成する。 3. data frame にvalueを入れる。 7. Define a query 1. クエリモデルを定義する。つまり、クエリで送信する変数。 2. モデルをフォームにバインドする。 3. queryメソッド内でプロパティを使用する。 8. Configure your data source 1. オプションモデルを定義する。 2. モデルをフォームにバインドする。 3. オプションを使用する。 9. Get data from an external API 10. Configurations ## Build a data source backend plugin 1. Introduction 2. Set up your environment 1. Grafana pluginフォルダをマウント。 2. Grafana を再起動。 3. Create a new plugin 1. `作り方`に従ってpluginを生成。 4. Anatomy of a backend plugin 1. `dist/plugins.json`の`type, name, id`に適切な値を設定する。 2. `module.ts`を作成する。これはエントリポイントを記述するもの。 5. Implement data queries 1. 6. Add support for health checks 1. 7. Enable Grafana Alerting 1. `yarn build` 8. Configurations ## プラグインの種類 プラグインは4種類ある。 > Grafanaプラグインには4つの主要なフレーバーがあります。これらは、データソース、バックエンド、パネル、アプリです。それぞれが独自の利点と制限を備えて設計されています。ここでは、それぞれの簡単な概要とそれらが達成することを示します。 > > - **データソース**:これらのプラグインを使用すると、HTTPを介して通信できる任意のデータベースとの対話を有効にできます。 > - **バックエンド**:バックエンドでデータソースをラップして、データのアラートを有効にします。 > - **パネル**:フロントエンドでデータをレンダリングするカスタム方法を提供します。 > - **アプリ**:ユーザーがページのまったく新しいスタイルを作成し、パネルとデータソースを一緒にラップし、システムのまったく異なるエクスペリエンスを提供できるようにします。 > > <https://qiita.com/MetricFire/items/95f0d6424eaac2164095>
adafce403d4a2d71780a2901f92cc671394a370e
[ "Markdown", "YAML", "Shell" ]
3
Shell
samples-projects/sample-grafana-plugins
831c1fc494d2c8eb6bbd29d6f81d802b326897ef
531a7b164d9e860954735253d703c553d15853b8
refs/heads/master
<file_sep>package ru.netology; import java.util.Scanner; public class CalculatorApp { static final int NUMBER_OF_MONTHS_IN_YEAR = 12; static final int NUMBER_OF_SIMBOLS_AFTER_COMMA = 2; public static void main(String[] args) { System.out.println("Кредитный калькулятор"); Scanner scanner = new Scanner(System.in); System.out.println("Введите сумму кредита:"); String inputCreditAmount = scanner.nextLine(); System.out.println("Введите годовую процентную ставку:"); String inputInterestRate = scanner.nextLine(); System.out.println("Введите срок кредита в месяцах:"); String inputTerm = scanner.nextLine(); double monthlyPayment = calculateMonthlyPayment(inputCreditAmount, inputInterestRate, inputTerm); double overpayment = calculateOverpayment(inputCreditAmount, inputInterestRate, inputTerm); double totalRefundAmount = calculateTotalRefundAmount(inputCreditAmount, inputInterestRate, inputTerm); String allOperations = addToString(monthlyPayment, overpayment, totalRefundAmount); System.out.println(allOperations); } public static String addToString(double monthlyPayment, double overpayment, double totalRefundAmount) { return "Результаты расчетов кредитного калькулятора: \n" + "Ежемесячный платеж: " + monthlyPayment + " р. Переплата за весь период: " + overpayment + " р. " + "Общая сумма к возврату в банк: " + totalRefundAmount + " р."; } public static double calculateMonthlyPayment(String inputCreditAmount, String inputInterestRate, String inputTerm) { double monthlyPayment = 0; try { double creditAmount = Double.parseDouble(inputCreditAmount); double interestRate = Double.parseDouble(inputInterestRate); double term = Double.parseDouble(inputTerm); if (creditAmount <= 0 || interestRate <= 0 || term <= 0) { System.out.println("Сумма кредита или процентная ставка или срок кредита не может быть меньше, либо равен нулю."); return 0; } double monthlyInterestRate = interestRate / (NUMBER_OF_MONTHS_IN_YEAR * 100); double scale = Math.pow(10, NUMBER_OF_SIMBOLS_AFTER_COMMA); monthlyPayment = Math.ceil(scale * (creditAmount * monthlyInterestRate / (1 - Math.pow(1 + monthlyInterestRate, -term)))) / scale; return monthlyPayment; } catch (NumberFormatException e) { System.out.println("Введено не число"); } return monthlyPayment; } public static double calculateOverpayment(String inputCreditAmount, String inputInterestRate, String inputTerm) { double overpayment = 0; try { double creditAmount = Double.parseDouble(inputCreditAmount); double interestRate = Double.parseDouble(inputInterestRate); double term = Double.parseDouble(inputTerm); if (creditAmount <= 0 || interestRate <= 0 || term <= 0) { System.out.println("Сумма кредита или процентная ставка или срок кредита не может быть меньше, либо равен нулю."); return 0; } double monthlyPayment = calculateMonthlyPayment(inputCreditAmount, inputInterestRate, inputTerm); double scale = Math.pow(10, NUMBER_OF_SIMBOLS_AFTER_COMMA); overpayment = Math.ceil(scale * ((monthlyPayment * term) - creditAmount)) / scale; return overpayment; } catch (NumberFormatException e) { System.out.println("Введено не число"); } return overpayment; } public static double calculateTotalRefundAmount(String inputCreditAmount, String inputInterestRate, String inputTerm) { double totalRefundAmount = 0; try { double creditAmount = Double.parseDouble(inputCreditAmount); double interestRate = Double.parseDouble(inputInterestRate); double term = Double.parseDouble(inputTerm); if (creditAmount <= 0 || interestRate <= 0 || term <= 0) { System.out.println("Сумма кредита или процентная ставка или срок кредита не может быть меньше, либо равен нулю."); return 0; } double overpayment = calculateOverpayment(inputCreditAmount, inputInterestRate, inputTerm); double scale = Math.pow(10, NUMBER_OF_SIMBOLS_AFTER_COMMA); totalRefundAmount = Math.ceil(scale * (creditAmount + overpayment)) / scale; return totalRefundAmount; } catch (NumberFormatException e) { System.out.println("Введено не число"); } return totalRefundAmount; } } <file_sep>rootProject.name = 'LoanCalculatorApp'
9384d49101382a2a58df1c41291ffb437373f982
[ "Java", "Gradle" ]
2
Java
MaryGavrilova/LoanCalculatorApp
b5b1d84dcabd367ceb517492af81313066239157
3562161bdd55c204d83886df34030a619a205f21
refs/heads/master
<file_sep>/** * Created by imran on 8/17/2016. */ /* Popup Model box html --> <form class="form-horizontal" enctype="multipart/form-data" role="form" method="POST" action=" "> <div class="model" onclick="model()" style="display:none" > <div class="col-sm-8 model-body"> <div class="model-content animated zoomIn"> </div> </div> </div> </form> // popup confirmation model for deletion <div class="conformbox" style="display:none" > <div class="col-sm-5 conformbox-body"> <div class="conformbox-content animated zoomIn"> <p> Do You Really Want to Delete This Record?</p> <span> <button class="btn btn-default" id="confirm" autofocus> Confirm </button> <button class="btn btn-danger right" onclick="confirmbox()" >Cancel</button> </span> </div> </div> </div> */ /* css for model .model{ position: fixed; top:0px; left:0px; right:0px; bottom:0px; background: rgba(22,22,2,.5); z-index: 99999; } .model-body{ padding-top:100px; padding-bottom:50px; margin-left:auto; margin-right: auto; float:none; min-height:100px; z-index: 99999; height:100%; overflow: auto; } .model-body::-webkit-scrollbar { width: 0px; } .model-body::-webkit-scrollbar-track { -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); border-radius: 10px; } .model-body::-webkit-scrollbar-thumb { border-radius: 10px; -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5); } .model-content{ float: left; width:100%; background-color: white; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; padding:10px; } .model-content h2 { text-align: center; padding: 0px; margin: 0px; font-style: italic; border-bottom: 2px solid rgba(9, 158, 58, 0.6); font-size: 18px; margin-bottom: 10px; } // conform box .conformbox{ position: fixed; top:0px; left:0px; right:0px; bottom:0px; background: rgba(22,22,2,.5); z-index: 99999; } .conformbox-body{ margin-top:100px; margin-left:auto; margin-right: auto; float:none; min-height:100px; z-index: 99999; } .conformbox-content{ float: left; width:100%; background-color: white; -webkit-border-radius:4px; -moz-border-radius:4px; border-radius:4px; padding:10px; } .conformbox-content > h2 { text-align: center; padding: 0px; margin: 0px; font-style: italic; border-bottom: 2px solid rgba(9, 158, 58, 0.6); font-size: 18px; } .conformbox-content >p{ margin: 0 0 10px; color: #01987d; font-size: 20px; } .conformbox-content >span{ background: #f6f2e8; width: 100%; float: left; } .right{ float:right !important; }*/ // for popup model $(".model-content").click(function(e) { e.stopPropagation(); }); // function for popup model function model() { if($('.model').css('display') == 'none') { $('.model').fadeIn(1000); }else{ $('.model').fadeOut(); } } // function for popup conform model function conformbox(id,action) { $('#confirm').attr('data-id',id); $('#confirm').attr('data-action',action); if($('.conformbox').css('display') == 'none') { $('.conformbox').fadeIn(); }else{ $('.conformbox').fadeOut(); } }
5d61b983ef2d17b2735a98eb5242919e488a81ee
[ "JavaScript" ]
1
JavaScript
emrancu/ModelBox
47affa50582064c65897c55ad4472e8d6023d77e
192693c321cd2b56e9f2d8e2cf15dbc086a5c936
refs/heads/master
<file_sep>IPcamera ======== 视频监控demo 这是一个android项目,可以通过adt直接导入 <file_sep>package com.ipcamer.demo; import java.nio.ByteBuffer; import java.util.Date; import object.p2pipcam.nativecaller.BridgeService; import object.p2pipcam.nativecaller.BridgeService.p2pPlayListener; import object.p2pipcam.nativecaller.NativeCaller; import android.app.Activity; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.PixelFormat; import android.graphics.PointF; import android.graphics.Shader.TileMode; import android.graphics.drawable.BitmapDrawable; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.DisplayMetrics; import android.util.FloatMath; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.OnGestureListener; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.TextView; import android.widget.Toast; public class PlayActivity extends Activity implements OnTouchListener, OnGestureListener, OnClickListener, p2pPlayListener { private static final String LOG_TAG = "PlayActivity"; private static final int AUDIO_BUFFER_START_CODE = 0xff00ff; private SurfaceView playSurface = null; private SurfaceHolder playHolder = null; private byte[] videodata = null; private int videoDataLen = 0; private int nVideoWidth = 0; private int nVideoHeight = 0; private View progressView = null; private boolean bProgress = true; private GestureDetector gt = new GestureDetector(this); @SuppressWarnings("unused") private int nSurfaceHeight = 0; private int nResolution = 0; @SuppressWarnings("unused") private int nMode = 0; @SuppressWarnings("unused") private int nFlip = 0; @SuppressWarnings("unused") private int nFramerate = 0; private TextView textosd = null; private String strName = null;; private String strDID = null;; private int streamType = ContentCommon.MJPEG_SUB_STREAM; private View osdView = null; private boolean bDisplayFinished = true; private surfaceCallback videoCallback = new surfaceCallback(); private int nPlayCount = 0; private CustomBuffer AudioBuffer = null; private AudioPlayer audioPlayer = null; private int nP2PMode = ContentCommon.PPPP_MODE_P2P_NORMAL; private TextView textTimeoutTextView = null; private boolean bTimeoutStarted = false; private int nTimeoutRemain = 180; private boolean isTakeVideo = false; private PopupWindow mPopupWindowProgress; private ImageView vidoeView; private ImageView videoViewStandard; private ImageButton ptzPlayMode; private Button ptzResolutoin; private boolean isTakepic = false; private boolean isExit = false; private PopupWindow resolutionPopWindow; private int timeTag = 0; private int timeOne = 0; private int timeTwo = 0; private BitmapDrawable drawable = null; private MyBrodCast brodCast = null; class MyBrodCast extends BroadcastReceiver { @Override public void onReceive(Context arg0, Intent arg1) { if (arg1.getIntExtra("ifdrop", 2) != 2) { PPPPMsgHandler.sendEmptyMessage(1004); } } } /** * 在UI线程中刷新界面状态 * **/ private Handler PPPPMsgHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1004: Toast.makeText(PlayActivity.this, "相机断线", 0).show(); PlayActivity.this.finish(); break; default: break; } } }; //请求实时视频流 private class surfaceCallback implements SurfaceHolder.Callback {//表面回调 public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { if (holder == playHolder) { streamType = 10; NativeCaller.StartPPPPLivestream(strDID, streamType);//直接调用提供的函数//请求实时视频流设备id } } public void surfaceCreated(SurfaceHolder holder) { } public void surfaceDestroyed(SurfaceHolder holder) { // finish(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mPopupWindowProgress != null && mPopupWindowProgress.isShowing()) { mPopupWindowProgress.dismiss(); } if (resolutionPopWindow != null && resolutionPopWindow.isShowing()) { resolutionPopWindow.dismiss(); } if (keyCode == KeyEvent.KEYCODE_BACK) { if (!bProgress) { Date date = new Date(); if (timeTag == 0) { timeOne = date.getSeconds(); timeTag = 1; Toast.makeText(PlayActivity.this, R.string.main_show_back,// 0).show(); } else if (timeTag == 1) { timeTwo = date.getSeconds(); if (timeTwo - timeOne <= 3) { Intent intent = new Intent("finish"); sendBroadcast(intent); PlayActivity.this.finish(); timeTag = 0; } else { timeTag = 1; Toast.makeText(PlayActivity.this, R.string.main_show_back, 0).show(); } } } else { showSureDialog1(); } return true; } if (keyCode == KeyEvent.KEYCODE_MENU) { if (!bProgress) { } else { showSureDialog1(); } } return super.onKeyDown(keyCode, event); } /**** * 退出确定dialog * */ public void showSureDialog1() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.app); builder.setTitle(getResources().getString(R.string.exit) + getResources().getString(R.string.app_name)); builder.setMessage(R.string.exit_alert); builder.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Process.killProcess(Process.myPid()); Intent intent = new Intent("finish"); sendBroadcast(intent); PlayActivity.this.finish(); } }); builder.setNegativeButton(R.string.str_cancel, null); builder.show(); } private void showToast(int i) { Toast.makeText(PlayActivity.this, i, 0).show(); } private void updateTimeout() { textTimeoutTextView.setText(getString(R.string.p2p_relay_mode_time_out) + nTimeoutRemain + getString(R.string.str_second)); } private Handler timeoutHandle = new Handler() { public void handleMessage(Message msg) { if (nTimeoutRemain > 0) { nTimeoutRemain = nTimeoutRemain - 1; updateTimeout(); Message msgMessage = new Message(); timeoutHandle.sendMessageDelayed(msgMessage, 1000); } else { if (!isExit) { Toast.makeText(getApplicationContext(), R.string.p2p_view_time_out, Toast.LENGTH_SHORT) .show(); } finish(); } } }; private void startTimeout() { if (!bTimeoutStarted) { Message msgMessage = new Message(); timeoutHandle.sendMessageDelayed(msgMessage, 1000); bTimeoutStarted = true; } } //预览模式时旋转进度条消失 private void setViewVisible() { if (bProgress) { bProgress = false; progressView.setVisibility(View.INVISIBLE); osdView.setVisibility(View.VISIBLE);//布局文件包括扫描在内的按钮 if (nP2PMode == ContentCommon.PPPP_MODE_P2P_RELAY) { updateTimeout(); textTimeoutTextView.setVisibility(View.VISIBLE); startTimeout(); } getCameraParams(); } } //和 implement p2pPlayListener有关 private Bitmap mBmp; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 1 || msg.what == 2) { setViewVisible(); } if (!isPTZPrompt) { isPTZPrompt = true; showToast(R.string.ptz_control); } switch (msg.what) { case 1: // h264 { Log.d("tagggg", "h264"); myGlSurfaceView.setVisibility(View.VISIBLE); vidoeView.setVisibility(View.GONE); int width = getWindowManager().getDefaultDisplay().getWidth(); int height = getWindowManager().getDefaultDisplay().getHeight(); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( width, width * 3 / 4); lp.gravity = Gravity.CENTER; myGlSurfaceView.setLayoutParams(lp); } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams( width, height); lp.gravity = Gravity.CENTER; myGlSurfaceView.setLayoutParams(lp); } myRender.writeSample(videodata, nVideoWidth, nVideoHeight); videoViewStandard.setVisibility(View.GONE); } break; case 2: // JPEG { // ptzTakeVideo.setVisibility(View.GONE); myGlSurfaceView.setVisibility(View.GONE); mBmp = BitmapFactory .decodeByteArray(videodata, 0, videoDataLen); if (mBmp == null) { Log.d(LOG_TAG, "bmp can't be decode..."); bDisplayFinished = true; return; } nVideoWidth = mBmp.getWidth(); nVideoHeight = mBmp.getHeight(); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { videoViewStandard.setVisibility(View.GONE); vidoeView.setVisibility(View.VISIBLE); vidoeView.setImageBitmap(mBmp); } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { videoViewStandard.setImageBitmap(mBmp); videoViewStandard.setVisibility(View.VISIBLE); vidoeView.setVisibility(View.GONE); } if (isTakepic) { isTakepic = false; // takePicture(mBmp); } } break; case 3: // { displayResolution(); } break; } if (msg.what == 1 || msg.what == 2) { // showTimeStamp(); bDisplayFinished = true; nPlayCount++; if (nPlayCount >= 100) { nPlayCount = 0; } } } }; protected void displayResolution() { /* * 0->640x480 1->320x240 2->160x120; 3->1280x720 4->640x360 5->1280x960 */ String strCurrResolution = null; switch (nResolution) { case 0:// vga strCurrResolution = "640x480"; break; case 1:// qvga strCurrResolution = "320x240"; break; case 2: strCurrResolution = "160x120"; break; case 3:// 720p strCurrResolution = "1280x720"; break; case 4: strCurrResolution = "640x360"; break; case 5: strCurrResolution = "1280x960"; break; default: return; } } private void getCameraParams() { NativeCaller.PPPPGetSystemParams(strDID, ContentCommon.MSG_TYPE_GET_CAMERA_PARAMS);//直接调用提供的函数 } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // getDataFromOther(); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.play); strName = SystemValue.deviceName;//利用SystemValue strDID = SystemValue.deviceId;//利用SystemValue findView(); InitParams(); AudioBuffer = new CustomBuffer(); audioPlayer = new AudioPlayer(AudioBuffer); // myvideoRecorder = new CustomVideoRecord(this, strDID); BridgeService.setP2pPlayListener(this);//p2pPlayListener实现 playHolder = playSurface.getHolder(); playHolder.setFormat(PixelFormat.RGB_565); playHolder.addCallback(videoCallback);//把流添加到控件的holder playSurface.setOnTouchListener(this);//添加触摸监听 playSurface.setLongClickable(true); getCameraParams(); // prompt user how to control ptz when first enter play SharedPreferences sharePreferences = getSharedPreferences("ptzcontrol", MODE_PRIVATE); isPTZPrompt = sharePreferences.getBoolean("ptzcontrol", false); if (!isPTZPrompt) { Editor edit = sharePreferences.edit(); edit.putBoolean("ptzcontrol", true); edit.commit(); } brodCast = new MyBrodCast(); IntentFilter filter = new IntentFilter(); filter.addAction("drop"); PlayActivity.this.registerReceiver(brodCast, filter); } private void InitParams() { DisplayMetrics dm = new DisplayMetrics(); this.getWindowManager().getDefaultDisplay().getMetrics(dm); nSurfaceHeight = dm.heightPixels; textosd.setText(strName); } private void StopAudio() { synchronized (this) { audioPlayer.AudioPlayStop(); AudioBuffer.ClearAll(); NativeCaller.PPPPStopAudio(strDID);//直接调用提供的函数 } } protected void setResolution(int Resolution) { Log.d("tag", "setResolution resolution:" + Resolution); NativeCaller.PPPPCameraControl(strDID, 0, Resolution);//直接调用提供的函数 设置分辨率等 } //绑定控件 private void findView() { playSurface = (SurfaceView) findViewById(R.id.playSurface); playSurface.setBackgroundColor(0xff000000); myGlSurfaceView = (GLSurfaceView) findViewById(R.id.myhsurfaceview); myRender = new MyRender(myGlSurfaceView);//画背景 myGlSurfaceView.setRenderer(myRender); //云台控制 imgUp = (ImageView) findViewById(R.id.imgup); imgDown = (ImageView) findViewById(R.id.imgdown); imgRight = (ImageView) findViewById(R.id.imgright); imgLeft = (ImageView) findViewById(R.id.imgleft); imgUp.setOnClickListener(this); imgDown.setOnClickListener(this); imgLeft.setOnClickListener(this); imgRight.setOnClickListener(this); vidoeView = (ImageView) findViewById(R.id.vedioview); videoViewStandard = (ImageView) findViewById(R.id.vedioview_standard); progressView = (View) findViewById(R.id.progressLayout); textosd = (TextView) findViewById(R.id.textosd); textTimeoutTextView = (TextView) findViewById(R.id.textTimeout); ptzResolutoin = (Button) findViewById(R.id.ptz_resoluti); ptzPlayMode = (ImageButton) findViewById(R.id.ptz_playmode); osdView = (View) findViewById(R.id.osdlayout);//布局文件包括正在连接旋转进度条 ptzResolutoin.setOnClickListener(this); ptzPlayMode.setOnClickListener(this); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.top_bg);//布局文件只包括扫描界面相反镜面 drawable = new BitmapDrawable(bitmap); drawable.setTileModeXY(TileMode.REPEAT, TileMode.REPEAT); drawable.setDither(true); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mBaseMatrix = new Matrix(); mSuppMatrix = new Matrix(); mDisplayMatrix = new Matrix(); videoViewStandard.setImageMatrix(mDisplayMatrix); } private boolean isDown = false; private boolean isSecondDown = false; private float x1 = 0; private float x2 = 0; private float y1 = 0; private float y2 = 0; //屏幕触摸 @Override public boolean onTouch(View v, MotionEvent event) { if (!isDown) { x1 = event.getX(); y1 = event.getY(); isDown = true; } switch (event.getAction() & MotionEvent.ACTION_MASK) { case MotionEvent.ACTION_DOWN: savedMatrix.set(matrix); start.set(event.getX(), event.getY()); mode = DRAG; originalScale = getScale(); break; case MotionEvent.ACTION_POINTER_UP: break; case MotionEvent.ACTION_UP: if (Math.abs((x1 - x2)) < 25 && Math.abs((y1 - y2)) < 25) { if (resolutionPopWindow != null && resolutionPopWindow.isShowing()) { resolutionPopWindow.dismiss(); } if (mPopupWindowProgress != null && mPopupWindowProgress.isShowing()) { mPopupWindowProgress.dismiss(); } if (!isSecondDown) { if (!bProgress) { } } isSecondDown = false; } else { } x1 = 0; x2 = 0; y1 = 0; y2 = 0; isDown = false; break; case MotionEvent.ACTION_POINTER_DOWN: isSecondDown = true; oldDist = spacing(event); if (oldDist > 10f) { savedMatrix.set(matrix); midPoint(mid, event); mode = ZOOM; } break; case MotionEvent.ACTION_MOVE: x2 = event.getX(); y2 = event.getY(); int midx = getWindowManager().getDefaultDisplay().getWidth() / 2; int midy = getWindowManager().getDefaultDisplay().getHeight() / 2; if (mode == ZOOM) { float newDist = spacing(event); if (newDist > 0f) { float scale = newDist / oldDist; Log.d("scale", "scale:" + scale); if (scale <= 2.0f && scale >= 0.2f) { // zoomTo(originalScale * scale, midx, midy); } } } } return gt.onTouchEvent(event); } private static final int NONE = 0; private static final int DRAG = 1; private static final int ZOOM = 2; private int mode = NONE; private float oldDist; private Matrix matrix = new Matrix(); private Matrix savedMatrix = new Matrix(); private PointF start = new PointF(); private PointF mid = new PointF(); float mMaxZoom = 2.0f; float mMinZoom = 0.3125f; float originalScale; float baseValue; protected Matrix mBaseMatrix = new Matrix(); protected Matrix mSuppMatrix = new Matrix(); private Matrix mDisplayMatrix = new Matrix(); private final float[] mMatrixValues = new float[9]; protected void zoomTo(float scale, float centerX, float centerY) { Log.d("zoomTo", "zoomTo scale:" + scale); if (scale > mMaxZoom) { scale = mMaxZoom; } else if (scale < mMinZoom) { scale = mMinZoom; } float oldScale = getScale(); float deltaScale = scale / oldScale; Log.d("deltaScale", "deltaScale:" + deltaScale); mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY); videoViewStandard.setScaleType(ImageView.ScaleType.MATRIX); videoViewStandard.setImageMatrix(getImageViewMatrix()); } protected Matrix getImageViewMatrix() { mDisplayMatrix.set(mBaseMatrix); mDisplayMatrix.postConcat(mSuppMatrix); return mDisplayMatrix; } protected float getScale(Matrix matrix) { return getValue(matrix, Matrix.MSCALE_X); } protected float getScale() { return getScale(mSuppMatrix); } protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } private float spacing(MotionEvent event) { try { float x = event.getX(0) - event.getX(1); float y = event.getY(0) - event.getY(1); return FloatMath.sqrt(x * x + y * y); } catch (Exception e) { } return 0; } private void midPoint(PointF point, MotionEvent event) { float x = event.getX(0) + event.getX(1); float y = event.getY(0) + event.getY(1); point.set(x / 2, y / 2); } @Override public boolean onDown(MotionEvent e) { Log.d("tag", "onDown"); return false; } private final int MINLEN = 80; // private RelativeLayout topbg; // private Animation showTopAnim; // private Animation dismissTopAnim; private boolean isPTZPrompt; @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { float x1 = e1.getX(); float x2 = e2.getX(); float y1 = e1.getY(); float y2 = e2.getY(); float xx = x1 > x2 ? x1 - x2 : x2 - x1; float yy = y1 > y2 ? y1 - y2 : y2 - y1; if (xx > yy) { if ((x1 > x2) && (xx > MINLEN)) {// left NativeCaller .PPPPPTZControl(strDID, ContentCommon.CMD_PTZ_RIGHT);//直接调用提供的函数 云台控制 } else if ((x1 < x2) && (xx > MINLEN)) {// right NativeCaller.PPPPPTZControl(strDID, ContentCommon.CMD_PTZ_LEFT);//直接调用提供的函数 } } else { if ((y1 > y2) && (yy > MINLEN)) {// down NativeCaller.PPPPPTZControl(strDID, ContentCommon.CMD_PTZ_DOWN);//直接调用提供的函数 } else if ((y1 < y2) && (yy > MINLEN)) {// up NativeCaller.PPPPPTZControl(strDID, ContentCommon.CMD_PTZ_UP);//直接调用提供的函数 } } return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { return false; } //退出dialog public void showSureDialogPlay() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.app); builder.setTitle(getResources().getString(R.string.exit_show)); builder.setMessage(R.string.exit_play_show); builder.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { PlayActivity.this.finish(); } }); builder.setNegativeButton(R.string.str_cancel, null); builder.show(); } //按钮点击操作 @Override public void onClick(View v) { switch (v.getId()) { //退出按钮 case R.id.login_top_back: if (!bProgress) { if (isTakeVideo == true) { showToast(R.string.eixt_show_toast); } else { showSureDialogPlay(); } } break; //云台控制 case R.id.imgup: NativeCaller.PPPPPTZControl(strDID, ContentCommon.CMD_PTZ_UP);//直接调用提供的函数 Log.d("tag", "up"); break; case R.id.imgdown: NativeCaller.PPPPPTZControl(strDID, ContentCommon.CMD_PTZ_DOWN);//直接调用提供的函数 Log.d("tag", "down"); break; case R.id.imgleft: NativeCaller.PPPPPTZControl(strDID, ContentCommon.CMD_PTZ_LEFT);//直接调用提供的函数 Log.d("tag", "left"); break; case R.id.imgright: NativeCaller.PPPPPTZControl(strDID, ContentCommon.CMD_PTZ_RIGHT);//直接调用提供的函数 Log.d("tag", "right"); break; } } private MyRender myRender = null; private GLSurfaceView myGlSurfaceView = null; //云台控制 private ImageView imgUp = null; private ImageView imgDown = null; private ImageView imgRight = null; private ImageView imgLeft = null; @Override protected void onDestroy() { NativeCaller.StopPPPPLivestream(strDID);//直接调用提供的函数 StopAudio(); if (myRender != null) { myRender.destroyShaders(); } if (brodCast != null) { unregisterReceiver(brodCast); } Log.d("tag", "PlayActivity onDestroy"); super.onDestroy(); } // 下边三个方法是 实现p2plistener的方法 @Override public void callBackAudioData(String arg0, byte[] pcm, int len) {//调音频文件 // TODO Auto-generated method stub Log.d(LOG_TAG, "AudioData: len :+ " + len); if (!audioPlayer.isAudioPlaying()) { return; } CustomBufferHead head = new CustomBufferHead(); CustomBufferData data = new CustomBufferData(); head.length = len; head.startcode = AUDIO_BUFFER_START_CODE; data.head = head; data.data = pcm; AudioBuffer.addData(data); } @Override public void callBackH264VideoData(String arg0, byte[] arg1, int arg2, int arg3) {//返回h264数据 // TODO Auto-generated method stub } @Override public void callBackVideoData(String did, byte[] videobuf, int h264Data, int len, int width, int height, int tim) {//返回h264解码后的yuv数据 Log.d(LOG_TAG, "Call VideoData...h264Data: " + h264Data + " len: " + len + " videobuf len: " + videobuf.length + "width==" + nVideoWidth + "height==" + nVideoHeight); if (!bDisplayFinished) { Log.d(LOG_TAG, "return bDisplayFinished"); return; } nVideoWidth = width; nVideoHeight = height; bDisplayFinished = false; videodata = videobuf; videoDataLen = len; Message msg = new Message(); if (h264Data == 1) { // H264 if (isTakepic) { isTakepic = false; byte[] rgb = new byte[width * height * 2]; NativeCaller.YUV4202RGB565(videobuf, rgb, width, height);//直接调用提供的函数 ByteBuffer buffer = ByteBuffer.wrap(rgb); mBmp = Bitmap .createBitmap(width, height, Bitmap.Config.RGB_565); mBmp.copyPixelsFromBuffer(buffer); // takePicture(mBmp); } msg.what = 1; } else { // MJPEG msg.what = 2; } mHandler.sendMessage(msg); } }
006523e93387283cf4736e6725fb6b1139fe5012
[ "Markdown", "Java" ]
2
Markdown
XoYoKing/IPcamera
33334aa4b0353e787fcb672eaf4259345be72671
ef956849cbddf7edbc4bfc542d997928a621ee96
refs/heads/master
<repo_name>heatherstafford/unit2.5<file_sep>/name.py #<NAME> #2/9/18 #name.py from ggame import * name = input('Enter your name: ') colorCode = input('Enter an RGB color code: ') color = Color(colorCode,1) black = Color(0x000000,1) colorOutline = LineStyle(2,color) colorRectangle = RectangleAsset(1000,2000, colorOutline, color) text = TextAsset(name, fill = black, style = 'italic 30pt Times') Sprite(colorRectangle) App().run() <file_sep>/README.md # unit-2.5<file_sep>/house.py #<NAME> #2/8/18 #house.py from ggame import * red = Color(0xFF0000,1) black = Color(0x000000,1) blue = Color(0x0000FF,.7) blackOutline = LineStyle(2,black) redRectangle = RectangleAsset(200,100, blackOutline, red) blackTriangle = PolygonAsset([(0,300),(120,180),(240,300)],blackOutline, black) blackRectangle = RectangleAsset(20,50, blackOutline, black) blueRectangle = RectangleAsset(50,25, blackOutline, blue) Sprite(redRectangle,(300,200)) Sprite(blackTriangle,(279,80)) Sprite(blackRectangle,(385,250)) Sprite(blueRectangle,(317, 250)) App().run() <file_sep>/graphicsDemo.py #<NAME> #2/7/18 #graphicsDemo.py - Intro to ggame from ggame import * red = Color(0xFF0000,1) #this is the color red green = Color(0x00FF00,1) blue = Color(0x000FF,1) black = Color(0x000000,1) blackOutline = LineStyle(2,black) redRectangle = RectangleAsset(200,100,blackOutline, red) #width, height, outline, fill blueCircle = CircleAsset(50,blackOutline,blue) #radius, outline, fill greenEllipse = EllipseAsset(100,50,blackOutline, green) #width, height, outline, fill blackLine = LineAsset(50,160,blackOutline) #x-endpoint, y-endpoint, lineStyle redTriangle = PolygonAsset([(0,0),(120,180),(60,300)],blackOutline, red) #enpoints, outlines, fill text = TextAsset('Heather', fill = red, style = 'italic 35pt Times') #text, other options Sprite(redRectangle) Sprite(blueCircle,(300,50)) #(moving it over by coordinates) Sprite(greenEllipse, (40,200)) Sprite(blackLine, (40,100)) Sprite(redTriangle) Sprite(text, (300,50)) App().run() <file_sep>/germany.py #<NAME> #2/9/18 #germany.py from ggame import * black = Color(0x000000,1) red = Color(0xFF0000,1) yellow = Color(0xFFE55C,1) blackOutline = LineStyle(2,black) redOutline = LineStyle(2,red) yellowOutline = LineStyle(2,yellow) blackRectangle = RectangleAsset(500,100, blackOutline, black) redRectangle = RectangleAsset(500,100, redOutline, red) yellowRectangle = RectangleAsset(500,100, yellowOutline, yellow) Sprite(blackRectangle) Sprite(redRectangle,(0,100)) Sprite(yellowRectangle,(0,200)) App().run() <file_sep>/remainder.py #<NAME> #3/7/18 #remainder.py from random import randint from ggame import * num1 = randint(10,20) num2 = randint(1,10) yellow = Color(0xFFFF00, 1) black = Color(0x000000,1) yellowCircle = CircleAsset(100, LineStyle(2,black), yellow) blackCircle = CircleAsset(50, LineStyle(2,black),black) yellowEdit = CircleAsset(50, LineStyle(2,yellow), yellow) blackEye = CircleAsset(10, LineStyle(2,black),black) answer = float(input('What is the remainder of '+ str(num1) + '/' + str(num2) + '?')) if answer == num1%num2: Sprite(yellowCircle) Sprite(blackCircle,(50,60)) Sprite(yellowEdit, (50,40)) Sprite(blackEye,(50,40)) Sprite(blackEye,(125,40)) else: Sprite(yellowCircle) Sprite(blackCircle, (50,80)) Sprite(yellowEdit, (50,98)) Sprite(blackEye,(50,40)) Sprite(blackEye,(125,40)) App().run()
0ef20c226d0dbbb761a6d0196e90bfa8c73fc6ee
[ "Markdown", "Python" ]
6
Python
heatherstafford/unit2.5
a09f19456bd80155e2dfd8f8f24af44db879223e
3579b46ae0a302cd6a53369b19455b795dd78809
refs/heads/master
<file_sep>const { getList, newBlog, delBlog, getDetail, updateBlog } = require('../controller/blog'); const { ErrorModel, SuccessModal } = require('../model/resModel'); const loginCheck = (req) => { const { username } = req.session; console.log('username', username); if (!username){ return Promise.resolve( new ErrorModel('未登录') ); } }; const handleBlogRouter = (req, res) => { const { method, url } = req; const id = req.query.id; const path = url&&url.split('?')[0]; // 获取博客列表 if (method == 'GET' && path == "/api/blog/list") { let { author, keyword, isAdmin } = req.query; if (isAdmin) { // 管理员界面 const loginCheckResult = loginCheck(req); if (loginCheckResult) { return loginCheckResult; } // 强制查询自己的博客 author = req.session.username; } return getList(author, keyword).then(listData => { return new SuccessModal(listData); }); // const listData = getList(author, keyword); // return new SuccessModal(listData); } // 获取博客详情 if (method == 'GET' && path == '/api/blog/detail') { const { id } = req.query; // const detailData = getDetail(id); // return new SuccessModal(detailData); // const loginCheckResult = loginCheck(req); // if (loginCheckResult) { // return loginCheckResult; // } return getDetail(id).then(data => { return new SuccessModal(data); }); } // 新建一篇博客 if (method == 'POST' && path == '/api/blog/new') { // const data = newBlog(req.body); // return new SuccessModal(data); const loginCheckResult = loginCheck(req); if (loginCheckResult) { return loginCheckResult; } req.body.author = req.session.username; console.log('req',req.body) return newBlog(req.body).then(data => { return new SuccessModal(data); }); } // 更新一篇博客 if (method == 'POST' && path == '/api/blog/update') { // const data = updateBlog(id, req.body); // if (data) { // return new SuccessModal(req.body); // }else { // return new ErrorModel('博客更新失败'); // } const loginCheckResult = loginCheck(req); if (loginCheckResult) { return loginCheckResult; } return updateBlog(id, req.body).then(data => { return data ? new SuccessModal(data) : new ErrorModel('博客更新失败'); }) } // 删除一篇博客 if (method == 'POST' && path == '/api/blog/del') { // const data = delBlog(id); // if (data) { // return new SuccessModal(data); // }else { // return new ErrorModel('删除博客失败'); // } const loginCheckResult = loginCheck(req); if (loginCheckResult) { return loginCheckResult; } return delBlog(id, req.session.username).then(data => { return data ? new SuccessModal(data) : new ErrorModel('博客删除失败'); }); } }; module.exports = handleBlogRouter; // https://dev.mysql.com/downloads/workbench<file_sep>/* 1.为什么有的编程规范要求使用void 0代替undefined 2.字符串有最大长度吗 3.0.1+0.2等于0.3吗?为什么js里不是这样的 4.ES6新加入的Symbol是什么? 5.为什么给对象添加的方法能用在基本类型上 6.七种数据类型 - undefined - null - boolean - string - number - symbol - object */ // javascript的代码undefined是一个变量,而并非是一个关键字,这是js语言公认的设计失误之一,所以,我们为了避免无意中被篡改,建议使用void 0来获取undefined值 const a = undefined; let b = void 0; //js中+0和-0在加法运算中它们没有区别,但是除法的场合则需要特别留意区分。 console.log(1/0); //Infinity 无穷大 console.log(1/-0); //-Infinity 无穷小 // 非整型number类型无法使用==和===来比较 console.log(0.1 + 0.2); // 0.30000000000000004 // 正确的比较方法是使用js提供的最小经度值 console.log(Math.abs(0.1+0.2-0.3) <= Number.EPSILON); // true // Symbol let mySymbol = Symbol('my Symbol'); console.log(mySymbol); // Symbol(my Symbol) // Number、String 和 Boolean,三个构造器是两用的,当跟new搭配时,它们产生对象,当直接调用时,他们表示强制类型转换 console.log(new Number(3), 3 == new Number(3), 3 === new Number(3)); // Number true false // 原生如何检测一个变量是否是一个数组 { const arr =[1, 2, 3]; function isArray(value) { if (Array.isArray === "function") { return Array.isArray(value); }else { return Object.prototype.toString.call(value)==='[object Array]'; } } console.log(isArray(arr), Object.prototype.toString.call(arr)); // true } // typeof console.log(typeof undefined, typeof [1,2] ,typeof null, typeof NaN, typeof function(){}); // undefined object object number function // undefined是否可以被赋值 undefined = null; console.log(undefined); // undefined function testUndefined() { var undefined = 2; console.log(undefined); // 2 } testUndefined();<file_sep>const express = require('express'); const router = express.Router(); const { getList, delBlog, newBlog, getDetail, updateBlog, } = require('../controller/blog'); const loginCheck = require('../middleware/loginCheck'); const { SuccessModel, ErrorModel } = require('../model/resModel'); router.get('/list', function (req, res, next) { let { author, keyword, isAdmin } = req.query; if (isAdmin) { // 管理员界面 if (req.session.username == null) { res.json( new ErrorModel('未登录') ); return; } // 强制查询自己的博客 author = req.session.username; } return getList(author, keyword).then(listData => { res.json( new SuccessModel(listData) ); }); }); // 博客详情 router.get('/detail', async function(req, res, next) { res.json( new SuccessModel(await getDetail(req.query.id)) ); }); // 新建博客 router.post('/new', loginCheck, async function(req, res, next) { req.body.author = req.session.username; res.json( new SuccessModel(await newBlog(req.body)) ) }); // 更新博客 router.post('/update', loginCheck, async (req, res, next) => { return await updateBlog(req.query.id, req.body) ? res.json(new SuccessModel('更新成功')) : res.json(new ErrorModel('更新博客失败')); }); // 删除博客 router.post('/del', loginCheck, async function(req, res, next) { const author = req.session.username; return await delBlog(req.query.id, author) ? res.json(new SuccessModel('删除成功')) : res.json(new ErrorModel('删除失败')); }) module.exports = router; <file_sep>const fs = require('fs'); const path = require('path'); // 两个文件名 const filePath1 = path.resolve(__dirname, 'data.txt'); const filePath2 = path.resolve(__dirname, 'data-back.txt'); // 读取文件的stream对象 const readStream = fs.createReadStream(filePath1); // 写入文件的stream对象 const writeStream = fs.createWriteStream(filePath2); // 执行拷贝,通过pipe readStream.pipe(writeStream); readStream.on('data', chunk => { console.log(chunk.toString()); }); // 数据读取完成 readStream.on('end', () => { console.log('拷贝完成'); }); <file_sep>const crypto = require('crypto'); const SECRET_KEY = '<KEY>'; function md5(content) { return crypto.createHash('md5').update(content).digest('hex'); } function generatePassword(password) { return md5(`password=${password}&key=${SECRET_KEY}`); } module.exports = { generatePassword }; <file_sep>const redis = require('redis'); const { REDIS_CONFIG } = require('../config/redis'); const client = redis.createClient(REDIS_CONFIG); client.on('error', err => { console.log('error', err); }); function setRedisValue(key, value) { if (typeof value == 'object') value = JSON.stringify(value); client.set(key, value, redis.print); } function getRedisValue(key) { return new Promise((resolve, reject) => { client.get(key, (err, value) => { if (err) { reject(); return; } if (value == null) { resolve(null); return; } try { resolve(JSON.parse(value)); }catch (err) { resolve(value); } }); }); } module.exports = { setRedisValue, getRedisValue }; <file_sep>const redis = require("redis"), { REDIS_CONFIG } = require('../db/redis'); redisClient = redis.createClient(REDIS_CONFIG); redisClient.on("error", function (err) { console.log("Error " + err); }); function setRedisValue(key, value) { if (typeof value == 'object') value = JSON.stringify(value); redisClient.set(key, value, redis.print); } function getRedisValue(key) { return new Promise((resolve, reject) => { redisClient.get(key, (err, value) => { if (err) { reject(err); return; } if (value == null) { reject(null); return; } try { resolve(JSON.parse(value)); }catch(err) { reject(value); } }); }); } module.exports = { redisClient, getRedisValue, setRedisValue }; <file_sep>const { generatePassword } = require('../utils/cryp'); const { executeSql, escape } = require('../db/mysql'); const loginCheck = (userName='zhangsan', password='123') => { // if (userName == 'zhangsan' && password == '123') { // return true; // } // return false; userName = escape(userName); password = generatePassword(escape(password)); const sql = `select username, realname from users where username=${userName} and password='${password}'`; console.log(sql) return executeSql(sql).then(data => { return data[0] || {}; }); }; module.exports = { loginCheck }; <file_sep>const fs = require('fs'); const path = require('path'); const readLine = require('readline'); const filePath = path.resolve(__dirname, '../../logs/access.log'); const readStream = fs.createReadStream(filePath); const readline = readLine.createInterface({ input: readStream }) let totalNum = 0; let chromeNum = 0; readline.on('line', lineData => { if (!lineData) return; totalNum++; if (lineData.split(' -- ')[2].includes('Chrome')) chromeNum++; }); readline.on('close', (err, data) => { console.log('Chrome占比为', (chromeNum / totalNum * 100).toFixed(2) + '%'); }); <file_sep>const fs = require('fs'); const path = require('path'); const filePath = path.resolve(__dirname, 'data.txt'); fs.readFile(filePath, (err, data) => { if (err) { console.log(err); return err; } console.log(data.toString()); }); fs.writeFile(filePath, '生死有命富贵在天', { flag: 'a'}, err => { if (err) { console.log(err); return; } }); // 判断文件是否存在 fs.exists(filePath, err => { console.log(err ? '存在' : '不存在'); }) <file_sep>const querystring = require('querystring'); const handleBlogRouter = require('./src/router/blog'); const handleUserRouter = require('./src/router/user'); const { writeAcessLog } = require('./src/utils/log'); const { setRedisValue, getRedisValue } = require('./src/db/redis'); let SESSION_DATA = {}; let needSetCookie = false; const parseRedis = (userId) => { return getRedisValue(userId).then(res => { if (!res) { needSetCookie = true; setRedisValue(userId, {}); return {}; }else { needSetCookie = false; return res; } }); }; const setCookieExpires = () => { const d = new Date(); d.setTime(d.getTime() + (24 * 60 * 60 * 1000)); return d.toGMTString(); }; const parseSession = (userId) => { if (!SESSION_DATA[userId]) { needSetCookie = true; SESSION_DATA[userId] = {}; }else { needSetCookie = false; } return SESSION_DATA[userId]; }; const setCookie = (res, userId) => { res.setHeader('Set-Cookie', `userid=${userId}; path=/; httpOnly; expires=${setCookieExpires()}`); }; const parseCookie = (cookieStr='') => { cookie = {}; cookieStr.split(';').forEach(element => { if(!element) return; const arr = element.split('='); const key = arr[0].trim(); const value = arr[1].trim(); cookie[key] = value; }); return cookie; }; const getPostData = (req) => { return new Promise((resolve, reject) => { let postData = ''; if (req.method != 'POST' || req.headers['content-type'] !== 'application/json') { resolve({}); return; } req.on('data', chunk => { postData += chunk.toString(); }); req.on('end', () => { if (!postData) { resolve({}); return; } resolve(JSON.parse(postData)); }); }); }; const serverHandle = (req, res) => { // 记录access-log writeAcessLog(`${req.method} -- ${req.url} -- ${req.headers['user-agent']} -- ${Date.now()}`); res.setHeader('Content-type', 'application/json'); // 解析query req.query = querystring.parse(req.url.split('?')[1]); // 解析cookie req.cookie = parseCookie(req.headers.cookie); // 解析session const userId = req.cookie.userid || `${Date.now()}_${Math.random()}`; req.sessionId = userId; console.log('req.sessionId', req.sessionId); // 用redis代替了session // req.session = parseSession(userId); parseRedis(userId).then(sessionData => { req.session = sessionData; return getPostData(req); }). // req.session = parseRedis(userId); // 处理post data // res.end('hello world'); // getPostData(req). then(postData => { // blog路由 req.body = postData; const blogResult = handleBlogRouter(req, res); if (blogResult) { blogResult.then(data => { if (needSetCookie) setCookie(res, userId); res.end(JSON.stringify(data)); }); return; } // const blogData = handleBlogRouter(req, res); // if (blogData) { // res.end(JSON.stringify(blogData)); // return; // } // user路由 // const userData = handleUserRouter(req, res); // if (userData) { // res.end(JSON.stringify(userData)); // return; // } // user路由promise写法 const userResult = handleUserRouter(req, res); if (userResult) { userResult.then(userData => { if (needSetCookie) setCookie(res, userId); if (userData){ res.end(JSON.stringify(userData)); } }); return; } // 未命中路由,返回404 res.writeHead(404, { "Content-type": "text/plain" }); res.write("404 Not Found\n"); res.end(); }).catch(err => { console.log(err); }); }; module.exports = serverHandle; <file_sep># nodejs nodejs学习总结 Nodejs是一个js的运行环境 运行在服务器做为web server 运行在本地做为打包、构建工具 ## nodejs和js的区别 ### ECMAScript 定义了语法,写js和nodejs都必须遵守 变量定义、循环、判断、函数 原型和原型链、作用域和闭包、异步 不能操作DOM,不能监听click事件,不能发送ajax请求 不能处理http请求,不能操作文件,只有ECMAScript,几乎做不了任何实际的项目 ### js 使用ECMAScript语法规范,外加Web API,缺一不可 DOM操作,BOM操作,事件绑定,Ajax等 两者结合,即可以完成浏览器端的任何操作 ### nodejs 使用ECMAScript语法规范,外加nodejs API,缺一不可,处理http,处理文件等,两者结合可以玩昵称server端的操作。 ## server端和前端的区别 server端可能会遭受各种恶意攻击和误操作,单个客户端可以意外挂掉,但是服务端不能。使用PM2做进程守候 客户端独占一个浏览器,内存和CPU都不是问题,server端要承载很多请求,CPU和内存都是稀缺资源,使用stream写日志,使用redis存session 前端也会参与写日志,但只是日志的发起方,不关心后续,server端要记录日志、存储日志、分析日志、前端不关心 server端要随时准备接受各种恶意攻击,前端则少很多,如:越权操作、数据库攻击等,登录验证,预防xss攻击和sql注入 产品发展速度快,流量可能会迅速增减,可以通过机器和服务拆分来承载大流量,集群和服务拆分 ## http概述 DNS解析,建立TCP连接,发送http请求 server接收到http请求处理并返回 客户端接收到返回数据,处理数据(如渲染页面,执行js) ## 数据库的基本操作 show tables; insert into users(username,`<PASSWORD>`, realname) values('lisi', '123', '李四'); select * from users; select id, username from users; select * from users where username='zhangsan'; select * from users where username='zhangsan' and `password`='123'; select * from users where username='zhangsan' or `password`='123'; select * from users where username like '%zhang%'; select * from users where `password` like '%1%' order by id; select * from users where `password` like '%1%' order by id desc; update users set realname='李四2' where username='lisi';更新内容时报错,错误信息如下: ``` update users set realname='李四2' where username='lisi' Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect. 0.0020 sec ``` 解决办法,执行如下语句SET SQL_SAFE_UPDATES=0; 删除某条数据 delete from users where username='lisi' 软删除 查询版本 select version(); ### Cookie 存储在浏览器的一段字符串最大5kb 跨域不共享 格式如k1=v1因此可以存储结构化数据 每次发送http请求,会将请求域的cookie一起发送给server sever可以修改cookie并返回给浏览器 浏览器中可以通过js修改cookie,有限制 ### js操作cookie 查看 document.cookie获取cookie 修改 document.cookie='k1=100'; 注意只能累加 httpOnly禁止前端修改cookie ## 从session到redis 1.进程内存有限,访问量国大,内存暴增怎么办? 2.正式线上运行是多进程,进程之间内存无法共享 cookie、session的区别: 1.cookie数据存放在客户的浏览器上,session数据放在服务器上。 2.cookie不是很安全,别人可以分析存放在本地的COOKIE并进行COOKIE欺骗 考虑到安全应当使用session。 3.session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能 考虑到减轻服务器性能方面,应当使用COOKIE。 4.单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie。 5.所以建议:将登陆信息等重要信息存放为session、其他信息如果需要保留,可以放在cookie中 redis webserver最常用的缓存数据库,数据存放在内存中 相比mysql访问速度快 但是成本更高,可存储的数据量更小 将webserver和redis拆分为两个单独的服务 双方都是独立的,都是可以扩展的,例如都扩展成集群 为什么session适用于redis? session访问频繁,对性能要求极高 session可不考虑断电丢失数据的问题 sesssion数据量不会太大 安装 ``` brew install redis ``` 启动 ``` redis-server redis-cli ``` ### nodejs连接redis `npm i redis -S` ``` // index.js var redis = require("redis"), client = redis.createClient(); client.on("error", function (err) { console.log("Error " + err); }); client.set('myName', 'FangFeiyue', redis.print); client.get('myName', (err, val) => { if (err) { console.log(err) return; } console.log('val', val); client.quit(); }); ``` node index.js ### ngix 高性能的web服务器,开源免费 一般用于做静态服务、负载均衡 反向代理 简单使用 测试配置文件格式是否正确 `ngix -t` 启动nginx `nginx` 重启nginx `nginx -s reload` 停止nginx `nginx -s stop` mac下nginx路径/usr/local/etc/nginx/nginx.conf ## 日志 访问日志 - access log 自定义日志(包括自定义事件、错误记录等) 日志要存储到文件中?为何不存储到mysql中,为何不存储到redis中? 使用crontab拆分日志文件 ## 安全 ### sql注入 例子:登录sql注入 zhangsan' -- zhangsan';delete from users; -- mysql.escape(zhangsan' -- ); ### xss攻击 攻击方式:在页面展示内容中掺杂js代码,以获取网页信息 预防措施:转换生成js的特殊字符 ``` npm i xss -S const xss = reqiure('xss'); const inputContent = xss(inputData); ``` ### 密码加密 ``` ``` asyn await要点 1.await后面可以追加promise对象,获取resolve的值 2.await必须包裹在async函数里面 3.async函数执行返回的也是一个promise对象 4.try-catch截获promise中reject的值 ## koa2 npm i koa-generator -D koa2 blog-koa2 ### express处理session 使用express-session和connect-redis # 问题 在使用mysql执行update的时候,如果不是用主键当where语句,会报如下错误,使用主键用于where语句中正常。 异常内容:Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Queries and reconnect. 这是因为MySql运行在safe-updates模式下,该模式会导致非主键条件下无法执行update或者delete命令,执行命令SET SQL_SAFE_UPDATES = 0;修改下数据库模式<file_sep>const mysql = require('mysql'); const { MYSQL_CONFIG } = require('../config/db'); const connection = mysql.createConnection(MYSQL_CONFIG); connection.connect(); function executeSql(sql) { return new Promise((resolve, reject) => { connection.query(sql, (err, res) => { if (err) { reject(err); return; } resolve(res); }); }); } module.exports = { executeSql, escape: mysql.escape }; <file_sep>#!/bin/sh cd /Users/sun/Desktop/guoan/learn/nodejs/blog/logs cp access.log $(date +%Y-%m-%d).access.log echo "" > access.log # /Users/sun/Desktop/guoan/learn/nodejs/blog/src/utils <file_sep>let arr1 = [1,1,2,3,4,5,4,3,4]; let arr2 = [4,5,6,7,8,9,4,6,7]; // 两个数组的并集 const result = Array.from(new Set(arr1.concat(arr2))); console.log(result); // [1, 2, 3, 4, 5, 6, 7, 8, 9] // 两个数组的交集 // 两个数组中重复元素最多的π<file_sep>const xss = require('xss'); const { executeSql } = require('../db/mysql'); const getList = async (author, keyword) => { let sql = `select * from blogs where 1=1 `; if (author) sql += `and author='${author}' `; if (keyword) sql += `and title like '%${keyword}%'`; sql += 'order by createtime desc'; return await executeSql(sql); }; const getDetail = async (id) => { const sql = `select * from blogs where id='${id}'`; return (await executeSql(sql))[0]; }; const newBlog = async (blogData = {}) => { const { author } = blogData; const createTime = Date.now(); const title = xss(blogData.title); const content = xss(blogData.content); const sql = `insert into blogs(title, content, author, createTime) values('${title}', '${content}', '${author}', ${createTime})`; return { id: (await executeSql(sql)).insertId }; }; const updateBlog = async (id, blogData = {}) => { const { title, content } = blogData; const sql = `update blogs set title='${title}', content='${content}' where id='${id}'`; return (await executeSql(sql)).affectedRows > 0 ? true : false; }; const delBlog = async (id, author) => { const sql = `delete from blogs where id='${id}' and author='${author}'`; return (await executeSql(sql)).affectedRows > 0 ? true : false; }; module.exports = { getList, delBlog, newBlog, getDetail, updateBlog };
fa54cae82e2f40e3a28aa861b47add98d488bae1
[ "JavaScript", "Markdown", "Shell" ]
16
JavaScript
fangfeiyue/nodejs
703f2a8010e2aabf6956faa3e5840b4478441460
52ac952bf21dbc8539284a7e406092175abcb617
refs/heads/master
<repo_name>AndraCoteanu/2A4-ProgramareAvansata<file_sep>/Laborator 2/Laborator 2 (optional)/src/Solution.java /** * @author <NAME>. * @version "%I%, %G%" * <p> Se calculeaza o solutie pentru problema creata </p> */ public class Solution { /** * <p> Class empty constructor </p> */ public Solution() { } /** * <p> Se creaza un string cu informatiile solutiei </p> * * @return stringul */ @Override public String toString() { return "Solutia pentru problema data este:"; } /* declar un obiect de tipul Problem pentru ai putea accesa functionalitatile */ Problem problema = new Problem(); public int[] Row = new int[problema.MATRIX_DIM]; public int[] Column = new int[problema.MATRIX_DIM]; /** * <p> Se verifica daca au fost modificate toate costurile cu 100 (o valoare mai mare decat 10) </p> * * @return 0 daca nu s-au terminat livrarile */ public int verificareLivrari() { for (int i = 0; i < problema.MATRIX_DIM; i++) { for (int j = 0; j < problema.MATRIX_DIM; j++) { if (problema.cost[i][j] <= 10) { return 0; //nu e gata } } } return 1; //gata livrarile } /** * <p> Parcurge fiecare rand din matricea de cost </p> * <p> Gaseste cele mai 2 mici costuri </p> * <p> Face diferenta lor si o memoreaza in vectorul Row[] </p> */ public void diffRow() { int min1, min2; for (int i = 0; i < problema.MATRIX_DIM; i++) { min1 = 20; min2 = 20; for (int j = 0; j < problema.MATRIX_DIM; j++) { if (problema.cost[i][j] < min1) { min2 = min1; min1 = problema.cost[i][j]; } else if (problema.cost[i][j] < min2) { min2 = problema.cost[i][j]; } } Row[i] = min2 - min1; } } /** * <p> Parcurge fiecare coloana din matricea de cost </p> * <p> Gaseste cele mai 2 mici costuri </p> * <p> Face diferenta lor si o memoreaza in vectorul Column[] </p> */ public void diffColumn() { int min1, min2; for (int i = 0; i < problema.MATRIX_DIM; i++) { min1 = 20; min2 = 20; for (int j = 0; j < problema.MATRIX_DIM; j++) { if (problema.cost[j][i] < min1) { min2 = min1; min1 = problema.cost[j][i]; } else if (problema.cost[j][i] < min2) { min2 = problema.cost[j][i]; } } Column[i] = min2 - min1; } } /** * <p> Se creaza instantele unei probleme si se afiseaza acestea </p> * <p> Metoda calculeaza apoi solutia problemei </p> * <p> Metoda folosita este cea explicata pe acest site: <a href="url">https://www.geeksforgeeks.org/transportation-problem-set-4-vogels-approximation-method/</a> </p> */ public void solutia() { /* se initializeaza datele problemei */ problema.makeProblem(); /* se afiseaza datele problemei */ System.out.println(""); System.out.println(problema); problema.printProblem(); /* se incepe rezolvarea problemei */ int costTotal = 0; int livrare; livrare = verificareLivrari(); while (livrare == 0) { diffColumn(); diffRow(); int locatie; //0-rand sau 1-coloana, in functie de unde se afla penalitatea maxima locatie = -1; int rand, coloana; //numarul randului/coloanei unde este penalitatea maxima rand = -1; coloana = -1; /* se calculeaza penalizarea: valoarea maxima a valorilor din Row[] si Column[] */ int penality = -1; for (int i = 0; i < problema.MATRIX_DIM; i++) { if (Row[i] > penality) { penality = Row[i]; locatie = 0; rand = i; } else if (Column[i] > penality) { penality = Column[i]; locatie = 1; coloana = i; } } /* dupa ce s-a identificat o linie sau coloana se parcurge aceasta si se gaseste costul minim */ int costMin = 20; int coordRand, coordColoana; coordColoana = 0; coordRand = 0; int i = -1; /* dupa ce s-a gasit costul minim se verifica cererea destinatiei si capacitatea sursei si se face un transport */ if (locatie == 0) //rand { for (i = 0; i < problema.MATRIX_DIM; i++) { if (problema.cost[rand][i] < costMin) { costMin = problema.cost[rand][i]; coordColoana = i; } } if (problema.destinatii.get(coordColoana).commodity > problema.surse.get(rand).capacity) { System.out.println(problema.surse.get(rand).name + " -> " + problema.destinatii.get(coordColoana).name + ": " + problema.surse.get(rand).capacity + " units * cost " + problema.cost[rand][coordColoana] + " = " + problema.surse.get(rand).capacity * problema.cost[rand][coordColoana]); costTotal += problema.surse.get(rand).capacity * problema.cost[rand][coordColoana]; problema.destinatii.get(coordColoana).commodity -= problema.surse.get(rand).capacity; problema.surse.get(rand).capacity = 0; for (i = 0; i < problema.MATRIX_DIM; i++) { problema.cost[rand][i] = 100; } } else if (problema.destinatii.get(coordColoana).commodity < problema.surse.get(rand).capacity) { System.out.println(problema.surse.get(rand).name + " -> " + problema.destinatii.get(coordColoana).name + ": " + problema.destinatii.get(coordColoana).commodity + " units * cost " + problema.cost[rand][coordColoana] + " = " + problema.destinatii.get(coordColoana).commodity * problema.cost[rand][coordColoana]); costTotal += problema.destinatii.get(coordColoana).commodity * problema.cost[rand][coordColoana]; problema.surse.get(rand).capacity -= problema.destinatii.get(coordColoana).commodity; problema.destinatii.get(coordColoana).commodity = 0; for (i = 0; i < problema.MATRIX_DIM; i++) { problema.cost[i][coordColoana] = 100; } } else { System.out.println(problema.surse.get(rand).name + " -> " + problema.destinatii.get(coordColoana).name + ": " + problema.destinatii.get(coordColoana).commodity + " units * cost " + problema.cost[rand][coordColoana] + " = " + problema.destinatii.get(coordColoana).commodity * problema.cost[rand][coordColoana]); costTotal += problema.destinatii.get(coordColoana).commodity * problema.cost[rand][coordColoana]; problema.surse.get(rand).capacity = 0; problema.destinatii.get(coordColoana).commodity = 0; for (i = 0; i < problema.MATRIX_DIM; i++) { problema.cost[rand][i] = 100; problema.cost[i][coordColoana] = 100; } } } else if (locatie == 1) // coloana { for (i = 0; i < problema.MATRIX_DIM; i++) { if (problema.cost[i][coloana] < costMin) { costMin = problema.cost[i][coloana]; coordRand = i; } } if (problema.destinatii.get(coloana).commodity > problema.surse.get(coordRand).capacity) { System.out.println(problema.surse.get(coordRand).name + " -> " + problema.destinatii.get(coloana).name + ": " + problema.surse.get(coordRand).capacity + " units * cost " + problema.cost[coordRand][coloana] + " = " + problema.surse.get(coordRand).capacity * problema.cost[coordRand][coloana]); costTotal += problema.surse.get(coordRand).capacity * problema.cost[coordRand][coloana]; problema.destinatii.get(coloana).commodity -= problema.surse.get(coordRand).capacity; problema.surse.get(coordRand).capacity = 0; for (i = 0; i < problema.MATRIX_DIM; i++) { problema.cost[coordRand][i] = 100; } } else if (problema.destinatii.get(coloana).commodity < problema.surse.get(coordRand).capacity) { System.out.println(problema.surse.get(coordRand).name + " -> " + problema.destinatii.get(coloana).name + ": " + problema.destinatii.get(coloana).commodity + " units * cost " + problema.cost[coordRand][coloana] + " = " + problema.destinatii.get(coloana).commodity * problema.cost[coordRand][coloana]); costTotal += problema.destinatii.get(coloana).commodity * problema.cost[coordRand][coloana]; problema.surse.get(coordRand).capacity -= problema.destinatii.get(coloana).commodity; problema.destinatii.get(coloana).commodity = 0; for (i = 0; i < problema.MATRIX_DIM; i++) { problema.cost[i][coloana] = 100; } } else { System.out.println(problema.surse.get(coordRand).name + " -> " + problema.destinatii.get(coloana).name + ": " + problema.destinatii.get(coloana).commodity + " units * cost " + problema.cost[coordRand][coloana] + " = " + problema.destinatii.get(coloana).commodity * problema.cost[coordRand][coloana]); costTotal += problema.destinatii.get(coloana).commodity * problema.cost[coordRand][coloana]; problema.surse.get(coordRand).capacity = 0; problema.destinatii.get(coloana).commodity = 0; for (i = 0; i < problema.MATRIX_DIM; i++) { problema.cost[coordRand][i] = 100; problema.cost[i][coloana] = 100; } } } /* dupa fiecare transport se verifica daca au fost facute toate livrarile */ livrare = verificareLivrari(); } /* afisam costul total */ System.out.println("Costul total este: " + costTotal); } }<file_sep>/Laborator 9/Compulsory/src/main/java/MovieThread.java import com.mchange.v2.c3p0.ComboPooledDataSource; import java.beans.PropertyVetoException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * <h3> Clasa MovieThread </h3> * <p> Implementeaza functii pe care le vor rula threadurile din connection pool. </p> * <p> Functionalitatea implementata este sa se caute in baza de date toate detaliile despre filmul cu id-ul 2. </p> */ public class MovieThread implements Runnable{ private int id; public MovieThread(int id) { this.id = id; } private void displayMovie(int id) throws SQLException, PropertyVetoException { Connection connection = null; String sql = "select * from movies where id_movie = ?"; PreparedStatement statement = null; try { ComboPooledDataSource filme = ConnectionPool.getInstance().getComboPooledDataSource(); connection = filme.getConnection(); statement = connection.prepareStatement(sql); statement.setInt(1, id); ResultSet rs = statement.executeQuery(); while (rs.next()) { System.out.println(" id: " + rs.getInt(1) + "\n movie: " + rs.getString(2) + "\n duration: " + rs.getInt(4) + " minutes\n score: " + rs.getInt(5)); } } finally { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } } public void run() { try { this.displayMovie(2); } catch (SQLException throwables) { throwables.printStackTrace(); } catch (PropertyVetoException e) { e.printStackTrace(); } } }<file_sep>/Laborator 11/README.md # Laborator 11 ## <NAME> 2A4 ### Compulsory + Am creat un proiect nou folosind Spring Initializer. + Am creat o noua baza de date (Oracle) si am adaugat modulul JPA pentru a putea lucra cu baze de date. + Pe baza BD-ului, cu ajutorul JPA-ului, am generat automat mapari pentru tabelele create: + users + friends + Am creat interfata UserRepository pentru a avea o evidenta mai clara a functiilor predefinite in SpringBoot pe care le-am folosit pentru operatiile pe BD. + In clasa UserService am folosit metodele din interfata pentru a defini functiile necesare. + In clasa UserController am definit metode REST pentru a putea face requesturile HTTP de modificare a BD-ului (cu ajutorul functiilor din UserService). + Am testat serverul creat cu SpringBoot in postman + id-ul este transmis direct in url + fisiere JSON pentru a crea noi useri (contin si id-ul si numele) + fie, pentru a modifica numele unui user: trimit id-ul prin url si numele ca parametru. ### Optional + Am creat interfata FriendRepository si clasele FriendService si FriendController. + Am facut serviciile REST pentru operatiile pentru: + inserarea unui prieten, + stergerea unui prieten, + afisarea tuturor prietenilor din lista. + Am testat cu Postman noile servicii create. + Am integrat laboratorul 10 cu 11 + am folosit proiectul din laboratorul 11 (cu unele modificari) drept server + am pastrat clientul din laboratorul 10 <file_sep>/Laborator 4/Laborator 4 - optional/src/main/java/Solution.java import javafx.util.Pair; import java.util.ArrayList; import java.util.List; /** * <p> Clasa solution descrie o solutie a unei probleme. </p> */ public class Solution { private List<Pair<Student, School>> matching = new ArrayList<>(); public Solution() { } /** * <p> Metoda va adauga o pereche Student-Liceu in lista cu repartizarile.</p> * * @param S studentul * @param H liceul */ public void addMatching(Student S, School H) { Pair<Student, School> pair = new Pair<>(S, H); matching.add(pair); } @Override public String toString() { String solutie = "Distribution: ["; solutie += "("; solutie += matching.get(0).getKey().getNume(); solutie += ":"; solutie += matching.get(0).getValue().getNume(); solutie += ")"; for (int index = 1; index < matching.size(); index++) { solutie += ", ("; solutie += matching.get(index).getKey().getNume(); solutie += ":"; solutie += matching.get(index).getValue().getNume(); solutie += ")"; } solutie += "]"; return solutie; } } <file_sep>/Laborator 3/Laborator 3 (optional)/src/TravelPlan.java import java.util.ArrayList; import java.util.List; /** * @author <NAME>. * * <p> In clasa Travel plan se va retine orasul vizitat si o lista cu preferinte. </p> * <p> Un calator poate insera maxim 5 locatii pe care vrea sa le viziteze. </p> */ public class TravelPlan { private City oras; List<Location> prefer = new ArrayList<>(); public TravelPlan(City oras, List<Location> prefer) { this.oras = oras; this.prefer = prefer; } public TravelPlan() { } public String getOras() { return oras.getName(); } public void setOras(City oras) { this.oras = oras; } public List<Location> getPrefer() { return prefer; } public void setPrefer(List<Location> prefer) { this.prefer = prefer; } @Override public String toString() { return "TravelPlan{" + "oras=" + oras + ", prefer=" + prefer + '}'; } } <file_sep>/Laborator 8/Bonus/src/main/java/MovieController.java import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * <h3> Clasa MovieController </h3> * <p> Implementeaza functiile din interfata MovieDAO </p> * <p> Se coneteaza la baza de date cu ajutorul unui obiect de tip Database. </p> */ public class MovieController implements MovieDAO { Database database; public MovieController(Database database) { this.database = database; } @Override public void create(int id_movie, String nume, int year, int duration, double score) { try { PreparedStatement statement = database.connection.prepareStatement("insert into movies (id_movie, title, release_date, duration, score) values(?, ?, to_date(?, 'yyyy'), ?, ?)"); statement.setInt(1, id_movie); statement.setString(2, nume); statement.setInt(3, year); statement.setInt(4, duration); statement.setDouble(5, score); statement.execute(); System.out.println("New row inserted"); statement.close(); //database.connection.close(); } catch (SQLException exp) { exp.printStackTrace(); } } @Override public Movie findByName(String name) throws NullPointerException { Movie lastMovie = null; try { PreparedStatement statement = database.connection.prepareStatement("select * from movie where title=?"); statement.setString(1, name); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { lastMovie = new Movie(resultSet.getInt(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getInt(4), resultSet.getInt(5)); System.out.println(lastMovie); } return lastMovie; } catch (SQLException exp) { exp.printStackTrace(); } return lastMovie; } public void allInfo() { try { PreparedStatement statement = database.connection.prepareStatement("select M.title, M.release_date, M.duration, M.score, G.nume from movies M, genres G, film F where M.id_movie = F.id_movie and G.id_genre = F.id_genre order by M.title"); ResultSet resultSet = statement.executeQuery(); String lastMovie = "null"; while (resultSet.next()) { if(lastMovie.equals(resultSet.getString(1))) { System.out.print(", " + resultSet.getString(5)); } else { PreparedStatement stmtDir = database.connection.prepareStatement("select P.prenume, P.nume from movies M, directors D, person P where M.id_movie = D.id_movie and D.id_pers = P.id_pers and M.title = ?"); stmtDir.setString(1, resultSet.getString(1)); ResultSet rsDir = stmtDir.executeQuery(); List<String> actori = new ArrayList<>(); PreparedStatement stmtActor = database.connection.prepareStatement("select P.prenume, P.nume from movies M, actors A, person P where M.id_movie = A.id_movie and A.id_pers = P.id_pers and M.title = ?"); stmtActor.setString(1, resultSet.getString(1)); ResultSet rsActor = stmtActor.executeQuery(); int i = 0; while(rsActor.next()) { actori.addAll(Collections.singleton(rsActor.getString(2) + " " + rsActor.getString(1))); i++; } System.out.println(); System.out.println("Movie:" + resultSet.getString(1)); System.out.println(" - score: " + resultSet.getDouble(4)); rsDir.next(); System.out.println(" - director: " + rsDir.getString(2) + " " + rsDir.getString(1)); System.out.println(" - released: " + resultSet.getString(2)); System.out.println(" - " + resultSet.getInt(3) + " minutes"); System.out.print(" - actors: " + actori.get(0)); for(int j=1; j<actori.size();j++) { System.out.print(", " + actori.get(j)); } System.out.println(); System.out.print(" - genre: " + resultSet.getString(5)); } lastMovie = resultSet.getString(1); } System.out.println(); } catch (SQLException exp) { exp.printStackTrace(); } } } <file_sep>/Laborator 3/Laborator 3 (optional)/src/main.java import java.util.ArrayList; import java.util.List; /** * @author <NAME>. * * <p> Clasa main va contine programul principal. </p> * <p> Toate obiectele instantiate vor avea numele "vx", unde x este indicele incepand de la 0. </p> */ public class main { /** * <p> 1. Initializez un oras. </p> * <p> 2. Adaug locatii pe "harta" orasului si le memorez adresa in lista acestuia. </p> * <p> 3. In mapa pun costurile deplasarilor de la o locatie la alta. </p> * <p> 4. Afisez informatiile cunoscute despre locatii si mai apoi despre costul deplasarii intre acestea. </p> * <p> 5. Verifica daca avem in Iasi locatii vizitabile unde nu trebuie sa plateasca. </p> * <p> 6. Se calculeaza cat timp este deschis Restaurantul v6. </p> * <p> 7. Initializam lista de preferinte a Calatorului_1 si le afisam. </p> * * @param args lista de parametri data in consola */ public static void main(String[] args) { /* 1. */ City Iasi = new City("Iasi"); /* 2. */ Hotel v1 = new Hotel("Unirii", "Unirea", 100, 80, 4); v1.address = v1; v1.address_name = "v1"; Iasi.locatii.add(v1); Museum v2 = new Museum("Iancu Bacalu", "Natura", 5, 30); v2.address = v2; v2.address_name = "v2"; Iasi.locatii.add(v2); Museum v3 = new Museum("Garii", "Istorie", 10, 50); v3.address = v3; v3.address_name = "v3"; Iasi.locatii.add(v3); Church v4 = new Church("<NAME>", "<NAME>", "ortodoxa"); v4.address = v4; v4.address_name = "v4"; Iasi.locatii.add(v4); Church v5 = new Church("Palas", "<NAME>", "catolica"); v5.address = v5; v5.address_name = "v5"; Iasi.locatii.add(v5); Restaurant v6 = new Restaurant("Mammamia", "fast-food", "Unirii"); v6.address = v6; v6.address_name = "v6"; v6.setOpenDuration(); Iasi.locatii.add(v6); Park v7 = new Park("Garii", "de copii", 18); v7.address = v7; v7.address_name = "v7"; Iasi.locatii.add(v7); /* 3. */ v1.setCost(v2, 10); v1.setCost(v3, 50); v2.setCost(v3, 20); v2.setCost(v4, 20); v2.setCost(v5, 10); v3.setCost(v2, 20); v3.setCost(v4, 20); v4.setCost(v5, 30); v4.setCost(v6, 10); v5.setCost(v4, 30); v5.setCost(v6, 20); /* 4. */ int i; for (i = 0; i < Iasi.locatii.size(); i++) { System.out.println(Iasi.locatii.get(i).address_name + ":" + Iasi.locatii.get(i).address); } for (i = 0; i < Iasi.locatii.size(); i++) { for (Location id : Iasi.locatii.get(i).cost.keySet()) { System.out.println(Iasi.locatii.get(i).address_name + " -> " + id.address_name + " are costul " + Iasi.locatii.get(i).cost.get(id)); } } /* 5. */ Iasi.Visit(); System.out.println(""); /* 6. */ long ora, minute; ora = v6.getOpenDuration() / 60; minute = v6.getOpenDuration() % 60; System.out.println(" Restaurantul " + v6.getName() + " este deschis " + ora + " ore si " + minute + " minute."); /* 7. */ TravelPlan calator_1 = new TravelPlan(); calator_1.setOras(Iasi); List<Location> preferinte = new ArrayList<>(); preferinte.add(v1); preferinte.add(v4); preferinte.add(v7); preferinte.add(v2); preferinte.add(v5); calator_1.setPrefer(preferinte); System.out.println(calator_1.getOras()); System.out.println(calator_1.getPrefer()); } } <file_sep>/Laborator 12/README.md # Laborator 12 ## <NAME> 2A4 ### Compulsory + Am creat interfata TestInterface (nu contine metode, insa creaza bean-urile pentru clasa de testare) + Am creat clasa TestClass + sunt definite metodele de testare aplicate asupra unei clase + implementeaza interfata creata pentru a putea folosi functionalitatea de testare + Am creat clasa ClassLoader care predefineste functii ajutatoare pentru definirea path-ului clasei ce va i testate + In Main: + am declarat un path pentru o clasa ce va fi testata + am verificat daca intr-adevar exista clasa la acea adresa + parcurg toate metodele din clasa TestClass + aplic metoda curenta pe clasa si in functie de rezultat se va incrementa testPassed sau testFailed + afisez cate teste au fost trecute si cate picate din cele aplicate pe acea clasa. <file_sep>/Laborator 1/Laborator 1 (compulsory)/src/Lab1.java import java.util.Scanner; public class Lab1 { /* autor: <NAME> 2A4 */ //Compulsory (1p) public static void main(String[] args) { // Write a Java application that implements the following operations: // Display on the screen the message "Hello World!". Run the application. If it works, go to step 2 :) System.out.println("Hello World!"); // Define an array of strings languages, containing {"C", "C++", "C#", "Python", "Go", "Rust", "JavaScript", "PHP", "Swift", "Java"} String[] languages = {"C", "C++", "C#", "Python", "Go", "Rust", "JavaScript", "PHP", "Swift", "Java"}; for (String element: languages) { System.out.println(element); } // Generate a random integer n: int n = (int) (Math.random() * 1_000_000); int n = (int) (Math.random() * 1_000_000); System.out.println("n = " + n); // Compute the result obtained after performing the following calculations: // multiply n by 3; n = n * 3; System.out.println("n*3 = " + n); // add the binary number 10101 to the result; String binary="10101"; int decimal=Integer.parseInt(binary,2); n = n + decimal; System.out.println("n*3+binary = " + n); // add the hexadecimal number FF to the result; String hex="FF"; decimal=Integer.parseInt(hex,16); n = n + decimal; System.out.println("n*3+binary+hex = " + n); // multiply the result by 6; n = n * 6; System.out.println("(n*3+binary+hex)*6 = " + n); // Compute the sum of the digits in the result obtained in the previous step. This is the new result. While the new result has more than one digit, continue to sum the digits of the result. int sum = n; while(sum > 9) { n = sum; sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } } System.out.println("the diggit is " + sum); // Display on the screen the message: "Willy-nilly, this semester I will learn " + languages[result]. System.out.println("Willy-nilly, this semester I will learn " + languages[sum]); //////////////////////////////////////////////////////////////////////////////////////////////////////// //Optional (2p) // Let n be an integer given as a command line argument. Validate the argument! // Create a n x n matrix, representing the adjacency matrix of a random graph . // Display on the screen the generated matrix (you might want to use the geometric shapes from the Unicode chart to create a "pretty" representation of the matrix). System.out.println("Input a number for the matrix: "); n=0; Scanner keyboard = new Scanner(System.in); int m = keyboard.nextInt(); while(m<=0) { System.out.println("Invalid number for a matrix. Try smth else."); m = keyboard.nextInt(); } long start = System.nanoTime(); //nanoseconds running time System.out.println("The matrix is " + m + "x" + m + ":"); int i,j; n = m; m = n + 1; int[][] A = new int[m][m]; if(n<100) { System.out.print(" | "); for(i=1;i<m;i++) { if(i<10) System.out.print(" " + i + " "); else System.out.print(i + " "); } System.out.println(""); System.out.print("---+"); for(i=1;i<m;i++) { System.out.print("---"); } System.out.println("-"); } for(i=1;i<m;i++) { for(j=1;j<m;j++) { if(i==j) A[i][j]=0; else { int k = (int) (Math.random() * m); A[i][j] = k; } } } // For larger n display the running time of the application in nanoseconds (DO NOT display the matrices). Try n > 30_000. You might want to adjust the JVM Heap Space using the VM options -Xms4G -Xmx4G. long stop = System.nanoTime(); long timp = stop - start; if(n<100) { for(i=1;i<m;i++) { if(i<10) System.out.print(" " + i + " | "); else System.out.print(i + " | "); for(j=1;j<m;j++) { if(A[i][j]<10) System.out.print(" " + A[i][j] + " "); else System.out.print(A[i][j] + " "); } System.out.println(""); } } else { System.out.println("Running time: " + timp + " nanoseconds."); } // Verify if the generated graph is connected and display the connected components (if it is not). // Assuming that the generated graph is connected, implement an algorithm that creates a partial tree of the graph. Display the adjacency matrix of the tree. // Launch the application from the command line, for example: java Lab1 100. } } <file_sep>/Laborator 3/Laborator 3 (compulsory)/src/Visitable.java import java.time.LocalTime; /** * @author <NAME>. * * <p> In interfata Visitable avem metode ce primesc ora deschiderii si ora inchiderii oricarei locatii care este vizitabila cu un program. </p> */ public interface Visitable { /** * <p> Primeste ora deschiderii. </p> * * @return ora deschiderii daca aceasta exista; null altfel */ LocalTime getOpeningTime(); /** * <p> Primeste ora inchiderii. </p> * * @return ora inchiderii daca aceasta exista; null altfel */ LocalTime getClosingTime(); } <file_sep>/Laborator 5/Compulsory/src/main/java/Main.java import java.io.IOException; /** * <p> Aplicatia principala unde se apeleaza functiile din clase. </p> */ public class Main { public static void main(String args[]) throws IOException, InvalidCatalogException { Main app = new Main(); app.testCreateSave(); app.testLoadView(); } private void testCreateSave() throws IOException { Catalog registru = new Catalog("1", "Ecran","c:/Users/andra/Desktop"); Picture image = new Picture("img1","Pozica", "c:/Users/andra/Desktop"); registru.add(image); CatalogUtil.save(registru); } private void testLoadView() throws InvalidCatalogException { Catalog NUL = new Catalog("NUL", "NUL", "NUL"); Catalog registru = CatalogUtil.load("c:/Users/andra/Desktop"); Item doc = registru.findById("img1"); if (doc != NUL) { System.out.println(registru.findById("img1").getName()); } CatalogUtil.view(registru); } } <file_sep>/Laborator 6/JavaFX/Compulsory/README.md Laborator 6 - compulsory Am incercat sa lucrez initial cu JavaFX si a mers bine pana la inserarea handle-urilor pentru actiuni (au aparut diverse bugguri). Singurele handle-uri pe care le-am putut implementa au fost cel pentru butonul de exit si un handle test pentru a afisa in consola mesaje la apasarea unui buton. <file_sep>/Laborator 3/Laborator 3 (optional)/READ ME.md Din optionalul de la Laboratorul 3 nu am abordat ultima bulina / ultimul subpunct. <file_sep>/Laborator 11/Compulsory/lab11/src/main/resources/application.properties server.port=8090 spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE spring.datasource.username=student spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=oracle.jdbc.OracleDriver <file_sep>/Laborator 2/Laborator 2 (optional)/src/Factories.java /** * @author <NAME>. * @version "%I%, %G%" * <p> Obiectele sursa pot fi de 2 tipuri, unul din ele este factory: </p> */ public class Factories extends Source { /** * <p> Class constructor se initializeaza obiecte de tip factory </p> * * @param name numele sursei * @param capacity capacitatea obiectului de tip sursa */ public Factories(String name, int capacity) { super(name, capacity); } /** * <p> Creaza un string cu informatii despre sursele de tip factory </p> * * @return stringul cu informatii */ @Override public String toString() { return "Source {" + "Factory " + name + ", capacity=" + capacity + '}'; } } <file_sep>/Laborator 6/Swing/Optional/src/main/java/EmptyListException.java /** * <p> Exceptia aruncata cand se apasa butonul de "undo" si lista de figuri este goala si nu se mai pot sterge elemente. </p> */ public class EmptyListException extends RuntimeException { public EmptyListException(String message) { super(message); } }<file_sep>/Laborator 6/JavaFX/Compulsory/src/sample/Main.java package sample; import com.sun.javafx.menu.MenuItemBase; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXMLLoader; import javafx.scene.Group; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.SubScene; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Button; import javafx.scene.control.ButtonBase; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import java.awt.*; import java.io.IOException; import java.util.EventObject; public class Main extends Application{ private void loadWhenClicked(ActionEvent event){ Button button = (Button) event.getSource(); System.out.println(button.getText()); // prints out button's text } @Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("sample.fxml")); Scene scena = new Scene(root, 600, 400); primaryStage.setTitle("Laborator 6"); primaryStage.setScene(scena); primaryStage.setIconified(false); /* javafx.scene.shape.Polygon hexagon = new Polygon(); hexagon.getPoints().addAll(new Double[]{ 200.0, 50.0, 400.0, 50.0, 450.0, 150.0, 400.0, 250.0, 200.0, 250.0, 150.0, 150.0, }); Group root1 = new Group(hexagon); Scene scene = new Scene(root1 ,600, 300); primaryStage.setScene(scene);*/ primaryStage.addEventHandler(KeyEvent.KEY_PRESSED, (key) -> { if(key.getCode()== KeyCode.ENTER) { System.out.println("You pressed enter"); } }); primaryStage.show(); } public static void main(String[] args) { launch(args); } } <file_sep>/Laborator 13/lab13/src/main/java/app/LocaleCommand.java package app; import java.text.DateFormatSymbols; import java.text.MessageFormat; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.ResourceBundle; public class LocaleCommand { private static Locale locale; private static ResourceBundle resourceBundle; private static final String name = "Messages"; /** * <p> Functia ia proprietatea unei comenzi din bundle-ul Messages si in functie de aceasta va formata parametri. </p> * @param key comanda apelata si cautata in bundle * @param arguments argumentele necesare pentru comanda respectiva * @return mesajul de apelare a functiei pentru comanda instantiata */ public static String message(String key, String ... arguments) { String commandName = resourceBundle.getString(key); String msg = new MessageFormat(commandName).format(arguments); return msg; } /* seteaza limba si in functie de aceasta va apela bundle-ul corespunzator */ public static void setLocale(String language) { LocaleCommand.locale = Locale.forLanguageTag(language); LocaleCommand.resourceBundle = ResourceBundle.getBundle(name, locale); message("locale.set", language); } /* afiseaza rezultatul comenzii */ public static void displayLocales() { System.out.println(LocaleCommand.message("locales")); for (Locale locale : Locale.getAvailableLocales()) { System.out.println(locale.toString()); } } public static void localeInfo() { System.out.println(LocaleCommand.message("locale.set",LocaleCommand.getLocale().getDisplayName())); DateFormatSymbols date = DateFormatSymbols.getInstance(LocaleCommand.getLocale()); System.out.println(LocaleCommand.getLocale().getCountry()); System.out.println(LocaleCommand.getLocale().getLanguage()); for (String i : date.getWeekdays()) { System.out.print(i + ' '); } System.out.println(); for (String i : date.getMonths()) { System.out.print(i + ' '); } System.out.println(); DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("DD/MMM/YYYY", LocaleCommand.getLocale()); LocalDateTime presentTime = LocalDateTime.now(); System.out.println(dateFormat.format(presentTime)); } public static Locale getLocale() { return LocaleCommand.locale; } }<file_sep>/Laborator 10/README.md # <NAME> - Laborator 10 ## Compulsory + In proiectul pentru aplicatia server am creat clasa SocialServer care: + se asigura ca socketul pentru server ruleaza la un anumit port (2121) + pentru fiecare nou client conectat la acest port creaza un thread + Clasa ClientThread din server: + este cea care face de fapt threadul pentru fiecare client (este apelata in SocialServer) + primeste requesturi de la client + creaza raspunsuri + le tirmite la client + Comenzile functionale sunt: stop, exit, iar orice mesaj care nu este recunscut ca si comanda va produce un raspuns pentru client + In proiectul pentru aplicatia client am creat clasa ClientCommands care: + citeste comenzile de la tastatura + le trimite serverului + primeste raspunsul si il afiseaza ## Optional + In proiectul pentru aplicatia server am creat clasa Client care retine date despre toti clientii conectati la server + Cu ajutorul unui string.split(" ") am impartit requestul de la client in cuvinte separate de spatiu: + primul cuvant va fi mereu comanda + urmatoarele cuvinte fiind fie numele de utilizator cu care vrea sa faca login / register sau numele prietenilor pe care vrea sa ii adauge + Am implementat toate functionalitatile: login, register, friend, send, read, exit, stop + Am adaugat un server timeout de 3 minute <file_sep>/Laborator 9/README.md # <NAME> - Laborator 9 ## Compulsory + Am adaptat proiectul (facut in IntelliJ) pentru laboratorul 8 pentru cel din 9: + am adaugat suport pentru JPA din setarile proiectului + am adaugat toate driverele necesare + am creat pesistence.xml + In persistence.xml am adaugat toate informatiile necesare pentru conectarea la baza de date + persistence.xml se afla in Laborator 9/Compulsory/target/classes/META-INF/ <file_sep>/Laborator 11/Optional/lab11server/src/main/java/com/example/lab11/controllers/UserController.java package com.example.lab11.controllers; import com.example.lab11.entities.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import com.example.lab11.services.UserService; import java.util.List; /** * <h3> Clasa UserController </h3> * <p> Clasa se foloseste de metodele din UserService pentru a defini metode pentru requesturi HTTP. </p> */ @RestController public class UserController { @Autowired private UserService userService; // public UserController(UserService userService) { // this.userService = userService; // } @RequestMapping(method = RequestMethod.GET, value = "/") public List<User> getUserList() { return userService.getAllUsers(); } @RequestMapping(method = RequestMethod.POST, value = "/") public User createUser(@RequestBody User user) { return userService.addUser(user); } @RequestMapping(method = RequestMethod.PUT, value = "/{id}") public User putUserName(@PathVariable short id, @RequestParam String name) { return userService.changeName(id, name); } @RequestMapping(method = RequestMethod.DELETE, value = "{id}") public void deleteUser(@PathVariable short id) { userService.deleteUser(id); } } <file_sep>/Laborator 6/Swing/Compulsory/README.md Laborator 6 - compulsory O abordare a laboratorului folosind Swing. Optiounile din partea de sus nu au nicio functionalitate specifica. Aplicatia generaza triunghiuri de dimensiuni si culori transprente random. Se pot salva imagini in locatia dorita si se pot incarca si poze din computer. <file_sep>/Laborator 5/Optional/src/main/java/Main.java import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * <p> Aplicatia principala unde se apeleaza functiile din clase. </p> */ public class Main { public static void main(String args[]) throws IOException, InvalidCatalogException { Main app = new Main(); app.testCreateSave(); app.testLoadView(); } private void testCreateSave() throws IOException { Catalog registru = new Catalog("1", "Ecran", "c:/Users/andra/Desktop"); Picture image = new Picture("img1", "Pozica", "c:/Users/andra/Desktop"); registru.add(image); registru.list(); CatalogUtil.save(registru); Scanner scanner = new Scanner(System.in); List<CatalogShellCommand> comenzi = new ArrayList<>(); CatalogUtilShell.ExitCommand exit = new CatalogUtilShell.ExitCommand("exit"); CatalogUtilShell input = new CatalogUtilShell(registru, scanner, 0, comenzi, exit); input.initialize(); } private void testLoadView() throws InvalidCatalogException { Catalog NUL = new Catalog("NUL", "NUL", "NUL"); Catalog registru = CatalogUtil.load("c:/Users/andra/Desktop"); Item doc = registru.findById("img1"); if (doc != NUL) { System.out.println(registru.findById("img1").getName()); } CatalogUtil.view(registru); } } <file_sep>/Laborator 3/Laborator 3 (optional)/src/City.java import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * @author <NAME>. * * <p> Clasa City tine evidenta oraselor si in ce tara se afla acestea. </p> */ public class City { public String name; protected List<Location> locatii = new ArrayList<>(); /** * <p> Class constructor. </p> * <p> Initializeaza numele orasului la declararea unui obiect de acest tip. </p> * * @param name numele orasului */ public City(String name) { this.name = name; } /** * <p> Primeste numele orasului unui obiect de tip City. </p> * * @return numele orasului */ public String getName() { return name; } /** * <p> Initializeaza numele unui obiect de tip City. </p> * * @param name numele orasului */ public void setName(String name) { this.name = name; } /** * <p> In lista de locatii dintr-un oras se mai poate adauga inca un hotel, museu, restaurant etc. </p> * * @param node obiectul adaugat in lista */ public void addLocation(Location node) { locatii.add(node); } /** * <p> Functia Visit verifica daca un obiect este vizitable dar nu si payable </p> */ public void Visit() { int i; List<Location> sortare = new ArrayList<>(); for (i = 0; i < this.locatii.size(); i++) { if (this.locatii.get(i).address instanceof Visitable) { if (!(this.locatii.get(i).address instanceof Payable)) { sortare.add(this.locatii.get(i).address); } } } System.out.println(""); System.out.println(" Locatiile vizitabile, unde nu se plateste, ordonate dupa ora deschiderii sunt: "); sortare.sort(Comparator.comparing(Location::toString)); for (i = 0; i < sortare.size(); i++) { System.out.println(sortare.get(i)); } } } <file_sep>/Laborator 11/Optional/lab11server/src/main/java/com/example/lab11/entities/Friend.java package com.example.lab11.entities; import javax.persistence.*; import java.io.Serializable; /** * <h3> Clasa Friend </h3> * <p> Un obiect instantiat cu aceasta clasa este echivalentul unei linii din tabela friends din baza de date.</p> */ @Entity @Table(name = "FRIENDS", schema = "STUDENT") public class Friend implements Serializable { private short idUser; private short idFriend; private Long id; @Basic @Id @Column(name = "ID_USER") public short getIdUser() { return idUser; } public void setIdUser(short idUser) { this.idUser = idUser; } @Basic @Id @Column(name = "ID_FRIEND") public Short getIdFriend() { return idFriend; } public void setIdFriend(Short idFriend) { this.idFriend = idFriend; } public void setId(Long id) { this.id = id; } } <file_sep>/Laborator 4/READ ME.md Laborator 4 - Java Mai multe detalii se afla in comentariul antet din clasa Main. <file_sep>/Laborator 8/Optional/target/classes/lab8.sql ---------------------------------------------------------------------------------------------- --JAVA - LAB 8 --@author: <NAME> ---------------------------------------------------------------------------------------------- drop table film; drop table actors; drop table directors; drop table movies; drop table genres; drop table person; create table movies ( id_movie number(4) primary key, title varchar2(50) not null, release_date date not null, duration number(5) not null, score number(3, 2) not null, check (duration > 0) ); create table genres ( id_genre number(4) primary key, nume varchar2(15) not null ); create table film ( id_movie number(4) references movies (id_movie), id_genre number(4) references genres (id_genre) ); create table person ( id_pers number(4) primary key, nume varchar2(20) not null, prenume varchar2(30) not null, gender varchar2(3) not null, check (gender in ('M','F','N/A')) ); create table actors ( id_pers number(4) references person(id_pers), id_movie number(4) references movies(id_movie) ); create table directors ( id_pers number(4) references person(id_pers), id_movie number(4) references movies(id_movie) ); ---------------------------------------------------------------------------------------------- insert into movies values (1, 'The Shawshank Redemption', to_date('1994', 'YYYY'), 142, 9.3); insert into movies values (2, 'The Godfather', to_date('1972', 'YYYY'), 175, 9.2); insert into movies values (3, 'The Dark Knight', to_date('2008', 'YYYY'), 152, 9.0); insert into genres values (1, 'Drama'); insert into genres values (2, 'Crime'); insert into genres values (3, 'Action'); insert into film values (1, 1); insert into film values (2, 1); insert into film values (2, 2); insert into film values (3, 1); insert into film values (3, 2); insert into film values (3, 3); insert into person values (1, 'Darabont', 'Frank', 'M'); insert into person values (2, 'Robbins', 'Tim', 'M'); insert into person values (3, 'Freeman', 'Morgan', 'M'); insert into person values (4, 'Gunton', 'Bob', 'M'); insert into person values (5, 'Coppola', '<NAME>', 'M'); insert into person values (6, 'Brando', 'Marlon', 'M'); insert into person values (7, 'Pacino', 'Al', 'M'); insert into person values (8, 'Nolan', 'Christopher', 'M'); insert into person values (9, 'Bale', 'Christian', 'M'); insert into person values (10, 'Ledger', 'Heath', 'M'); insert into directors values (1, 1); insert into directors values (5, 2); insert into directors values (8, 3); insert into actors values (2, 1); insert into actors values (3, 1); insert into actors values (4, 1); insert into actors values (6, 2); insert into actors values (7, 2); insert into actors values (9, 3); insert into actors values (10, 3); ---------------------------------------------------------------------------------------------- <file_sep>/Laborator 6/Swing/Optional/src/main/java/NodeShape.java import java.awt.geom.Ellipse2D; /** * <p> Constructorul din NodeShape class creaza un cerc cu datele introduse. </p> */ public class NodeShape extends Ellipse2D.Double { public NodeShape(double x, double y, double radius) { super(x-radius/2,y-radius/2,radius,radius); } } <file_sep>/Laborator 3/Laborator 3 (compulsory)/src/Hotel.java import java.time.LocalTime; /** * @author <NAME>. * * <p> Clasa Hotel retine locatia, numele, numarul de persoane pe care le poate caza si pretul RON/persoana/noapte. </p> */ public class Hotel extends Location implements Visitable, Payable, Classifiable { public String name; public int capacity; public int price; /** * <p> Class constructor. </p> * * @param name numele hotelului * @param capacity numarul de persoane care pot fi cazate intr-o noapte * @param price pretul cazarii RON/persoana/noapte */ public Hotel(String name, int capacity, int price) { this.name = name; this.capacity = capacity; this.price = price; } /** * <p> Primeste numele unui obiect si il returneaza. </p> * * @return numele hotelului */ public String getName() { return name; } /** * <p> Initializeaza numele unui obiect. </p> * * @param name numele hotelului */ public void setName(String name) { this.name = name; } /** * <p> Primeste capacitatea unui obiect si o returneaza. </p> * * @return capacitatea hotelului */ public int getCapacity() { return capacity; } /** * <p> Initializeaza capacitatea unui obiect. </p> * * @param capacity capacitatea hotelului */ public void setCapacity(int capacity) { this.capacity = capacity; } /** * <p> Primeste pretul unui obiect si il returneaza. </p> * * @return pretul de cazare la hotel */ public int getPrice() { return price; } /** * <p> Initializeaza pretul unui obiect. </p> * * @param price pretul de cazare la hotel */ public void setPrice(int price) { this.price = price; } @Override public int getRank() { return 0; } @Override public double getTicketPrice() { return 0; } @Override public LocalTime getOpeningTime() { return null; } @Override public LocalTime getClosingTime() { return null; } @Override public int compareTo(Location o) { return 0; } @Override public String toString() { return "Hotel{" + "name='" + name + '\'' + ", capacity=" + capacity + ", price=" + price + ", address='" + address + '\'' + '}'; } } <file_sep>/Laborator 13/lab13/src/main/java/com/Info.java package com; import app.LocaleCommand; public class Info { public Info() { LocaleCommand.localeInfo(); } } // //import java.text.DateFormatSymbols; //import java.text.SimpleDateFormat; //import java.util.Currency; //import java.util.Locale; // //public class Info { // private String country; // private String language; // // public Info(String country, String language) { // this.country = country; // this.language = language; // } // // public void showCurrentLocale() { // Locale myLocale = new Locale(this.country, this.language); // Currency currency = Currency.getInstance(Locale.forLanguageTag(myLocale.getCountry())); // String[] weekDays = new DateFormatSymbols(Locale.forLanguageTag(myLocale.getCountry())).getWeekdays(); // SimpleDateFormat D = new SimpleDateFormat("F", Locale.forLanguageTag(myLocale.getCountry())); // SimpleDateFormat M = new SimpleDateFormat("M", Locale.forLanguageTag(myLocale.getCountry())); // SimpleDateFormat Y = new SimpleDateFormat("y", Locale.forLanguageTag(myLocale.getCountry())); // System.out.println("Country: " + myLocale.getCountry()); // System.out.println("Language: " + myLocale.getLanguage()); // System.out.println("Currency: " + currency); // for (int i = 0; i < weekDays.length; i++) { // System.out.println(weekDays[i] + ","); // } // System.out.println("Today is: " + D + " " + M + " " + Y); } //} <file_sep>/Laborator 10/Compulsory/Lab10server/src/main/java/SocialServer.java import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; /** * <h3> Clasa SocialServer </h3> * <p> Defineste portul de conectare al serverului. </p> * <p> Serverul asteapta conexiuni din partea clientilor. </p> * <p> Pentru fiecare client nou conectat se va crea un fir de executie / thread. </p> */ public class SocialServer { public static final int PORT = 2121; private static List<ClientThread> clients = new ArrayList(); public SocialServer() throws IOException { ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(PORT); while(true) { System.out.println("Waiting :) ... "); Socket socket = serverSocket.accept(); new ClientThread(socket).start(); } } catch (IOException exception) { System.err.println("Upsiez..." + exception); } finally { serverSocket.close(); } } public static List<ClientThread> getClients() { return clients; } }<file_sep>/Laborator 13/README.md # Laborator 13 ## <NAME> 2A4 + Am creat pachetul com cu 3 clase pentru functionalitatile celor 3 comenzi + Am creat pachetul app cu 2 clase: + clasa main LocaleExlore unde pentru fiecare comanda se apeleaza functia corespunzatoare ( si se ruleaza aplicatia) + clasa LocaleCommand unde sunt descrise functiile pentru comenzi + Am creat pachetul res in care am facut un bundle pentru mesaje si inca unul pentru gestionarea comenzilor de la tastatura, insa programul nu le identifica a fi resurse valide asa ca le-am mutat in folderul resources <file_sep>/Laborator 3/Laborator 3 (optional)/src/Church.java import java.time.LocalTime; import java.util.ArrayList; import java.util.List; /** * @author <NAME> * * <p> Clasa Church memoreaza numele, religia, adresa si programul de functionare al unei biserici. </p> */ public class Church extends Location implements Visitable { public static final String BLUE = "\u001B[34m"; public static final String RESET = "\u001B[0m"; private String name; private String religion; private LocalTime openingHour; private LocalTime closingHour; private long OpenDuration; /** * <p> Class constructor </p> * * @param street strada pe care se afla biserica * @param name numele bisericii * @param religion religia pe care o reprezinta * @param openingHour ora la care se deschide * @param closingHour ora la care se inchide */ public Church(String street, String name, String religion, LocalTime openingHour, LocalTime closingHour) { super(street); this.name = name; this.religion = religion; this.openingHour = openingHour; this.closingHour = closingHour; } /** * <p> Class constructor </p> * <p> Daca la instantierea obiectului nu este specificata ora, atunci aceasta va fi by default 6:00 - 18:00. </p> * * @param street strada pe care se afla biserica * @param name numele bisericii * @param religion religia pe care o reprezinta */ public Church(String street, String name, String religion) { super(street); this.name = name; this.religion = religion; this.openingHour = LocalTime.of(6, 00, 00); this.closingHour = LocalTime.of(18, 00, 00); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getReligion() { return religion; } public void setReligion(String religion) { this.religion = religion; } public LocalTime getOpeningHour() { return openingHour; } public void setOpeningHour(LocalTime openingHour) { this.openingHour = openingHour; } public LocalTime getClosingHour() { return closingHour; } public void setClosingHour(LocalTime closingHour) { this.closingHour = closingHour; } public long getOpenDuration() { return this.OpenDuration; } public void setOpenDuration() { OpenDuration = Visitable.getVisitingDuration(openingHour, closingHour); } @Override public void setOpeningTime(LocalTime hour) { this.openingHour = hour; } @Override public void setClosingTime(LocalTime hour) { this.closingHour = hour; } @Override public LocalTime getOpeningTime() { return this.openingHour; } @Override public LocalTime getClosingTime() { return this.closingHour; } @Override public int compareTo(Location o) { if (this == o) return 1; return 0; } @Override public String toString() { return BLUE + "Biserica " + RESET + religion + " " + name + " se afla pe strada " + street + " si este deschisa intre " + openingHour + " - " + closingHour + "." + "\n"; } } <file_sep>/Laborator 8/Compulsory/src/main/resources/lab8.sql ---------------------------------------------------------------------------------------------- --JAVA - LAB 8 --@author: <NAME> ---------------------------------------------------------------------------------------------- drop table film; drop table movies; drop table genres; create table movies ( id_movie number(4) primary key, title varchar2(50) not null, release_date date not null, duration number(5) not null, score number(3, 2) not null, check (duration > 0) ); create table genres ( id_genre number(4) primary key, nume varchar2(15) not null ); create table film ( id_movie number(4) references movies (id_movie), id_genre number(4) references genres (id_genre) ); ---------------------------------------------------------------------------------------------- insert into movies values (1, 'The Shawshank Redemption', to_date('1994', 'YYYY'), 142, 9.3); insert into movies values (2, 'The Godfather', to_date('1972', 'YYYY'), 175, 9.2); insert into movies values (3, 'The Dark Knight', to_date('2008', 'YYYY'), 152, 9.0); insert into genres values (1, 'Drama'); insert into genres values (2, 'Crime'); insert into genres values (3, 'Action'); insert into film values (1, 1); insert into film values (2, 1); insert into film values (2, 2); insert into film values (3, 1); insert into film values (3, 2); insert into film values (3, 3); ---------------------------------------------------------------------------------------------- <file_sep>/Laborator 8/Compulsory/src/main/java/GenreDAO.java /** * <h3> Interfata GenreDAO </h3> * <p> Contine functii pentru inserarea / crearea de noua linie in tabelul genre si pentru a identifica un anumit tip de filme dupa nume. </p> */ public interface GenreDAO { void create(int id_genre, String nume); Genres findByName(String name); } <file_sep>/README.md # ProgramareAvansata Buna ziua! Codul sursa se afla in ProgramareAvansata/Laborator nr/src. .png-urile sunt screenshot-uri cu outputul afisat de cod. <file_sep>/Laborator 5/Optional/README.md LABORATOR 5 - OPTIONAL Am continuat proiectul laborator5-compulsory si am lucrat la exercitiul optional. Clasele se afla in folderul src, iar fisierul .jar in .idea <file_sep>/Laborator 11/Optional/lab11server/src/main/java/com/example/lab11/controllers/FriendController.java package com.example.lab11.controllers; import com.example.lab11.entities.Friend; import com.example.lab11.entities.User; import com.example.lab11.services.FriendService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * <h3> Clasa FriendController </h3> * <p> Clasa se foloseste de metodele din FriendService pentru a defini metode pentru requesturi HTTP. </p> */ @RestController @RequestMapping("friends") public class FriendController { @Autowired private FriendService friendService; // public FriendController(FriendService friendService) { // this.friendService = friendService; // } @RequestMapping(method = RequestMethod.GET, value = "/{idUser}") public List<Friend> getUserFriendList(@PathVariable short idUser) { return friendService.getAllFriends(idUser); } @RequestMapping(method = RequestMethod.POST, value = "/") public Friend addFriend(@RequestBody Friend friend) { return friendService.addFriend(friend); } @RequestMapping(method = RequestMethod.DELETE, value = "{idUser}/{idFriend}") public void deleteFriend(@PathVariable short idUser, @PathVariable short idFriend) { friendService.deleteFriend(idUser, idFriend); } } <file_sep>/Laborator 11/Compulsory/lab11/src/main/java/com/example/lab11/services/UserService.java package com.example.lab11.services; import com.example.lab11.entities.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.lab11.repository.UserRepository; import java.util.List; /** * <h3> Clasa UserService </h3> * <p> Se creaza functii cu ajutorul metodelor din interfata UserRepository pentru cerintele din enunt. </p> */ @Service public class UserService { private final UserRepository userRepository; @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public List<User> getAllUsers() { return userRepository.findAll(); } public User addUser(User user) { userRepository.save(user); return user; } public User changeName(short id, String nume) { User user = userRepository.getUserByIdUser(id); user.setName(nume); userRepository.save(user); return user; } public void deleteUser(short id) { User user = userRepository.getUserByIdUser(id); userRepository.deleteUserByIdUser(user.getIdUser()); } } <file_sep>/Laborator 6/Swing/Optional/src/main/java/DrawingPanel.java import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** * <p> Clasa DrawingPanel controleaza figurile afisate in canvas. </p> */ public class DrawingPanel extends JPanel { final MainFrame frame; List<Shape> shapes = new ArrayList<>(); final static int W = 1250, H = 600; BufferedImage image; //the offscreen image Graphics2D graphics; //the "tools" needed to draw in the image public DrawingPanel(MainFrame frame) { this.frame = frame; createOffscreenImage(); init(); } protected void createOffscreenImage() { image = new BufferedImage(W, H, BufferedImage.TYPE_INT_ARGB); graphics = image.createGraphics(); graphics.setColor(Color.WHITE); //fill the image with white graphics.fillRect(0, 0, W, H); } private void init() { shapes.clear(); setPreferredSize(new Dimension(W, H)); //don’t use setSize. Why? setBorder(BorderFactory.createEtchedBorder()); //for fun this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { drawShape(e.getX(), e.getY()); repaint(); } //Can’t use lambdas, JavaFX does a better job in these cases }); } public void deleteLastShape() { int lastIndex = shapes.size()-1; shapes.remove(lastIndex); drawShapeList(); } public void drawShapeList() { this.createOffscreenImage(); frame.repaint(); for (Shape shape : this.shapes) { graphics.setColor(shape.getColor()); if(shape.getType().equals("Polygon")) { graphics.fill(new RegularPolygon(shape.getX(), shape.getY(), shape.getRadius(), shape.getSides())); } else { graphics.fill(new NodeShape(shape.getX(), shape.getY(), shape.getRadius())); } } } private void drawShape(int x, int y) { int radius = frame.configPanel.size.getValue(); int sides = (int) frame.configPanel.sidesField.getValue(); //System.out.println(sides); String culoare = (String) frame.configPanel.colorCombo.getSelectedItem(); Color Color = new Color((int) (100 * Math.random()), (int) (100 * Math.random()), (int) (100 * Math.random()), 70); if (culoare != null && culoare.equals("Black")) { Color = new Color(0, 0, 0, 50); } String type = (String) frame.configPanel.shapeType.getSelectedItem(); shapes.add(new Shape(x,y,radius,sides,type,Color)); drawShapeList(); } @Override public void update(Graphics g) { } //Why did I do that? @Override protected void paintComponent(Graphics g) { g.drawImage(image, 0, 0, this); } }<file_sep>/Laborator 1/Laborator 1 (compulsory + optional)/src/Lab1.java //import java.util.Scanner; public class Lab1 { /* autor: <NAME> 2A4 */ /* am initializat niste stringuri cu nume mai sugestiv cu coduri de culori */ public static final String PURPLE = "\u001B[35m"; public static final String PURPLE_BOLD = "\033[1;35m"; public static final String RESET = "\u001B[0m"; /* DFS recursiv */ public static void DFS(int i, int[][] graf, int m, int[] vizitat) { if(vizitat[i] == 0) { vizitat[i] = 1; // a fost vizitat System.out.print(i + " "); int j; for(j=0;j<m;j++) { if (graf[i][j]==1 && vizitat[j]==0) { DFS(j, graf, m, vizitat); } } } } /* oarecum similar cu DFS-ul se verifica daca exista cicluri in graf*/ public static int esteCerc(int[][] graf, int n, int u, int[] vizitat, int tata) { vizitat[u] = 1; for(int v = 0; v<n; v++) { if(graf[u][v]==1) { if(vizitat[v]==0) { if(esteCerc(graf, n, v, vizitat, u)==1) { return 1; } } else if(v != tata) { return 1; //este cerc } } } return 0; //nu este cerc } //Compulsory (1p) public static void main(String[] args) { // Write a Java application that implements the following operations: // Display on the screen the message "Hello World!". Run the application. If it works, go to step 2 :) System.out.println(PURPLE_BOLD + "Compulsory:" + RESET); System.out.println("Hello World!"); // Define an array of strings languages, containing {"C", "C++", "C#", "Python", "Go", "Rust", "JavaScript", "PHP", "Swift", "Java"} String[] languages = {"C", "C++", "C#", "Python", "Go", "Rust", "JavaScript", "PHP", "Swift", "Java"}; for (String element: languages) { System.out.println(element); } // Generate a random integer n: int n = (int) (Math.random() * 1_000_000); int n = (int) (Math.random() * 1_000_000); System.out.println("n = " + n); // Compute the result obtained after performing the following calculations: // multiply n by 3; n = n * 3; System.out.println("n*3 = " + n); // add the binary number 10101 to the result; String binary="10101"; int decimal=Integer.parseInt(binary,2); n = n + decimal; System.out.println("n*3+binary = " + n); // add the hexadecimal number FF to the result; String hex="FF"; decimal=Integer.parseInt(hex,16); n = n + decimal; System.out.println("n*3+binary+hex = " + n); // multiply the result by 6; n = n * 6; System.out.println("(n*3+binary+hex)*6 = " + n); // Compute the sum of the digits in the result obtained in the previous step. This is the new result. While the new result has more than one digit, continue to sum the digits of the result. int sum = n; while(sum > 9) { n = sum; sum = 0; while (n != 0) { sum = sum + n % 10; n = n/10; } } System.out.println("the diggit is " + sum); // Display on the screen the message: "Willy-nilly, this semester I will learn " + languages[result]. System.out.println("Willy-nilly, this semester I will learn " + languages[sum]); //////////////////////////////////////////////////////////////////////////////////////////////////////// //Optional (2p) // Let n be an integer given as a command line argument. Validate the argument! // Create a n x n matrix, representing the adjacency matrix of a random graph . // Display on the screen the generated matrix (you might want to use the geometric shapes from the Unicode chart to create a "pretty" representation of the matrix). System.out.println(" "); System.out.println(PURPLE_BOLD + "Optional:" + RESET); System.out.println("Input a number for the matrix: "); n=0; /* Scanner keyboard = new Scanner(System.in); int m = keyboard.nextInt(); */ //initial am citit m de la tastatura => merge doar RUN din IDE /* pentru rulat din cmd: */ /* nu pot fi decomentate sau comentate ambele linii cu "int m" */ //int m = Integer.parseInt(args[0]); //decomentat => merge rulat din cmd/terminal int m=10; //decomentat => (un artificiu) la run in inteliji afiseaza si unicodurile if(m<=0) //nu exista matrici adiacente de -5 x -5 sau 0 x 0 { System.out.println("Invalid number for a matrix. Try smth else."); } else { long start = System.nanoTime(); //timpul in nanosecunde in momentul cand programul ajunge aici System.out.println("The matrix is " + m + "x" + m + " and the data it's stored like this:"); int i,j; n = m; m = n + 1; int[][] graf = new int[m][m]; if(n<1000) //pentru un numar "decent" de afisat matricea se pregateste afisarea acesteia { System.out.print(" | "); for(i=1;i<m;i++) { if(i<10) System.out.print(" " + i + " "); else System.out.print(i + " "); } System.out.println(""); System.out.print("---+"); for(i=1;i<m;i++) { System.out.print("---"); } System.out.println("-"); } /* se genereaza matricea de adiacenta */ for(i=1;i<m;i++) { for (j = 1; j < m; j++) { if (i == j) graf[i][j] = 0; else { int k = (int) (Math.random() * 2); graf[i][j] = k; graf[j][i] = k; } } } // For larger n display the running time of the application in nanoseconds (DO NOT display the matrices). Try n > 30_000. You might want to adjust the JVM Heap Space using the VM options -Xms4G -Xmx4G. long stop = System.nanoTime(); //timpul in nanosecunde dupa ce s-a generat matricea long timp = stop - start; //timpul de rulare in nanosecunde if(n<1000) //se afiseaza matricea { for(i=1;i<m;i++) { if(i<10) System.out.print(" " + i + " | "); else System.out.print(i + " | "); for(j=1;j<m;j++) { if(graf[i][j]<10) System.out.print(" " + graf[i][j] + " "); else System.out.print(graf[i][j] + " "); } System.out.println(""); } System.out.println(" "); System.out.println("Your matrix looks like this:"); /* matricea folosint unicoduri */ for(i=1;i<m;i++) { for(j=1;j<m;j++) { if(graf[i][j]==1) { System.out.print(PURPLE + "\u25C8 " + RESET); } else { System.out.print("\u25C7 "); } } System.out.println(" "); } } else //pentru n>1000 se afiseaza unning time in nanosecunde { System.out.println("Running time: " + timp + " nanoseconds."); } // Verify if the generated graph is connected and display the connected components (if it is not). /* se parcurge in adancime matricea si se afiseaza componentele si daca graful este conex */ int[] vizitat = new int[1000]; int count = 0; // numarul de componente conexe for(i = 1; i < m; i++) { if(vizitat[i]==0) { System.out.print("Componenta: " ); DFS(i,graf, m, vizitat); System.out.println(""); ++count; } } if(count>0) { System.out.println("Graful este conex si are " + count + " componente cu nodurile afisate mai sus."); } else { System.out.println("Graful nu este conex."); } // Assuming that the generated graph is connected, implement an algorithm that creates a partial tree of the graph. Display the adjacency matrix of the tree. /* crearea unui arbore partial */ /* ideea ar fi: daca in graful de mai sus exista cicluri, acestea sa fie sparte prin eliminarea unei muchii */ /* am incercat un algoritm care sa aleaga random o muchie dar exista foarte multe posibilitati => dureaza prea mult sa ruleze si se cam blocheaza aici*/ int ok, id1, id2; int arbore_partial=0; //0 = nu avem arbore partial int[] viz = new int[1000]; int[][] graf2 = new int[m][m]; while(arbore_partial==0) { /* se genereaza o pozitie random a unui element din graf */ id1 = (int) (Math.random() * m); id2 = (int) (Math.random() * m); while(graf[id1][id2]==0) { /* se genereaza pozitia pana se gaseste o muchie */ id1 = (int) (Math.random() * m); id2 = (int) (Math.random() * m); } /* se face o copie matricei */ for(i=1;i<m;i++) { for(j=1;j<m;j++) { graf2[i][j]=graf[i][j]; } } /* se sterge o muchie din graf pentru a se elimina ciclul daca acesta exista */ graf2[id1][id2]=0; /* se verifica daca subgraful obtinut este arbore partial */ ok = esteCerc(graf2, n,1, viz,1); if(ok==1) { arbore_partial=0; //System.out.println("Nu este arbore."); } else if(ok==0 && count==1) //arbore = nu are ciclu + are o componenta conexa { arbore_partial=1; System.out.println("Este arbore."); } } } // Launch the application from the command line, for example: java Lab1 100. /* Pasi: * 1. localizez fisierul .java si deschid cmd-ul (sau direct din terminalul din inteliji) * 2. setez locatia jdk-ului cu set path * 3. compilez programul: javac Lab1.java * 4. rulez executabilul si ii dau un parametru pentru m: java Lab1 10 */ } }<file_sep>/Laborator 2/Laborator 2 (optional)/README.md In directorul "javadoc" se afla toata filele generate de acesta In directorul "javadoc (classes only)" se afla doar filele legate strict de clase Solutia fesabila pe care am folosit-o a fost euristica prezentata la bonus (urmeaza sa il abordez si pe acesta si am vrut sa lucrez mai eficient folosint aceeasi idee de rezolvare la optional si bonus). <file_sep>/Laborator 6/Swing/Optional/README.md Exercitiul optional din cadrul laboratorului 6 - am introdus toate fromele intr-o lista si cu ajutorul acestei liste am introdus si butonul undo - in aplicatie se pot desena poligoane (se pot modifica numarul de muchii pentru a obtine diverse forme) + cercuri de marimi si culori diverse - in optiunile de forme extista "FreeDrawing": identifica daca a fost desenata o linie si o afiseaza pe ecran <file_sep>/Laborator 7/Compulsory/src/main/java/Game.java public class Game extends Thread{ private Board board; private Player player1; private Player player2; public Game(Board board, Player player1, Player player2) { this.board = board; this.player1 = player1; this.player2 = player2; } public Board getBoard() { return board; } public void setBoard(Board board) { this.board = board; } public Player getPlayer1() { return player1; } public void setPlayer1(Player player1) { this.player1 = player1; } public Player getPlayer2() { return player2; } public void setPlayer2(Player player2) { this.player2 = player2; } public void runGame() { this.player1.activateTurn(); boolean player1Turn = this.player1.isTurnActive(); Thread player1Thread = new Thread((Runnable) this.player1); player1Thread.start(); Thread player2Thread = new Thread((Runnable) this.player2); player2Thread.start(); } } <file_sep>/Laborator 3/Laborator 3 (optional)/src/Restaurant.java import java.time.LocalTime; /** * @author <NAME>. * * <p> Clasa Restaurant retine numele, tipul de mancare servita, numarul de stele, * pretul in medie, intervalul orar de functionare si adresa localului. </p> */ public class Restaurant extends Location implements Visitable, Payable, Classifiable { public static final String RED = "\u001B[31m"; public static final String RESET = "\u001B[0m"; private long OpenDuration; private String name; private String type; private int stars; private int avgPrice; //pretul mancarii in medie private LocalTime openingHour; private LocalTime closingHour; /** * <p> Class constructor </p> * * @param name numele restaurantului * @param type tipul de mancare servita * @param stars clasificarea - numarul de stele ale restaurantului * @param avgPrice pretul in medie al mancarii servite * @param openingHour ora deschiderii * @param closingHour ore inchiderii */ public Restaurant(String street, String name, String type, int stars, int avgPrice, LocalTime openingHour, LocalTime closingHour) { super(street); this.name = name; this.type = type; this.stars = stars; this.avgPrice = avgPrice; this.openingHour = openingHour; this.closingHour = closingHour; } /** * <p> Class constructor </p> * <p> Daca la instantierea obiectului nu se da programul de vizitare acesta va fi initializat by default cu intervalul 09-20. </p> * * @param name numele restaurantului * @param type tipul de mancare servita * @param stars clasificarea - numarul de stele ale restaurantului * @param avgPrice pretul in medie al mancarii servite */ public Restaurant(String street, String name, String type, int stars, int avgPrice) { super(street); this.name = name; this.type = type; this.stars = stars; this.avgPrice = avgPrice; this.openingHour = LocalTime.of(9, 00, 00); this.closingHour = LocalTime.of(22, 00, 00); } /** * <p> Class constructor </p> * <p> Daca la instantierea obiectului nu se da programul de vizitare acesta va fi initializat by default cu intervalul 09-20. </p> * <p> Daca pretul nu este mentionat la instantierea unui obiect, atunci acesta va fi dat by default ca fiind 15. (valoarea in RONi). </p> * * @param name numele restaurantului * @param type tipul de mancare servita * @param stars clasificarea - numarul de stele ale restaurantului */ public Restaurant(String street, String name, String type, int stars) { super(street); this.name = name; this.type = type; this.stars = stars; this.avgPrice = 15; this.openingHour = LocalTime.of(9, 00, 00); this.closingHour = LocalTime.of(22, 00, 00); } /** * <p> Class constructor </p> * <p> Daca la instantierea obiectului nu se da programul de vizitare acesta va fi initializat by default cu intervalul 09-20. </p> * <p> Daca pretul nu este mentionat la instantierea unui obiect, atunci acesta va fi dat by default ca fiind 15. (valoarea in RONi). </p> * <p> Daca nu se mentioneaza numarul de stele al restaurantului, acesta va fi by default 3. </p> * * @param name numele restaurantului * @param type tipul de mancare servita */ public Restaurant(String name, String type, String street) { super(street); this.name = name; this.type = type; this.street = street; this.stars = 3; this.avgPrice = 15; this.setDefaultProgram(); } public long getOpenDuration() { return this.OpenDuration; } public void setOpenDuration() { OpenDuration = Visitable.getVisitingDuration(openingHour, closingHour); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public int getStars() { return stars; } public void setStars(int stars) { this.stars = stars; } public int getAvgPrice() { return avgPrice; } public void setAvgPrice(int avgPrice) { this.avgPrice = avgPrice; } public LocalTime getOpeningHour() { return openingHour; } public void setOpeningHour(LocalTime openingHour) { this.openingHour = openingHour; } public LocalTime getClosingHour() { return closingHour; } public void setClosingHour(LocalTime closingHour) { this.closingHour = closingHour; } @Override public int getRank() { return this.stars; } @Override public double getTicketPrice() { return this.avgPrice; } @Override public LocalTime getOpeningTime() { return this.openingHour; } @Override public LocalTime getClosingTime() { return this.closingHour; } @Override public void setOpeningTime(LocalTime hour) { this.openingHour = hour; } @Override public void setClosingTime(LocalTime hour) { this.closingHour = hour; } @Override public int compareTo(Location o) { if (this == o) return 1; return 0; } @Override public String toString() { return RED + "Restaurantul " + RESET + name + " de " + stars + " stele " + " se afla pe Strada " + street + " si serveste mancare " + type + ". Pretul in medie este " + avgPrice + " RON. Programul de functionare este " + openingHour + " - " + closingHour + '.' + "\n"; } } <file_sep>/Laborator 3/Laborator 3 (optional)/src/Location.java import java.util.HashMap; import java.util.Map; /** * @author <NAME>. * * <p> Clasa Location retine adresele tuturor tipurilor de locatii. </p> */ public abstract class Location implements Comparable<Location> { protected Location address; //adresa obiectului protected String address_name; //numele acestei adrese, eg: v1 protected String street; protected Map<Location, Integer> cost = new HashMap<>(); public Location(String street) { this.street = street; } public String getAddress_name() { return address_name; } public void setAddress_name(String address_name) { this.address_name = address_name; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public Location getAddress() { return address; } public void setAddress(Location address) { this.address = address; } public Map<Location, Integer> getCost() { return cost; } public void setCost(Location node, int value) { cost.put(node, value); } @Override public String toString() { return "Location{" + "address='" + address + '\'' + '}'; } } <file_sep>/Laborator 2/Laborator 2 (bonus)/README.md Solutia fesabila pe care am folosit-o a fost euristica prezentata la bonus (am vrut sa lucrez mai eficient folosint aceeasi idee de rezolvare la optional si bonus). <file_sep>/Laborator 4/Laborator 4 - optional/src/main/java/Main.java import com.github.javafaker.Faker; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * <h> Compulsory: </h> * <p> 1. Declararea obiectelor din enunt </p> * <p> 2. In studentList adaug obiectele de tip stundets de la indicii 1-3 si la urma pe cel de pe indicele 0. * Se poate observa la afisare ca sunt sortate dupa nume. </p> * <p> 3. Afisarea TreeSet-ului. </p> * <p> 4. Afisarea map-urilor cu preferinte. </p> * * <h> Optional: </h> * <p> 5. Studenti care au in lista de preferinte o mini-lista de licee. </p> * <p> 6. Liceele care au un anumit student ca top preference. </p> * <p> 7. Genereaza nume fake random pentru studenti si licee. </p> * <p> 8. Se repartizeaza studentii la licee in baza notei de la examen si a preferintelor. </p> */ public class Main { public static void main(String[] args) { System.out.println("COMPULSORY:"); /* 1. */ var students = IntStream.rangeClosed(0, 3).mapToObj(i -> new Student("S" + i)).toArray(Student[]::new); var licee = IntStream.rangeClosed(0, 2).mapToObj(i -> new School("H" + i, 0)).toArray(School[]::new); licee[0].setCapacitate(1); licee[1].setCapacitate(2); licee[2].setCapacitate(2); List<School> preferinteS = new ArrayList<>(); List<Student> preferinteH = new ArrayList<>(); /* H0: */ preferinteH.add(students[3]); preferinteH.add(students[0]); preferinteH.add(students[1]); preferinteH.add(students[2]); licee[0].setPreferinte(preferinteH); preferinteH.clear(); /* H1: */ preferinteH.add(students[0]); preferinteH.add(students[2]); preferinteH.add(students[1]); licee[1].setPreferinte(preferinteH); preferinteH.clear(); /* H2: */ preferinteH.add(students[0]); preferinteH.add(students[1]); preferinteH.add(students[3]); licee[2].setPreferinte(preferinteH); preferinteH.clear(); /* S0: */ preferinteS.add(licee[0]); preferinteS.add(licee[1]); preferinteS.add(licee[2]); students[0].setPreferinte(preferinteS); preferinteS.clear(); /* S1: */ preferinteS.add(licee[0]); preferinteS.add(licee[1]); preferinteS.add(licee[2]); students[1].setPreferinte(preferinteS); preferinteS.clear(); /* S2: */ preferinteS.add(licee[0]); preferinteS.add(licee[1]); students[2].setPreferinte(preferinteS); preferinteS.clear(); /* S3: */ preferinteS.add(licee[0]); preferinteS.add(licee[2]); students[3].setPreferinte(preferinteS); preferinteS.clear(); System.out.println("Licee si studenti: "); for (int i = 0; i < licee.length; i++) { System.out.println(licee[i]); } for (int i = 0; i < students.length; i++) { System.out.println(students[i]); } /* 2. */ System.out.println(""); System.out.println("Lista de studenti sortata: "); List<Student> studentList = new ArrayList<>(); for (int i = 1; i < students.length; i++) { studentList.add(students[i]); } studentList.add(students[0]); List<Student> newSortedList = studentList.stream().sorted(Comparator.comparing(Student::getNume)).collect(Collectors.toList()); System.out.println(newSortedList); /* 3. */ System.out.println(""); System.out.println("TreeSet-ul scolilor: "); TreeSet<School> tsH = new TreeSet<School>(); for (int i = 0; i < licee.length; i++) { tsH.add(licee[i]); } System.out.println(tsH); /* 4. */ System.out.println(""); System.out.println("Mapele studentilor si a liceelor: "); Map<Student, List> preferS = new HashMap<Student, List>(); Map<School, List> preferH = new HashMap<School, List>(); List<School> preferinteS0 = new ArrayList<>(); preferinteS0.add(licee[0]); preferinteS0.add(licee[1]); preferinteS0.add(licee[2]); preferS.put(students[0], preferinteS0); List<School> preferinteS1 = new ArrayList<>(); preferinteS1.add(licee[0]); preferinteS1.add(licee[1]); preferinteS1.add(licee[2]); preferS.put(students[0], preferinteS0); List<School> preferinteS2 = new ArrayList<>(); preferinteS2.add(licee[0]); preferinteS2.add(licee[1]); List<School> preferinteS3 = new ArrayList<>(); preferinteS3.add(licee[0]); preferinteS3.add(licee[2]); preferS.put(students[0], preferinteS0); preferS.put(students[1], preferinteS1); preferS.put(students[2], preferinteS2); preferS.put(students[3], preferinteS3); List<Student> preferinteH0 = new ArrayList<>(); preferinteH0.add(students[3]); preferinteH0.add(students[0]); preferinteH0.add(students[1]); preferinteH0.add(students[2]); List<Student> preferinteH1 = new ArrayList<>(); preferinteH1.add(students[0]); preferinteH1.add(students[2]); preferinteH1.add(students[1]); List<Student> preferinteH2 = new ArrayList<>(); preferinteH2.add(students[0]); preferinteH2.add(students[1]); preferinteH2.add(students[3]); preferH.put(licee[0], preferinteH0); preferH.put(licee[1], preferinteH1); preferH.put(licee[2], preferinteH2); for (Map.Entry<Student, List> i : preferS.entrySet()) { System.out.print(i.getKey().getNume() + ":"); System.out.println(i.getValue()); } for (Map.Entry<School, List> i : preferH.entrySet()) { System.out.print(i.getKey().getNume() + ":"); System.out.println(i.getValue()); } /* 5. */ System.out.println("\nOPTIONAL:"); List<School> target = Arrays.asList(licee[0], licee[2]); List<Student> result = studentList.stream().filter(std -> preferS.get(std).containsAll(target)).collect(Collectors.toList()); System.out.print("Students who find acceptable schools H0 and H2: "); for (int index = 0; index < result.size(); index++) { System.out.print(result.get(index).getNume() + " "); } /* 6. */ System.out.println("\nSchools that have student S3 as their top preference: "); tsH.stream().filter(std -> preferH.get(std).contains(students[3])).forEach(System.out::println); /* 7. */ System.out.println("\nFake student and school:"); Faker faker = new Faker(); String firstName = faker.name().firstName(); // Emory String lastName = faker.name().lastName(); // Barton Student S1 = new Student(firstName); School H1 = new School(lastName, 3); System.out.println(S1); System.out.println(H1); /* 8. */ students[0].setExamScore(70); students[1].setExamScore(96); students[2].setExamScore(83); students[3].setExamScore(64); Problem repartizare = new Problem(); repartizare.addToLicee(licee[0], licee[0].getPreferinte()); repartizare.addToLicee(licee[1], licee[1].getPreferinte()); repartizare.addToLicee(licee[2], licee[2].getPreferinte()); repartizare.addToStudenti(students[0], students[0].getPreferinte()); repartizare.addToStudenti(students[1], students[1].getPreferinte()); repartizare.addToStudenti(students[2], students[2].getPreferinte()); repartizare.addToStudenti(students[3], students[3].getPreferinte()); System.out.println(""); repartizare.makeSolution(); } } <file_sep>/Laborator 6/Swing/Compulsory/src/main/java/ConfigPanel.java import javax.swing.*; public class ConfigPanel extends JPanel { final MainFrame frame; JSpinner sidesField; // number of sides JComboBox colorCombo; // the color of the shape JComboBox size; //size of shape JComboBox shape; //name of the shape public ConfigPanel(MainFrame frame) { this.frame = frame; init(); } private void init() { sidesField = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1)); sidesField.setValue(3); //default number of sides //create the colorCombo, containing the values: Random and Black String[] colorStrings = { "Black", "Blue", "Purple", "Red", "Green" }; colorCombo = new JComboBox(colorStrings); colorCombo.setSelectedIndex(0); String[] sizeStrings = {"small", "medium", "big", "huge"}; size = new JComboBox(sizeStrings); String[] shapeStrings = {"square", "circle", "triangle", "polygon"}; shape = new JComboBox(shapeStrings); shape.setSelectedIndex(3); //...TODO // JLabel label = new JLabel(" Insert your preffered configuration for the image. Note: The polygon will be only one with the number of sides specified. Other shapes can be 1-100.\n "); // add(label); JLabel label1 = new JLabel(" Choose a shape: "); add(label1); add(shape); JLabel label2 = new JLabel(" Choose the size: "); add(label2); add(size); JLabel label3 = new JLabel(" Choose the number of sides / shapes: "); add(label3); //JPanel uses FlowLayout by default add(sidesField); JLabel label4 = new JLabel(" Choose the color: "); add(label4); add(colorCombo); } } <file_sep>/Laborator 3/Laborator 3 (compulsory)/src/main.java /** * @author <NAME>. * * <p> Clasa main va contine programul principal. </p> * <p> Toate obiectele instantiate vor avea numele "vx", unde x este indicele incepand de la 0. </p> */ public class main { /** * <p> 1. Initializez un oras. </p> * <p> 2. Adaug locatii pe "harta" orasului si le memorez adresa in lista acestuia. </p> * <p> 3. In mapa pun costurile deplasarilor de la o locatie la alta. </p> * <p> 4. Afisez informatiile cunoscute despre locatii si mai apoi despre costul deplasarii intre acestea. </p> * * @param args lista de parametri data in consola */ public static void main(String[] args) { /* 1. */ City Iasi = new City("Iasi"); /* 2. */ Hotel v1 = new Hotel("Unirea", 50, 100); v1.address = "v1"; Iasi.locatii.add(v1); Museum v2 = new Museum("Natura", 30); v2.address = "v2"; Iasi.locatii.add(v2); Museum v3 = new Museum("Istorie", 50); v3.address = "v3"; Iasi.locatii.add(v3); Church v4 = new Church("Sfanta Maria", "ortodoxa"); v4.address = "v4"; Iasi.locatii.add(v4); Church v5 = new Church("Sfantul Iosif", "catolica"); v5.address = "v5"; Iasi.locatii.add(v5); Restaurant v6 = new Restaurant("Mammamia", "fast food"); v6.address = "v6"; Iasi.locatii.add(v6); /* 3. */ v1.setCost(v2, 10); v1.setCost(v3, 50); v2.setCost(v3, 20); v2.setCost(v4, 20); v2.setCost(v5, 10); v3.setCost(v2, 20); v3.setCost(v4, 20); v4.setCost(v5, 30); v4.setCost(v6, 10); v5.setCost(v4, 30); v5.setCost(v6, 20); /* 4. */ int i; for (i = 0; i < Iasi.locatii.size(); i++) { System.out.println(Iasi.locatii.get(i).address + ": " + Iasi.locatii.get(i)); } for (i = 0; i < Iasi.locatii.size(); i++) { for (Location id : Iasi.locatii.get(i).cost.keySet()) { System.out.println(Iasi.locatii.get(i).address + " -> " + id.address + " are costul " + Iasi.locatii.get(i).cost.get(id)); } } } } <file_sep>/Laborator 8/README.md # <NAME> - LABORATOR 8 ## Compulsory * Am ales sa folosesc baza de date Oracle fiind deja familiara cu aceasta. * Scriptul lab8.sql se afla in folderul cu resursele proiectului. * contine codul pentru crearea celor 3 tabele * contine cateva inserturi in tabele * In pom.xml am adaugat 2 dependente: * driverul pentru baza de date * pentru a putea rula scriptul .sql * Am folosit 2 interfete MovieDAO si GenreDAO pentru a fluidiza codul. Interfetele contin 2 functii: * crearea unui insert * o interogare de tip select pentru a gasi un element in tabel dupa nume (de film sau de gen) * Testul implementat pe baza de date presupune: * conectarea la baza de date * inserarea unui film in tabela movies * inserarea unui gen de filme in tabela genres ## Optional * Am adaugat in lab8.sql tabelele pentru actori si directori ca extensie a tabelei persoane * Pentru datele cu care lucreaza acteasta aplicatie Java: * am modificat butonul "connect to DB" in "Test Connection" - se vor insera 2 randuri in tabelele genres si movies ca sa se testeze daca functioneaza conexiunea * am adaugat butonul "All Movies Info" - afiseaza informatii despre toate filmele din baza de date ex: titlu, scor, director, actori, genuri, etc * am adaugat butonul "Genres" - se selecteaza un gen de film si se vor afisa toate filmele existene in baza de date cu acel gen * dupa selectarea unei optiuni apare o fereastra de tip pop-up care anunta ca toate informatiile au fost afisate in consola ## Bonus * Am implementat clasa ConnectionPool pentru a realiza conexiuni la baza de date cu c3p0. * Clasa MovieThread implementeaza functia care va fi rulata de threaduri in conexiune. * Clasa MovieThreadPool creaza threaduri pentru conexiunea cu c3p0. * Am creat intr-un for 20 de threaduri si am monitorizat activitatea lor cu Visual VM #### In plus: am implementat si o interfata grafica cu javaFX pentru a face aplicatia mai user friendly. <file_sep>/Laborator 3/Laborator 3 (compulsory)/src/Restaurant.java import java.rmi.registry.LocateRegistry; import java.time.LocalTime; import java.util.ArrayList; import java.util.List; /** * @author <NAME>. * * <p> Clasa Restaurant retine numele, tipul de mancare servita si adresa localului </p> */ public class Restaurant extends Location implements Visitable, Payable, Classifiable { public String name; public String type; public Restaurant(String name, String type) { this.name = name; this.type = type; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } @Override public int getRank() { return 0; } @Override public double getTicketPrice() { return 0; } @Override public LocalTime getOpeningTime() { return null; } @Override public LocalTime getClosingTime() { return null; } @Override public int compareTo(Location o) { return 0; } @Override public String toString() { return "Restaurant{" + "address='" + address + '\'' + ", name='" + name + '\'' + ", type='" + type + '\'' + '}'; } } <file_sep>/Laborator 12/compulsory/src/main/java/ClassLoader.java import java.net.URL; import java.net.URLClassLoader; public class ClassLoader extends URLClassLoader { public ClassLoader() { super(new URL[0], ClassLoader.getSystemClassLoader()); } @Override public void addURL(URL url) { super.addURL(url); } } <file_sep>/Laborator 5/Compulsory/src/main/java/CatalogUtil.java import java.awt.*; import java.io.*; /** * <p> Clasa care implementeaza functii utile pentru obiectele din catalog. </p> */ public class CatalogUtil { public static void save(Catalog catalog) throws IOException { try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(catalog.getLocation()))) { oos.writeObject(catalog); } } public static Catalog load(String path) throws InvalidCatalogException { try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path))){ return (Catalog) ois.readObject(); } catch(ClassNotFoundException|IOException exception){ throw new InvalidCatalogException(exception); } } public static void view(Catalog registru) { Desktop desktop = Desktop.getDesktop(); } } <file_sep>/Laborator 4/Laborator 4 - compulsory/READ ME.md Laborator 4 - compulsory Din pacate am inteles ca oricare componenta a laboratorului poate fi trimisa pana la data Laboratorului 5. :< Totusi am abordat toate subpunctele din partea obligatorie urmand indicatiile oferite. <file_sep>/Laborator 8/Optional/src/main/java/Movie.java /** * <h3> Clasa Movie </h3> * <p> Defineste un element din tabela Movie sub forma de obiect. </p> */ public class Movie { int id_Movie; String title; int release_date; int duration; double score; public Movie(int id_Movie, String title, int release_date, int duration, double score) { this.id_Movie = id_Movie; this.title = title; this.release_date = release_date; this.duration = duration; this.score = score; } public int getId_Movie() { return id_Movie; } public void setId_Movie(int id_Movie) { this.id_Movie = id_Movie; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public int getRelease_date() { return release_date; } public void setRelease_date(int release_date) { this.release_date = release_date; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } } <file_sep>/Laborator 13/lab13/src/main/java/app/LocaleExplore.java package app; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Properties; import java.util.Scanner; public class LocaleExplore { Properties command = new Properties(); public void run() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, IOException { command.load(this.getClass().getClassLoader().getResourceAsStream("command.properties")); LocaleCommand.setLocale("en-US"); Scanner scan = new Scanner(System.in); while (true) { System.out.print(LocaleCommand.message("prompt")); String com = scan.nextLine(); if (com.equals("exit")) break; String[] params = com.trim().split("\\s+"); switch (params[0]) { case "locales" : { Class cls = Class.forName(command.getProperty("display-locale.impl")); cls.getConstructor().newInstance(); break; } case "set" : { Class cls = Class.forName(command.getProperty("set-locale.impl")); cls.getConstructor(String.class).newInstance(params[1]); break; } case "info" : { Class cls = Class.forName(command.getProperty("info-locale.impl")); cls.getConstructor().newInstance(); break; } default : System.out.println(LocaleCommand.message("invalid")); } } } public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException { new LocaleExplore().run(); } }<file_sep>/Laborator 5/Compulsory/README.md Laboratorul 5 - compulsory Nu am implementat exceptia pentru datele invalide inca.
65ab240e53d8d5acf4836487086040ca4d62f1b6
[ "Markdown", "Java", "SQL", "INI" ]
58
Java
AndraCoteanu/2A4-ProgramareAvansata
22a28367ce0528c75f5f759652f73fc9fff9235e
1d7cb36fc0fe1fb25bb7676e9ca495bda11add54
refs/heads/master
<repo_name>CodingMan95/starbucks20190826<file_sep>/src/main/java/com/eim/service/WechatService.java package com.eim.service; import com.eim.entity.DecodeInfo; public interface WechatService { /** * 获取微信用户信息 */ String decodeInfo(DecodeInfo info); } <file_sep>/src/main/java/com/eim/mapper/StoreInfoMapper.java package com.eim.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.eim.entity.StoreInfo; import java.util.List; public interface StoreInfoMapper extends BaseMapper<StoreInfo> { List<StoreInfo> selectByIdSet(String city, int[] ids); List<StoreInfo> getByPage(int start, int num); List<String> getCityByProvince(String province, int[] ids); List<String> getAreaByCity(String city, int[] ids); List<StoreInfo> getStoreByArea(String area, String city, int[] ids); List<String> getProvince(int[] ids); List<String> getAllCityByProvince(String province); List<String> getAllAreaByCity(String city); List<StoreInfo> getAllStoreByArea(String area, String city); List<String> getAllProvince(); List<StoreInfo> selectStoreByIdSet(int[] ids); List<StoreInfo> getStoreList(String[] ids); } <file_sep>/src/main/java/com/eim/controller/common/CommonController.java package com.eim.controller.common; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.eim.entity.StoreInfo; import com.eim.exception.BusinessException; import com.eim.kit.ConstantKit; import com.eim.model.ResultTemplate; import com.eim.service.StoreInfoService; import com.eim.service.UploadService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; @Api(tags = "通用接口管理") @RestController @RequestMapping("/common/") public class CommonController { @Autowired private StoreInfoService storeInfoService; @Autowired private UploadService uploadService; @ApiOperation("获取省市区及门店") @GetMapping("getByType.do") public ResultTemplate getAll(@RequestParam int type, @RequestParam(required = false) String parm, @RequestParam(required = false) Integer activeId, @RequestParam(required = false) String cityName) { Map<String, Object> map; if (null == activeId || activeId == 0) { //获取全部省市区及门店 map = storeInfoService.getAllStore(type, parm, cityName); } else { //获取参与活动的省市区及门店 map = storeInfoService.getStoreLimit(type, parm, cityName, activeId); } return ResultTemplate.success(map); } @ApiOperation("上传图片") @PostMapping("upload.do") public ResultTemplate upload(@RequestParam MultipartFile file, HttpServletRequest request) { if (null == file) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.NO_PARAMETER); } String baseUrl = request.getSession().getServletContext().getRealPath(""); baseUrl = baseUrl.replaceAll("\\\\", "/"); String imgUrl = uploadService.uploadImg(file, baseUrl); return ResultTemplate.success(imgUrl); } @ApiOperation("校验门店编号是否存在") @GetMapping("verifyStore.do") public ResultTemplate verifyStore(@RequestParam String storeId) { int count = storeInfoService.count(new QueryWrapper<StoreInfo>().eq("store_id", storeId)); if (count == 0) { return ResultTemplate.success(); } return ResultTemplate.error(ConstantKit.BAD_REQUEST, ConstantKit.HAVE_STOREID); } @ApiOperation("校验门店名称是否存在") @GetMapping("verifyStoreName.do") public ResultTemplate verifyStoreName(@RequestParam String storeName) { int count = storeInfoService.count(new QueryWrapper<StoreInfo>().eq("store_name", storeName)); if (count == 0) { return ResultTemplate.success(); } return ResultTemplate.error(ConstantKit.BAD_REQUEST, ConstantKit.HAVE_STORENAME); } @ApiOperation("查询全省/市全部门店") @GetMapping("getStoreByType.do") public ResultTemplate getStoreByType(@RequestParam int type, @RequestParam String parm) { if (StringUtils.isEmpty(parm)) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.NO_PARAMETER); } List<StoreInfo> store = storeInfoService.getStoreByType(type, parm); return ResultTemplate.success(store); } @ApiOperation("通过门店列表获取门店对应id列表 ") @ApiImplicitParam(name = "nameList", value = "例子:{\"武汉江夏中百广场店\";\"光谷德国风情街店\";\"南昌铜锣湾广场店\"}", paramType = "query") @PostMapping("getIdList.do") public ResultTemplate getIdList(@RequestParam String nameList) { if (StringUtils.isEmpty(nameList)) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.NO_PARAMETER); } if (nameList.startsWith("{") && nameList.endsWith("}") && nameList.contains("\"")) { nameList = nameList.substring(1, nameList.length() - 1).replaceAll("\"", ""); String[] names = nameList.split(";"); List<StoreInfo> storeList = storeInfoService.getStoreList(names); return ResultTemplate.success(storeList); } return ResultTemplate.error(ConstantKit.BAD_REQUEST, ConstantKit.ERROR_STYLE); } } <file_sep>/src/main/java/com/eim/entity/ActivityOrder.java package com.eim.entity; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.Date; @Data public class ActivityOrder { private int orderId; @ApiModelProperty("活动id") private String activityId; //微信相关信息 private String openId; @ApiModelProperty(hidden = true) private String nickName; @ApiModelProperty(hidden = true) private String avatarUrl; //活动相关信息 @ApiModelProperty(hidden = true) private String coverUrl; @ApiModelProperty(hidden = true) private String bannerUrl; @ApiModelProperty(hidden = true) private String title; @ApiModelProperty(hidden = true) private String introduce; @ApiModelProperty(value = "参与时间") private String activityTime; @ApiModelProperty(value = "预约的门店") private String storeName; @ApiModelProperty(value = "预约的门店id") private int storeId; @ApiModelProperty(value = "姓名") private String name; @ApiModelProperty(value = "电话") private String mobile; @ApiModelProperty(value = "地址") private String address; @ApiModelProperty(value = "套餐id") private int comboId; private String comboName; private String comboPic; @ApiModelProperty(value = "预约人数") private int peopleNum; @ApiModelProperty(value = "共计花费") private double totalCost; @ApiModelProperty(value = "报名时间", hidden = true) private Date addTime; @ApiModelProperty(value = "预约状态 为1时预约成功,为2时店员签到成功,为0时活动结束", hidden = true) private int status; } <file_sep>/src/main/java/com/eim/service/StoreInfoService.java package com.eim.service; import com.baomidou.mybatisplus.extension.service.IService; import com.eim.entity.StoreInfo; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; import java.util.Map; public interface StoreInfoService extends IService<StoreInfo> { /** * 获取门店列表 */ List<StoreInfo> selectByIdSet(String city, int activeId); /** * 新增门店 */ boolean addStore(StoreInfo storeInfo); /** * 删除门店信息 */ boolean deleteStore(int id); /** * 分页查询门店信息 */ Map<String, Object> getByPage(int page, int limit); Map<String, Object> getStoreLimit(int type, String parm, String cityName, int activeId); Map<String, Object> getAllStore(int type, String parm, String cityName); List<StoreInfo> selectStoreByIdSet(int[] ids); List<StoreInfo> getStoreByType(int type, String parm); List<StoreInfo> getStoreList(String[] ids); } <file_sep>/src/main/java/com/eim/controller/admin/AdminUserController.java package com.eim.controller.admin; import com.eim.exception.BusinessException; import com.eim.kit.ConstantKit; import com.eim.model.ResultTemplate; import com.eim.service.AdminUserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @Api(tags = "后台-用户管理") @RestController @RequestMapping("/admin-user/") public class AdminUserController { @Autowired private AdminUserService adminUserService; @ApiOperation("修改登录密码") @PostMapping("changePwd.do") public ResultTemplate changePwd(@RequestParam String oldPassword, @RequestParam String newPassword, @RequestParam String storeId) { if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword) || StringUtils.isEmpty("storeId")) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.NO_PARAMETER); } boolean changePwd; try { changePwd = adminUserService.changePwd(storeId, oldPassword, newPassword); } catch (BusinessException e) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.CHANGE_ERROR); } if (changePwd) { return ResultTemplate.success(); } return ResultTemplate.error(ConstantKit.BAD_REQUEST, ConstantKit.CHANGE_ERROR); } } <file_sep>/src/main/java/com/eim/exception/ApiException.java package com.eim.exception; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class ApiException extends RuntimeException { protected int errorCode; protected Object data; public ApiException(int errorCode, String message, Object data, Throwable e) { super(message, e); this.errorCode = errorCode; this.data = data; } public ApiException(int errorCode, String message, Object data) { this(errorCode, message, data, null); } public ApiException(int errorCode, String message) { this(errorCode, message, null, null); } public ApiException(Throwable e) { super(e); } } <file_sep>/src/main/java/com/eim/mapper/ActivityInfoMapper.java package com.eim.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.eim.entity.ActivityInfo; import java.util.List; public interface ActivityInfoMapper extends BaseMapper<ActivityInfo> { List<ActivityInfo> getActivityByCity(String city); List<ActivityInfo> getActivityByPage(int start, int num); } <file_sep>/src/main/java/com/eim/config/RedisConfig.java package com.eim.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration public class RedisConfig { @Value("${spring.redis.host}") public String REDIS_HOST; @Value("${spring.redis.port}") public int REDIS_PORT; @Value("${spring.redis.password}") public String REDIS_PASSWORD; } <file_sep>/src/main/java/com/eim/service/impl/AdminUserServiceImpl.java package com.eim.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.eim.config.RedisConfig; import com.eim.exception.BusinessException; import com.eim.kit.ConstantKit; import com.eim.mapper.AdminUserMapper; import com.eim.entity.AdminUser; import com.eim.service.AdminUserService; import com.eim.util.Md5Util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import redis.clients.jedis.Jedis; import java.util.Date; import java.util.HashMap; import java.util.Map; @Service @Transactional public class AdminUserServiceImpl extends ServiceImpl<AdminUserMapper, AdminUser> implements AdminUserService { @Autowired private AdminUserMapper userMapper; @Autowired private RedisConfig redisConfig; @Override public Map<String, Object> userLogin(String storeId, String password) { int userNum = userMapper.selectCount(new QueryWrapper<AdminUser>().eq("store_id", storeId)); if (userNum == 0) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.NO_USER); } //对密码进行加密 //String md5Password = Md5Util.getMD5String(password); AdminUser user = userMapper.selectOne(new QueryWrapper<AdminUser>().eq("store_id", storeId).eq("password", password)); if (null == user) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.ERROR_PASSWORD); } Jedis jedis = new Jedis(redisConfig.REDIS_HOST, redisConfig.REDIS_PORT); jedis.auth(redisConfig.REDIS_PASSWORD); //生成token String token = Md5Util.generate(storeId, password); //存入redis jedis.set(storeId, token); jedis.expire(storeId, ConstantKit.TOKEN_EXPIRE_TIME); jedis.set(token, storeId); jedis.expire(token, ConstantKit.TOKEN_EXPIRE_TIME); Long currentTime = System.currentTimeMillis(); jedis.set(token + storeId, currentTime.toString()); jedis.expire(token + storeId, ConstantKit.TOKEN_EXPIRE_TIME); //用完关闭 jedis.close(); Map<String, Object> map = new HashMap<>(); map.put("token", token); map.put("role", user.getRoleId()); return map; } @Override public boolean changePwd(String storeId, String oldPassword, String newPassword) { AdminUser adminUser = userMapper.selectOne(new QueryWrapper<AdminUser>().eq("store_id", storeId).eq("password", <PASSWORD>)); if (null == adminUser) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.ERROR_PASSWORD); } userMapper.update(adminUser, new UpdateWrapper<AdminUser>().set("password", <PASSWORD>).set("update_time", new Date()).eq("store_id", storeId)); return true; } } <file_sep>/src/main/java/com/eim/entity/AdminUser.java package com.eim.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.util.Date; @Data @TableName("sys_user") @NoArgsConstructor @AllArgsConstructor public class AdminUser { private String storeId; private String password; private int roleId; private boolean status; private Date createTime; private Date updateTime; public AdminUser(String storeId, String password, int roleId, boolean status, Date createTime) { this.storeId = storeId; this.password = <PASSWORD>; this.roleId = roleId; this.status = status; this.createTime = createTime; } } <file_sep>/src/main/java/com/eim/service/ActivityInfoService.java package com.eim.service; import com.baomidou.mybatisplus.extension.service.IService; import com.eim.entity.ActivityInfo; import java.util.List; import java.util.Map; public interface ActivityInfoService extends IService<ActivityInfo> { /** * 根据城市获取相关活动 */ List<ActivityInfo> getActivityByCity(String city); /** * 根据活动id获取活动详情 */ ActivityInfo getActivityDetail(int activeId); /** * 创建活动 */ boolean addActivityInfo(ActivityInfo activityInfo); /** * 分页查看所有活动 */ Map<String, Object> allActivity(int page); /** * 更新活动状态 */ String updateStatus(int activeId, boolean status); /** * 删除活动 */ boolean delete(int activeId); /** * 获取某一店铺参与的活动列表 */ List<ActivityInfo> getActiveOfStore(String storeId); ActivityInfo ActivityDetail(int activeId); } <file_sep>/src/main/java/com/eim/controller/admin/ComboController.java package com.eim.controller.admin; import com.eim.entity.Combo; import com.eim.exception.BusinessException; import com.eim.kit.ConstantKit; import com.eim.model.ResultTemplate; import com.eim.service.ComboService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.*; @Api(tags = "后台-套餐管理") @RestController @RequestMapping("/combo/") public class ComboController { @Autowired private ComboService comboService; @ApiOperation("添加套餐") @PostMapping("add.do") public ResultTemplate addCombo(@RequestParam String name, @RequestParam String pic, @RequestParam int comboId) { if (StringUtils.isEmpty(name) || StringUtils.isEmpty(pic)) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.NO_PARAMETER); } int id = comboService.add(name, pic, comboId); if (id != 0) { return ResultTemplate.success(id); } return ResultTemplate.error(ConstantKit.BAD_REQUEST, ConstantKit.FAIL); } @ApiOperation("删除套餐") @GetMapping("delete.do") public ResultTemplate delete(@RequestParam Integer comboId) { if (null == comboId || comboId <= 0) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.NO_PARAMETER); } try { boolean delete = comboService.delete(comboId); if (delete) { return ResultTemplate.success(); } return ResultTemplate.error(ConstantKit.BAD_REQUEST, ConstantKit.FAIL); } catch (BusinessException e) { e.printStackTrace(); return ResultTemplate.error(ConstantKit.BAD_REQUEST, ConstantKit.COMBO_ORDERED); } } } <file_sep>/src/main/java/com/eim/entity/StoreInfo.java package com.eim.entity; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data @TableName("shop_info") public class StoreInfo { @ApiModelProperty("门店id(添加时不传,更新时传)") private int id; @ApiModelProperty(value = "门店id(如:S00001)") private String storeId; @ApiModelProperty(value = "门店名称") private String storeName; @ApiModelProperty(value = "门店地址") private String address; @ApiModelProperty(value = "所在省") private String province; @ApiModelProperty(value = "所在市") private String city; @ApiModelProperty(value = "所在区") private String area; } <file_sep>/src/main/java/com/eim/entity/DecodeInfo.java package com.eim.entity; import lombok.Data; @Data public class DecodeInfo { private String nickName; private int gender; private String avatarUrl; private String code; } <file_sep>/src/main/java/com/eim/service/impl/ComboServiceImpl.java package com.eim.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.eim.entity.ActivityOrder; import com.eim.entity.Combo; import com.eim.exception.BusinessException; import com.eim.kit.ConstantKit; import com.eim.mapper.ComboMapper; import com.eim.service.ActivityOrderService; import com.eim.service.ComboService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; @Service @Transactional public class ComboServiceImpl extends ServiceImpl<ComboMapper, Combo> implements ComboService { @Autowired private ComboMapper comboMapper; @Autowired private ActivityOrderService orderService; @Override public List<Combo> selectByIdSet(int[] ids) { return comboMapper.selectByIdSet(ids); } @Override public int add(String name, String pic, int id) { Combo combo = new Combo(); combo.setName(name); combo.setPic(pic); boolean status; if (id > 0) { combo.setId(id); //更新 status = update(combo, new UpdateWrapper<Combo>().eq("id", id)); } else { //添加 combo.setCreateTime(new Date()); status = comboMapper.addCombo(combo); } if (status) { return combo.getId(); } return 0; } @Override public boolean delete(int id) { //如果该套餐已有人预约,则不允许删除 int count = orderService.count(new QueryWrapper<ActivityOrder>().eq("combo_id", id)); if (count > 0) { throw new BusinessException(ConstantKit.BAD_REQUEST, ConstantKit.COMBO_ORDERED); } int delete = comboMapper.delete(new QueryWrapper<Combo>().eq("id", id)); if (delete == 1) { return true; } return false; } } <file_sep>/src/main/java/com/eim/service/impl/ActivityOrderServiceImpl.java package com.eim.service.impl; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.eim.entity.ActivityInfo; import com.eim.entity.ActivityOrder; import com.eim.entity.Combo; import com.eim.entity.StoreInfo; import com.eim.exception.BusinessException; import com.eim.kit.ConstantKit; import com.eim.mapper.ActivityOrderMapper; import com.eim.service.ActivityInfoService; import com.eim.service.ActivityOrderService; import com.eim.service.ComboService; import com.eim.service.StoreInfoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @Service @Transactional public class ActivityOrderServiceImpl extends ServiceImpl<ActivityOrderMapper, ActivityOrder> implements ActivityOrderService { @Autowired private ActivityOrderMapper activityOrderMapper; @Autowired private ActivityInfoService activityInfoService; @Autowired private ComboService comboService; @Autowired private StoreInfoService storeInfoService; @Override public boolean addActivity(ActivityOrder order) { order.setStatus(ConstantKit.ORDER_SUCCESS); order.setAddTime(new Date()); activityOrderMapper.insert(order); return true; } @Override public List<ActivityOrder> list(String openId) { List<ActivityOrder> activityOrders = activityOrderMapper.selectList(new QueryWrapper<ActivityOrder>().select("order_id", "activity_id", "activity_time", "store_name", "status").eq("open_id", openId)); if (null == activityOrders) { return null; } for (ActivityOrder order : activityOrders) { ActivityInfo activityInfo = activityInfoService.getOne(new QueryWrapper<ActivityInfo>() .select("cover_url", "title").eq("active_id", order.getActivityId())); order.setCoverUrl(activityInfo.getCoverUrl()); order.setTitle(activityInfo.getTitle()); } return activityOrders; } @Override public boolean cancelOrder(int orderId) { int delete = activityOrderMapper.delete(new QueryWrapper<ActivityOrder>().eq("order_id", orderId)); if (delete == 1) { return true; } return false; } @Override public ActivityOrder orderDetail(int orderId) { ActivityOrder activityOrder = activityOrderMapper.selectOne(new QueryWrapper<ActivityOrder>() .select("order_id", "activity_id", "activity_time", "store_name", "combo_id", "people_num", "total_cost", "status").eq("order_id", orderId)); if (null == activityOrder) { return null; } ActivityInfo activityInfo = activityInfoService.getOne(new QueryWrapper<ActivityInfo>() .select("banner_url", "title", "introduce").eq("active_id", activityOrder.getActivityId())); activityOrder.setBannerUrl(activityInfo.getBannerUrl()); activityOrder.setTitle(activityInfo.getTitle()); activityOrder.setIntroduce(activityInfo.getIntroduce()); if (activityOrder.getComboId() != 0) { Combo combo = comboService.getOne(new QueryWrapper<Combo>().select("pic", "name").eq("id", activityOrder.getComboId())); activityOrder.setComboName(combo.getName()); activityOrder.setComboPic(combo.getPic()); } return activityOrder; } @Override public Map<String, Object> selectData(String province, String city, String area, String storeName, Integer activeId, int page, int num) { Map<String, Object> map = new HashMap<>(); int start; if (page == 1) { start = 0; } else { start = (page - 1) * num; } List<ActivityOrder> orders = activityOrderMapper.selectData(province, city, area, storeName, activeId, start, num); int count = activityOrderMapper.selectTotal(province, city, area, storeName, activeId); int signNum = activityOrderMapper.selectSignNum(province, city, area, storeName, activeId); int orderNum = activityOrderMapper.selectOrderNum(province, city, area, storeName, activeId); map.put("orderList", orders); //总数 map.put("total", count); //签到人数 map.put("signNum", signNum); //总条数 map.put("orderNum", orderNum); return map; } @Override public Map<String, Object> selectDataOfStore(Integer activeId, String storeId, int page, int num) { Map<String, Object> map = new HashMap<>(); int start; if (page == 1) { start = 0; } else { start = (page - 1) * num; } StoreInfo storeInfo = storeInfoService.getOne(new QueryWrapper<StoreInfo>().select("id").eq("store_id", storeId)); List<ActivityOrder> orders = activityOrderMapper.selectDataOfStore(activeId, storeInfo.getId(), start, num); map.put("orderList", orders); StoreInfo one = storeInfoService.getOne(new QueryWrapper<StoreInfo>().eq("store_id", storeId).select("id")); int count = activityOrderMapper.selectCount(new QueryWrapper<ActivityOrder>().eq("activity_id", activeId).eq("store_id", one.getId())); map.put("total", count); return map; } @Override public boolean sign(int orderId) { boolean update = update(new UpdateWrapper<ActivityOrder>().eq("order_id", orderId).set("status", 2)); return update; } } <file_sep>/src/main/java/com/eim/mapper/AdminUserMapper.java package com.eim.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.eim.entity.AdminUser; public interface AdminUserMapper extends BaseMapper<AdminUser> { } <file_sep>/src/main/java/com/eim/entity/ActivityInfo.java package com.eim.entity; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import java.util.Date; import java.util.List; @Data @ApiModel(value = "ActivityInfo") public class ActivityInfo { @ApiModelProperty(value = "活动id(唯一)") private int activeId; @ApiModelProperty(value = "活动列表缩略图") private String coverUrl; @ApiModelProperty(value = "活动内容头图") private String bannerUrl; @ApiModelProperty(value = "活动名称") private String title; @ApiModelProperty(value = "活动说明") private String introduce; @ApiModelProperty(value = "参与活动的店铺id集合(用,隔开)") private String storeId; @ApiModelProperty(value = "活动可选时间") private String activeTime; @ApiModelProperty(value = "报名填写信息(用,隔开)") private String applyInfo; @ApiModelProperty(value = "套餐id集合(用,隔开)") private String comboId; @ApiModelProperty(value = "套餐列表", hidden = true) private List<Combo> comboList; @ApiModelProperty(value = "店铺列表", hidden = true) private List<StoreInfo> storeInfoList; @ApiModelProperty(value = "套餐价格") private double comboPrice; @ApiModelProperty(value = "报名填写信息(用,隔开)") private Date createTime; @ApiModelProperty(value = "活动状态:开启为true/关闭为false") private boolean status; @ApiModelProperty(value = "涉及活动的城市集合(用,隔开)") private String city; }
6c675a2c9e274aff6011cdaa6127c9ad7402ea06
[ "Java" ]
19
Java
CodingMan95/starbucks20190826
adde64d6a5f9db0610bda2196cf55c47b10f67a1
072cfc594b7b6e668b469be259450ab8c6931ad3
refs/heads/master
<file_sep>package envi import ( "encoding/json" "fmt" "io/ioutil" "os" ) // Config is struct to model enviroments configs type Config struct { Database struct { Host string `json:"host"` Port string `json:"port"` User string `json:"user"` Dbname string `json:"dbname"` Password string `json:"<PASSWORD>"` Sslmode string `json:"sslmode"` } Server struct { Host string `json:"host"` Port string `json:"port"` } } func profile(filename string) (Config, error) { var config Config configFile, err := os.Open(filename) defer configFile.Close() if err != nil { fmt.Printf("Error opening file: %v\n", err) return config, err } file, err := ioutil.ReadFile(filename) if err != nil { fmt.Printf("File reading file: %v\n", err) os.Exit(1) } json.Unmarshal(file, &config) return config, err } <file_sep>package envi import ( "fmt" "os" "github.com/jinzhu/gorm" _ "github.com/jinzhu/gorm/dialects/postgres" ) // CreteStrConn for the connection protocol with the application file and its environment func CreteStrConn() string { var config Config var err error srvPort := os.Getenv("PORT") if srvPort == "" { config, err = profile("application-dev.json") } else { fmt.Println("SET PROFILE PRODUCTION") config, err = profile("application-prod.json") } if err != nil { fmt.Println(err.Error()) panic("error open file profile") } host := config.Database.Host port := config.Database.Port user := config.Database.User dbname := config.Database.Dbname password := config.Database.Password sslmode := config.Database.Sslmode strConn := fmt.Sprintf("host=%s port=%s user=%s dbname=%s password=%s sslmode=%s", host, port, user, dbname, password, sslmode) return strConn } // DbCon To create uri connection with db func DbCon() *gorm.DB { uri := CreteStrConn() db, err := gorm.Open("postgres", uri) db.SingularTable(true) // fmt.Printf("--- method: DbCon -> db: {%d}", db) if err != nil { fmt.Println(err.Error()) panic("Failed to connect to database") } db.DB().SetMaxIdleConns(0) db.LogMode(true) return db }
21191ded739123ac8c1a24652745e26f3f7882f7
[ "Go" ]
2
Go
danilodesousacubas/go-gionicjwt
221a9c74ba3572b08d94db2985002acda2768d2e
4e2f3b54bf4b8eee5c220390676a1ae69267a455
refs/heads/master
<repo_name>ditunes/unit-test-share<file_sep>/src/main/java/person/ditunes/example/db/UserLoginLogInfoDAO.java package person.ditunes.example.db; import java.util.List; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.annotation.Transactional; public class UserLoginLogInfoDAO { private static String TABLE_NAME = "cas_user_login_log"; private static String INSERT_LOG_INFO = "insert into "+TABLE_NAME+"(userId,ip,location,loginTime) values(?,?,?,?)"; private static String QUERY_TAGET_NUMS_INFO_BY_USER_AND_LOCATION = "select 1 from "+TABLE_NAME+" where userId = ? and location=? limit ?"; private static String EXIST_LOGIN_INFO = "select 1 from "+TABLE_NAME+" where userId = ? limit 1 "; private JdbcTemplate jdbcTemplate; public UserLoginLogInfoDAO(JdbcTemplate jdbcTemplate) { super(); this.jdbcTemplate = jdbcTemplate; } public UserLoginLogInfoDAO() { super(); } public boolean existLoginInfo(Long userId){ try { Integer flag = jdbcTemplate.queryForObject(EXIST_LOGIN_INFO, new Object[]{userId}, Integer.class); return flag == 1; } catch (EmptyResultDataAccessException e) { return false; } } public boolean existTargetNumUserLoginInfoByLocation(UserLoginLogInfo info, int num){ List<Integer> list = jdbcTemplate.queryForList(QUERY_TAGET_NUMS_INFO_BY_USER_AND_LOCATION, new Object[]{info.getUserId(), info.getLocation(),num}, Integer.class); return list.size() >= num; } @Transactional public void insertUserLoginLogInfo(UserLoginLogInfo loginInfo){ jdbcTemplate.update(INSERT_LOG_INFO, new Object[]{loginInfo.getUserId(),loginInfo.getIp(), loginInfo.getLocation(), loginInfo.getLoginTime()}); } } <file_sep>/src/main/java/person/ditunes/example/badDesign/RoomySmsHttpClientUtils.java /*** Eclipse Class Decompiler plugin, copyright (c) 2016 <NAME> (<EMAIL>) ***/ /* */package person.ditunes.example.badDesign; /* */ /* *///import cn.roomy.framework.utils.SpringUtils; /* */ import com.google.common.collect.Lists; /* */ import java.io.FileInputStream; import java.io.InputStream; /* */ import java.util.List; /* */ import java.util.Map; /* */ import java.util.Properties; /* */ import org.apache.http.HttpEntity; /* */ import org.apache.http.HttpResponse; /* */ import org.apache.http.client.entity.UrlEncodedFormEntity; /* */ import org.apache.http.client.methods.HttpGet; /* */ import org.apache.http.client.methods.HttpPost; /* */ import org.apache.http.impl.client.CloseableHttpClient; /* */ import org.apache.http.impl.client.HttpClients; /* */ import org.apache.http.message.BasicNameValuePair; /* */ import org.apache.http.util.EntityUtils; /* */ import org.slf4j.Logger; /* */ import org.slf4j.LoggerFactory; import org.springframework.util.ResourceUtils; /* */ /* */public abstract class RoomySmsHttpClientUtils /* */{ /* 38 */private static Logger logger = LoggerFactory .getLogger(RoomySmsHttpClientUtils.class); /* */private static String appId; /* */private static String sercet; /* */private static String serverUrl; /* */ /* */public static String post(String url, Map<String, String> params) /* */{ return null; /* */} /* */ /* */public static Map<String, String> getToken() /* */{ return null; } /* */ /* */static /* */{ /* */try /* */{ /* 52 */SmsClient client = null; /* 53 */appId = client.getAppId(); /* 54 */sercet = client.getAppSercet(); /* 55 */serverUrl = client.getUapServer(); /* */} catch (Exception e) { /* */try { /* 59 */InputStream is = new FileInputStream( ResourceUtils.getFile("classpath:roomy-sms-client.properties")); /* 60 */Properties properties = new Properties(); /* 61 */properties.load(is); /* 62 */appId = properties .getProperty("roomy.uap.client.appId"); /* 63 */sercet = properties .getProperty("roomy.uap.client.sercet"); /* 64 */serverUrl = properties .getProperty("roomy.uap.server.url"); /* */} catch (Exception e1) { /* 66 */logger .info("�޷���roomy-sms-client.properties��ȡ���ã�����application.properties�ļ���ȡ��"); /* */try { /* 68 */InputStream is = new FileInputStream( ResourceUtils.getFile("classpath:application.properties")); /* 69 */Properties properties = new Properties(); /* 70 */properties.load(is); /* 71 */appId = properties .getProperty("roomy.uap.client.appId"); /* 72 */sercet = properties .getProperty("roomy.uap.client.sercet"); /* 73 */serverUrl = properties .getProperty("roomy.uap.server.url"); /* */} catch (Exception e2) { /* 75 */logger.info("�޷���ȡ�ͻ��������ļ�������ϵͳ�����ж�ȡ��"); /* 76 */appId = System .getProperty("roomy.uap.client.appId"); /* 77 */sercet = System .getProperty("roomy.uap.client.sercet"); /* 78 */serverUrl = System .getProperty("roomy.uap.server.url"); /* */} /* */} /* */} /* */} /* */ }<file_sep>/src/test/java/person/ditunes/example/badDesign/ResetUserPasswordServiceTest.java package person.ditunes.example.badDesign; import org.junit.Test; /** * Created by linhan on 16/9/22. */ public class ResetUserPasswordServiceTest { @Test public void testS(){ ResetUserPasswordService s = new ResetUserPasswordService(); s.reset("22"); } } <file_sep>/src/main/java/person/ditunes/example/badDesign/ResetUserPasswordService.java package person.ditunes.example.badDesign; /** * Created by linhan on 16/9/20. */ public class ResetUserPasswordService { public void reset(String userId){ if(notExistUser(userId)){ throw new RuntimeException("user not exist"); }else{ String getUserPhone = getUserPhone(userId); try { RoomySmsClientUtil.sendSms(getUserPhone,"reset password as <PASSWORD>",null, null,"2014-09-02","qa",null); }catch (Exception e){ throw resolveExpcetion(e); } sendSuccessResetMsg(); } } private void sendSuccessResetMsg() { } private RuntimeException resolveExpcetion(Exception e) { return new RuntimeException(e); } private String getUserPhone(String userId) { return "18106981399"; } private boolean notExistUser(String userId) { return false; } } <file_sep>/src/test/java/person/ditunes/example/mock/MockTest.java package person.ditunes.example.mock; import java.util.LinkedList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; import static org.mockito.Mockito.*; /** * Created by linhan on 16/9/21. */ public class MockTest { @Test public void what_is_the_spy(){ List list = new LinkedList(); List spy = spy(list); //optionally, you can stub out some methods: when(spy.size()).thenReturn(100); //using the spy calls real methods spy.add("one"); spy.add("two"); Assert.assertEquals("spy invoke real word and the first item should be one","one", spy.get(0)); Assert.assertEquals("spy alseo can be stubbed and return expected", 100,spy.size()); verify(spy).add("one"); verify(spy).add("two"); } @Test public void what_is_the_mock(){ List list = new LinkedList(); List spy = spy(list); List mock = mock(List.class); mock.add("1"); Assert.assertEquals("if you not ndefined the action, mock obj can't do anything",0, mock.size()); doReturn(3).when(mock).size(); Assert.assertEquals("mock just do stub and return what you defined",3, mock.size()); } } <file_sep>/src/test/resources/cas-user-login-log-schema.sql CREATE TABLE `cas_user_login_log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL , `ip` varchar(30) NULL DEFAULT NULL , `loginTime` timestamp NULL DEFAULT CURRENT_TIMESTAMP , `location` varchar(30) NOT NULL , PRIMARY KEY (`id`) )ENGINE=InnoDB DEFAULT CHARSET=utf8 ; <file_sep>/src/main/java/person/ditunes/example/badDesign/RoomySmsClientUtil.java /*** Eclipse Class Decompiler plugin, copyright (c) 2016 <NAME> (<EMAIL>) ***/ /* */package person.ditunes.example.badDesign; /* */ /* */ import com.alibaba.fastjson.JSON; import com.google.common.collect.Maps; /* */ import java.util.Map; /* */ /* */public abstract class RoomySmsClientUtil /* */{ /* */ /* */public static Map<String, String> sendSms(String phone, String content, String prov, String deadline, String sendDate, String account, String addSerial) /* */{ /* 34 */Map tokenMap = RoomySmsHttpClientUtils.getToken(); /* 35 */String token = (String) tokenMap.get("token"); /* 36 */Map param = Maps.newHashMap(); /* 37 */param.put("token", token); /* 38 */param.put("tels", phone); /* 39 */param.put("content", content); /* 40 */if (null != prov) { /* 41 */param.put("prov", prov); /* */} /* 43 */if (null != deadline) { /* 44 */param.put("dl", deadline); /* */} /* 46 */if (null != sendDate) { /* 47 */param.put("st", sendDate); /* */} /* 49 */param.put("account", account); /* 50 */if (null != addSerial) { /* 51 */param.put("addSerial", addSerial); /* */} /* 53 */String resutl = RoomySmsHttpClientUtils.post( "/service/call/smsSender", param); /* 54 */return ((Map) JSON.parseObject(resutl,Map.class)); /* */} }
f3b615a611126ddd82746e50719fb26610546d10
[ "Java", "SQL" ]
7
Java
ditunes/unit-test-share
5d2ab793fa58eddb23cbb4379c2eefdd60a31785
f6bfa229475179b01edb6efbba2bea009c55376e
refs/heads/master
<file_sep>package com.hucheng.loancalc; import android.os.Bundle; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; public class LoanCalcActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_loan_calc); FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.container, new LoanCalcFragment()); transaction.commit(); } } <file_sep>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.hucheng.loancalc" minSdkVersion 14 targetSdkVersion 23 versionCode 1 versionName "1.0" } //签名配置 signingConfigs { debugConfig { } releaseConfig { keyAlias "key" keyPassword "383686357" storeFile file("D:\\AndroidProject\\Key\\fykey.jks") storePassword "<PASSWORD>" } } buildTypes { release { // 不显示Log buildConfigField "boolean", "LOG_DEBUG", "false" //混淆 minifyEnabled true //Zipalign优化 zipAlignEnabled true // 移除无用的resource文件 shrinkResources true //加载默认混淆配置文件 proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' //签名 signingConfig signingConfigs.releaseConfig } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' } <file_sep>package com.hucheng.loancalc; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.TextView; import java.text.DecimalFormat; /** * A simple {@link Fragment} subclass. */ public class LoanCalcFragment extends Fragment implements TextWatcher{ private RadioGroup mLoanTypeGp; private RadioGroup mPaybackWayGp; private View mPafAndCommercial; private View mCombined; private View mEachMonthDesc; private TextView mTxtEachMonthPay; private TextView mTxtEachMonthDesc; private TextView mTxtTotalInterest; private TextView mTxtTotalPayback; private EditText mEdtLoanMoney; private TextView mEtLoanYears; private TextView mTxtLiLv; private View mLiLvSelect; private View mYearsSelect; //{ combined private View mYearsSelectCombined; private TextView mEtLoanYearsCombined; private View mCommericalInterestSelect; private View mPafInterestSelect; private TextView mTxtPafInterest; private TextView mTxtCommericalInterest; private EditText mEdtPafLoanMoney; private EditText mEdtCommericalLoanMoney; //} private TextWatcher mInterestWatcher = new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (TextUtils.isEmpty(s)) { return; } if (Integer.parseInt(s.toString()) <= 5) { mBaseRatePaf = BASERATE_PAF[0]; mBaseRateCommerical = BASERATE_COMMERICAL[0]; } else { mBaseRatePaf = BASERATE_PAF[1]; mBaseRateCommerical = BASERATE_COMMERICAL[1]; } doCalculate(); } @Override public void afterTextChanged(Editable s) { } }; public LoanCalcFragment() { // Required empty public constructor } private String[] YEARS ={"5", "10", "15", "20", "25", "30"}; private final double[] BASERATE_PAF={2.75, 3.25, 3.25, 3.25, 3.25, 3.25, }; private final double[] BASERATE_COMMERICAL={4.75, 4.90, 4.90, 4.90, 4.90, 4.90}; private double mBaseRatePaf = BASERATE_PAF[1]; private double mBaseRateCommerical = BASERATE_COMMERICAL[1]; private double mRatePafRatio = 1.00; private double mRateCommericalRatio = 1.00; private DecimalFormat mDoubleFormat2 = new DecimalFormat("######0.00"); private DecimalFormat mDoubleFormat3 = new DecimalFormat("######0.000"); private final String[] COMERICAL_RATE = { "基准利率", "9折利率", "9.5折利率", "9.8折利率" , "1.1倍利率"}; private final double[] COMERICAL_RATE_COEFF = {1.0, 0.9, 0.95, 0.98, 1.1}; private final String[] PAF_RATE = {"基准利率", "1.1倍利率"}; private final double[] PAF_RATE_COEFF = {1.0, 1.1}; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_loan_calc, container, false); mLoanTypeGp = (RadioGroup) view.findViewById(R.id.rbg_loantype); mPaybackWayGp = (RadioGroup) view.findViewById(R.id.rbg_payback_way); mPafAndCommercial = view.findViewById(R.id.gp_commercial_and_paf); mCombined = view.findViewById(R.id.gp_combined_loan); mEachMonthDesc = view.findViewById(R.id.each_month_desc); mTxtEachMonthPay = (TextView) view.findViewById(R.id.txt_each_month_pay); mTxtEachMonthDesc = (TextView) view.findViewById(R.id.txt_each_month_desc); mTxtTotalInterest = (TextView) view.findViewById(R.id.txt_total_interest); mTxtTotalPayback = (TextView) view.findViewById(R.id.txt_total_payback); mEdtLoanMoney = (EditText) view.findViewById(R.id.edt_loan_money); mEtLoanYears = (TextView) view.findViewById(R.id.et_years); mTxtLiLv = (TextView) view.findViewById(R.id.txt_lv); mLiLvSelect = view.findViewById(R.id.lv_select); mYearsSelect = view.findViewById(R.id.years_select); mEdtLoanMoney.addTextChangedListener(this); //{ combined mYearsSelectCombined = view.findViewById(R.id.years_select_combined); mEtLoanYearsCombined = (TextView)view.findViewById(R.id.et_years_combined); mEtLoanYearsCombined.addTextChangedListener(mInterestWatcher); //} mEtLoanYears.addTextChangedListener(mInterestWatcher); mLoanTypeGp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(checkedId == R.id.rb_paf || checkedId == R.id.rb_commercial){ mPafAndCommercial.setVisibility(View.VISIBLE); mCombined.setVisibility(View.GONE); }else { mPafAndCommercial.setVisibility(View.GONE); mCombined.setVisibility(View.VISIBLE); } reset(); } }); mLiLvSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); if(mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_paf) { builder.setItems(PAF_RATE, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mRatePafRatio = PAF_RATE_COEFF[which]; mTxtLiLv.setText(mDoubleFormat3.format(mBaseRatePaf * mRatePafRatio)); doCalculate(); } }); }else if(mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_commercial){ builder.setItems(COMERICAL_RATE, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mRateCommericalRatio = COMERICAL_RATE_COEFF[which]; mTxtLiLv.setText(mDoubleFormat3.format(mBaseRateCommerical * mRateCommericalRatio)); doCalculate(); } }); } builder.create().show(); } }); mPaybackWayGp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { if(checkedId == R.id.rb_benjin){ mEachMonthDesc.setVisibility(View.VISIBLE); }else { mEachMonthDesc.setVisibility(View.GONE); } doCalculate(); } }); //{ for combined mCommericalInterestSelect = view.findViewById(R.id.commerical_interest_select); mPafInterestSelect = view.findViewById(R.id.paf_interest_select); mTxtPafInterest = (TextView)view.findViewById(R.id.txt_paf_interest); mTxtCommericalInterest = (TextView)view.findViewById(R.id.txt_commercial_interest); mEdtPafLoanMoney = (EditText)view.findViewById(R.id.edt_paf_loan_money); mEdtCommericalLoanMoney = (EditText)view.findViewById(R.id.edt_commerical_loan_money); mEdtPafLoanMoney.addTextChangedListener(this); mEdtCommericalLoanMoney.addTextChangedListener(this); mCommericalInterestSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setItems(COMERICAL_RATE, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mRateCommericalRatio = COMERICAL_RATE_COEFF[which]; mTxtCommericalInterest.setText(mDoubleFormat3.format(mBaseRateCommerical * mRateCommericalRatio)); doCalculate(); } }); builder.create().show(); } }); mPafInterestSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setItems(PAF_RATE, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mRatePafRatio = PAF_RATE_COEFF[which]; mTxtPafInterest.setText(mDoubleFormat3.format(mBaseRatePaf * mRatePafRatio)); doCalculate(); } }); builder.create().show(); } }); //} return view; } private void refreshInterestRatio(){ if(mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_paf){ mTxtLiLv.setText(mDoubleFormat3.format(mBaseRatePaf * mRatePafRatio)); }else if(mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_commercial){ mTxtLiLv.setText(mDoubleFormat3.format(mBaseRateCommerical * mRateCommericalRatio)); }else if(mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_combined){ mTxtCommericalInterest.setText(mDoubleFormat3.format(mBaseRateCommerical * mRateCommericalRatio)); mTxtPafInterest.setText(mDoubleFormat3.format(mBaseRatePaf * mRatePafRatio)); } } private void reset(){ if(mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_paf){ mBaseRatePaf = BASERATE_PAF[1]; mRatePafRatio = 1.00; mTxtLiLv.setText(mDoubleFormat3.format(mBaseRatePaf * mRatePafRatio)); //mTxtLoanYears.setText(YEARS[3]); }else if(mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_commercial){ mBaseRateCommerical = BASERATE_COMMERICAL[1]; mRateCommericalRatio = 1.00; mTxtLiLv.setText(mDoubleFormat3.format(mBaseRateCommerical * mRateCommericalRatio)); //mTxtLoanYears.setText(YEARS[3]); }else { mBaseRatePaf = BASERATE_PAF[1]; mRatePafRatio = 1.00; mTxtPafInterest.setText(mDoubleFormat3.format(mBaseRatePaf * mRatePafRatio)); mBaseRateCommerical = BASERATE_COMMERICAL[1]; mRateCommericalRatio = 1.00; mTxtCommericalInterest.setText(mDoubleFormat3.format(mBaseRateCommerical * mRateCommericalRatio)); mTxtEachMonthDesc.setText("0.00"); mTxtTotalPayback.setText("0.00"); mTxtTotalInterest.setText("0.00"); mTxtEachMonthPay.setText("0.00"); //mTxtLoanYears.setText(YEARS[3]); } doCalculate(); } private void doCalculate() { double monthToPay = 0.0; double totalPay = 0.0; double totalInterest = 0.0; double monthDesc = 0.0; // 贷款年限不能为空 if (TextUtils.isEmpty(mEtLoanYears.getText().toString().trim())) { return; } if (mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_commercial || mLoanTypeGp.getCheckedRadioButtonId() == R.id.rb_paf) { if (TextUtils.isEmpty(mEdtLoanMoney.getText().toString().trim())) { return; } double loanMoney = Double.parseDouble(mEdtLoanMoney.getText().toString()) * 10000; double totalMonth = Double.parseDouble(mEtLoanYears.getText().toString()) * 12; double monthRatio = Double.parseDouble(mTxtLiLv.getText().toString()) / (12 * 100); LoanCalc result; if (mPaybackWayGp.getCheckedRadioButtonId() == R.id.rb_benxi) { result = new LoanCalc(loanMoney, totalMonth, monthRatio, true); } else { result = new LoanCalc(loanMoney, totalMonth, monthRatio, false); } monthToPay = result.monthToPay; totalPay = result.totalPay; totalInterest = result.totalInterest; monthDesc = result.monthDesc; } else { // combined if (TextUtils.isEmpty(mEdtPafLoanMoney.getText().toString().trim()) && TextUtils.isEmpty(mEdtCommericalLoanMoney.getText().toString().trim())) { return; } double loanMoneyPaf = TextUtils.isEmpty(mEdtPafLoanMoney.getText().toString()) ? 0.0 : Double.parseDouble(mEdtPafLoanMoney.getText().toString()) * 10000; double loanMoneyComm = TextUtils.isEmpty(mEdtCommericalLoanMoney.getText().toString()) ? 0.0 : Double.parseDouble(mEdtCommericalLoanMoney.getText().toString()) * 10000; double totalMonth = Double.parseDouble(mEtLoanYearsCombined.getText().toString()) * 12; double monthRatioPaf = Double.parseDouble(mTxtPafInterest.getText().toString()) / (12 * 100); double monthRatioComm = Double.parseDouble(mTxtCommericalInterest.getText().toString()) / (12 * 100); LoanCalc resultPaf, resultComm; if (mPaybackWayGp.getCheckedRadioButtonId() == R.id.rb_benxi) { resultPaf = new LoanCalc(loanMoneyPaf, totalMonth, monthRatioPaf, true); resultComm = new LoanCalc(loanMoneyComm, totalMonth, monthRatioComm, true); } else { resultPaf = new LoanCalc(loanMoneyPaf, totalMonth, monthRatioPaf, false); resultComm = new LoanCalc(loanMoneyComm, totalMonth, monthRatioComm, false); } monthToPay = resultPaf.monthToPay + resultComm.monthToPay; totalPay = resultPaf.totalPay + resultComm.totalPay; totalInterest = resultPaf.totalInterest + resultComm.totalInterest; monthDesc = resultPaf.monthDesc + resultComm.monthDesc; } mTxtEachMonthDesc.setText(mDoubleFormat2.format(monthDesc)); mTxtTotalPayback.setText(mDoubleFormat2.format(totalPay)); mTxtTotalInterest.setText(mDoubleFormat2.format(totalInterest)); mTxtEachMonthPay.setText(mDoubleFormat2.format(monthToPay)); } class LoanCalc { public double monthToPay = 0.0; public double totalPay = 0.0; public double totalInterest = 0.0; public double monthDesc = 0.0; public LoanCalc(double loanMoney, double totalMonth, double monthRatio, boolean isBenxi){ if(isBenxi){ monthToPay = loanMoney * monthRatio * Math.pow(1 + monthRatio, totalMonth) / (Math.pow(1 + monthRatio, totalMonth) - 1); totalPay = monthToPay * totalMonth; totalInterest = totalPay - loanMoney; }else { monthToPay = loanMoney / totalMonth + loanMoney * monthRatio; monthDesc = loanMoney / totalMonth * monthRatio; totalPay = ((loanMoney / totalMonth + loanMoney * monthRatio) + loanMoney/totalMonth*(1+monthRatio)) / 2 * totalMonth; totalInterest = totalPay - loanMoney; } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if(TextUtils.isEmpty(s)){ return; } doCalculate(); } @Override public void afterTextChanged(Editable s) { } }
d308bbac2eb461fe3af5b7f56e27b290cfd70dcf
[ "Java", "Gradle" ]
3
Java
SmallSmallProgrammer/LoanCalc
f2efb34f3a8308d65e5ea877dbfe03215ffcb79a
245fae65a1c346809f356d4eaad1c66d4162efe3
refs/heads/master
<repo_name>KingJA/IndexHelper<file_sep>/app/src/main/java/sample/kingja/indexhelper/City.java package sample.kingja.indexhelper; import android.support.annotation.NonNull; import android.util.Log; import com.kingja.indexhelper.FirstLetter; /** * Description:TODO * Create Time:2017/4/24 10:24 * Author:KingJA * Email:<EMAIL> */ public class City implements FirstLetter{ private String name; private String pinyin; public City(String name, String pinyin) { this.name = name; this.pinyin = pinyin; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPinyin() { return pinyin.substring(0, 1); } public void setPinyin(String pinyin) { this.pinyin = pinyin; } public String getFirstLetter() { return pinyin.substring(0, 1); } } <file_sep>/app/src/main/java/sample/kingja/indexhelper/Constants.java package sample.kingja.indexhelper; /** * Description:TODO * Create Time:2017/4/24 10:13 * Author:KingJA * Email:<EMAIL> */ public class Constants { public static final String[] citys = {"北京市", "上海市", "广州市", "深圳市", "成都市", "杭州市", "武汉市", "天津市", "南京市", "重庆市", "长沙市", "西安市", "青岛市", "沈阳市", "大连市", "济南市", "苏州市", "宁波市", "无锡市", "福州市", "合肥市", "郑州市", "哈尔滨市", "佛山市", "东莞市", "昆明市", "太原市", "南昌市", "南宁市", "温州市", "石家庄市", "长春市", "哈尔滨","安庆市"}; } <file_sep>/settings.gradle include ':app', ':lib-indexhelper' <file_sep>/README.md TODO * wrap_content * pinyin4j深入
30e8777afc855e277ae4a4326bac348019512e59
[ "Markdown", "Java", "Gradle" ]
4
Java
KingJA/IndexHelper
f65181018f5aaf809e49a1fcd232d78b208e268c
760f53ec4a89cabd17e4ef8d141a615113a81d6e
refs/heads/master
<file_sep>#define SCMARG(n) FPARG(IMM(n+2)) #define SCMENV FPARG(IMM(0)) #define SCMNARGS FPARG(IMM(1)) #define SOB_BOOLEAN_FALSE 0 #define SOB_BOOLEAN_TRUE 1 #define MAKE_NUMBER(i) PUSH(IMM(i)); CALL(MAKE_SOB_NUMBER);DROP(1) #define MAKE_INTEGER(i) PUSH(IMM(i)); CALL(MAKE_SOB_INTEGER);DROP(1) #define GET_INTEGER MOV(R0,INDD(R0,1)) #define MAKE_BOOL(i) MOV(R0,IMM(i)); MUL(R0,IMM(2)); ADD(R0,IMM(3)) #define MAKE_CHAR(i) PUSH(IMM(i)); CALL(MAKE_SOB_CHAR);DROP(1) #define MAKE_VECTOR(i) PUSH(IMM(i)); CALL(MAKE_SOB_VECTOR);DROP(1) #define MAKE_SYMBOL(i) PUSH(IMM(i)); CALL(MAKE_SOB_SYMBOL);DROP(1) #define MAKE_STRING(i) PUSH(IMM(i)); PUSH(IMM(1)); CALL(MAKE_SOB_STRING); DROP(2) #define MOV_PVAR(j) MOV(R0,SCMARG(j)) #define MOV_BVAR(i, j) MOV(R0, SCMENV); MOV(R0, INDD(R0, i)); MOV(R0, INDD(R0, j)) #define MAKE_CLOSURE(FUNC) PUSH(LABEL(FUNC));PUSH(R12);CALL(MAKE_SOB_CLOSURE); DROP(2); #define T_NUMBER 101555 #define PUSHAD \ PUSH(R1); \ PUSH(R2); \ PUSH(R3); \ PUSH(R4); \ PUSH(R5); \ PUSH(R6); \ PUSH(R7); \ PUSH(R8); \ PUSH(R9); \ PUSH(R10); \ PUSH(R11); \ PUSH(R12); \ PUSH(R13); \ PUSH(R14); \ PUSH(R15); #define POPAD \ POP(R15); \ POP(R14); \ POP(R13); \ POP(R12); \ POP(R11); \ POP(R10); \ POP(R9); \ POP(R8); \ POP(R7); \ POP(R6); \ POP(R5); \ POP(R4); \ POP(R3); \ POP(R2); \ POP(R1); <file_sep>// This code is to be appended to the final cisc file created by our compiler JUMP(EXIT); lnot_proc: printf("not proc \n"); // INFO; JUMP(EXIT); l_NOT_VALID_ARGUMENTS: // INFO; JUMP(EXIT); l_NOT_PAIR: printf("not PAIR \n"); //INFO; SHOW("",INDD(R0,0)); JUMP(EXIT); EXIT: STOP_MACHINE; return 0; } <file_sep>petite --libdirs "src/" --program examples/example1.ss <file_sep>#!/bin/bash set -x wget http://www.scheme.com/download/pcsv8.4-a6le.tar.gz tar xzf pcsv8.4-a6le.tar.gz cd csv8.4/custom ./configure make sudo make install <file_sep>#include <stdio.h> #include <stdlib.h> /* change to 1 for debug info to be printed: */ #define DO_SHOW 1 #include "arch/cisc.h" #define SOB_FALSE IMM(3) #define SOB_NIL IMM(2) int main() { START_MACHINE; ADD(IND(0),1000); MOV(R12,IMM(31004)); JUMP(CONTINUE); #include "functions.lib" CONTINUE: <file_sep>#!/bin/sh if [ "$#" -ne 2 ]; then echo "Usage: $0 <input-file> <output-file>" exit 1 fi inputfile=$1 outputfile=$2 output=$(echo $outputfile | cut -d"." -f1) petite --script compile.scm $inputfile $outputfile gcc -o $output -g $outputfile echo "Executable file is $output" <file_sep>#!/bin/sh # set -x # verbose # set -e # exit on error verbose=false while getopts "v" OPTION do case $OPTION in v) verbose=true ;; esac done # define text-colors red=$'\e[1;31m' green=$'\e[1;32m' end=$'\e[0m' bold=`tput bold` smul=`tput smul` normal=`tput sgr0` # import the rellevant files from the compiler dir mkdir arch cp -r ../arch/* arch/ cp ../functions.lib . cp ../macros.h . # counters failed=0 passed=0 total=0 dir="tmp-tests" for f in *.scm; do if [[ $f != pre.scm && $f != post.scm && $f != petite* ]]; then # only files that are not pre.scm post.scm and doesn't contain the prefix petite total=$[total+1] echo "${bold}${smul}*** Testing $f... ***${normal}" should_delete=false # delete only if the script created files # If outputfile doesn't exist if ! [[ -e "petite-$f.out" ]]; then $verbose && echo "Output file already exist, skipping running with petite" cat pre.scm $f post.scm > "petite-$f" # create file to be run with petite petite --script "petite-$f" > "petite-$f.out" # run in petite and save the output should_delete=true fi # compile with our compiler pushd .. >> /dev/null petite --script compile.scm "$dir/$f" "$dir/$f.c" popd >> /dev/null executable=$(echo "$f" | cut -d"." -f1) $verbose && echo "Executing GCC" # compile using GCC gcc -o "$executable" "$f.c" $verbose && echo "Running the executable" ./"$executable" > "$f.out" $verbose && echo "Deleteing the executable and compiled file" rm -rf "$executable" "$f.c" # outputs of our compiler matches expected output if cmp -s "petite-$f.out" "$f.out"; then # files are the same printf ${green} echo "**********************" echo "* Test for $f passed *" echo "**********************" printf $end passed=$[passed+1] else # files are different printf ${red} echo "**********************" echo "* Test for $f FAILED *" echo "Expected:" cat "petite-$f.out" echo "But got:" cat "$f.out" echo "**********************" failed=$[failed+1] printf $end fi # if we have created petite file and outputfile if [[ "$should_delete" = true ]]; then $verbose && echo "Deleting petite file and outfile" rm -rf "petite-$f" "petite-$f.out" fi $verbose && echo "Deleting output file generated by our compiler" rm -rf "$f.out" echo "${passed}/${total} passed" fi done $verbose && echo "removig temporary files" rm -rf arch macros.h functions.lib # $verbose && echo "removig created files..." # rm -rf petite* # $verbose && echo "removig output files" # rm -rf *.out echo "Total passed tests: $passed" echo "Total failed tests: $failed" echo "Total tests: $total" exit $failed <file_sep># compilation-final-project ![build status](https://circleci.com/gh/hagai-lvi/compilation-final-project.svg?&style=shield&circle-token=<KEY>) <file_sep>.SUFFIXES: .c C_FILES := $(wildcard *.c) FILE_NAMES=$(basename $(C_FILES)) $(FILE_NAMES): $(FILE_NAMES).c gcc -o $@ $^
d91e2b8f6046e81294374293e54c066b5a38f0d8
[ "Markdown", "C", "Makefile", "Shell" ]
9
C
hagai-lvi/compilation-final-project
1dcb55e4697cc38b963481eef4a64a31d1948d68
1a508cc276a3e0f8e09057e38e98e76d22019471
refs/heads/master
<repo_name>dev-donghwan/CustomCalendarJava<file_sep>/app/src/main/java/com/example/customcalendarjava/base/BaseActivity.java package com.example.customcalendarjava.base; import android.os.Bundle; import android.util.DisplayMetrics; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import static com.example.customcalendarjava.base.BaseApplication.getMetricsY; import static com.example.customcalendarjava.base.BaseApplication.getNavigationBarHeight; import static com.example.customcalendarjava.base.BaseApplication.getStatusBarHeight; import static com.example.customcalendarjava.base.BaseApplication.setActualDeviceHeight; import static com.example.customcalendarjava.base.BaseApplication.setDpi; import static com.example.customcalendarjava.base.BaseApplication.setMetricsX; import static com.example.customcalendarjava.base.BaseApplication.setMetricsY; public abstract class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics); setMetricsX(displayMetrics.widthPixels); setMetricsY(displayMetrics.heightPixels); setDpi(displayMetrics.densityDpi); setActualDeviceHeight(getMetricsY() - getNavigationBarHeight() - getStatusBarHeight()); } } <file_sep>/app/src/main/java/com/example/customcalendarjava/calendar/CustomCalendarUtil.java package com.example.customcalendarjava.calendar; import android.util.Log; import java.util.Calendar; import static java.util.Calendar.getInstance; public class CustomCalendarUtil { public static int monthStartCheck(int year, int month) { //Month의 1일이 무슨 요일인지 Day of Week로 판별한다 Calendar cal = getInstance(); cal.set(year, month - 1, 1); Log.d("동환", "Calendar Day Of Week : " + cal.get(Calendar.DAY_OF_WEEK)); return cal.get(Calendar.DAY_OF_WEEK) - 1; } public static int MonthMax(int year, int month) { //Month의 끝이 몇인지 판별 2월(28 29) 1,3,5,7,8,10,12월 (30) 4,6,9,11월 (31) Calendar cal = Calendar.getInstance(); cal.set(year, month - 1, 1); return cal.getActualMaximum(Calendar.DAY_OF_MONTH); } } <file_sep>/app/src/main/java/com/example/customcalendarjava/Util.java package com.example.customcalendarjava; import static com.example.customcalendarjava.base.BaseApplication.getDpi; public class Util { public static int dpToPx(int dp) { return (dp * (getDpi() / 160)); } public static int pxToDp(int px) { return (px / (getDpi() / 160)); } } <file_sep>/settings.gradle rootProject.name='CustomCalendarJava' include ':app' <file_sep>/README.md # 달력만들기 Javad CustomView, GridView, PrevMonth, NextMonth, TodayCheck
54432b53ba3fba43a6aebf665483ef06086da21e
[ "Markdown", "Java", "Gradle" ]
5
Java
dev-donghwan/CustomCalendarJava
3a92440e5e24be8a903023d096611b8316bf94f5
984136a12615b2a155282694d2bd962088c5e8ff
refs/heads/master
<repo_name>hujimori/go-algorithms<file_sep>/numeric/gcd_test.go package numeric import "testing" func TestGcdBase(t *testing.T) { tests := []struct { a int b int expected int }{ { 3, 6, 3, }, { 1, 12, 1, }, { 12, 12, 12, }, { 352342100, 34343659132, 4, }, { 0, 0, 0, }, // { // 12, // 12, // 1, // }, } for _, tt := range tests { evaluated := gcdBase(tt.a, tt.b) if evaluated != tt.expected { t.Errorf("[Error] gcd(%d,%d) is Error. got=%d", tt.a, tt.b, evaluated) } } } func TestGcd(t *testing.T) { tests := []struct { inputs []int expected int }{ { []int{3, 6, 9}, 3, }, { []int{120, 50, 5}, 5, }, { []int{64, 58, 9}, 1, }, } for _, tt := range tests { evaluated := Gcd(tt.inputs[0], tt.inputs[1], tt.inputs[2]) if evaluated != tt.expected { t.Errorf("[Error] gcd(%d,%d, %d) is Error. got=%d", tt.inputs[0], tt.inputs[1], tt.inputs[2], evaluated) } } } <file_sep>/numeric/lcm.go package numeric func lcmBase(a, b int) int { return a * (b / gcdBase(a, b)) } // Lcm return Least common multiple func Lcm(args ...int) int { b := args[0] for _, a := range args { b = lcmBase(a, b) } return b } <file_sep>/stack/stack_test.go package stack import ( "testing" ) func TestStack(t *testing.T) { tests := []int{ 1, 2, 3, 4, 5, } s := NewStack() for _, tt := range tests { s.Push(tt) if tt != s.Peek() { t.Errorf("push(%d) is Error. got=%d", tt, s.Peek()) } t.Log(s.Peek()) } if s.Size() != len(tests) { t.Errorf("Size() is Error. got=%d. expected=%d", s.Size(), len(tests)) } for i := len(tests) - 1; i >= 0; i-- { x := s.Pop() t.Log(x) if x != tests[i] { t.Errorf("pop() is Error. got=%d. expected=%d", x, tests[i]) } } } <file_sep>/numeric/gcd.go package numeric func gcdBase(a, b int) int { if b == 0 { return a } return gcdBase(b, a%b) } // Gcd return Greatest common divisor func Gcd(args ...int) int { b := args[0] for _, a := range args { b = gcdBase(a, b) } return b } <file_sep>/binarysearch/binarysearch.go package binarysearch func LowerBound(t []int, k int) int { lb := -1 ub := len(t) for ub-lb > 1 { mid := (lb + ub) / 2 if t[mid] >= k { ub = mid } else { lb = mid } } return ub } func UpperBound(t []int, k int) int { lb := -1 ub := len(t) for ub-lb > 1 { mid := (lb + ub) / 2 if t[mid] <= k { lb = mid } else { ub = mid } } return ub } <file_sep>/queue/queue.go package queue type QueueData struct { data interface{} prev *QueueData } type Queue struct { front *QueueData last *QueueData top int } func NewQueue() *Queue { return &Queue{top: 0} } func (q *Queue) Enqueue(data interface{}) { qd := &QueueData{data: data, prev: nil} if q.top == 0 { q.front = qd q.last = q.front q.top++ return } q.last.prev = qd q.last = qd q.top++ } func (q *Queue) Dequeue() interface{} { if q.top > 0 { d := q.front.data q.front = q.front.prev q.top-- return d } return nil } func (q *Queue) Front() interface{} { return q.front.data } func (q *Queue) Last() interface{} { return q.last.data } func (q *Queue) IsEmpty() bool { if q.top == 0 { return true } return false } func (q *Queue) Size() int { return q.top } <file_sep>/queue/queue_test.go package queue import "testing" var q *Queue var tests = []int{ 1, 2, 3, 4, 5, } func testInit() { q = NewQueue() for _, tt := range tests { q.Enqueue(tt) } } func TestDequeue(t *testing.T) { testInit() for _, tt := range tests { var d interface{} if d = q.Dequeue(); d != tt { t.Errorf("Dequeue() is error. got=%d. expected=%d", d, tt) } t.Log(d) } } func TestFront(t *testing.T) { testInit() if q.Front() != tests[0] { t.Errorf("Front() is error. got=%d. expected=%d", q.Front(), tests[0]) } } func TestLast(t *testing.T) { testInit() if q.Last() != tests[len(tests)-1] { t.Errorf("Last() is error. got=%d. exptected=%d", q.Last(), tests[len(tests)-1]) } } func TestIsEmpty(t *testing.T) { testInit() if q.IsEmpty() { t.Errorf("IsEmpty() is error. got=%t.", q.IsEmpty()) } } func TestSize(t *testing.T) { testInit() if q.Size() != len(tests) { t.Errorf("Size() is error. got=%d. expected=%d.", q.Size(), len(tests)) } } <file_sep>/stack/stack.go package stack type StackData struct { data interface{} next *StackData } type Stack struct { sp *StackData top int } func NewStack() *Stack { return &Stack{top: 0} } func (s *Stack) Push(data interface{}) { s.sp = &StackData{data: data, next: s.sp} s.top++ } func (s *Stack) Pop() interface{} { if s.top > 0 { item := s.sp.data s.sp = s.sp.next s.top-- return item } return nil } func (s *Stack) Peek() interface{} { if s.top > 0 { return s.sp.data } return nil } func (s *Stack) IsEmpty() bool { if s.top == 0 { return true } return false } func (s *Stack) Size() int { return s.top }
89db49716d3d47046e5b8730f7ef500deb9f7d5e
[ "Go" ]
8
Go
hujimori/go-algorithms
56e984396cf27a4960067e50e98a79562feec66b
579c454141675ea6b1cdbdc62c0b7871bfb25180
refs/heads/master
<repo_name>seba--/sugarj<file_sep>/deployment/cli-scripts/u/extract.ruby #!/usr/bin/ruby # cai 19.09.12 # script to copy classes out of a built sugarj project repository # the script cli-script/u/classpath builds a classpath that contains # the bin directories of known SugarJ projects. $this_dir = File.expand_path(File.dirname(__FILE__)) $cliscript = File.dirname($this_dir) $classpath = `#{$this_dir}/classpath` $classes = "#{$cliscript}/classes" $native = "#{$cliscript}/native" $nat_nat = "#{$native}/native" def cpdir(path) # we copy $native/org into class folder # return if(path == $native) path = "#{path}/org" if File.exist?(path) # copy everything into classes $stderr.puts(cmd = "cp -nvr #{path} #{$classes}") cp_out = `#{cmd}` $stderr.puts cp_out if $? != 0 else # path/org does not exist $stderr.puts "FATAL ERROR: #{path}/org does not exist." exit 1 end end def cpjar(path) # extract jar-file into classes # cai 23.08.12 # 1. is there a way to issue warning on overwrite? # A: Maybe, but we don't want it. See #2. # # 2. will un-jarring only */org cause problems? # A: YES! In the form of # permissivegrammars: Could not find imported # term file Comments.pp.af # So it seems we have to tolerate overwritting # common files, say META-INF/Manifest, over and over. $stderr.puts(cmd = "cd #{$classes} && jar xf #{path}") `#{cmd}` end def cpall(path) # recursive expansion of paths if File.directory?(path) cpdir(path) elsif File.extname(path) == ".jar" cpjar(path) elsif path[-1, 1] == "*" Dir.glob(path) do |file| cpall(file) end else $stderr.puts "FATAL ERROR: #{path} is not recognised." end end # clean the classes dir. could be dangerous. `rm -rf #{$classes}/*` # copy native into classes `cp -r #{$native}/* #{$classes}` $classpath.split(':').each do |path| path.strip! cpall(path) end <file_sep>/deployment/update-site/copy-to-server.sh #!/bin/sh SERVER=login.mathematik.uni-marburg.de DIR=public_html/projects/sugarj/update rm artifacts.jar rm content.jar rsync -avz . $SERVER:$DIR <file_sep>/deployment/cli-scripts/u/make_util.ruby #!/usr/bin/ruby # cai 04.10.12 # utility script that provides: # 1. the global variable $destination, an absolute path, # as the only argument from the command line. # 2. the function shell_try, which launches a command-line # utility and aborts if it signals failure by exiting # with a non-zero code. # cai 24.09.12 # ALWAYS PRINT STUFF THROUGH $stderr # Rationale: # In IO.popen() or `cmd`, $stdout is directed into a buffer # or a string while $stderr is printed directly to the screen. # We want immediate feedback in these scripts. # Therefore, $stderr always. # The situation will become more comfortable in Ruby 1.9 # where the option :err of IO.popen enables a more # structured approach. if ARGV.length != 1 $stderr.puts("Usage: #{__FILE__} <destination directory>") exit 255 else $destination = File.expand_path(ARGV.first) end $this_dir = File.expand_path(File.dirname(__FILE__)) $script = File.dirname($this_dir) def shell_try(command) $stderr.puts(command) $v = `#{command}` if $?.exitstatus != 0 $stderr.puts "FAILED: #{command}" exit 1 end return $v end <file_sep>/deployment/cli-scripts/u/classpath #!/bin/bash # cai 17.08.12 # script to print classpath # find base directory of sugarj sugarj="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../../.." && pwd )" script="$sugarj/deployment/cli-scripts" common="$sugarj/common/bin" compiler="$sugarj/compiler/bin" stdlib="$sugarj/stdlib/bin" layout="$sugarj/layout-parsing/jsglr-layout/bin" cliroot="$sugarj/compiler" strategojar=`echo $STRATEGO_JAR` clijars="$strategojar:$cliroot/make_permissive.jar:$cliroot/commons-cli-1.2.jar" langroot="$sugarj/language-libraries" langlibs="$langroot/base/bin:$langroot/haskell/bin:$langroot/java/bin:$langroot/prolog/bin" # essential paths classpath="$compiler:$clijars:$common:$stdlib:$langlibs:$layout" # what we try to combine # somehow the nativebundle does not cooperate no matter what I do with it # zip, jar, etc won't help the star locate SDFBundleCommand.class sdfbundle="$script/native" classpath="$classpath:$sdfbundle" classpath="$classpath:$script/jars/*" exec echo "$classpath" <file_sep>/deployment/cli-scripts/u/make_sugarj_zip.ruby #!/usr/bin/ruby # seba 01.10.12 # creates sugarj.zip at ARGV[0]/sugarj.jar # which contains classes compiled from sugarj projects $this_dir = File.expand_path(File.dirname(__FILE__)) $script = File.dirname($this_dir) load "#{$this_dir}/make_util.ruby" load "#{$this_dir}/extract.ruby" shell_try "cd '#{$script}' && zip -r sugarj.zip sugarj" shell_try "cd '#{$script}' && mv sugarj.zip '#{$destination}'" <file_sep>/deployment/cli-scripts/u/make_sugarhaskell_cabal.ruby #!/usr/bin/ruby # seba 01.10.12 # 1. nuke the location in ARGV[0] # 2. rebuild it for cabal package deployment $this_dir = File.expand_path(File.dirname(__FILE__)) $script = File.dirname($this_dir) load "#{$this_dir}/make_util.ruby" $stdout.print "Really overwrite '#{$destination}'?\n(y/n) " $stdout.flush if STDIN.gets.chomp == "y" load "#{$this_dir}/extract.ruby" shell_try "rm -rf '#{$destination}'" # we do `cp -r` instead of symlink because we do `rm -r` # beforehand and we don't want to have to repolupate # cli-scripts/classes every time (although in essense, we do.) shell_try "cd '#{$script}' && cp -r sugarj '#{$destination}'" shell_try "cd '#{$script}' && cp -r cabal/* '#{$destination}'" shell_try "cd '#{$script}' && rm -rf '#{$destination}'/bin" shell_try "cd '#{$destination}' && ghc -o Setup Setup.hs" shell_try "cd '#{$destination}' && ./Setup configure" shell_try "cd '#{$destination}' && ./Setup sdist" end <file_sep>/README.md SugarJ Eclipse plugin (recommended) =================================== Visit the SugarJ web site http://sugarj.org Installation ------------ 1. Install Eclipse (follow instructions on eclipse.org). 2. Start Eclipse. 3. In Eclipse, select 'Install New Software' in the 'Help' menu. 4. In the 'work with' field, copy the SugarJ update site http://update.sugarj.org and hit enter. 5. Be sure to deselect the 'Group items by category' checkbox on the bottom of the window. 6. Select the latest instance of Sugarclipse and click continue. This will install the SugarJ compiler, Spoofax and the Sugarclipse plugin. In addition, please ensure enough stack space (about 4-16 MB) is available for the SDF parser. You can set the stack space of your Java runtime using the -Xss16m command line argument when starting Eclipse or setting -Xss16m in your eclipse.ini file. Setting up a SugarJ project --------------------------- 1. Create a new Java project. 2. As for now, we need to register the SugarJ builder for this project by hand: Open your project's '.project' file in any text editor and replace the Java build command by the following code: <buildCommand> <name>org.sugarj.editor.SugarJBuilder</name> <arguments></arguments> </buildCommand> 3. We're ready to go. Note: SugarJ source files must have the file extension ".sugj". SugarJ standalone compiler ========================== Precompiled Java binaries: [http://sugarj.org/binaries/](http://sugarj.org/binaries/) Installing SugarJ ----------------- The SugarJ compiler is self-contained and only requires an installation of a Java runtime version 6 or higher. Download [`sugarj.zip`](http://sugarj.org/binaries/) and extract it to a location of your choice. The directory structure of the archive is as follows. sugarj/ bin/ Scripts to invoke SugarJ sugarj Compiler for *nix sugarj.bat Compiler for Windows sugh Alias of `sugarj -l haskell` for *nix sugh.bat Alias of `sugarj -l haskell` for Windows sugj Alias of `sugarj -l java` for *nix sugj.bat Alias of `sugarj -l java` for Windows case-studies/ Sample SugarJ projects lib/ The back end README.md This file Invoking SugarJ --------------- If the current directory is your working directory containing the source files, calling SugarJ is very easy: bin/sugarj -l java closures/Test.sugj The `-l` flag is necessary to specify your host language of choice. Currently, we support Haskell, Java, and Prolog. If your source files are located in `case-studies/closure/src`, you can invoke the compiler like this on *nix: bin/sugarj -l java \ --sourcepath case-studies/closures/src \ -d case-studies/closures/bin \ concretesyntax/Test.sugj # file(s) to compile relative # to sourcepath On Windows: bin\sugarj -l java ^ --sourcepath case-studies/closures/src ^ -d case-studies/closures/bin ^ concretesyntax\Test.sugj The generated `Test.class` may be executed thus: java -cp case-studies/closures/bin concretesyntax.Test Compiler options ---------------- --atomic-imports Parse all import statements simultaneously. --cache <arg> Specifiy a directory for caching. --cache-info Show where files are cached -cp,--buildpath <arg> Specify where to find compiled files. Multiple paths can be given separated by ':'. -d <arg> Specify where to place compiled files --full-command-line Show all arguments to subprocesses --gen-files Generate files? --help Print this synopsis of options -l,--language <arg> Specify a language library to activate. --no-checking Do not check resulting SDF and Stratego files. --read-only-cache Specify the cache to be read-only. --silent-execution Try to be silent --sourcepath <arg> Specify where to find source files. Multiple paths can be given separated by ':'. --sub-silent-execution Do not display output of subprocesses -v,--verbose Show verbose output --write-only-cache Specify the cache to be write-only. <file_sep>/deployment/cli-scripts/sugarj-dev #!/bin/bash # cai 09.08.12 # script to invoke sugarj from command line # using latest-available classes # find base directory of sugarj # CELEBRATION: No longer dependent on eclipse's location sugarj="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../.." && pwd )" script="$sugarj/deployment/cli-scripts" common="$sugarj/common/bin" compiler="$sugarj/compiler/bin:$sugarj/compiler/bin/*" stdlib="$sugarj/stdlib/bin" layout="$sugarj/layout-parsing/jsglr-layout/bin" deployment="$sugarj/deployment/cli-scripts/jars/*" cliroot="$sugarj/compiler" langroot="$sugarj/language-libraries" langlibs="$langroot/base/bin:$langroot/haskell/bin:$langroot/java/bin:$langroot/prolog/bin:$langroot/fomega/bin" # essential paths classpath="$compiler:$common:$stdlib:$langlibs:$layout:$deployment" # cli-script/u/extract.ruby will put classes nicely # together to avoid nasty resolutions # we put them behind other class paths so that # update in sugarj project is reflected immediately classes="$script/classes" native="$script/native" classpath="$classpath:$classes:$native" exec java -Xss64m -Xmx1024m -cp "$classpath" org.sugarj.driver.cli.Main $*
88b943db18b68d539ffb200474dd7b0276d10076
[ "Markdown", "Ruby", "Shell" ]
8
Ruby
seba--/sugarj
1ac5018cbccb248d9116cb59d43c7da0f8d49262
c22237775bedee612e0179ca1e7be703089f5fc5
refs/heads/master
<repo_name>Artogn/safenet<file_sep>/src/safe.js var Request = require('./request.js').Factory, storage = require('./storage.js'); var namespaces = { auth: require('./api/auth.js'), dns: require('./api/dns.js'), nfs: require('./api/nfs.js') }; /** * * @param app obj containing name, version, vendor, and id * @param permissions array containing permissions (only SAFE_DRIVE_ACCESS avail) * @param conf obj containing instance of storage class to use * @constructor */ function Safe(app, permissions, conf) { permissions = permissions || []; conf = conf || {}; if (!app.name || !app.version || !app.vendor || !app.id) { throw new Error('`app` must be an object containing name, version, vendor, and id.') } // Set the storage class to be used for saving/fetching auth data if (conf.storage) { this.storage = conf.storage; } else { if (typeof localStorage !== 'undefined') { this.storage = storage.localStorage; } else { throw new Error('Default storage is localStorage, which is not present in this environment.' + ' You must provide a storage class that has the `set`, `get`, and `clear` methods. See readme for details.'); } } this.app = app; this.permissions = permissions; this.Request = new Request(this); this._auth = { token: null, symKey: null, symNonce: null }; // Bind namespace api endpoints bindNamespaces.call(this); Safe.log('Instantiated new Safe instance.'); } // All we're doing here is A) namespacing api calls (e.g. call using Safe.dns.getName() vs // Safe.getName(), and B) binding "this" within each api call to the main Safe object function bindNamespaces() { for (var namespace in namespaces) { for (var func in namespaces[namespace]) { namespaces[namespace][func] = namespaces[namespace][func].bind(this); } this[namespace] = namespaces[namespace]; }; } // Set up logging capability that can be overridden by the useur Safe.log = function() {} // Make it accessible from the Safe instance Safe.prototype.log = function() { this.constructor.log.apply(this, arguments); } // Helper to get auth data Safe.prototype.getAuth = function(key) { return !key ? this._auth : this._auth[key]; } module.exports = Safe;<file_sep>/README.md # SafeNet JS ## What is it? SafeNet JS is a low-level library for communicating with the Safe Launcher. It is written in pure javascript and can be used in a node and browser environment. The goal is to provide 1-to-1 compatibility with the launcher's API. It is only 53kb compressed (which includes encryption and stream base64 libraries). ## [Demo](http://app.playground.safenet/) Start the [SAFE launcher](https://maidsafe.readme.io/docs/getting-started) and then [click here](http://app.playground.safenet/) for the playground on the SAFE network. Or, simply follow installation for development detailed below (npm install and start), then run the `playground.html` file in your browser. It includes the ability to view the source code for each function. #### Security Warning Running SAFE apps in the browser is currently not secure and no privacy or security should be expected in its current state. It is currently possible to mix safenet and conventional internet requests, thus exposing yourself to many cross-site vulnerabilities. This demo is useful for learning about the SAFE network and the API, and browser apps can be created with the intention of running them when more secure browser solutions are created. ## Installation If using node or a browser compiler such as Webpack, use `npm install safenet`. If you simply want to include the library in the browser, add the following script tag tag to the header of your html file: ```html <script src="http://app.playground.safenet/lib/index.js"></script> ``` For development, clone this repo, run `npm install`, then `npm start`. ## Usage All methods return promises. The return values stated for each method refers to the resolved value. You may refer to the demo app for example usage of each method. #### new SafeApp(app, permissions, config) Instantiates new SafeApp object. - `app`: object containing app info, as per description in the [auth docs](https://maidsafe.readme.io/docs/auth): - name - version - vendor - id - `permissions`: array of permissions. Only `SAFE_DRIVE_ACCESS` currently supported. - `config`: optional object containing additional configuration: - `storage`: object that should be used for saving authentication token and symmetric keys for sending and receiving encrypted data from the launcher. localStorage is used by default in the browser. Storage for Node has not been implemented yet. See **this file** for example implementation. To supply your own object for saving auth data, you must provide three properties: - `set`: function with a single argument, a value to save to storage. - `get`: function with no arguments. Returns data from storage. - `clear`: function with no arguments. Clears data from storage. ### Errors If an error occur with an API request, the promise will be rejected with a SafeError object. All SafeError objects contain the following properties: * `isSafeError`: `true` * `message`: string of error * `type`: one of `launcher`, `http`, `network`, or `error`. Here is a description of each: * `error`: generic error * `network`: could not connect to the network/launcher * `http`: a generic http response error, e.g. a non-2xx response, but without a SAFE-related error attached. * `launcher`: the launcher returned an error * `status`: status code. If `http` error, it'll be the http header code (e.g. `400`). If launcher, the launcher error code (e.g. `-502`) * `response`: if an `http` or `launcher` type, this will contain the [`Response`](https://developer.mozilla.org/en-US/docs/Web/API/Response) object returned from the request. Body has already been retrieved and is in the `message` property above. If another type, this will be `undefined`. ### Authorization (SafeApp.auth) Methods related to authentication. #### authorize() This is the only method that doesn't have a matching api call in the documentation, but makes authentication much easier. If auth data is saved in storage, it is used to check if already authorized with the launcher using `isAuth()`. If not authorized, it requests authorization. If no data saved in storage, immediately proceed to request for authentication from the launcher using `authenticate()`. This is the recommended way to authenticate. **Returns:** `undefined` #### authenticate() [docs](https://maidsafe.readme.io/docs/auth) Authenticates with the launcher using the app info and permission used when creating the SafeApp object. It generates a new public keypair for initial communication with the launcher, and then saves the resulting auth token and symmetrical key and nonce to storage. If authentication fails, the invalid auth data is cleared from storage. **Returns:** `undefined` #### isAuth() [docs](https://maidsafe.readme.io/docs/is-token-valid) Checks if it is authenticated with the network. This is the only case where a launcher 401 (unauthorized) error is caught in order to return a boolean value with the promise. **Returns:** `true` or `false` #### deauthorize() [docs](https://maidsafe.readme.io/docs/revoke-token) Deauthorizes the app from the launcher and clears the token and key from storage. **Returns:** `true` or `false` ### DNS (SafeApp.dns) #### listNames() [docs](https://maidsafe.readme.io/docs/dns-list-long-names) List the app's registered names. Known as "long names" in the launcher API. **Returns:** array of string names #### createName(name) [docs](https://maidsafe.readme.io/docs/dns-create-long-name) Create a new name with the provided string value. **Returns:** `undefined` #### deleteName(name) Delete an existing name with the provided string value. **Returns:** `undefined` #### listServices(name) [docs](https://maidsafe.readme.io/docs/dns-list-services) List all services for a given name. Services act as "subdomains" for a given name. **Returns:** `array` #### createServiceForName(obj) [docs](https://maidsafe.readme.io/docs/dns) Create a service for an existing name. Provide an object with the following properties: - `longName`: the name as a string to create the service for. It should have been created at this point using `createName()` above. - `serviceName`: the new service name as a string. - `serviceHomeDirPath`: the service should map to this directory on the SAFE network. The path should have been created already using `SafeApp.nfs.createDirectory()`. - `isPathShared`: was the directory provided above created in the user's SAFEDrive? **Returns:** `undefined` #### createServiceAndName(obj) [docs](https://maidsafe.readme.io/docs/dns-register-service) Create a service and a name at the same time. Provide an object with the same properties as `createServiceForName()`. The only difference is that the provided name must not exist yet. **Returns:** `undefined` #### getServiceDir(service, name) [docs](https://maidsafe.readme.io/docs/dns-get-home-dir) Fetches the mapped directory provided a service and name. Read response details in [MaidSafe docs](https://maidsafe.readme.io/docs/dns-get-home-dir). **Returns:** `object` #### getFile(service, name, filePath, options = {}) [docs](https://maidsafe.readme.io/docs/dns-get-file-unauth) Fetches the contents of the file using the provided service, name, and file path. `options` is an optional object allowing you to get a substring of the file. The object can contain an `offset` and/or `length`. **Returns:** `object` with `body` property containing contents of file and `meta` containing file-related headers. #### deleteService(service, name) Fetches the contents of the file using the provided service, name, and file path. `options` is an optional object allowing you to get a substring of the file. The object can contain an `offset` and/or `length`. **Returns:** `undefined` ### NFS (SafeApp.nfs) #### createDirectory(dir, options) [docs](https://maidsafe.readme.io/docs/nfs-create-directory) Creates a new directory. - `dir`: directory string - `options`: object with the following properties: - `isPrivate`: should the contents of files in this directory be encrypted? If so, only the currently authenticated user will be able to access them. - `metadata`: a string of metadata - `isVersioned`: boolean, whether or not directory changes should be versioned - `isPathShared`: boolean, whether or not to use the SAFEDrive directory as the root directory. The `SAFE_DRIVE_ACCESS` permission must be provided upon authentication in order to set this option to `true`. **Returns:** `undefined` #### getDirectory(dir, options) [docs](https://maidsafe.readme.io/docs/nfs-get-directory) Gets information about the provided directory. `options` should contain the `isPathShared` property. #### deleteDirectory(dir, options) [docs](https://maidsafe.readme.io/docs/nfs-delete-directory) Deletes the directory at the provided path. `options` should contain the `isPathShared` property. **Returns:** `undefined` #### createFile(filePath, options) [docs](https://maidsafe.readme.io/docs/nfsfile) Creates an empty file at the given path. - `filePath`: file path string - `options`: object with the following properties: - `metadata`: a string of metadata - `isVersioned`: boolean, whether or not directory changes should be versioned - `isPathShared`: boolean, whether or not to use the SAFEDrive directory as the root directory. The `SAFE_DRIVE_ACCESS` permission must be provided upon authentication in order to set this option to `true`. **Returns:** `undefined` #### updateFile(filePath, content, options) [docs](https://maidsafe.readme.io/docs/nfs-update-file-content) Update a file at the given path with the provided content. - `filePath`: file path string - `content`: string or TypedArray with the content you wish to write to the file. - `options`: - `isPathShared`: boolean, whether or not to use the SAFEDrive directory as the root directory. The `SAFE_DRIVE_ACCESS` permission must be provided upon authentication in order to set this option to `true`. - `offset`: (optional) integer from where to start writing the file. Characters will be replaced one-by-one. If not provided, the entire file is overwritten. **Returns:** `undefined` #### getFile(filePath, options) [docs](https://maidsafe.readme.io/docs/nfs-get-file) Fetches the contents of the file using the provided file path. `options` is an object that contains `isPathShared` (required) and `offset` and `length` properties (optional), allowing you to get a substring of the file. **Returns:** `object` with `body` property containing contents of file and `meta` containing file-related headers. #### deleteFile(filePath, options) [docs](https://maidsafe.readme.io/docs/nfs-delete-file) Deletes the file. `options` must contain `isPathShared`. **Returns:** `undefined` ## To Do * Unit tests * Missing NFS calls ([as listed in the safe launcher](https://github.com/maidsafe/safe_launcher/blob/master/app/server/routes/version_0_4.js)) * Bugfixes: * Missing headers when fetching files <file_sep>/src/index.js require('./init.js'); var Safe = require('./safe.js'); // If Node environment, export Safe. Otherwise, attach to window. if (typeof process === 'object' && process+'' === '[object process]') { module.exports = Safe; } else { window.SafeApp = Safe; } <file_sep>/src/storage.js // The storage object only needs to contain "save", "clear", and "get" module.exports = { localStorage: { set: function(string) { localStorage.setItem('auth', string); }, get: function() { return localStorage.getItem('auth'); }, clear: function() { localStorage.removeItem('auth'); } } }<file_sep>/src/api/nfs.js var toUTF8 = require('../utils.js').decodeUTF8; module.exports = { createDirectory: function(dir, options) { // Metadata needs to be base64 encoded if (options && options.metadata) options.metadata = btoa(options.metadata); var payload = Object.assign({}, {dirPath: dir}, options); return this.Request.post('/nfs/directory').auth().body(payload).execute(); }, getDirectory: function(dir, options) { return this.Request .get('/nfs/directory/'+encodeURIComponent(dir)+'/'+pathSharedString(options.isPathShared)) .auth() .execute() .then(function(dir) { // Metadata needs to be base64 decoded if (dir.info.metadata) dir.info.metadata = atob(dir.info.metadata); return dir; }); }, deleteDirectory: function(dir, options) { return this.Request.delete('/nfs/directory/'+encodeURIComponent(dir)+'/'+pathSharedString(options.isPathShared)).auth().execute(); }, createFile: function(file, options) { // Metadata needs to be base64 encoded if (options && options.metadata) options.metadata = btoa(options.metadata); var payload = Object.assign({}, {filePath: file}, options); return this.Request.post('/nfs/file').auth().body(payload).execute(); }, updateFile: function(file, content, options) { // If content is a TypedArray, then convert it to a string first. if (ArrayBuffer.isView(content)) content = toUTF8(content); var query = {}; if (options.offset) query.offset = options.offset; return this.Request.put('/nfs/file/'+encodeURIComponent(file)+'/'+pathSharedString(options.isPathShared)) .auth().body(content).query(query).execute(); }, getFile: function(file, options) { var query = {}; if (options.offset) query.offset = options.offset; if (options.length) query.length = options.length; return this.Request .get('/nfs/file/'+encodeURIComponent(file)+'/'+pathSharedString(options.isPathShared)) .query(query) .auth() .returnMeta() .execute(); }, deleteFile: function(file, options) { return this.Request.delete('/nfs/file/'+encodeURIComponent(file)+'/'+pathSharedString(options.isPathShared)).auth().execute(); } }; /** * Returns a string "true" or "false" * * @param isPathShared * @returns {string} */ function pathSharedString(isPathShared) { if (typeof isPathShared === 'string') { return isPathShared === 'true' ? 'true' : 'false'; } else { return isPathShared ? 'true' : 'false'; } }<file_sep>/src/api/dns.js module.exports = { listNames: function() { return this.Request.get('/dns').auth().execute(); }, createName: function(name) { return this.Request.post('/dns/' + encodeURIComponent(name)).auth().execute(); }, deleteName: function(name) { return this.Request.delete('/dns/' + encodeURIComponent(name)).auth().execute(); }, listServices: function(name) { return this.Request.get('/dns/'+encodeURIComponent(name)).auth().execute(); }, createServiceAndName: function(payload) { return this.Request.post('/dns').auth().body(payload).execute(); }, createServiceForName: function(payload) { return this.Request.put('/dns').auth().body(payload).execute(); }, getServiceDir: function(serviceName, name) { // Surprise! You can't authenticate this request. return this.Request.get('/dns/'+encodeURIComponent(serviceName)+'/'+encodeURIComponent(name)).execute(); }, getFile: function(serviceName, name, filePath, options) { var query = {}; if (options.offset) query.offset = options.offset; if (options.length) query.length = options.length; return this.Request .get('/dns/'+encodeURIComponent(serviceName)+'/'+encodeURIComponent(name)+'/'+encodeURIComponent(filePath)) .query(query) .returnMeta() .execute(); }, deleteService: function(serviceName, name) { return this.Request.delete('/dns/'+encodeURIComponent(serviceName)+'/'+encodeURIComponent(name)).auth().execute(); } };
6089ff7334a3150c4eaa10b9a71d36ecffcb49d0
[ "JavaScript", "Markdown" ]
6
JavaScript
Artogn/safenet
8438251bf0999b43f39c231df299b05d01dd4618
42e2c720b2dac14daea8ba943ad0c04fe4cff92a
refs/heads/main
<repo_name>dobby12/XGGYH<file_sep>/src/dao/impl/AdminAskDaoImpl.java package dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import common.JDBCTemplate; import dao.face.AdminAskDao; import dto.XAsk; import dto.XComment; import util.Paging; public class AdminAskDaoImpl implements AdminAskDao { PreparedStatement ps = null; ResultSet rs = null; @Override public int selectCntAll(Connection conn) { String sql = ""; sql += "SELECT count(*) FROM xask"; //총 게시글 수 int count = 0; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return count; } @Override public List<XAsk> selectAskAll(Connection conn, Paging paging) { String sql = ""; sql += "SELECT * FROM (SELECT rownum rnum, A.* FROM (SELECT ask_no, mem_id, ask_title, ask_date, ask_kind, ask_state FROM xask ORDER BY ask_state ASC, ask_no DESC) A) xask"; sql += " WHERE rnum BETWEEN ? AND ?"; List<XAsk> askList = new ArrayList<>(); try { ps = conn.prepareStatement(sql); ps.setInt(1, paging.getStartNo()); ps.setInt(2, paging.getEndNo()); rs = ps.executeQuery(); while( rs.next() ) { XAsk xask = new XAsk(); xask.setAskNo( rs.getInt("ask_no")); xask.setMemId( rs.getString("mem_id")); xask.setAskTitle( rs.getString("ask_title")); xask.setAskDate( rs.getDate("ask_date")); xask.setAskKind( rs.getString("ask_kind")); xask.setAskState( rs.getString("ask_state")); askList.add(xask); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return askList; } @Override public XAsk selectAskByAskNo(Connection conn, XAsk xaskno) { String sql =""; sql += "SELECT ask_no, mem_id, ask_title, ask_content, ask_date, ask_kind, ask_state"; sql += " FROM XAsk WHERE ask_no = ?"; //조회된 결과를 저장할 객체 XAsk result = new XAsk(); try { ps = conn.prepareStatement(sql); ps.setInt(1, xaskno.getAskNo() ); rs = ps.executeQuery(); while( rs.next() ) { result.setAskNo( rs.getInt("ask_no") ); result.setMemId( rs.getString("mem_id") ); result.setAskTitle( rs.getString("ask_title") ); result.setAskContent( rs.getString("ask_content") ); result.setAskDate( rs.getDate("ask_date") ); result.setAskKind( rs.getString("ask_kind") ); result.setAskState( rs.getString("ask_state") ); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return result; } @Override public String getNickByMemId(Connection conn, XAsk xask) { String sql = ""; sql += "SELECT mem_nick FROM xmem"; sql += " WHERE mem_id = ?"; String nick = null; try { ps = conn.prepareStatement(sql); ps.setString(1, xask.getMemId()); rs = ps.executeQuery(); while( rs.next() ) { nick = rs.getString("mem_nick"); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return nick; } @Override public int insertComment(Connection conn, XComment comment) { String sql = ""; sql += "INSERT INTO xcomment( comment_no, ask_no, admin_id, comment_content)"; sql += " VALUES ( xcomment_seq.nextval, ?, ?, ?)"; int res = 0; try { ps = conn.prepareStatement(sql); ps.setInt(1, comment.getAskNo()); ps.setString(2, comment.getAdminId()); ps.setString(3, comment.getCommentContent()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } @Override public XComment selectCommentByAskNo(Connection conn, XAsk xaskno) { String sql =""; sql += "SELECT comment_no, admin_id, comment_content"; sql += " FROM XComment WHERE ask_no = ?"; //조회된 결과를 저장할 객체 XComment com = new XComment(); try { ps = conn.prepareStatement(sql); ps.setInt(1, xaskno.getAskNo() ); rs = ps.executeQuery(); while( rs.next() ) { com.setCommentNo(rs.getInt("comment_no")); com.setAdminId(rs.getString("admin_id")); com.setCommentContent(rs.getString("comment_content")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return com; } @Override public void deleteCommentByAskNo(Connection conn, XAsk xaskno) { String sql = ""; sql += "DELETE xcomment WHERE ask_no = ?"; try { ps = conn.prepareStatement(sql); ps.setInt(1, xaskno.getAskNo()); ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } } @Override public int updateAskStateToN(Connection conn, XAsk xask) { String sql = ""; sql += "UPDATE xask SET ask_state = 'n'"; sql += " WHERE ask_no = ?"; int res = 0; try { ps = conn.prepareStatement(sql); ps.setInt(1, xask.getAskNo()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } @Override public int updateAskStateToY(Connection conn, XAsk xask) { String sql = ""; sql += "UPDATE xask SET ask_state = 'y'"; sql += " WHERE ask_no = ?"; int res = 0; try { ps = conn.prepareStatement(sql); ps.setInt(1, xask.getAskNo()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } @Override public int updateComment(Connection conn, XComment comment) { String sql = ""; sql += "UPDATE xcomment SET admin_id = ?, comment_content = ?"; sql += " WHERE comment_no = ?"; int res = 0; try { ps = conn.prepareStatement(sql); ps.setString(1, comment.getAdminId()); ps.setString(2, comment.getCommentContent()); ps.setInt(3, comment.getCommentNo()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } } <file_sep>/src/controller/admin/AdminShowWriteController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dto.XAdmin; import service.face.AdminService; import service.face.AdminShowService; import service.impl.AdminServiceImpl; import service.impl.AdminShowServiceImpl; @WebServlet("/admin/show/write") public class AdminShowWriteController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminShowService adminShowService = new AdminShowServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { req.getRequestDispatcher("/WEB-INF/views/admin/show/write.jsp").forward(req, resp); return; } resp.sendRedirect("/admin"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); adminShowService.setShow( req ); // // System.out.println("showContent: " + req.getParameter("showContent")); // System.out.println("showStart : " + req.getParameter("showStart")); // System.out.println("showEnd : " + req.getParameter("showEnd")); resp.sendRedirect("/admin/show/list"); } } <file_sep>/src/controller/mem/MemberIdCheckController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.face.MemberService; import service.impl.MemberServiceImpl; @WebServlet("/join/idcheck") public class MemberIdCheckController extends HttpServlet { private static final long serialVersionUID = 1L; private MemberService memberService = new MemberServiceImpl(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/join/idcheck [POST]"); String memid = req.getParameter("memid"); boolean doesExist = memberService.checkId(memid); resp.getWriter().print(doesExist); return; } } <file_sep>/src/controller/mem/ReviewWriteController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XShow; import service.face.ReviewService; import service.face.ShowService; import service.impl.ReviewServiceImpl; import service.impl.ShowServiceImpl; @WebServlet("/review/write") public class ReviewWriteController extends HttpServlet { private static final long serialVersionUID = 1L; private ReviewService reviewService = new ReviewServiceImpl(); private ShowService showService = new ShowServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/review/write [GET]"); if( req.getSession().getAttribute("login") == null || !(boolean)req.getSession().getAttribute("login") ) { resp.sendRedirect("/"); return; } System.out.println("@" + req.getParameter("showNo")); System.out.println("@" + req.getSession().getAttribute("memid")); if(reviewService.getReviewOverlap(req)) { resp.sendRedirect("/show/detail?showNo=" + req.getParameter("showNo") + "&from=alert"); return; } XShow showNo = showService.getShowNo(req); XShow showDetail = showService.viewShowInfo(showNo); req.setAttribute("showDetail", showDetail); req.setAttribute("showTitle", req.getParameter("showTitle")); req.getRequestDispatcher("/WEB-INF/views/mem/review/write.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/review/write [POST]"); reviewService.write(req); resp.sendRedirect("/review/list"); } } <file_sep>/src/dao/face/AdminShowDao.java package dao.face; import java.sql.Connection; import java.util.List; import dto.XFile; import dto.XShow; import util.Paging; public interface AdminShowDao { /** * 특정 공연 정보 조회 * * @param conn * @param showno * @return 공연 객체 */ public XShow selectShowByShowno(Connection conn, XShow showno); /** * kind_no를 이용해서 kind_name 조회 * * @param conn * @param showno * @return kind_name */ public String selectKindByKindno(Connection conn, XShow viewShow); /** * genre_no를 이용해서 genre_name조회 * * @param conn * @param showno * @return genre_name */ public String selectGenrebyGenreno(Connection conn, XShow viewShow); /** * hall_no를 이용해서 hall_name 조회 * * @param conn * @param showno * @return hall_name */ public String selectHallnameByHallno(Connection conn, XShow viewShow); /** * 첨부파일 조회 * * @param conn * @param viewShow * @return */ public XFile selectFile(Connection conn, XShow viewShow); /** * 페이지 수 구하기 * * @param connection - DB 정보 객체 * @return int */ public int selectCntAll(Connection connection); /** * 게시판 리스트 조회 * * @param conn - DB 연결 객체 * @param paging - paging 정보 객체 * @return List<XShow> - XShow 테이블 전체 조회 */ public List<XShow> selectShowAll(Connection conn, Paging paging); /** * 공연 정보 파일 삭제 * * @param conn * @param showno * @return */ public int deleteShowFile(Connection conn, XShow showno); /** * 공연 정보 글 삭제 * * @param conn * @param showno * @return */ public int deleteShow(Connection conn, XShow showno); /** * XShow_seq.nextval로 show_no 만들기 * * @param conn - DB 연결 객체 * @return int */ public int selectNextShowno(Connection conn); /** * XShow 공연 정보 저장 * * @param conn - DB 연결 객체 * @param xshow - 전달받은 공연 정보 * @return int */ public int insertShow(Connection conn, XShow xshow); /** * 공연 정보 수정 * * @param conn - DB 연결 객체 * @param xshow - 전달받은 공연 정보 * @return int */ public int updateShow(Connection conn, XShow xshow); /** * 검색된 전체 공연 수 조회 * * @param conn * @param keyword - 검색어 * @return 전체 인원 */ public int selectCntSearchShowAll(Connection conn, String keyword); /** * 공연 제목으로 검색 * * @param conn * @param keyword * @return 공연 리스트 객체 */ public List<XShow> selectShowSearchByShowtitle(Connection conn, String keyword, Paging paging); } <file_sep>/src/controller/admin/AdminShowListController.java package controller.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XShow; import service.face.AdminService; import service.face.AdminShowService; import service.impl.AdminServiceImpl; import service.impl.AdminShowServiceImpl; import util.Paging; @WebServlet("/admin/show/list") public class AdminShowListController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminShowService adminShowService = new AdminShowServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/admin/show/list [GET]"); Paging paging = adminShowService.getPaging(req); List<XShow> list = adminShowService.getShowList(paging); req.setAttribute("list", list); req.setAttribute("paging", paging); req.setAttribute("linkUrl", "/admin/show/list"); if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { req.getRequestDispatcher("/WEB-INF/views/admin/show/list.jsp").forward(req, resp); return; } resp.sendRedirect("/admin"); } } <file_sep>/src/controller/admin/AdminMemDeleteController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XMem; import service.face.AdminMemberService; import service.face.AdminService; import service.impl.AdminMemberServiceImpl; import service.impl.AdminServiceImpl; @WebServlet("/admin/mem/delete") public class AdminMemDeleteController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminMemberService adminMemberService = new AdminMemberServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/admin/mem/delete [GET]"); XMem memid = adminMemberService.getMemId(req); adminMemberService.setMemDelete(memid); if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { resp.sendRedirect("/admin/mem/list"); return; } resp.sendRedirect("/admin"); } } <file_sep>/src/controller/admin/AdminAskDetailController.java package controller.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dto.XAdmin; import dto.XAsk; import dto.XComment; import service.face.AdminAskService; import service.face.AdminService; import service.impl.AdminAskServiceImpl; import service.impl.AdminServiceImpl; @WebServlet("/admin/ask/detail") public class AdminAskDetailController extends HttpServlet { private static final long serialVersionUID = 1L; AdminAskService adminAskService = new AdminAskServiceImpl(); AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { XAsk xaskno = adminAskService.getAskNo(req); XAsk xask = adminAskService.getAskDetail(xaskno); // System.out.println(xask); XComment xcomment = adminAskService.getComment(xaskno); // System.out.println(xcomment); XAdmin admin = adminService.getLoginAdmin(req); HttpSession session = req.getSession(); req.setAttribute("xask", xask); req.setAttribute("xaskno", xaskno); req.setAttribute("nick", adminAskService.getNick(xask)); req.setAttribute("xcomment", xcomment); if(adminService.loginAdmin(admin)) { session.setAttribute("adminlogin", true); session.setAttribute("adminid", adminService.getAdmin(admin).getAdminId()); session.setAttribute("adminname", adminService.getAdmin(admin).getAdminName()); session.setAttribute("adminauthority", adminService.getAdmin(admin).getAdminAuthority()); } else { session.setAttribute("loginfail", true); } req.getRequestDispatcher("/WEB-INF/views/admin/ask/detail.jsp").forward(req, resp); } } <file_sep>/src/dao/face/MemberDao.java package dao.face; import java.sql.Connection; import dto.XMem; public interface MemberDao { /** * 전달받은 mem의 memid와 mempw가 일치하는 행의 개수 반환 * @param connection - DB연결객체 * @param mem - DB를 조회해 보려는 memid와 mempw가 저장된 XMem객체 * @return 1 == 아이디가 있으며 패스워드가 일치함 */ public int selectCntMemByMemidMempw(Connection connection, XMem mem); /** * 전달받은 mem의 memid와 일치하는 행의 mem_id, mem_nick 반환 * @param connection - DB연결객체 * @param mem - DB를 조회해 보려는 memid가 저장된 XMem객체 * @return mem_id, mem_nick이 저장된 XMem객체 */ public XMem selectMemByMemid(Connection connection, XMem mem); /** * 회원가입정보 삽입하기 * * @param member - 회원가입 정보 객체 */ public int insert(Connection conn, XMem member); /** * * @param parameter * @return */ public String selectMemidByMemmail(Connection connection, String parameter); /** * * @param connection * @param mailForPw * @param uuidPw */ public int updateMempw(Connection connection, String mailForPw, String uuidPw); /** * * * @param connection - DB연결객체 * @param memid - 현재 로그인 중인 아이디 * @return */ public XMem selectMemByMemid(Connection connection, String memid); /** * * @param conn * @param mem * @return */ public int updateMem(Connection conn, XMem mem); /** * * @param conn * @param memId * @return */ public int deleteMem(Connection conn, XMem mem); /** * * @param connection * @param kakaoemail * @return */ public int selectCntMemByKakao(Connection connection, String kakaoemail); /** * * @param kakaoemail * @return */ public XMem selectMemByKakao(Connection connection, String kakaoemail); /** * kakao로 로그인한 email의 kakao column이 y인 행의 개수 * @param connection * @param kakaoemail * @return */ public int selectCntMemByKakaoY(Connection connection, String kakaoemail); /** * * @param connection * @param kakaoagree */ public int updateMemKakaoByMemmail(Connection conn, String kakaoagree); /** * * @param conn * @param mem * @return */ public int insertMemWithKakao(Connection conn, XMem mem); } <file_sep>/src/dao/impl/AdminReviewDaoImpl.java package dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import common.JDBCTemplate; import dao.face.AdminReviewDao; import dto.XFile; import dto.XMem; import dto.XReview; import util.Paging; public class AdminReviewDaoImpl implements AdminReviewDao { private PreparedStatement ps = null; private ResultSet rs = null; @Override public int selectCntReviewAll(Connection conn) { //SQL작성 String sql = ""; sql += "SELECT count(*) FROM xreview"; int count = 0; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return count; //전체 게시글의 수 반환 } @Override public List<XReview> selectReviewAll(Connection conn, Paging paging) { String sql = ""; sql += "SELECT * FROM ("; sql += " SELECT rownum rnum, XR.* FROM ("; sql += " SELECT review_no, show_no, file_no, mem_id, review_title, review_content, review_date, review_score, review_hit "; sql += " FROM xreview"; sql += " ORDER BY review_no DESC"; sql += " ) XR"; sql += " )XREVIEW"; sql += " WHERE rnum BETWEEN ? AND ?"; List<XReview> reviewList = new ArrayList<XReview>(); try { ps = conn.prepareStatement(sql); ps.setInt(1, paging.getStartNo()); ps.setInt(2, paging.getEndNo()); rs = ps.executeQuery(); while(rs.next()) { XReview review = new XReview(); review.setReviewNo(rs.getInt("review_no")); review.setShowNo(rs.getInt("show_no")); review.setFileNo(rs.getInt("file_no")); review.setMemId(rs.getString("mem_id")); review.setReviewTitle(rs.getString("review_title")); review.setReviewContent(rs.getString("review_content")); review.setReviewDate(rs.getDate("review_date")); review.setReviewScore(rs.getInt("review_score")); review.setReviewHit(rs.getInt("review_hit")); reviewList.add(review); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return reviewList; } @Override public XReview selectReviewbyReviewno(Connection conn, XReview reviewno) { String sql = ""; sql += "SELECT * FROM Xreview"; sql += " WHERE review_no = ?"; XReview viewReview = null; try { ps = conn.prepareStatement(sql); ps.setInt(1, reviewno.getReviewNo()); rs = ps.executeQuery(); while(rs.next()) { viewReview = new XReview(); viewReview.setReviewNo(rs.getInt("review_no")); viewReview.setShowNo(rs.getInt("show_no")); viewReview.setFileNo(rs.getInt("file_no")); viewReview.setMemId(rs.getString("mem_id")); viewReview.setReviewTitle(rs.getString("review_title")); viewReview.setReviewContent(rs.getString("review_content")); viewReview.setReviewDate(rs.getDate("review_date")); viewReview.setReviewScore(rs.getInt("review_score")); viewReview.setReviewHit(rs.getInt("review_hit")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return viewReview; } @Override public String selectNickByMemid(Connection conn, XReview viewReview) { String sql = ""; sql += "SELECT mem_nick FROM Xmem"; sql += " WHERE mem_id = ?"; String mem_nick = null; try { ps = conn.prepareStatement(sql); ps.setString(1, viewReview.getMemId()); rs = ps.executeQuery(); while(rs.next()) { mem_nick = rs.getString("mem_nick"); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return mem_nick; } @Override public String selectShowTitleByShowno(Connection conn, XReview viewReview) { String sql = ""; sql += "SELECT show_title FROM XShow"; sql += " WHERE show_no = ?"; String show_title = null; try { ps = conn.prepareStatement(sql); ps.setInt(1, viewReview.getShowNo()); rs = ps.executeQuery(); while(rs.next()) { show_title = rs.getString("show_title"); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return show_title; } @Override public XFile selectFile(Connection conn, XReview viewReview) { String sql = ""; sql += "SELECT * FROM XFile"; sql += " WHERE file_no = ?"; XFile reviewFile = null; try { ps = conn.prepareStatement(sql); ps.setInt(1, viewReview.getFileNo()); rs = ps.executeQuery(); while(rs.next()) { reviewFile = new XFile(); reviewFile.setFileNo(rs.getInt("file_no")); reviewFile.setFileOriginName(rs.getString("file_origin_name")); reviewFile.setFileStoredName(rs.getString("file_stored_name")); reviewFile.setFileSize(rs.getString("file_size")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return reviewFile; } @Override public int deleteReview(Connection conn, XReview reviewno) { String sql = ""; sql += "DELETE xreview"; sql += " WHERE review_no = ?"; int res = -1; try { ps = conn.prepareStatement(sql); ps.setInt(1, reviewno.getReviewNo()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } @Override public int deleteReviewFile(Connection conn, XReview reviewno) { String sql = ""; sql += "DELETE xfile"; sql += " WHERE file_no = ?"; int res = -1; try { ps = conn.prepareStatement(sql); ps.setInt(1, reviewno.getFileNo()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } @Override public List<XReview> selectReviewByMemid(Connection conn, Paging paging, XMem reviewMem) { String sql = ""; sql += "SELECT * FROM ("; sql += " SELECT rownum rnum, XR.* FROM ("; sql += " SELECT review_no, show_no, file_no, mem_id, review_title, review_content, review_date, review_score, review_hit "; sql += " FROM xreview"; sql += " WHERE mem_id = ?"; sql += " ORDER BY review_no DESC"; sql += " ) XR"; sql += " )XREVIEW"; sql += " WHERE rnum BETWEEN ? AND ?"; List<XReview> memReviewList = new ArrayList<XReview>(); try { ps = conn.prepareStatement(sql); ps.setString(1, reviewMem.getMemId()); ps.setInt(2, paging.getStartNo()); ps.setInt(3, paging.getEndNo()); rs = ps.executeQuery(); while(rs.next()) { XReview review = new XReview(); review.setReviewNo(rs.getInt("review_no")); review.setShowNo(rs.getInt("show_no")); review.setFileNo(rs.getInt("file_no")); review.setMemId(rs.getString("mem_id")); review.setReviewTitle(rs.getString("review_title")); review.setReviewContent(rs.getString("review_content")); review.setReviewDate(rs.getDate("review_date")); review.setReviewScore(rs.getInt("review_score")); review.setReviewHit(rs.getInt("review_hit")); memReviewList.add(review); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return memReviewList; } } <file_sep>/src/service/face/AskService.java package service.face; import java.util.List; import javax.servlet.http.HttpServletRequest; import dto.XAsk; import dto.XComment; import util.Paging; public interface AskService { /** * 게시글 전체 조회 * * @return List<XAsk> - 게시글 전체 조회 결과 리스트 */ public List<XAsk> getList(); /** * 게시글 전체 조회 * 페이징 처리 추가 * * @param paging - 페이징 정보 객체 * @return List<XAsk> - 게시글 전체 조회 결과 리스트 */ public List<XAsk> getList(Paging paging); /** * 페이징 객체 생성 * * 요청파라미터 curPage를 구한다 * XAsk테이블과 curPage값을 이용하여 Paging객체를 구하여 반환한다 * * @param req - 요청정보 객체 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPaging(HttpServletRequest req); /** * 요청파라미터 얻기 * * @param req - 요청정보객체 * @return XAsk - 전달파라미터 ask_no를 포함한 객체 */ public XAsk getAskNo(HttpServletRequest req); /** * 게시글 작성 * 입력한 게시글 내용을 DB에 저장 * * @param req - 요청정보 객체(게시글내용 + 첨부파일) * */ public void write(HttpServletRequest req); /** * 페이징 객체 생성 * * @param req - 요청정보 객체 * @param memid * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPagingByMemId(HttpServletRequest req, String memid); /** * 멤버id 게시글 조회 * 페이징 처리 추가 * * @param paging - 페이징 정보 객체 * @param memid - 로그인 된 회원 아이디 * @return List<XReview> - 멤버id 게시글 조회 결과 리스트 */ public List<XAsk> getAskListByMemid(Paging paging, String memid); /** * * @param askNo * @return */ public XAsk detail(XAsk askNo); /** * * @param askNo * @return */ public XComment getComment(XAsk askNo); } <file_sep>/src/controller/mem/MemberDetailController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XMem; import service.face.MemberService; import service.impl.MemberServiceImpl; @WebServlet("/mypage/myinfo") public class MemberDetailController extends HttpServlet { private static final long serialVersionUID = 1L; private MemberService memberService = new MemberServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/mypage/myinfo [GET]"); //로그인한 회원아이디 String memid = (String)req.getSession().getAttribute("memid"); XMem myinfo = memberService.getMyInfo(memid); System.out.println(myinfo); req.setAttribute("myinfo", myinfo); //로그인 되어있지 않으면 리다이렉트 if( req.getSession().getAttribute("login") == null || !(boolean)req.getSession().getAttribute("login") ) { resp.sendRedirect("/"); return; } req.getRequestDispatcher("/WEB-INF/views/mem/mypage/mem/detail.jsp").forward(req, resp); } } <file_sep>/src/controller/mem/MemberFindController.java package controller.mem; import java.io.IOException; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.face.AdminMailService; import service.face.MemberService; import service.impl.AdminMailServiceImpl; import service.impl.MemberServiceImpl; @WebServlet("/member/find") public class MemberFindController extends HttpServlet { private static final long serialVersionUID = 1L; private MemberService memberService = new MemberServiceImpl(); private AdminMailService adminMailService = new AdminMailServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getRequestDispatcher("/WEB-INF/views/mem/find.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); String mailForId = req.getParameter("mailForId"); String mailForPw = req.getParameter("mailForPw"); //ID 찾기 if("".equals(mailForPw) && mailForId!=null) { String idForMail = memberService.getMemid(mailForId); //입력한 메일이 DB에 있을 경우 if(idForMail!=null) { req.setAttribute("findid", idForMail); //입력한 메일이 DB에 없을 경우 } else { req.setAttribute("noMailId", "입력하신 " + mailForId + "로 가입된 회원 정보가 없습니다."); } //ID 찾기를 실행 req.setAttribute("id", true); //PW 찾기 } else if("".equals(mailForId) && mailForPw!=null) { String idForMail = memberService.getMemid(mailForPw); //입력한 메일이 DB에 있을 경우 if(idForMail!=null) { //uuid를 통한 PW 변경 UUID uuid = UUID.randomUUID(); String uuidPw = uuid.toString().split("-")[0]; memberService.setMempwUpdate(mailForPw, uuidPw); //보낼 메일 제목 String mailTitle = "[공공연히] 재설정한 "+idForMail+"님의 패스워드"; //보낼 메일 내용 String mailContent = "안녕하세요. 귀하의 비밀번호는 ["+uuidPw+"]으로 변경되었습니다."; //메일 발송 adminMailService.sendMail(mailForPw, mailTitle, mailContent); //입력한 메일이 DB에 없을 경우 } else { req.setAttribute("noMailPw", "입력하신 " + mailForPw + "로 가입된 회원 정보가 없습니다."); } //PW 찾기를 실행 req.setAttribute("pw", true); } req.getRequestDispatcher("/WEB-INF/views/mem/findresult.jsp").forward(req, resp); } } <file_sep>/src/controller/mem/MyCalendarController.java package controller.mem; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XShow; import service.face.JjimService; import service.impl.JjimServiceImpl; import util.Paging; @WebServlet("/mycalendar") public class MyCalendarController extends HttpServlet { private static final long serialVersionUID = 1L; private JjimService jjimService = new JjimServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/mycalendar [GET]"); String memid = (String)req.getSession().getAttribute("memid"); Paging paging = jjimService.getPaging(req, memid); List<XShow> showList = jjimService.getShowNoByMemId(paging, memid); System.out.println(showList); req.setAttribute("paging", paging); req.setAttribute("memid", memid); req.setAttribute("showList", showList); //로그인 되어있지 않으면 리다이렉트 if( req.getSession().getAttribute("login") == null || !(boolean)req.getSession().getAttribute("login") ) { resp.setContentType("text/html; charset=UTF-8"); PrintWriter writer = resp.getWriter(); writer.println("<script>alert('로그인 후 이용 가능한 서비스입니다. 로그인 해주세요.');" + "location.href='/login';</script>"); writer.close(); return; } req.getRequestDispatcher("/WEB-INF/views/mem/mycalendar/mycalendar.jsp").forward(req, resp); } } <file_sep>/src/dto/XAdmin.java package dto; public class XAdmin { private String adminId; private String adminPw; private String adminName; private String adminAuthority; @Override public String toString() { return "XAdmin [adminId=" + adminId + ", adminPw=" + adminPw + ", adminName=" + adminName + ", adminAuthority=" + adminAuthority + "]"; } public String getAdminId() { return adminId; } public void setAdminId(String adminId) { this.adminId = adminId; } public String getAdminPw() { return adminPw; } public void setAdminPw(String adminPw) { this.adminPw = adminPw; } public String getAdminName() { return adminName; } public void setAdminName(String adminName) { this.adminName = adminName; } public String getAdminAuthority() { return adminAuthority; } public void setAdminAuthority(String adminAuthority) { this.adminAuthority = adminAuthority; } } <file_sep>/src/dao/face/AdminAskDao.java package dao.face; import java.sql.Connection; import java.util.List; import dto.XAsk; import dto.XComment; import util.Paging; public interface AdminAskDao { /** * 페이지 수 구하기 * * @param connection - DB 정보 객체 * @return int */ public int selectCntAll(Connection conn); /** * 게시판 리스트 조회 * * @param conn - DB 연결 객체 * @param paging - paging 정보 객체 * @return List<XAsk> - XAsk 테이블 전체 조회 결과 */ public List<XAsk> selectAskAll(Connection conn, Paging paging); /** * ask_no을 통해서 해당 게시글 정보 조회 * * @param conn - DB 연결 객체 * @param xaskno - 게시글 조회를 위한 ask_no * @return XAsk 객체 */ public XAsk selectAskByAskNo(Connection conn, XAsk xaskno); /** * id를 이용 * @param conn - DB 이용 객체 * @param xask - 조회할 id를 가진 객체 * @return String - 작성자 닉네임 */ public String getNickByMemId(Connection conn, XAsk xask); /** * 댓글 정보 저장 * * @param conn - DB 연결 객체 * @param comment - 전달된 댓글 정보 * @return - 1 or 0 */ public int insertComment(Connection conn, XComment comment); /** * 댓글 정보 조회 * * @param conn - DB 연결 객체 * @param xaskno - 전달된 ask_no * @return XComment */ public XComment selectCommentByAskNo(Connection conn, XAsk xaskno); /** * 댓글 정보 삭제 * * @param conn - DB 연결 객체 * @param xaskno - 전달된 ask_no */ public void deleteCommentByAskNo(Connection conn, XAsk xaskno); /** * ask_state n으로 변경 * * @param conn - DB 연결 객체 * @param xask - ask_no * @return int */ public int updateAskStateToN(Connection conn, XAsk xask); /** * ask_state y로 변경 * * @param conn - DB 연결 객체 * @param xask - ask_no * @return int */ public int updateAskStateToY(Connection conn, XAsk xask); /** * comment 수정 * * @param conn - DB 연결 객체 * @param comment - 수정된 comment * @return int */ public int updateComment(Connection conn, XComment comment); } <file_sep>/src/controller/admin/AdminShowSearchController.java package controller.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XShow; import service.face.AdminService; import service.face.AdminShowService; import service.impl.AdminServiceImpl; import service.impl.AdminShowServiceImpl; import util.Paging; @WebServlet("/admin/show/search") public class AdminShowSearchController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminShowService adminShowService = new AdminShowServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/admin/show/search [GET]"); Paging paging = adminShowService.getParameterPaging(req); System.out.println("AdminShowListController [GET] - " + paging); //전달 파라미터 searchtype, keyword를 통해서 searchMember객체를 반환 List<XShow> searchShowList = adminShowService.searchShowList(req, paging); req.setAttribute("searchShowList", searchShowList); req.setAttribute("paging", paging); req.setCharacterEncoding("UTF-8"); req.setAttribute("linkUrl", "/admin/show/search?keyword=" + req.getParameter("keyword")); req.setAttribute("keyword", req.getParameter("keyword")); // System.out.println("linkUrl : admin/show/search?searchtype=" + req.getParameter("searchtype") + "&keyword=" + req.getParameter("keyword")); if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { req.getRequestDispatcher("/WEB-INF/views/admin/show/search.jsp").forward(req, resp); return; } resp.sendRedirect("/admin"); } } <file_sep>/src/dao/impl/JjimDaoImpl.java package dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import common.JDBCTemplate; import dao.face.JjimDao; import dto.XJjim; import dto.XShow; import util.Paging; public class JjimDaoImpl implements JjimDao { private PreparedStatement ps = null; private ResultSet rs = null; @Override public int insertJjim(Connection conn, XJjim jjim) { String sql = ""; sql += "INSERT INTO XJJIM( jjim_no, mem_id, show_no)"; sql += " VALUES ( xjjim_seq.nextval, ?, ?)"; int res = 0; try { ps = conn.prepareStatement(sql); ps.setString(1, jjim.getMemId()); ps.setInt(2, jjim.getShowNo()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } // @Override // public XJjim selectAllByMemId(Connection conn, String memid) { // // String sql = ""; // sql += "SELECT * FROM XJJIM"; // sql += " WHERE MEM_ID = ?"; // // XJjim jjim = null; // // try { // ps = conn.prepareStatement(sql); // ps.setString(1, memid); // // rs = ps.executeQuery(); // // while(rs.next()) { // // jjim = new XJjim(); // // jjim.setJjimNo( rs.getInt("jjim_no") ); // jjim.setMemId( rs.getString("Mem_id") ); // jjim.setShowNo( rs.getInt("show_no") ); // // System.out.println(rs.getInt("jjim_no")); // System.out.println(rs.getString("Mem_id")); // System.out.println(rs.getInt("show_no")); // // } // // } catch (SQLException e) { // e.printStackTrace(); // } finally { // JDBCTemplate.close(rs); // JDBCTemplate.close(ps); // } // // return jjim; // } @Override public int selectCntByMemId(Connection conn, String memid) { //SQL 작성 String sql = ""; sql += "SELECT count(*) FROM xjjim"; sql += " WHERE mem_id = ?"; //총 게시글 수 int count = 0; try { ps = conn.prepareStatement(sql); ps.setString(1, memid); rs = ps.executeQuery(); while(rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return count; } @Override public List<XShow> selectShowByMemId(Connection conn, Paging paging, String memid) { String sql = ""; sql += "SELECT * FROM ("; sql += " SELECT * FROM XSHOW"; sql += " WHERE show_no IN ("; sql += " SELECT show_no FROM XJJIM"; sql += " WHERE mem_id = ?))"; sql += "WHERE rownum BETWEEN ? AND ?"; List<XShow> showList = new ArrayList<>(); try { ps = conn.prepareStatement(sql); ps.setString(1, memid); ps.setInt(2, paging.getStartNo()); ps.setInt(3, paging.getEndNo()); System.out.println(paging.getStartNo()); System.out.println(paging.getEndNo()); rs = ps.executeQuery(); while(rs.next()) { XShow show = new XShow(); show.setShowNo(rs.getInt("show_no")); show.setFileNo(rs.getInt("file_no")); show.setAdminId(rs.getString("admin_id")); show.setKindNo(rs.getInt("kind_no")); show.setGenreNo(rs.getInt("genre_no")); show.setHallNo(rs.getInt("hall_no")); show.setShowTitle(rs.getString("show_title")); show.setShowContent(rs.getString("show_content")); show.setShowDate(rs.getDate("show_date")); show.setShowAge(rs.getString("show_age")); show.setShowDirector(rs.getString("show_director")); show.setShowActor(rs.getString("show_actor")); show.setShowStart(rs.getDate("show_start")); show.setShowEnd(rs.getDate("show_end")); showList.add(show); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return showList; } @Override public List<XShow> selectShowByMemId(Connection conn, String memid) { String sql = ""; sql += "SELECT * FROM ("; sql += " SELECT * FROM XSHOW"; sql += " WHERE show_no IN ("; sql += " SELECT show_no FROM XJJIM"; sql += " WHERE mem_id = ?))"; List<XShow> showList = new ArrayList<>(); try { ps = conn.prepareStatement(sql); ps.setString(1, memid); rs = ps.executeQuery(); while(rs.next()) { XShow show = new XShow(); show.setShowNo(rs.getInt("show_no")); show.setFileNo(rs.getInt("file_no")); show.setAdminId(rs.getString("admin_id")); show.setKindNo(rs.getInt("kind_no")); show.setGenreNo(rs.getInt("genre_no")); show.setHallNo(rs.getInt("hall_no")); show.setShowTitle(rs.getString("show_title")); show.setShowContent(rs.getString("show_content")); show.setShowDate(rs.getDate("show_date")); show.setShowAge(rs.getString("show_age")); show.setShowDirector(rs.getString("show_director")); show.setShowActor(rs.getString("show_actor")); show.setShowStart(rs.getDate("show_start")); show.setShowEnd(rs.getDate("show_end")); showList.add(show); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return showList; } @Override public int deleteJjim(Connection conn, String memId, String showNo) { // XJjim 테이블에 조건에 맞는 행 삭제 String sql = ""; sql += "DELETE XJjim "; sql += "WHERE mem_id = ? AND show_no = ?"; // 총 게시글 수 int isDeleted = 0; try { ps = conn.prepareStatement(sql); ps.setString(1, memId); ps.setString(2, showNo); isDeleted = ps.executeUpdate(); if(isDeleted > 0) System.out.println("삭제 성공"); else System.out.println("해당하는 정보가 없습니다."); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return isDeleted; } @Override public boolean selectXJjimByMemIdShowNo(Connection conn, String memId, int showNo) { // SQL 작성 String sql = ""; sql += "SELECT * FROM xjjim"; sql += " WHERE mem_id = ? AND show_no = ?"; // 총 게시글 수 boolean isSelected = false; try { ps = conn.prepareStatement(sql); ps.setString(1, memId); ps.setInt(2, showNo); rs = ps.executeQuery(); if(rs.next()) { System.out.println("이미 찜했음"); } else { System.out.println("게시글 찜 안했었음"); isSelected = true; } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return isSelected; } } <file_sep>/src/service/face/NoticeService.java package service.face; import java.util.List; import javax.servlet.http.HttpServletRequest; import dto.XFile; import dto.XNotice; import util.Paging; public interface NoticeService { /** * 게시글 전체 조회 * * @return List<XNotice> - 게시글 전체 조회 결과 리스트 */ public List<XNotice> getNoticeList(); /** * 게시글 전체 조회 * 페이징 처리 추가 * * @param paging - 페이징 정보 객체 * @return List<XNotice> - 게시글 전체 조회 결과 리스트 */ public List<XNotice> getNoticeList(Paging paging); /** * 페이징 객체 생성 * * 요청파라미터 curPage를 구한다 * XNotice 테이블과 curPage값을 이용하여 Paging객체를 구하여 반환한다 * * @param req - 요청정보 객체 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPaging(HttpServletRequest req); /** * 요청파라미터 얻기 * * @param req - 요청정보객체 * @return XNotice - 전달파라미터 NoticeNo를 포함한 객체 */ public XNotice getNoticeNo(HttpServletRequest req); /** * XNotice 객체의 ID를 이용한 닉네임 조회 * * @param viewNotice - 조회할 게시글 정보 * @return String - 게시글 관리자의 닉네임 */ public String getAdminName(XNotice viewNotice); /** * 첨부파일 정보 조회 * * @param viewNotice - 첨부파일과 연결된 게시글번호를 포함한 DTO객체 * @return XFile - 첨부파일 정보 DTO객체 */ public XFile viewFile(XNotice viewNotice); /** * * @param noticeNo * @return */ public XNotice view(XNotice noticeNo); } <file_sep>/src/controller/mem/MemberKakaoJoinController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XMem; import service.face.MemberService; import service.impl.MemberServiceImpl; @WebServlet("/kakaojoin") public class MemberKakaoJoinController extends HttpServlet { private static final long serialVersionUID = 1L; private MemberService memberService = new MemberServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); XMem mem = new XMem(); mem.setMemId(req.getParameter("memid")); mem.setMemPw(req.getParameter("mempw")); mem.setMemNick(req.getParameter("memnick")); mem.setMemMail(req.getParameter("memmail")); mem.setMailState(req.getParameter("memstate")); mem.setGenreNo(Integer.parseInt(req.getParameter("genreno"))); try { memberService.setMemWithKakao(mem); resp.getWriter().print(true); } catch(Exception e) { resp.getWriter().print(false); } return; } } <file_sep>/src/service/face/ReviewService.java package service.face; import java.util.List; import javax.servlet.http.HttpServletRequest; import dto.XFile; import dto.XReview; import dto.XShow; import util.Paging; public interface ReviewService { // /** // * 게시글 전체 조회 // * // * @return List<XReview> - 게시글 전체 조회 결과 리스트 // */ // public List<XReview> getList(); /** * 게시글 전체 조회 * 페이징 처리 추가 * * @param paging - 페이징 정보 객체 * @return List<XReview> - 게시글 전체 조회 결과 최신순 리스트 */ public List<XReview> getList(Paging paging); /** * 게시글 전체 조회 * 페이징 처리 추가 * * @param paging - 페이징 정보 객체 * @return List<XReview> - 게시글 전체 조회 결과 조회순 리스트 */ public List<XReview> getListhit(Paging paging); /** * 멤버id 게시글 조회 * 페이징 처리 추가 * * @param paging - 페이징 정보 객체 * @param memid - 로그인 된 회원 아이디 * @return List<XReview> - 멤버id 게시글 조회 결과 리스트 */ public List<XReview> getReviewListByMemid(Paging paging, String memid); /** * 페이징 객체 생성 * * 요청파라미터 curPage를 구한다 * XReview테이블과 curPage값을 이용하여 Paging객체를 구하여 반환한다 * * @param req - 요청정보 객체 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPaging(HttpServletRequest req); /** * 페이징 객체 생성 * XReview테이블과 curPage값과 listCount를 이용하여 Paging객체를 구하여 반환한다 * * @param req - 요청정보 객체 * @param listCount - 한번에 몇개 보여줄지 결정하는 매개변수 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPaging(HttpServletRequest req, int listCount, int showNo); /** * 페이징 객체 생성 * * @param req - 요청정보 객체 * @param memid * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPagingByMemId(HttpServletRequest req, String memid); /** * 요청파라미터 얻기 * * @param req - 요청정보객체 * @return XReview - 전달파라미터 review_no를 포함한 객체 */ public XReview getReviewNo(HttpServletRequest req); /** * 요청파라미터 얻기 * * @param req - 요청정보객체 * @return XSHow - 전달파라미터 show_no를 포함한 객체 */ public XShow getShowNo(HttpServletRequest req); /** * 주어진 review_no를 이용하여 게시글을 조회한다 * 조회된 게시글의 조회수를 1 증가시킨다 * * @param review_no - review_no를 가지고 있는 객체 * @return XReview - 조회된 게시글 */ public XReview view(XReview review_no); /** * XReview 객체의 id 를 이용한 닉네임 조회 * * @param viewReview - 조회할 게시글 정보 * @return String - 게시글 작성자의 닉네임 */ public String getMemNick(XReview viewReview); /** * XReview테이블 show_no를 통해 show_title 조회 * * @param viewReview * @return - 공연제목 */ public String getShowTitle(XReview viewReview); /** * 게시글 작성 * 입력한 게시글 내용을 DB에 저장 * * 첨부파일을 함께 업로드 할 수 있도록 처리 * * @param req - 요청정보 객체(게시글내용 + 첨부파일) * */ public void write(HttpServletRequest req); /** * 첨부파일 정보 조회 * * @param viewReview - 첨부파일과 연결된 게시글번호를 포함한 DTO객체 * @return XFile - 첨부파일 정보 DTO객체 */ public XFile viewFile(XReview viewReview); /** * 전달받은 숫자를 reviewNo로 가진 XFile객체 반환 * * @param reviewNo - 조회할 reviewno * @return DB에서 조회한 XFile 객체 */ public XFile getFile(int reviewno); /** * 게시글 수정 * * @param req - 요청 정보 객체 */ public void update(HttpServletRequest req); /** * 게시글 삭제 * * @param reviewno - 삭제할 게시글 번호를 가진 객체 */ public void delete(int reviewno); /** * 전달받은 숫자를 reviewno로 가진 XReview객체 반환 * @param reviewno - 조회할 reviewno * @return DB에서 조회한 XReview객체 */ public XReview getReviewDetail(int reviewno); /** * 검색결과 페이징 * * @param req * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getParameterPaging(HttpServletRequest req); /** * * @req - 요청파라미터로 searchtype, keyword가지고 있음 * @return parameter로 찾은 review객체 반환 */ public List<XReview> searchReviewList(HttpServletRequest req, Paging paging); /** * showno를 통해 reviewScore의 평균값을 구함 * * @param showno - 조회할 공연 * @return - 평균값 */ public double getAvgReviewScoreByShowNo(int showNo); /** * req로 전달된 show_no와 mem_id로 작성한 글이 있다면 true * @param req * @return boolean */ public boolean getReviewOverlap(HttpServletRequest req); public List<XReview> getListDateByShowNo(Paging paging, int showNo); } <file_sep>/src/controller/admin/AdminCommentDeleteController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XAsk; import service.face.AdminAskService; import service.face.AdminService; import service.impl.AdminAskServiceImpl; import service.impl.AdminServiceImpl; @WebServlet("/admin/comment/delete") public class AdminCommentDeleteController extends HttpServlet { private static final long serialVersionUID = 1L; AdminAskService adminAskService = new AdminAskServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("승인된 관리자 로그인 상태 : "+adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))); if(!adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { resp.sendRedirect("/admin"); return; } System.out.println("/admin/comment/delete [GET]"); System.out.println(req.getParameter("askNo")); // 전달 파라미터 얻기 - askno XAsk xaskno = adminAskService.getAskNo(req); adminAskService.deleteComment(xaskno); resp.sendRedirect(req.getContextPath() + "/admin/ask/detail?askNo=" + req.getParameter("askNo")); } } <file_sep>/src/service/face/ShowService.java package service.face; import java.util.List; import javax.servlet.http.HttpServletRequest; import dto.XMem; import dto.XShow; import util.Paging; public interface ShowService { /** * 공연 정보 (XShow 테이블) 전체 조회 * @return List<XShow> - 공연 정보가 전체 조회 된 리스트 */ public List<XShow> getShowList(); /** * 공연 정보 (XShow 테이블) 전체 조회 * 페이징 처리 추가 * @return List<XShow> - 공연 정보가 전체 조회 된 리스트 */ public List<XShow> getShowList(Paging paging); /** * 공연 정보 (XShow 테이블) 전체 조회 * 페이징 처리 추가 * @return List<XShow> - 공연 정보가 전체 조회 된 리스트 */ public List<XShow> getShowList(Paging paging, int kindNo); /** * 페이징 객체 생성 * * 요청파라미터 curPage를 구한다 * XShow테이블과 curPage값을 이용하여 Paging객체를 구하여 반환한다 * * @param req - 요청정보 객체 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPaging(HttpServletRequest req); /** * 페이징 객체 생성 * * 요청파라미터 curPage를 구한다 * XShow테이블과 curPage값을 이용하여 Paging객체를 구하여 반환한다 * * @param req - 요청정보 객체 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getParameterPaging(HttpServletRequest req, int kindNo); /** * 요청파라미터 curPage를 구한다 * XShow테이블과 curPage값을 이용하여 Paging객체를 구하여 반환한다 * * @param req - 요청정보 객체 * @param showTitle * @param kindNo * @return */ public Paging getParameterPaging(HttpServletRequest req, String showTitle, int kindNo); public Paging getParameterPaging(HttpServletRequest req, String showTitle); public Paging getParameterPaging(HttpServletRequest req, int kindNo, int memGenre); /** * 요청파라미터 얻기 * * @param req - 요청정보객체 * @return XShow - 전달파라미터 ShowNo를 포함한 객체 */ public XShow getShowNo(HttpServletRequest req); /** * 요청파라미터 얻기 * * @param req - 요청정보객체 * @return XShow - 전달파라미터 kindNo를 포함한 객체 */ public int getKindNo(HttpServletRequest req); /** * 주어진 showNo를 이용하여 게시글을 조회한다 * * @param showNo - showNo를 가지고 있는 객체 * @return XShow - 조회된 게시글 */ public XShow viewShowInfo(XShow showNo); /** * kindNo를 통해 XKIND 테이블의 kind_name을 조회하고 반환 * @param kindNo - 현재 보고있는 페이지의 kind_no * @return - 현재 보고 있는 페이지의 종류 */ public String getkindName(int kindNo); /** * showInfo의 genreNo를 통해 XGENRE 테이블의 genre_name을 조회하고 반환 * @param showInfo - genreNo를 가지고 있는 객체 * @return - 공연장 이름 */ public String getGenreName(XShow showInfo); /** * showInfo의 hallNo를 통해 XHALL 테이블의 hall_name을 조회하고 반환 * @param showInfo - hallNo를 가지고 있는 객체 * @return - 공연장 이름 */ public String getHallName(XShow showInfo); public List<XShow> getSearchShowList(HttpServletRequest req, Paging paging); public List<XShow> getShowMemGenreList(XMem memInfo, int kindNo, Paging paging); public List<XShow> getShowGenrenoList(int loginIdGenreno, int kindNo); } <file_sep>/src/service/impl/AdminAskServiceImpl.java package service.impl; import java.sql.Connection; import java.util.List; import javax.servlet.http.HttpServletRequest; import common.JDBCTemplate; import dao.face.AdminAskDao; import dao.impl.AdminAskDaoImpl; import dto.XAsk; import dto.XComment; import service.face.AdminAskService; import util.Paging; public class AdminAskServiceImpl implements AdminAskService { AdminAskDao adminAskDao = new AdminAskDaoImpl(); @Override public Paging getPaging(HttpServletRequest req) { String param = req.getParameter("curPage"); int curPage = 0; if(param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] curPage값이 null입니다."); } int totalCount = adminAskDao.selectCntAll(JDBCTemplate.getConnection()); Paging paging = new Paging(totalCount, curPage); return paging; } @Override public List<XAsk> getAskList(Paging paging) { Connection conn = JDBCTemplate.getConnection(); List<XAsk> list = adminAskDao.selectAskAll(conn, paging); return list; } @Override public XAsk getAskNo(HttpServletRequest req) { XAsk ask_no = new XAsk(); //ask_no 전달 파라미터 검증 - !null, !"" String param = req.getParameter("askNo"); if(param!=null && !"".equals(param)) { ask_no.setAskNo( Integer.parseInt(param) ); } return ask_no; } @Override public XAsk getAskDetail(XAsk xaskno) { Connection conn = JDBCTemplate.getConnection(); XAsk xask = adminAskDao.selectAskByAskNo(conn, xaskno); return xask; } @Override public String getNick(XAsk xask) { Connection conn = JDBCTemplate.getConnection(); return adminAskDao.getNickByMemId( conn, xask ); } @Override public XComment setCommentWrite(HttpServletRequest req, XAsk xaskno) { XComment comment = new XComment(); comment.setAskNo(Integer.parseInt(req.getParameter("askNo"))); comment.setCommentContent(req.getParameter("comment")); comment.setAdminId( req.getParameter("adminId") ); Connection conn = JDBCTemplate.getConnection(); if( adminAskDao.insertComment(conn, comment) > 0 ) { int res = adminAskDao.updateAskStateToY(conn, xaskno); JDBCTemplate.commit(conn); } else { JDBCTemplate.rollback(conn); } return comment; } @Override public XComment getComment(XAsk xaskno) { Connection conn = JDBCTemplate.getConnection(); XComment comment= adminAskDao.selectCommentByAskNo(conn, xaskno); return comment; } @Override public int getAskNoInt(HttpServletRequest req) { int ask_no = 0; //ask_no 전달 파라미터 검증 - !null, !"" String param = req.getParameter("askNo"); if(param!=null && !"".equals(param)) { ask_no = Integer.parseInt(param); } return ask_no; } @Override public void deleteComment(XAsk xaskno) { Connection conn = JDBCTemplate.getConnection(); //댓글 삭제 adminAskDao.deleteCommentByAskNo(conn, xaskno); //댓글 상태 변환 int res = adminAskDao.updateAskStateToN(conn, xaskno); JDBCTemplate.commit(conn); } @Override public void updateAskStatetoN(XAsk xask) { Connection conn = JDBCTemplate.getConnection(); int res = adminAskDao.updateAskStateToN(conn, xask); if( res > 0) { JDBCTemplate.commit(conn); } else { JDBCTemplate.rollback(conn); } } @Override public void updateAskStatetoY(XAsk xask) { Connection conn = JDBCTemplate.getConnection(); int res = adminAskDao.updateAskStateToY(conn, xask); if( res > 0) { JDBCTemplate.commit(conn); } else { JDBCTemplate.rollback(conn); } } @Override public int getCommentNo(HttpServletRequest req) { int comment_no = 0; //ask_no 전달 파라미터 검증 - !null, !"" String param = req.getParameter("commentNo"); if(param!=null && !"".equals(param)) { comment_no = Integer.parseInt(param); } return comment_no; } @Override public XComment setCommentUpdate(HttpServletRequest req, int commentno) { XComment comment = new XComment(); comment.setCommentContent(req.getParameter("comment")); comment.setAdminId( req.getParameter("adminId") ); comment.setCommentNo(commentno); Connection conn = JDBCTemplate.getConnection(); if( adminAskDao.updateComment(conn, comment) > 0 ) { JDBCTemplate.commit(conn); } else { JDBCTemplate.rollback(conn); } return comment; } } <file_sep>/src/controller/admin/AdminReviewListController.java package controller.admin; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XReview; import service.face.AdminReviewService; import service.face.AdminService; import service.face.ReviewService; import service.impl.AdminReviewServiceImpl; import service.impl.AdminServiceImpl; import service.impl.ReviewServiceImpl; import util.Paging; @WebServlet("/admin/review/list") public class AdminReviewListController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminReviewService adminReviewService = new AdminReviewServiceImpl(); private AdminService adminService = new AdminServiceImpl(); private ReviewService reviewService = new ReviewServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { // //현재 로그인 되어 있는 관리자 아이디 adminid이 DB에 저장된 admin_id이며, admin_authority값이 y인 경우가 맞다면 // req.getRequestDispatcher("/WEB-INF/views/admin/review/list.jsp").forward(req, resp); // // return; // } // // resp.sendRedirect("/admin"); //요청 파라미터 전달 -> 페이징 객체 생성 Paging paging = adminReviewService.getPaging(req); System.out.println("AdminReviewListController [GET] - " + paging); //게시글 전체 조회 List<XReview> reviewList = adminReviewService.getReviewList(paging); ArrayList<String> showTitle = new ArrayList<>(); for (int i = 0; i < reviewList.size(); i++) { showTitle.add(reviewService.getShowTitle(reviewList.get(i))); } req.setAttribute("showTitle", showTitle); req.setAttribute("reviewList", reviewList); req.setAttribute("paging", paging); req.setAttribute("linkUrl", "/admin/review/list"); if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { req.getRequestDispatcher("/WEB-INF/views/admin/review/list.jsp").forward(req, resp); return; } resp.sendRedirect("/admin"); } } <file_sep>/src/service/impl/AdminMailServiceImpl.java package service.impl; import java.util.List; import java.util.Properties; import javax.mail.Address; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import service.face.AdminMailService; import util.mail.MailAuth; public class AdminMailServiceImpl implements AdminMailService { @Override public void sendMail(List<String> mailList, String mailTitle, String mailContent) { Properties p = new Properties(); p.put("mail.smtp.user","<EMAIL>"); p.put("mail.smtp.host","smtp.gmail.com"); p.put("mail.smtp.port", "465"); p.put("mail.smtp.starttls.enable", "true"); p.put("mail.smtp.auth", "true"); p.put("mail.smtp.debug", "true"); p.put("mail.smtp.socketFactory.port", "465"); p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); p.put("mail.smtp.socketFactory.fallback", "false"); p.put("mail.smtp.ssl.trust", "smtp.gmail.com"); p.put("mail.smtp.ssl.protocols", "TLSv1.2"); try { Authenticator auth = new MailAuth(); Session session = Session.getInstance(p, auth); session.setDebug(true); MimeMessage msg = new MimeMessage(session); String message = mailContent; msg.setSubject(mailTitle); Address fromAddr = new InternetAddress("<EMAIL>"); msg.setFrom(fromAddr); // Address toAddr = new InternetAddress(memMail); InternetAddress[] addArray = new InternetAddress[mailList.size()]; for(int i=0; i<mailList.size(); i++) { addArray[i] = new InternetAddress((String) mailList.get(i)); } msg.addRecipients(Message.RecipientType.BCC, addArray); msg.setContent(message, "text/html; charset=EUC-KR"); Transport.send(msg); } catch (Exception e) { e.printStackTrace(); } } @Override public void sendMail(String mailForPw, String mailTitle, String mailContent) { Properties p = new Properties(); p.put("mail.smtp.user","<EMAIL>"); p.put("mail.smtp.host","smtp.gmail.com"); p.put("mail.smtp.port", "465"); p.put("mail.smtp.starttls.enable", "true"); p.put("mail.smtp.auth", "true"); p.put("mail.smtp.debug", "true"); p.put("mail.smtp.socketFactory.port", "465"); p.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); p.put("mail.smtp.socketFactory.fallback", "false"); p.put("mail.smtp.ssl.trust", "smtp.gmail.com"); p.put("mail.smtp.ssl.protocols", "TLSv1.2"); try { Authenticator auth = new MailAuth(); Session session = Session.getInstance(p, auth); session.setDebug(true); MimeMessage msg = new MimeMessage(session); String message = mailContent; msg.setSubject(mailTitle); Address fromAddr = new InternetAddress("<EMAIL>"); msg.setFrom(fromAddr); Address toAddr = new InternetAddress(mailForPw); // InternetAddress[] addArray = new InternetAddress[mailList.size()]; // for(int i=0; i<mailList.size(); i++) { // addArray[i] = new InternetAddress((String) mailList.get(i)); // } msg.addRecipient(Message.RecipientType.TO, toAddr); msg.setContent(message, "text/html; charset=EUC-KR"); Transport.send(msg); } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/src/controller/admin/AdminShowDetailController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XFile; import dto.XShow; import service.face.AdminService; import service.face.AdminShowService; import service.impl.AdminServiceImpl; import service.impl.AdminShowServiceImpl; @WebServlet("/admin/show/detail") public class AdminShowDetailController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminShowService adminShowService = new AdminShowServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { XShow showno = adminShowService.getShowno(req); XShow viewShow = adminShowService.getShowDetail(showno); req.setAttribute("viewShow", viewShow); //장르 전달 req.setAttribute("showGenre", adminShowService.getGenre(viewShow)); //공연 종류 전달 req.setAttribute("showKind", adminShowService.getKind(viewShow)); //공연장 이름 전달 req.setAttribute("showHall", adminShowService.getHallname(viewShow)); XFile showFile = adminShowService.getFile(viewShow); //첨부파일 정보 전달 req.setAttribute("showFile", showFile); if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { req.getRequestDispatcher("/WEB-INF/views/admin/show/detail.jsp").forward(req, resp); return; } resp.sendRedirect("/admin"); } } <file_sep>/src/controller/mem/JjimDeleteController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.face.JjimService; import service.impl.JjimServiceImpl; /** * Servlet implementation class JjimDeleteController */ @WebServlet("/mem/jjim/delete") public class JjimDeleteController extends HttpServlet { private static final long serialVersionUID = 1L; private JjimService jjimService = new JjimServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/mem/jjim/delete [POST]"); String memId = req.getParameter("memId"); String showNo = req.getParameter("showNo"); int isDeleteAble = jjimService.setJjimDelete(memId, showNo); System.out.println("삭제 여부 : " + isDeleteAble); if(isDeleteAble == 0) System.out.println("찜 목록 삭제 실패"); else System.out.println("찜 목록 삭제 성공"); System.out.println(req.getRequestURL()); String from = req.getParameter("from"); if("mycalendar".equals(from)) { resp.sendRedirect("/mycalendar"); return; } if("myjjim".equals(from)) { resp.sendRedirect("/mypage/myjjim"); return; } if("detail".equals(from)) { resp.sendRedirect("/show/detail?showNo=" + req.getParameter("showNo")); return; } } } <file_sep>/src/controller/admin/AdminNoticeDeleteController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dto.XNotice; import service.face.AdminNoticeService; import service.face.AdminService; import service.impl.AdminNoticeServiceImpl; import service.impl.AdminServiceImpl; @WebServlet("/admin/notice/delete") public class AdminNoticeDeleteController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminNoticeService adminNoticeService = new AdminNoticeServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("승인된 관리자 로그인 상태 : "+adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))); if(!adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { resp.sendRedirect("/admin"); return; } System.out.println("###TEST### AdminNoticeDeleteController Get"); String param = req.getParameter("noticeno"); int noticeno = 0; if(param!=null && !"".equals(param)) { noticeno = Integer.parseInt(param); } else { System.out.println("!!!ERROR!!! noticeno로 전달된 파라미터가 숫자가 아닙니다."); return; } adminNoticeService.setNoticeDelete(noticeno); resp.sendRedirect("/admin/notice/list"); } } <file_sep>/src/controller/mem/NoticeDetailController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XFile; import dto.XNotice; import service.face.NoticeService; import service.impl.NoticeServiceImpl; @WebServlet("/notice/detail") public class NoticeDetailController extends HttpServlet { private static final long serialVersionUID = 1L; private NoticeService noticeService = new NoticeServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //전달파라미터 얻기 - noticeno XNotice noticeNo = noticeService.getNoticeNo(req); //상세보기 결과 조회 XNotice viewNotice = noticeService.view(noticeNo); //조회결과 MODEL값 전달 req.setAttribute("viewNotice", viewNotice); //첨부파일 정보 조회 XFile noticeFile = noticeService.viewFile(viewNotice); //첨부파일 정보 MODEL값 전달 req.setAttribute("noticeFile", noticeFile); //VIEW 지정 및 응답 - forward req.getRequestDispatcher("/WEB-INF/views/mem/mypage/notice/detail.jsp").forward(req, resp); } } <file_sep>/src/controller/mem/JjimController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XJjim; import service.face.JjimService; import service.impl.JjimServiceImpl; /** * Servlet implementation class JjimController */ @WebServlet("/mem/jjim") public class JjimController extends HttpServlet { private static final long serialVersionUID = 1L; private JjimService jjimService = new JjimServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/mem/jjim [POST]"); XJjim jjim = jjimService.getJjimInfo(req); if (req.getSession().getAttribute("login") == null || !(boolean) req.getSession().getAttribute("login")) { System.out.println("로그인 안됨"); return; } else { System.out.println(req.getParameter("memId")); System.out.println(req.getParameter("showNo")); System.out.println("로그인 정보 가져오기 성공"); int insertAble = jjimService.setJjim(jjim); if (insertAble == 0) System.out.println("찜 목록 추가 실패"); else System.out.println("찜 목록 추가 성공"); } System.out.println("jjim : " + jjim); resp.sendRedirect("/show/detail?showNo=" + req.getParameter("showNo")); } } <file_sep>/src/service/impl/ShowServiceImpl.java package service.impl; import java.sql.Connection; import java.util.List; import javax.servlet.http.HttpServletRequest; import common.JDBCTemplate; import dao.face.ShowDao; import dao.impl.ShowDaoImpl; import dto.XMem; import dto.XShow; import service.face.ShowService; import util.Paging; public class ShowServiceImpl implements ShowService { // ShowDao 객체 생성 private ShowDao showDao = new ShowDaoImpl(); @Override public List<XShow> getShowList() { return showDao.selectShowAll(JDBCTemplate.getConnection()); } // 페이징 객체 추가 @Override public List<XShow> getShowList(Paging paging) { return showDao.selectShowAll(JDBCTemplate.getConnection(), paging); } // 카테고리 번호 추가 @Override public List<XShow> getShowList(Paging paging, int kindNo) { return showDao.selectShowAllByKindNo(JDBCTemplate.getConnection(), paging, kindNo); } @Override public Paging getPaging(HttpServletRequest req) { String param = req.getParameter("curPage"); int curPage = 0; // 한번에 몇개씩 보여줄건지 int listCount = 6; if (param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] curPage값이 null이거나 비어있습니다"); } int totalCount = showDao.selectCntAll(JDBCTemplate.getConnection()); Paging paging = new Paging(totalCount, curPage, listCount); return paging; } //공연 종류로 골라낸 리스트 수 추가해서 페이징 객체 생성 @Override public Paging getParameterPaging(HttpServletRequest req, int kindNo) { String param = req.getParameter("curPage"); int curPage = 0; // 한번에 몇개씩 보여줄건지 int listCount = 6; if(param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] curPage값이 null이거나 비어있습니다"); } int totalCount = showDao.selectCntBykindNo(JDBCTemplate.getConnection(), kindNo); Paging paging = new Paging(totalCount, curPage, listCount); return paging; } @Override public Paging getParameterPaging(HttpServletRequest req, String showTitle) { String param = req.getParameter("curPage"); int curPage = 0; // 한번에 몇개씩 보여줄건지 int listCount = 6; if(param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] curPage값이 null이거나 비어있습니다"); } int totalCount = showDao.selectCntByShowTitle(JDBCTemplate.getConnection(), showTitle); Paging paging = new Paging(totalCount, curPage, listCount); return paging; } @Override public Paging getParameterPaging(HttpServletRequest req, int kindNo, int memGenre) { String param = req.getParameter("curPage"); int curPage = 0; // 한번에 몇개씩 보여줄건지 int listCount = 5; if(param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] suggest curPage값이 null이거나 비어있습니다"); } int totalCount = showDao.selectCntBymemGenre(JDBCTemplate.getConnection(), kindNo, memGenre); Paging paging = new Paging(totalCount, curPage, listCount); return paging; } //공연 이름으로 골라낸 리스트 수 추가해서 페이징 객체 생성 @Override public Paging getParameterPaging(HttpServletRequest req, String showTitle, int kindNo) { String param = req.getParameter("curPage"); int curPage = 0; // 한번에 몇개씩 보여줄건지 int listCount = 6; if(param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] curPage값이 null이거나 비어있습니다"); } int totalCount = showDao.selectCntByshowTitle(JDBCTemplate.getConnection(), showTitle, kindNo); Paging paging = new Paging(totalCount, curPage, listCount); return paging; } @Override public XShow getShowNo(HttpServletRequest req) { // ShowNo를 저장할 객체 생성 XShow showNo = new XShow(); String param = req.getParameter("showNo"); if (param != null && !"".equals(param)) { showNo.setShowNo(Integer.parseInt(param)); } return showNo; } @Override public int getKindNo(HttpServletRequest req) { // kindNo를 저장할 객체 생성 int kindNo = 0; String param = req.getParameter("kindNo"); if (param != null && !"".equals(param)) { kindNo = Integer.parseInt(param); } return kindNo; } @Override public XShow viewShowInfo(XShow showNo) { Connection conn = JDBCTemplate.getConnection(); // 게시글 조회 XShow showInfo = showDao.selectShowByShowno(conn, showNo); return showInfo; } @Override public String getkindName(int kindNo) { return showDao.selectKindNameByKindNo(JDBCTemplate.getConnection(), kindNo); } @Override public String getGenreName(XShow showInfo) { return showDao.selectGenreNameByGenreNo(JDBCTemplate.getConnection(), showInfo); } @Override public String getHallName(XShow showInfo) { return showDao.selectHallNameByHallNo(JDBCTemplate.getConnection(), showInfo); } @Override public List<XShow> getSearchShowList(HttpServletRequest req, Paging paging) { String showKind = (String)req.getParameter("kindNo").trim(); String keyword = (String)req.getParameter("keyword"); if(Integer.parseInt(showKind) == 0) { return showDao.selectAllShowSearchByshowTitle(JDBCTemplate.getConnection(), keyword, paging); } return showDao.selectShowSearchByshowTitle(JDBCTemplate.getConnection(), keyword, Integer.parseInt(showKind), paging); } @Override public List<XShow> getShowMemGenreList(XMem memInfo, int kindNo, Paging paging) { return showDao.selectShowSearchByMemgenre(JDBCTemplate.getConnection(), memInfo, kindNo, paging); } @Override public List<XShow> getShowGenrenoList(int loginIdGenreno, int kindNo) { return showDao.selectShowByGenreno(JDBCTemplate.getConnection(), loginIdGenreno, kindNo); } } <file_sep>/src/dto/XGenre.java package dto; public class XGenre { private int genreNo; private String genreName; @Override public String toString() { return "XGenre [genreNo=" + genreNo + ", genreName=" + genreName + "]"; } public int getGenreNo() { return genreNo; } public void setGenreNo(int genreNo) { this.genreNo = genreNo; } public String getGenreName() { return genreName; } public void setGenreName(String genreName) { this.genreName = genreName; } } <file_sep>/src/controller/admin/AdminReviewDetailController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XFile; import dto.XReview; import service.face.AdminReviewService; import service.face.AdminService; import service.impl.AdminReviewServiceImpl; import service.impl.AdminServiceImpl; @WebServlet("/admin/review/detail") public class AdminReviewDetailController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminReviewService adminReviewService = new AdminReviewServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //전달파라미터 얻기 - reviewno XReview reviewno = adminReviewService.getReviewno(req); //상세보기 결과 조회 XReview viewReview = adminReviewService.getReviewDetail(reviewno); //조회결과 전달 req.setAttribute("viewReview", viewReview); //닉네임 전달 req.setAttribute("memNick", adminReviewService.getNick(viewReview)); //공연 제목 전달 req.setAttribute("showTitle", adminReviewService.getTitle(viewReview)); //첨부파일 정보 조회 XFile reviewFile = adminReviewService.getFile(viewReview); //첨부파일 정보 model값 전달 req.setAttribute("reviewFile", reviewFile); if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { req.getRequestDispatcher("/WEB-INF/views/admin/review/detail.jsp").forward(req, resp); return; } resp.sendRedirect("/admin"); } } <file_sep>/src/controller/mem/MemberLogoutController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/logout") public class MemberLogoutController extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("###TEST### LogoutController doGet()"); HttpSession session = req.getSession(); session.invalidate(); resp.sendRedirect("/main"); //로그아웃 시 메인페이지로 이동 @@@수정 꼭 } } <file_sep>/src/dao/impl/AdminDaoImpl.java package dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import common.JDBCTemplate; import dao.face.AdminDao; import dto.XAdmin; public class AdminDaoImpl implements AdminDao { PreparedStatement ps = null; ResultSet rs = null; @Override public int selectCntAdminByAdminidAdminpw(Connection connection, XAdmin admin) { int count = 0; //성공 시 1로 반환될 결과 변수 String sql = "SELECT COUNT(*) FROM XADMIN WHERE ADMIN_ID=? AND ADMIN_PW=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, admin.getAdminId()); ps.setString(2, admin.getAdminPw()); rs = ps.executeQuery(); while(rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return count; } @Override public XAdmin selectAdminByAdminid(Connection connection, XAdmin admin) { XAdmin res = null; String sql = "SELECT ADMIN_ID, ADMIN_NAME, ADMIN_AUTHORITY FROM XADMIN WHERE ADMIN_ID=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, admin.getAdminId()); rs = ps.executeQuery(); while(rs.next()) { res = new XAdmin(); res.setAdminId(rs.getString("admin_id")); res.setAdminName(rs.getString("admin_name")); res.setAdminAuthority(rs.getString("admin_authority")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return res; } @Override public int selectCntAdminByAdminid(Connection connection, String attribute) { int count = 0; //성공 시 1로 반환될 결과 변수 String sql = "SELECT COUNT(*) FROM XADMIN WHERE ADMIN_ID=? AND ADMIN_AUTHORITY=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, attribute); ps.setString(2, "y"); rs = ps.executeQuery(); while(rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return count; } }<file_sep>/src/service/impl/AdminMemberServiceImpl.java package service.impl; import java.sql.Connection; import java.util.List; import javax.servlet.http.HttpServletRequest; import common.JDBCTemplate; import dao.face.AdminMemberDao; import dao.impl.AdminMemberDaoImpl; import dto.XMem; import service.face.AdminMemberService; import util.Paging; public class AdminMemberServiceImpl implements AdminMemberService { private AdminMemberDao adminMemberDao = new AdminMemberDaoImpl(); @Override public Paging getPaging(HttpServletRequest req) { String param = req.getParameter("curPage"); int curPage = 0; if(param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] curPage값이 null이거나 비어있습니다"); } int totalCount = adminMemberDao.selectCntMemAll(JDBCTemplate.getConnection()); Paging paging = new Paging(totalCount, curPage); return paging; } @Override public Paging getParameterPaging(HttpServletRequest req) { String param = req.getParameter("curPage"); int curPage = 0; if(param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] curPage값이 null이거나 비어있습니다"); } String searchtype = (String)req.getParameter("searchtype"); String keyword = (String)req.getParameter("keyword"); int totalCount = adminMemberDao.selectCntSearchMemAll(JDBCTemplate.getConnection(), searchtype, keyword); Paging paging = new Paging(totalCount, curPage); return paging; } @Override public List<XMem> getMemList(Paging paging) { return adminMemberDao.selectMemAll(JDBCTemplate.getConnection(), paging); } @Override public XMem getMemId(HttpServletRequest req) { XMem memid = new XMem(); String param = req.getParameter("memid"); if(param != null && !"".equals(param)) { memid.setMemId(param); } return memid; } @Override public void setMemDelete(XMem memid) { Connection conn = JDBCTemplate.getConnection(); if(adminMemberDao.deleteMem(conn, memid) > 0 ) { JDBCTemplate.commit(conn); } else { JDBCTemplate.rollback(conn); } } @Override public List<XMem> searchMemList(HttpServletRequest req, Paging paging) { //전달 파라미터 얻기 - searchtype, keyword String searchtype = (String)req.getParameter("searchtype"); String keyword = (String)req.getParameter("keyword"); System.out.println(searchtype); System.out.println(keyword); if("memnick".equals(searchtype)) return adminMemberDao.selectMemSearchByMemnick(JDBCTemplate.getConnection(), keyword, paging); else return adminMemberDao.selectMemSearchByMemid(JDBCTemplate.getConnection(), keyword, paging); } } <file_sep>/src/dao/impl/AdminNoticeDaoImpl.java package dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import common.JDBCTemplate; import dao.face.AdminNoticeDao; import dto.XFile; import dto.XNotice; import util.Paging; public class AdminNoticeDaoImpl implements AdminNoticeDao { PreparedStatement ps = null; ResultSet rs = null; @Override public List<XNotice> selectNoticeAll(Connection connection) { String sql = "SELECT NOTICE_NO, ADMIN_ID, FILE_NO, NOTICE_TITLE, NOTICE_CONTENT, NOTICE_DATE FROM XNOTICE ORDER BY NOTICE_NO DESC"; List<XNotice> list = new ArrayList<>(); try { ps = connection.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()) { XNotice notice = new XNotice(); notice.setNoticeNo(rs.getInt("notice_no")); notice.setAdminId(rs.getString("admin_id")); notice.setFileNo(rs.getInt("file_no")); notice.setNoticeTitle(rs.getString("notice_title")); notice.setNoticeContent(rs.getString("notice_content")); notice.setNoticeDate(rs.getDate("notice_date")); list.add(notice); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return list; } @Override public int selectCntNoticeAll(Connection conn) { //SQL작성 String sql = ""; sql += "SELECT count(*) FROM xnotice"; int count = 0; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()) { count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return count; //전체 공지 개수 반환 } @Override public XNotice selectNoticeByNoticeno(Connection connection, int noticeno) { String sql = "SELECT NOTICE_NO, ADMIN_ID, FILE_NO, NOTICE_TITLE, NOTICE_CONTENT, NOTICE_DATE FROM XNOTICE WHERE NOTICE_NO=?"; XNotice res = null; try { ps = connection.prepareStatement(sql); ps.setInt(1, noticeno); rs = ps.executeQuery(); while(rs.next()) { res = new XNotice(); res.setNoticeNo(rs.getInt("notice_no")); res.setAdminId(rs.getString("admin_id")); res.setFileNo(rs.getInt("file_no")); res.setNoticeTitle(rs.getString("notice_title")); res.setNoticeContent(rs.getString("notice_content")); res.setNoticeDate(rs.getDate("notice_date")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return res; } @Override public XFile selectFileByFileno(Connection connection, int noticeno) { String sql = "SELECT FILE_NO, FILE_ORIGIN_NAME, FILE_STORED_NAME, FILE_SIZE FROM XFILE WHERE FILE_NO=(SELECT FILE_NO FROM XNOTICE WHERE NOTICE_NO=?)"; XFile res = null; try { ps = connection.prepareStatement(sql); ps.setInt(1, noticeno); rs = ps.executeQuery(); while(rs.next()) { res = new XFile(); res.setFileNo(rs.getInt("file_no")); res.setFileOriginName(rs.getString("file_origin_name")); res.setFileStoredName(rs.getString("file_stored_name")); res.setFileSize(rs.getString("file_size")); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return res; } @Override public int selectNextNoticeno(Connection conn) { String sql = "SELECT XNOTICE_SEQ.NEXTVAL FROM DUAL"; int nextNoticeno = 0; try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()) { nextNoticeno = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return nextNoticeno; } @Override public int insertNotice(Connection conn, XNotice notice) { String sql = "INSERT INTO XNOTICE(NOTICE_NO, ADMIN_ID, FILE_NO, NOTICE_TITLE, NOTICE_CONTENT)" + " VALUES(?, ?, ?, ?, ?)"; int res = 0; try { ps = conn.prepareStatement(sql); ps.setInt(1, notice.getNoticeNo()); ps.setString(2, notice.getAdminId()); if(notice.getFileNo()==0) { ps.setObject(3, null); } else { ps.setInt(3, notice.getFileNo()); } ps.setString(4, notice.getNoticeTitle()); ps.setString(5, notice.getNoticeContent()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } @Override public int updateNotice(Connection connection, XNotice notice) { String sql = "UPDATE XNOTICE SET NOTICE_TITLE=?, NOTICE_CONTENT=?"; if(notice.getFileNo()==0) { sql += " WHERE NOTICE_NO=?"; } else { sql += ", FILE_NO=? WHERE NOTICE_NO=?"; } int res = -1; try { ps = connection.prepareStatement(sql); ps.setString(1, notice.getNoticeTitle()); ps.setString(2, notice.getNoticeContent()); if(notice.getFileNo()==0) { ps.setInt(3, notice.getNoticeNo()); } else { ps.setInt(3, notice.getFileNo()); ps.setInt(4, notice.getNoticeNo()); } res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } @Override public int deleteNotice(Connection conn, int noticeno) { System.out.println(noticeno); String sql = "DELETE XNOTICE WHERE NOTICE_NO=?"; int res = -1; try { ps = conn.prepareStatement(sql); ps.setInt(1, noticeno); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } System.out.println(res); return res; } @Override public List<XNotice> selectNoticeAll(Connection connection, Paging paging) { String sql = "SELECT * FROM (SELECT rownum rnum, XN.* FROM (SELECT NOTICE_NO, ADMIN_ID, FILE_NO, NOTICE_TITLE, NOTICE_CONTENT, NOTICE_DATE FROM XNOTICE ORDER BY NOTICE_NO DESC) XN) XNOTICE WHERE RNUM BETWEEN ? AND ?"; List<XNotice> list = new ArrayList<>(); try { ps = connection.prepareStatement(sql); ps.setInt(1, paging.getStartNo()); ps.setInt(2, paging.getEndNo()); rs = ps.executeQuery(); while(rs.next()) { XNotice notice = new XNotice(); notice.setNoticeNo(rs.getInt("notice_no")); notice.setAdminId(rs.getString("admin_id")); notice.setFileNo(rs.getInt("file_no")); notice.setNoticeTitle(rs.getString("notice_title")); notice.setNoticeContent(rs.getString("notice_content")); notice.setNoticeDate(rs.getDate("notice_date")); list.add(notice); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(rs); JDBCTemplate.close(ps); } return list; } @Override public int deleteFileno(Connection conn, XNotice notice) { String sql = "UPDATE XNOTICE SET FILE_NO='' WHERE NOTICE_NO=?"; int res = -1; try { ps = conn.prepareStatement(sql); ps.setInt(1, notice.getNoticeNo()); res = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCTemplate.close(ps); } return res; } } <file_sep>/src/controller/mem/ReviewListController.java package controller.mem; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XReview; import service.face.ReviewService; import service.impl.ReviewServiceImpl; import util.Paging; @WebServlet("/review/list") public class ReviewListController extends HttpServlet { private static final long serialVersionUID = 1L; private ReviewService reviewService = new ReviewServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Paging paging = reviewService.getPaging(req); System.out.println("ReviewListController [GET] - " + paging); List<XReview> reviewList = reviewService.getList(paging); ArrayList<String> showTitle = new ArrayList<>(); for (int i = 0; i < reviewList.size(); i++) { showTitle.add(reviewService.getShowTitle(reviewList.get(i))); } ArrayList<String> memNick = new ArrayList<>(); for( int i=0 ; i<reviewList.size() ; i++ ) { memNick.add(reviewService.getMemNick(reviewList.get(i))); } req.setAttribute("showTitle", showTitle); req.setAttribute("memNick", memNick); req.setAttribute("reviewList", reviewList); req.setAttribute("paging", paging); req.setAttribute("linkUrl", "/review/list"); req.getRequestDispatcher("/WEB-INF/views/mem/review/list.jsp").forward(req, resp); } }<file_sep>/src/controller/admin/AdminCommentWriteController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XAsk; import dto.XComment; import service.face.AdminAskService; import service.face.AdminService; import service.impl.AdminAskServiceImpl; import service.impl.AdminServiceImpl; @WebServlet("/admin/comment/write") public class AdminCommentWriteController extends HttpServlet { private static final long serialVersionUID = 1L; AdminAskService adminAskService = new AdminAskServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("승인된 관리자 로그인 상태 : "+adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))); if(!adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { resp.sendRedirect("/admin"); return; } req.setCharacterEncoding("UTF-8"); XAsk xaskno = adminAskService.getAskNo(req); XComment comment = adminAskService.setCommentWrite( req, xaskno ); req.setAttribute("comment", comment); resp.sendRedirect(req.getContextPath() + "/admin/ask/detail?askNo=" + req.getParameter("askNo")); } } <file_sep>/src/dao/face/ShowDao.java package dao.face; import java.sql.Connection; import java.util.List; import dto.XMem; import dto.XShow; import util.Paging; public interface ShowDao { /** * XShow 테이블의 정보 전체 조회 * * @param conn - DB연결 객체 * @return List<XReview> - XShow테이블의 전체 조회 결과 리스트를 반환함 */ public List<XShow> selectShowAll(Connection conn); /** * XShow 테이블의 정보 전체 조회 페이징 처리 추가 * * @param paging - 페이징 정보 객체 * @param conn - DB연결 객체 * @return List<XReview> - XShow테이블의 전체 조회 결과 리스트를 반환함 */ public List<XShow> selectShowAll(Connection conn, Paging paging); /** * XShow 테이블의 정보 전체 조회 페이징 처리 추가, 카테고리 기능 추가 * * @param conn - DB 연결 객체 * @param paging - 페이징 정보 객체 * @param kindNo - 카테고리 종류 * @return List<XReview> - XShow테이블의 종류로만 따로 걸러진 리스트 반환함 */ public List<XShow> selectShowAllByKindNo(Connection conn, Paging paging, int kindNo); /** * XShow 테이블의 전체 행 수 조회 * * @param conn - DB연결 객체 * @return int - XShow 테이블의 전체 행 수가 몇개인지 반환 */ public int selectCntAll(Connection conn); /** * XShow 테이블에서 공연 종류에 따라 행 수 조회 * * @param conn - DB연결 객체 * @param kindNo - 공연 종류가 뭔지 알려주는 객체 * @return int - XShow 테이블의 전체 행 수가 몇개인지 반환 */ public int selectCntBykindNo(Connection conn, int kindNo); /** * XShow 테이블에서 공연 제목에 따라 행 수 조회 * 공연 검색 서비스에서만 사용 * * @param conn - DB연결 객체 * @param kindNo - 공연 종류가 뭔지 알려주는 객체 * @return int - XShow 테이블의 전체 행 수가 몇개인지 반환 */ public int selectCntByshowTitle(Connection conn, String showTitle, int kindNo); public int selectCntByShowTitle(Connection connection, String showTitle); public int selectCntBymemGenre(Connection conn, int kindNo, int memGenre); /** * 특정 게시글 조회 * * @param showNo - 조회할 showNo를 가진 객체 * @return XShow - 조회된 결과 객체 */ public XShow selectShowByShowno(Connection conn, XShow showNo); /** * KindNo를 통해 KindName을 조회 : 나중에 이걸로 통일할거 같음 * * @param conn * @param kindNo - 공연장 번호 * @return 공연 종류 이름 */ public String selectKindNameByKindNo(Connection conn, int kindNo); /** * showInfo의 GenreNo를 통해 GenreName을 조회 * * @param conn * @param showInfo - 현재 상세보기 하고 있는 게시물의 GenreNo를 가진 객체 * @return 공연 장르 이름 */ public String selectGenreNameByGenreNo(Connection conn, XShow showInfo); /** * showInfo의 hallNo를 통해 hallName을 조회 * * @param conn * @param showInfo - 현재 상세보기 하고 있는 게시물의 hallNo를 가진 객체 * @return 공연장 이름 */ public String selectHallNameByHallNo(Connection conn, XShow showInfo); public List<XShow> selectShowSearchByshowTitle(Connection conn, String keyword, int kindNo, Paging paging); public List<XShow> selectAllShowSearchByshowTitle(Connection connection, String keyword, Paging paging); public List<XShow> selectShowSearchByMemgenre(Connection conn, XMem memInfo, int kindNo, Paging paging); public List<XShow> selectShowByGenreno(Connection connection, int loginIdGenreno, int kindNo); } <file_sep>/src/controller/admin/AdminCommentUpdateController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dto.XAdmin; import dto.XAsk; import dto.XComment; import service.face.AdminAskService; import service.face.AdminService; import service.impl.AdminAskServiceImpl; import service.impl.AdminServiceImpl; @WebServlet("/admin/comment/update") public class AdminCommentUpdateController extends HttpServlet { private static final long serialVersionUID = 1L; AdminAskService adminAskService = new AdminAskServiceImpl(); AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { XAsk xaskno = adminAskService.getAskNo(req); XAsk xask = adminAskService.getAskDetail(xaskno); // System.out.println(xask); XComment xcomment = adminAskService.getComment(xaskno); // System.out.println(xcomment); XAdmin admin = adminService.getLoginAdmin(req); HttpSession session = req.getSession(); req.setAttribute("xask", xask); req.setAttribute("xaskno", xaskno); req.setAttribute("nick", adminAskService.getNick(xask)); req.setAttribute("xcomment", xcomment); req.getRequestDispatcher("/WEB-INF/views/admin/ask/updateComment.jsp").forward(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); int commentno = adminAskService.getCommentNo(req); XComment comment = adminAskService.setCommentUpdate( req, commentno ); req.setAttribute("comment", comment); resp.sendRedirect(req.getContextPath() + "/admin/ask/detail?askNo=" + req.getParameter("askNo")); } } <file_sep>/src/controller/admin/AdminNoticeListController.java package controller.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XNotice; import service.face.AdminNoticeService; import service.face.AdminService; import service.impl.AdminNoticeServiceImpl; import service.impl.AdminServiceImpl; import util.Paging; @WebServlet("/admin/notice/list") public class AdminNoticeListController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminNoticeService adminNoticeService = new AdminNoticeServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("승인된 관리자 로그인 상태 : "+adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))); if(!adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { resp.sendRedirect("/admin"); return; } System.out.println("###TEST### AdminNoticeListController Get"); Paging paging = adminNoticeService.getPaging(req); System.out.println("/admin/notice/list [GET] - " + paging); // List<XNotice> list = adminNoticeService.getNoticeList(); List<XNotice> list = adminNoticeService.getNoticeList(paging); req.setAttribute("noticeList", list); req.setAttribute("paging", paging); req.setAttribute("linkUrl", "/admin/notice/list"); req.getRequestDispatcher("/WEB-INF/views/admin/notice/list.jsp").forward(req, resp); } } <file_sep>/src/controller/mem/ShowListController.java package controller.mem; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XMem; import dto.XShow; import service.face.MemberService; import service.face.ShowService; import service.impl.MemberServiceImpl; import service.impl.ShowServiceImpl; import util.Paging; /** * Servlet implementation class ShowListController */ @WebServlet("/show") public class ShowListController extends HttpServlet { private static final long serialVersionUID = 1L; //ShowListController에서만 사용할 ShowService 객체 private ShowService showService = new ShowServiceImpl(); private MemberService memberService = new MemberServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/show/list : Get"); //페이징 객체 생성 Paging paging = null; int kindNo = showService.getKindNo(req); System.out.println("showlistcontroller kindno : " + kindNo); //값 있음 String kindName = showService.getkindName(kindNo); List<XShow> showList = null; if(kindNo==1) { req.setAttribute("imgKind", "mu"); } else if(kindNo==2) { req.setAttribute("imgKind", "ac"); } else if(kindNo==3) { req.setAttribute("imgKind", "co"); } else if(kindNo==4) { req.setAttribute("imgKind", "op"); } if(kindNo == 0) { //showService에서 XShow 테이블의 정보를 가진 리스트를 받아옴 paging = showService.getPaging(req); showList = showService.getShowList(paging); List<String> welcomeMsg = new ArrayList<>(); welcomeMsg.add("공연의 모든 것"); welcomeMsg.add("이번 주는 이런 공연 어떠세요"); welcomeMsg.add("좋은 사람과 좋은 공연"); welcomeMsg.add("굿모닝, 굿애프터눈, 굿나잇"); welcomeMsg.add("쉬어가는 날"); welcomeMsg.add("금강산도 식후공연"); welcomeMsg.add("봄, 여름, 가을, 겨울"); Collections.shuffle(welcomeMsg); req.setAttribute("kindName", welcomeMsg.get(1)+", 공공연히"); } else { //showService에서 XShow 테이블의 정보를 가진 리스트를 받아옴. 이거는 공연 종류로 가져옴 paging = showService.getParameterPaging(req, kindNo); showList = showService.getShowList(paging, kindNo); req.setAttribute("kindName", kindName); } String loginId = (String)req.getSession().getAttribute("memid"); if(loginId!=null) { System.out.println("로그인 되어 있는 id : " + loginId); XMem mem = new XMem(); mem.setMemId(loginId); int loginIdGenreno = memberService.getMem(mem).getGenreNo(); System.out.println("로그인 되어 있는 id가 선택한 genreno : " + loginIdGenreno); req.setAttribute("loginIdGenreno", loginIdGenreno); List<XShow> fiveShowList = showService.getShowGenrenoList(loginIdGenreno, kindNo); Collections.shuffle(fiveShowList); if(fiveShowList.size()>5) { List<XShow> fiveShowListCut = new ArrayList<>(); fiveShowListCut.add(fiveShowList.get(1)); fiveShowListCut.add(fiveShowList.get(2)); fiveShowListCut.add(fiveShowList.get(3)); fiveShowListCut.add(fiveShowList.get(4)); fiveShowListCut.add(fiveShowList.get(5)); req.setAttribute("fiveShowList", fiveShowListCut); } else { req.setAttribute("fiveShowList", fiveShowList); } } //XShow 테이블의 전체 정보를 가진 showList 객체를 "showList"라는 이름을 가진 요소로 설정 req.setAttribute("showList", showList); //페이징 정보 MODEL값 전달 req.setAttribute("paging", paging); //종류 정보 MODEL값 전달 req.setAttribute("kindNoToSearch", kindNo); req.setAttribute("userNick", req.getSession().getAttribute("memnick")); // /show/list 라는 url을 "linkUrl" 이라는 이름을 가진 요소로 설정 (페이징을 위해 넣은 객체) req.setAttribute("linkUrl", "/show?kindNo=" + kindNo); //요청 보내기 req.getRequestDispatcher("/WEB-INF/views/mem/show/list.jsp").forward(req, resp); } }<file_sep>/src/service/face/AdminMemberService.java package service.face; import java.util.List; import javax.servlet.http.HttpServletRequest; import dto.XMem; import util.Paging; public interface AdminMemberService { /** * * 페이징 객체 생성 * * 요청파라미터 curPage를 구한다 * XReview테이블과 curPage값을 이용, Paging객체를 구하여 반환 * * @param req - 요청정보 객체 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPaging(HttpServletRequest req); /** * 검색결과 페이징 * * @param req * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getParameterPaging(HttpServletRequest req); /** * * 회원 정보 전체 리스트 형식으로 조회 * 페이징 처리 있음. * * @param paging * @return List<XMem> - 전체 회원 정보 리스트 */ public List<XMem> getMemList(Paging paging); /** * 요청파라미터로 memId를 가지고 있는 Xmem객체를 반환 * * @param req * @return memId정보를 가지고 있는 Xmem객체 */ public XMem getMemId(HttpServletRequest req); /** * 회원정보 삭제 * * @param memid - 삭제할 mem객체 */ public void setMemDelete(XMem memid); /** * * @req - 요청파라미터로 searchtype, keyword가지고 있음 * @return parameter로 찾은 mem객체 반환 */ public List<XMem> searchMemList(HttpServletRequest req, Paging paging); } <file_sep>/src/dao/face/AdminMailDao.java package dao.face; public interface AdminMailDao { } <file_sep>/src/service/impl/JjimServiceImpl.java package service.impl; import java.util.List; import javax.servlet.http.HttpServletRequest; import common.JDBCTemplate; import dao.face.JjimDao; import dao.impl.JjimDaoImpl; import dto.XJjim; import dto.XShow; import service.face.JjimService; import util.Paging; public class JjimServiceImpl implements JjimService { private JjimDao jjimDao = new JjimDaoImpl(); @Override public Paging getPaging(HttpServletRequest req, String memid) { String param = req.getParameter("curPage"); int curPage = 0; if (param != null && !"".equals(param)) { curPage = Integer.parseInt(param); } else { System.out.println("[WARNING] curPage값이 null이거나 비어있습니다"); } //CntByMemId가 맞나...? int totalCount = jjimDao.selectCntByMemId(JDBCTemplate.getConnection(), memid); Paging paging = new Paging(totalCount, curPage); return paging; } @Override public int setJjim(XJjim jjim) { int isAble = jjimDao.insertJjim(JDBCTemplate.getConnection(), jjim); if (isAble > 0) JDBCTemplate.commit(JDBCTemplate.getConnection()); else JDBCTemplate.rollback(JDBCTemplate.getConnection()); return isAble; } @Override public XJjim getJjimInfo(HttpServletRequest req) { XJjim jjimInfo = new XJjim(); String param = req.getParameter("showNo"); if (param != null && !"".equals(param)) { jjimInfo.setShowNo(Integer.parseInt(param)); } else { System.out.println("[WARNING] showNo값이 null이거나 비어있습니다"); } param = req.getParameter("memId"); if (param != null && !"".equals(param)) { jjimInfo.setMemId(param); } else { System.out.println("[WARNING] memId값이 null이거나 비어있습니다"); } return jjimInfo; } @Override public List<XShow> getShowNoByMemId(Paging paging, String memid) { return jjimDao.selectShowByMemId(JDBCTemplate.getConnection(), paging, memid); } @Override public List<XShow> getShowNoByMemId(String memid) { return jjimDao.selectShowByMemId(JDBCTemplate.getConnection(), memid); } @Override public int setJjimDelete(String memId, String showNo) { int isDeleted = jjimDao.deleteJjim(JDBCTemplate.getConnection(), memId, showNo); if (isDeleted > 0) JDBCTemplate.commit(JDBCTemplate.getConnection()); else JDBCTemplate.rollback(JDBCTemplate.getConnection()); return isDeleted; } @Override public boolean getisJjim(String memId, int showNo) { return jjimDao.selectXJjimByMemIdShowNo(JDBCTemplate.getConnection(), memId, showNo); } } <file_sep>/src/dao/face/AdminDao.java package dao.face; import java.sql.Connection; import dto.XAdmin; public interface AdminDao { /** * 전달받은 admin의 adminid와 adminpw가 일치하는 행의 개수 반환 * @param connection - DB연결객체 * @param admin - DB를 조회해 보려는 adminid와 adminpw가 저장된 XAdmin객체 * @return 1 == 아이디가 있으며 패스워드가 일치함 */ public int selectCntAdminByAdminidAdminpw(Connection connection, XAdmin admin); /** * 전달받은 admin의 adminid와 일치하는 행의 admin_id, admin_name, admin_authority 반환 * @param connection - DB연결객체 * @param admin - DB를 조회해 보려는 adminid가 저장된 XAdmin객체 * @return admin_id, admin_name, admin_authority가 저장된 XAdmin객체 */ public XAdmin selectAdminByAdminid(Connection connection, XAdmin admin); /** * 전달 받은 adminid와 일치하는 admin_id가 있는 지 확인한 후 boolean 반환 * @param connection - DB연결객체 * @param attribute - DB를 조회해 보려는 adminid * @return 1 == 아이디가 존재하며 admin_authority가 y임 */ public int selectCntAdminByAdminid(Connection connection, String attribute); } <file_sep>/src/controller/admin/AdminShowUpdateController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import dto.XAdmin; import dto.XFile; import dto.XShow; import service.face.AdminService; import service.face.AdminShowService; import service.impl.AdminServiceImpl; import service.impl.AdminShowServiceImpl; @WebServlet("/admin/show/update") public class AdminShowUpdateController extends HttpServlet { private static final long serialVersionUID = 1L; AdminShowService adminShowService = new AdminShowServiceImpl(); AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { XShow xshowno = adminShowService.getShowno(req); XShow xshow = adminShowService.getShowDetail(xshowno); System.out.println(xshow); XFile file = adminShowService.getFile(xshow); req.setAttribute("xshow", xshow); req.setAttribute("file", file); XAdmin admin = adminService.getLoginAdmin(req); HttpSession session = req.getSession(); if(adminService.loginAdmin(admin)) { session.setAttribute("adminlogin", true); session.setAttribute("adminid", adminService.getAdmin(admin).getAdminId()); session.setAttribute("adminname", adminService.getAdmin(admin).getAdminName()); session.setAttribute("adminauthority", adminService.getAdmin(admin).getAdminAuthority()); } else { session.setAttribute("loginfail", true); } if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { req.getRequestDispatcher("/WEB-INF/views/admin/show/update.jsp").forward(req, resp); return; } resp.sendRedirect("/admin"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); adminShowService.setShowUpdate(req); resp.sendRedirect("/admin/show/list"); } } <file_sep>/src/controller/admin/AdminReviewDeleteController.java package controller.admin; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dto.XReview; import service.face.AdminReviewService; import service.face.AdminService; import service.impl.AdminReviewServiceImpl; import service.impl.AdminServiceImpl; @WebServlet("/admin/review/delete") public class AdminReviewDeleteController extends HttpServlet { private static final long serialVersionUID = 1L; private AdminReviewService adminReviewService = new AdminReviewServiceImpl(); private AdminService adminService = new AdminServiceImpl(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("admin/review/delete [GET]"); XReview reviewno = adminReviewService.getReviewno(req); adminReviewService.setReviewDelete(reviewno); if(adminService.authorAdmin((String)req.getSession().getAttribute("adminid"))) { resp.sendRedirect("/admin/review/list"); return; } resp.sendRedirect("/admin"); } } <file_sep>/src/controller/mem/MemberNickCheckController.java package controller.mem; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.face.MemberService; import service.impl.MemberServiceImpl; @WebServlet("/join/nickcheck") public class MemberNickCheckController extends HttpServlet { private static final long serialVersionUID = 1L; private MemberService memberService = new MemberServiceImpl(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("/join/nickcheck [POST]"); String memnick = req.getParameter("memnick"); boolean doesExist = memberService.checkNick(memnick); resp.getWriter().print(doesExist); return; } } <file_sep>/src/service/face/AdminReviewService.java package service.face; import java.util.List; import javax.servlet.http.HttpServletRequest; import dto.XFile; import dto.XMem; import dto.XReview; import util.Paging; public interface AdminReviewService { /** * 페이징 객체 생성 * * 요청파라미터 curPage를 구한다 * XReview테이블과 curPage값을 이용, Paging객체를 구하여 반환 * * @param req - 요청정보 객체 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPaging(HttpServletRequest req); /** * XReview 게시판 전체 조회 * 페이징 처리 추가 * * @param paging - 페이징 정보 객체 * @return List<XReview> - 리뷰게시판 전체 조회 결과 리스트 */ public List<XReview> getReviewList(Paging paging); /** * 요청파라미터로 Review번호 구하고, 객체 반환 * * @param req - 요청정보 객체 * @return - Review객체 */ public XReview getReviewno(HttpServletRequest req); /** * reviewno객체를 통해 게시글 조회 * * @param reviewno * @return Review - 조회된 게시글 */ public XReview getReviewDetail(XReview reviewno); /** * Review 객체의 mem_id를 통해 mem_nick조회 * * @param viewReview - 조회할 리뷰글 정보 * @return - 리뷰 작성자의 닉네임 */ public String getNick(XReview viewReview); /** * Review 객체의 show_no를 통해 show_title조회 * * @param viewReview * @return show_title */ public String getTitle(XReview viewReview); /** * 게시글 삭제 * * @param reviewno - 요청 정보 객체 */ public void setReviewDelete(XReview reviewno); /** * 첨부파일 정보 조회 * * @param viewReview - 파일 번호를 가지고 있는 리뷰 객체 * @return reviewFile - 첨부파일 정보 DTO객체 */ public XFile getFile(XReview viewReview); /** * member객체로 member_id를 구하고, 회원이 작성한 리뷰 리스트 반환 * * @param paging - 페이징 정보 객체 * @param reviewMem - member_id를 가진 리뷰 객체 * @return List<XReview> - 리뷰게시판 조회 리스트 */ public List<XReview> getReviewListByMem(Paging paging, XMem reviewMem); } <file_sep>/src/service/face/AdminAskService.java package service.face; import java.util.List; import javax.servlet.http.HttpServletRequest; import dto.XAsk; import dto.XComment; import util.Paging; public interface AdminAskService { /** * 페이징 객체 생성 * * 요청 파라미터 curPage를 구함 * XAsk 테이블과 curPage값을 이용하여 Paging 객체를 구하여 반환 * * @param req - 요청 정보 객체 * @return 페이징 계산이 완료된 Paging 객체 */ public Paging getPaging(HttpServletRequest req); /** * 게시판의 게시글 리스트 조회 paging처리 * * @param paging - paging 객체 * @return 게시글 리스트 반환 */ public List<XAsk> getAskList(Paging paging); /** * 문의 askNo 구함 * * @param req - 요청 정보 객체 * @return XAsk */ public XAsk getAskNo(HttpServletRequest req); /** * 선택한 ask_no에 맞는 게시글 상세 조회 * * @param xaskno - 선택한 ask_no * @return 해당 ask_no에 맞는 XAsk 내용 */ public XAsk getAskDetail(XAsk xaskno); /** * XAsk 객체의 mem_id를 이용한 닉네임 조회 * * @param - 조회할 게시글 정보 * @return - 게시글 작성자의 닉네임 */ public String getNick(XAsk xask); /** * ask_no을 통해서 해당 ask_no에 맞는 문의에 댓글 작성 * * @param req - 요청 객체 * @param xaskno - 문의 번호 */ public XComment setCommentWrite(HttpServletRequest req, XAsk xaskno); /** * ask_no을 통해서 해당 ask_no에 맞는 댓글 조회 * @param xaskno - ask_no * @return List<XComment> */ public XComment getComment(XAsk xaskno); /** * ask_no int로 가져오기 * * @param req - 요청 객체 * @return int ask_no */ public int getAskNoInt(HttpServletRequest req); /** * ask_no로 댓글 삭제하기 * * @param xaskno - XAsk ask_no */ public void deleteComment(XAsk xaskno); /** * 답변이 null이 아니면 y로 변경 * * @param xaskno - 해당 ask_no */ public void updateAskStatetoY(XAsk xask); /** * 답변이 null이면 n로 변겨 * * @param xask - 해당 ask_no */ public void updateAskStatetoN(XAsk xask); /** * comment_no 구함 * * @param req - 요청 정보 객체 * @return int */ public int getCommentNo(HttpServletRequest req); /** * comment_no을 통해 해당 comment 수정 * * @param req - 요청 정보 객체 * @param commentno - comment_no * @return XComment */ public XComment setCommentUpdate(HttpServletRequest req, int commentno); }
be1bdea16c07e8bd0f76fd1badce91f485b10d38
[ "Java" ]
53
Java
dobby12/XGGYH
67f3d1570416a1aa88ef3af8a541e82d5e91436e
55230df7a0526a04cabe44ba18505e25bcad706a
refs/heads/master
<file_sep>import axios from 'axios'; export const apiowm = axios.create({ baseURL: 'https://api.openweathermap.org/data/2.5/weather', }); export const apispotifycategories = axios.create({ baseURL: 'https://api.spotify.com/v1/browse/categories', }); export const apispotifytracks = axios.create({ baseURL: 'https://api.spotify.com/v1/playlists', }); export const autorization = axios.create({ baseURL: 'https://accounts.spotify.com/api/token', headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', }, }); <file_sep>import User from '../models/User'; import OpenWeatherMap from '../../services/owm'; import Spotify from '../../services/spotify'; class PlaylistController { async index(req, res) { const user = await User.findByPk(req.userId); let category = ''; const result = await OpenWeatherMap.execut(user.hometown); const { temp } = result.main; if (temp > 30) { category = 'party'; } else if (temp >= 15 || temp <= 30) { category = 'pop'; } else if (temp >= 10 || temp <= 14) { category = 'rock'; } else { category = 'classical'; } const responseSpotify = await Spotify.playlists(category); return res.json(responseSpotify); } } export default new PlaylistController(); <file_sep>import Spotify from '../../services/spotify'; class TracksController { async index(req, res) { const { playlistId } = req.params; const responseTracks = await Spotify.tracks(playlistId); return res.json(responseTracks); } } export default new TracksController(); <file_sep>import { Router } from 'express'; import UserController from './app/controllers/UserController'; import Authentication from './middleware/Auth'; import SessionController from './app/controllers/SessionController'; import PlaylistController from './app/controllers/PlaylistController' import TracksController from './app/controllers/TracksController' import ForgotPasswordController from './app/controllers/ForgotPasswordController' const routes = new Router(); routes.post('/users', UserController.store); routes.post('/sessions', SessionController.store); routes.post('/forgotpassword', ForgotPasswordController.store) routes.put('/forgotpassword', ForgotPasswordController.update) routes.use(Authentication); routes.put('/users', UserController.update); routes.get('/playlists', PlaylistController.index); routes.get('/playlists/tracks', TracksController.index); export default routes; <file_sep>import { apiowm } from './api'; class OpenWeatherMap { constructor() { this.execut(); } async execut(city) { const response = await apiowm.get('/', { params: { q: city, appid: process.env.KEYOWM, units: 'metric', }, }); return response.data; } } export default new OpenWeatherMap(); <file_sep># Music Climate Music Climate é uma api desenvolvida com Nodejs a partir do framework Express. Este foi desenvolvido com a finalidade de comprovar minha proficiencia em Javascript,ferramentas auxiliáres para desenvolvimento de apis rest completas e frameworks presentes na stack Node, Postgres e Redis. A utilização do Docker tem como objetivo a disponibilização dos bancos de dados através de containers totalmente desacoplados ao serviço. ## Getting Started Para fins de teste você deve ter instalado em sua máquina uma versão LTS ou superior do NodeJs e o Docker com as imagens do Postgres e Redis devidamente configuradas. ### Pré Requisitos Segue os pré requisitos para rodar o projeto em localhost * [NODE] (https://nodejs.org/en/download/) * [YARN] (https://yarnpkg.com/pt-BR/docs/install) * [DOCKER] (https://docs.docker.com/toolbox/toolbox_install_windows/) * [MAILTRAP] (https://mailtrap.io) O projeto music climate. #### Instalação Docker: * [DOCKER TOOL BOX - WINDOWS](https://docs.docker.com/toolbox/toolbox_install_windows/) - No meu caso utilizei a toolbox para windows #### Criar Container redis e prostgress ``` docker run --name pg_music_climate -e POSTGRES_PASSWORD=<PASSWORD> POSTGRESQL_DATABASE=music_climate -p 5432:5432 -d postgres:11 docker run --name redis_music_climate -p 6379:6379 -d -t redis:alpine ``` Verifique se os containers estão funcionando corretamente: ``` docker ps -a /* caso os containers contendo os bancos de dados não estejam funcionando rode os seguintes comandos */ docker start {nome/id do container} ``` #### Serviço de email para teste * [MAILTRAP](https://mailtrap.io) - para envio de emails Para configurar o mailtrap.io, acesse sua conta e vá para a tela de configuração. Lá você encontrará as credenciais necessárias para que o serviço funcione corretamente Antes de iniciar o serviço, crie um arquivo .env com as configurações necessárias de Bancos de dados, emails, e outras variáveis de ambiente necessárias ### Instalação Passo a passo para rodar o projeto em localhost Clonar o projeto ``` https://github.com/Sanguinettecode/music_climate.git ``` ### dependencias ``` /* instalando as dependencias */ yarn ``` Com todos as dependências instaladas digite o comando adequado ``` /*iniciando o serviço*/ yarn dev /*iniciando o serviço app*/ yarn queue /*iniciando o seviço filas*/ ``` Respequitivamente para iniciar o serviço da api rest e o monitoramento das filas com Redis Documentação https://documenter.getpostman.com/view/12268446/T1LFmVRz <file_sep>import crypto from 'crypto'; import * as Yup from 'yup'; import moment from 'moment'; import User from '../models/User'; import Queue from '../../lib/Queue'; import ForgotPassword from '../jobs/ForgotPassword'; class ForgotPasswordController { async store(req, res) { const { email, redirect_url } = req.body; const user = await User.findOne({ where: { email } }); if (!user) { return res.status(404).json({ error: { message: 'algo nao deu certo, verifique o email e tente novamente', }, }); } const forgot_token = await crypto.randomBytes(10).toString('hex'); user.forgot_token = forgot_token; user.token_created_at = new Date(); await user.save(); await Queue.add(ForgotPassword.key, { user, redirect_url, forgot_token, }); return res.json('email de recuperação de senha enviado'); } async update(req, res) { const schema = Yup.object().shape({ forgot_token: Yup.string(), password: Yup.string() .min(6) .when('oldpassword', (oldpassword, field) => { return oldpassword ? field.required() : field; }), confirmpassword: Yup.string().when('password', (password, field) => { return password ? field.required().oneOf([Yup.ref('password')]) : field; }), }); if (!(await schema.isValid(req.body))) { res.status(400).json({ error: 'Validation fail' }); } const { forgot_token, password } = req.body; const user = await User.findOne({ where: { forgot_token } }); if (!user) { return res.status(401).json({ error: { message: 'Você não está autorizado', }, }); } const tokenExpired = moment() .subtract('2', 'days') .isAfter(user.token_created_at); if (tokenExpired) { return res.status(403).json({ error: { message: 'data limite de recuperação excedida', }, }); } user.password = <PASSWORD>; user.forgot_token = null; user.token_created_at = null; await user.save(); return res.json('Sucesso! Retorne ao aplicativo para fazer o login'); } } export default new ForgotPasswordController(); <file_sep>import path from 'path'; import * as rfs from 'rotating-file-stream'; const accessLogStream = rfs.createStream('access.log', { interval: '1d', path: path.join(__dirname, '..', 'temp', 'log'), }); export default accessLogStream; <file_sep>import axios from 'axios'; import { apispotifycategories, apispotifytracks } from './api'; class Spotify { constructor() { this.playlists(); this.tracks(); } async playlists(category_id) { const auth = await getToken(); apispotifycategories.defaults.headers.Authorization = `Bearer ${ // eslint-disable-next-line no-use-before-define auth.data.access_token }`; const response1 = await apispotifycategories.get( `${category_id}/playlists` ); return response1.data; } async tracks(trackId) { const auth = await getToken(); apispotifytracks.defaults.headers.Authorization = `Bearer ${ // eslint-disable-next-line no-use-before-define auth.data.access_token }`; const response = await apispotifytracks.get(`${trackId}/tracks`); return response.data; } } const getToken = async () => { const resultAuth = await axios({ url: 'https://accounts.spotify.com/api/token', method: 'post', params: { grant_type: 'client_credentials', }, headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', }, auth: { username: process.env.USER_ID, password: <PASSWORD>, }, }); return resultAuth; }; export default new Spotify(); <file_sep>import Mail from '../../lib/Mail'; class ForgotPassword { get key() { return 'ForgotPassword'; } async handle({ data }) { const { user, redirect_url, forgot_token } = data; await Mail.sendMail({ to: `${user.name} <${user.email}>`, subject: 'Recuperação de senha', html: `<p>Acesse o link para recuperar sua senha </p> <p>para recuperar sua senha, utilize este código de segurança (${forgot_token}) ou click no link abaixo</p> <a href="${redirect_url}?token=${user.forgot_token}" target="blank">recuperação de senha</a> `, }); } } export default new ForgotPassword();
343a013cab2b336f5674e9d3ed00884e2ae2941f
[ "JavaScript", "Markdown" ]
10
JavaScript
endhesoarescnx/music_climate
8bd6e5592828c915df992cbb885952d93e1ca57b
c6e94a4eafd496af373d23895291a25b9c1d993b
refs/heads/master
<repo_name>jessicakfl/fountain<file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.restboot</groupId> <artifactId>restboot</artifactId> <packaging>jar</packaging> <version>1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>3.11.0</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.7.4</version> </dependency> <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.6</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <defaultGoal>install</defaultGoal> <plugins> <!-- Package as an executable jar/war --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> <plugin> <artifactId>maven-failsafe-plugin</artifactId> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.22.0</version> </plugin> </plugins> </build> </project> <file_sep>/src/main/java/com/restboot/bean/Branch.java package com.restboot.bean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class Branch { private String Name; private String[] CustomerSegment; private Availability Availability; private String Type; private ContactInfo[] ContactInfo; private PostalAddress PostalAddress; private OtherServiceAndFacility[] OtherServiceAndFacility; private String SequenceNumber; private String Identification; private String[] Accessibility; public String getName () { return Name; } public void setName (String Name) { this.Name = Name; } public String[] getCustomerSegment () { return CustomerSegment; } public void setCustomerSegment (String[] CustomerSegment) { this.CustomerSegment = CustomerSegment; } public Availability getAvailability () { return Availability; } @JsonProperty("Availability") public void setAvailability (Availability Availability) { this.Availability = Availability; } public String getType () { return Type; } public void setType (String Type) { this.Type = Type; } public ContactInfo[] getContactInfo () { return ContactInfo; } @JsonProperty("ContactInfo") public void setContactInfo (ContactInfo[] ContactInfo) { this.ContactInfo = ContactInfo; } public PostalAddress getPostalAddress () { return PostalAddress; } @JsonProperty("PostalAddress") public void setPostalAddress (PostalAddress PostalAddress) { this.PostalAddress = PostalAddress; } public OtherServiceAndFacility[] getOtherServiceAndFacility () { return OtherServiceAndFacility; } public void setOtherServiceAndFacility (OtherServiceAndFacility[] OtherServiceAndFacility) { this.OtherServiceAndFacility = OtherServiceAndFacility; } public String getSequenceNumber () { return SequenceNumber; } public void setSequenceNumber (String SequenceNumber) { this.SequenceNumber = SequenceNumber; } public String getIdentification () { return Identification; } public void setIdentification (String Identification) { this.Identification = Identification; } public String[] getAccessibility () { return Accessibility; } public void setAccessibility (String[] Accessibility) { this.Accessibility = Accessibility; } @Override public String toString() { return "ClassPojo [Name = "+Name+", CustomerSegment = "+CustomerSegment+", Availability = "+Availability+", Type = "+Type+", ContactInfo = "+ContactInfo+", PostalAddress = "+PostalAddress+", OtherServiceAndFacility = "+OtherServiceAndFacility+", SequenceNumber = "+SequenceNumber+", Identification = "+Identification+", Accessibility = "+Accessibility+"]"; } } <file_sep>/src/main/java/com/restboot/bean/GeographicCoordinates.java package com.restboot.bean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class GeographicCoordinates { private String Latitude; private String Longitude; public String getLatitude () { return Latitude; } @JsonProperty("Latitude") public void setLatitude (String Latitude) { this.Latitude = Latitude; } public String getLongitude () { return Longitude; } @JsonProperty("Longitude") public void setLongitude (String Longitude) { this.Longitude = Longitude; } @Override public String toString() { return "ClassPojo [Latitude = "+Latitude+", Longitude = "+Longitude+"]"; } } <file_sep>/src/main/java/com/restboot/service/RestBootApp.java package com.restboot.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class RestBootApp implements CommandLineRunner { @Autowired private BankService bankService; public static void main(String[] args) throws Exception { SpringApplication app = new SpringApplication(RestBootApp.class); app.run(args); // SpringApplication.run(SpringBootConsoleApplication.class, args); } public void run(String... args) throws Exception { // bankService.getBranchLocation(); // bankService.getBranchLocationByCity("LIVERPOOL"); // exit(0); } }<file_sep>/src/main/java/com/restboot/bean/Availability.java package com.restboot.bean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class Availability { private StandardAvailability StandardAvailability; public StandardAvailability getStandardAvailability () { return StandardAvailability; } @JsonProperty("StandardAvailability") public void setStandardAvailability (StandardAvailability StandardAvailability) { this.StandardAvailability = StandardAvailability; } @Override public String toString() { return "ClassPojo [StandardAvailability = "+StandardAvailability+"]"; } }<file_sep>/src/main/resources/readme.txt restbootapp ---- To run and build ---- $ mvn clean install, $ cd Target $ java -jar restboot-1.0.jar open browser http://localhost:8080/listBranchLocation http://localhost:8080/listBranchLocationByCity/LIVERPOOL <file_sep>/src/main/java/com/restboot/bean/OtherServiceAndFacility.java package com.restboot.bean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class OtherServiceAndFacility { private String Name; private String Description; private String Code; public String getName () { return Name; } public void setName (String Name) { this.Name = Name; } public String getDescription () { return Description; } public void setDescription (String Description) { this.Description = Description; } public String getCode () { return Code; } public void setCode (String Code) { this.Code = Code; } @Override public String toString() { return "ClassPojo [Name = "+Name+", Description = "+Description+", Code = "+Code+"]"; } } <file_sep>/src/main/java/com/restboot/bean/OpeningHours.java package com.restboot.bean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class OpeningHours { private String OpeningTime; private String ClosingTime; public String getOpeningTime () { return OpeningTime; } public void setOpeningTime (String OpeningTime) { this.OpeningTime = OpeningTime; } public String getClosingTime () { return ClosingTime; } public void setClosingTime (String ClosingTime) { this.ClosingTime = ClosingTime; } @Override public String toString() { return "ClassPojo [OpeningTime = "+OpeningTime+", ClosingTime = "+ClosingTime+"]"; } } <file_sep>/src/main/java/com/restboot/bean/Day.java package com.restboot.bean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class Day { private String Name; private OpeningHours[] OpeningHours; public String getName () { return Name; } public void setName (String Name) { this.Name = Name; } public OpeningHours[] getOpeningHours () { return OpeningHours; } @JsonProperty("OpeningHours") public void setOpeningHours (OpeningHours[] OpeningHours) { this.OpeningHours = OpeningHours; } @Override public String toString() { return "ClassPojo [Name = "+Name+", OpeningHours = "+OpeningHours+"]"; } } <file_sep>/src/main/java/com/restboot/bean/Brand.java package com.restboot.bean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class Brand { private Branch[] Branch; private String BrandName; public Branch[] getBranch () { return Branch; } @JsonProperty("Branch") public void setBranch (Branch[] Branch) { this.Branch = Branch; } public String getBrandName () { return BrandName; } public void setBrandName (String BrandName) { this.BrandName = BrandName; } @Override public String toString() { return "ClassPojo [Branch = "+Branch+", BrandName = "+BrandName+"]"; } }<file_sep>/src/main/java/com/restboot/bean/GeoLocation.java package com.restboot.bean; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY) public class GeoLocation { private GeographicCoordinates GeographicCoordinates; public GeographicCoordinates getGeographicCoordinates () { return GeographicCoordinates; } @JsonProperty("GeographicCoordinates") public void setGeographicCoordinates (GeographicCoordinates GeographicCoordinates) { this.GeographicCoordinates = GeographicCoordinates; } @Override public String toString() { return "ClassPojo [GeographicCoordinates = "+GeographicCoordinates+"]"; } }
658039b4d1b69547ef6c56a75b0daf4991c70b42
[ "Text", "Java", "Maven POM" ]
11
Maven POM
jessicakfl/fountain
973d607939ce176a785edaade9212728ce69ecc2
a157d724886ed199fa4e3aba3b89aad86fef54a9
refs/heads/master
<repo_name>locaulker/gatsby-starter-tutorial<file_sep>/src/components/button.js import styled from 'styled-components' export const Button = styled.button` background-color: green; color: #fff; font-size: 2rem; display: inline-block; padding: .8rem 1rem; font-weight: 100; border: none; `
e818b41d86fa35d926319dd42a0469188c552249
[ "JavaScript" ]
1
JavaScript
locaulker/gatsby-starter-tutorial
61c085f440103fee4c33e4d3770aa7567f81a34d
73ab6bdd0f42330b8df2b9d3a9310d1a51d9b464
refs/heads/main
<file_sep>import requests import time base = "http://127.0.0.1:5002/" alphanumeric = {"1":'o','2':'t','3':"t",'4':"f",'5':"f",'6':"s",'7':"s",'8':"e",'9':"n",'0':"z",'.':"d"} time = time.time() slug = "" for i in str(time): slug += alphanumeric[i] print(slug) response = requests.post(base +"shorter/",json={"android_link":"this is android link","ios_link":"this ios Link","web_link":"www.facebook.com"}) print(response.json()) print(time)<file_sep>from typing import Collection from flask import Flask , request, json, Response from pymongo import MongoClient from bson.objectid import ObjectId import datetime class MongoAPI: def __init__(self,data): self.client = MongoClient("mongodb+srv://titoelfoly:<EMAIL>/myFirstDatabase?retryWrites=true&w=majority") database= data['database'] collection= data['collection'] cursor = self.client[database] self.collection = cursor[collection] self.data = data # Get Json By Slug def read(self, slug): documents = self.collection.find() output = [{item:data[item] for item in data if item != '_id'and item !="user"} for data in documents if data["slug"] == slug] return output def write_short_links(self,slug, ios_link, android_link, web_link, user): try: ts = datetime.datetime.now() id = ObjectId.from_datetime(ts) response = self.collection.insert({"_id": ObjectId(id),"slug":slug, "ios_link":ios_link,"android_link":android_link, "web_link":web_link, "user":ObjectId(user)}) return slug except KeyError: raise ValueError('invalid inpu') def get_user(self,email): email = self.collection.find_one({"email": email}) return email def get_user(self,data): email = self.collection.find_one({"email":data['email'], "password":data['<PASSWORD>']}) return email def add_user(self, info): try: ts = datetime.datetime.now() id=ObjectId.from_datetime(ts) info["_id"]= (ObjectId(id)) info["date"] = datetime.datetime.now() response = self.collection.insert_one(info) return response except KeyError: raise ValueError def get_links(self,user): links = self.collection.find({"user":ObjectId(user)}) res = [] for document in links: dicti= {} for key,value in document.items(): if not key=="_id" and not key=="user": dicti[key] = value res.append(dicti) print(res) return res if __name__ =="__main__": data = { "database":"<dbname>", "collection":"shorterrs" } mongo_obj = MongoAPI(data) # mongo_obj.get_user({"email":"<EMAIL>","password":"<PASSWORD>"}) mongo_obj.get_links("5ffd38d43fc3c772f141409a") # mongo_obj.get_user({"email":"<EMAIL>"}) # mongo_obj.add_user({"email":"<EMAIL>","password":"<PASSWORD>","name":'name'}) <file_sep>aniso8601==9.0.1 certifi==2021.5.30 charset-normalizer==2.0.4 click==8.0.1 dataclasses==0.8 dnspython==1.16.0 Flask==2.0.1 Flask-Cors==3.0.10 Flask-JWT-Extended==4.2.3 Flask-PyMongo==2.3.0 Flask-RESTful==0.3.9 idna==3.2 importlib-metadata==4.6.3 itsdangerous==2.0.1 Jinja2==3.0.1 MarkupSafe==2.0.1 pkg-resources==0.0.0 PyJWT==2.1.0 pymongo==3.10.1 python-slugify==5.0.2 pytz==2021.1 requests==2.26.0 six==1.16.0 text-unidecode==1.3 typing-extensions==3.10.0.0 urllib3==1.26.6 Werkzeug==2.0.1 zipp==3.5.0 <file_sep>alphanumeric = {"1":'o','2':'t','3':"t",'4':"f",'5':"f",'6':"s",'7':"s",'8':"e",'9':"n",'0':"z",'.':"d"} def slugify(t): slug="" for i in str(t): slug += alphanumeric[i] return slug <file_sep>from models.db import MongoAPI from flask import Flask, request, jsonify, Response, redirect from flask_cors import CORS from flask_restful import Resource, Api, reqparse from flask_jwt_extended import JWTManager, jwt_required , create_access_token, get_jwt_identity from utils import slugify import time import json app = Flask(__name__) CORS(app) api = Api(app) jwt = JWTManager(app) app.config["JWT_SECRET_KEY"] = "Mukhtar El-foly" data = MongoAPI({ "database":"<dbname>", "collection":"shorterrs" }) auth = MongoAPI({ "database":"<dbname>", "collection":"users" }) @app.after_request def add_headers(response): response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization') return response @app.route("/register", methods=["POST"]) def register(): email = request.form["email"] test = auth.get_user(email) if test: return jsonify(message="User ALready Exist"), 409 else: name = request.form["name"] email = request.form["email"] password = request.form["password"] user_info = dict(name=name, email=email, password=password) data.add_user(user_info) return jsonify(message="User added sucessfully"), 201 @app.route("/login", methods=["POST"]) def login(): if request.is_json: email= request.json["email"] password = request.json["password"] else: email = request.form["email"] password = request.form["password"] test = auth.get_user({"email":email, "password":password}) if test: access_token = create_access_token(identity=str(test['_id'])) return jsonify(message="Login Succeeded!", token=access_token , user=str(test['_id']), name=test['name']), 201 else: return jsonify(message="Bad Email or Password") @app.route("/links", methods=["GET"]) @jwt_required() def links(): # print("before user id") user_id = get_jwt_identity() print(user_id) return json.dumps(data.get_links(user_id)) @app.route("/<slug>", methods=["GET"]) def map_to_url(slug): # load from db where slug = slug # get the url from the database # redirect to that url response = data.read(slug) return redirect(response[0]['web_link']) @app.route("/shorter/<slug>", methods=["GET"]) def getLinks(slug): response = data.read(slug) print(response) return response shorter_put_args = reqparse.RequestParser() shorter_put_args.add_argument("slug", type=str, help="Slug") shorter_put_args.add_argument("android_link", type=str, help="Please Enter Android Link") shorter_put_args.add_argument("ios_link", type=str, help="Please Enter IOS Link") shorter_put_args.add_argument("web_link", type=str, help="Please Enter WebLink") shorter_put_args.add_argument("user", type=str, help="User_id") class Shorter(Resource): def get(self, slug): print(slug) response = data.read(slug) # return jsonify(data.read()) print(request.user_agent) print(response) return response class ShorterPost(Resource): def post(self): args = shorter_put_args.parse_args() now = time.time() sluggy = slugify(now) print(args) try: response = data.write_short_links(sluggy,args['ios_link'],args['android_link'],args['web_link'], args['user']) # returned_slug = json.dumps({"slug":sluggy}) return jsonify(sluggy) except ConnectionError: raise ConnectionError('connection failed') # api.add_resource(Shorter,"/shorter/<slug>") api.add_resource(ShorterPost,"/shorter/") if __name__ == '__main__': app.run(debug=True,host="localhost",port=5000)
9ee4c3394ed83c46a900414411591b3fa03f8f18
[ "Python", "Text" ]
5
Python
titoelfoly/shorter-server
50234a34e53b262e07cbc16625133de3def5b354
f8bbb423c76e2ad8aba238029ca5bd7d726b994e
refs/heads/master
<repo_name>Aiadictive/threeSum<file_sep>/threeSum.py class Solution(object): def threeSum(self,num): num.sort() res=[] i=0 while (i < len(num)-2): if (i == 0 or (i > 0 and num[i] != num[i-1])): lo = i+1 hi = len(num)-1 sum = 0 - num[i] while (lo < hi): curre=[] if (num[lo] + num[hi] == sum): curre.append(num[i]) curre.append(num[lo]) curre.append(num[hi]) res.append(curre) while (lo < hi and num[lo] == num[lo+1]): lo=lo+1 while (lo < hi and num[hi] == num[hi-1]): hi=hi-1 lo=lo+1 hi=hi-1 elif (num[lo] + num[hi] < sum): lo=lo+1 else: hi=hi-1 i=i+1 return res <file_sep>/README.md # threeSum threeSum
2d37b04c946fd865db052239ab14534348fec6f2
[ "Markdown", "Python" ]
2
Python
Aiadictive/threeSum
f5c26e8d53d52811867478db742354efd91fdef5
d7079b9ad65268ce5248269a3baa8662713a8cba
refs/heads/master
<file_sep>#include<iostream> using namespace std; class complex { private: float imag,real; public: complex(float x,float y) { real=x; imag=y; } complex() {} complex operator +(complex c) { complex temp; temp.real=real+c.real; temp.imag=imag+c.imag; return temp; } void display() { cout<<real<<"+j"<<imag<<endl; } }; int main() { complex c1(2.5,3.6); complex c2(1.5,1.4); c1.display(); c2.display(); complex c3=c1+c2; c3.display(); } <file_sep>#include<iostream> using namespace std; class banking { private: int balance,debitted,creditted; public: void initialise() { cout<<"enter initial amount to be deposited in your account min 500\n"; cin>>balance; while(balance<500) { cout<<"You have entered less than 500 please enter greater than 500\n"; cin>>balance; } } void debit() { cout<<"enter amount to be debitted\n"; cin>>debitted; if(balance<debitted) { cout<<"you don't have suifficient balance in your account\n"; cout<<"available balance in your account is :"<<balance<<endl; } else { balance=balance-debitted; cout<<"\n your account has been succesfuilly debitted with :"<<debitted; cout<<"\n after debit available balance in account is : "<<balance; } } void credit() { cout<<"enter amount to be credited :"; cin>>creditted; balance=balance+creditted; cout<<" \n your account has been succesfully creditted with :"<<creditted; cout<<"\n available balance in your account after credit is : "<<balance; } }; int main() { banking b; b.initialise(); b.credit(); b.debit(); } <file_sep>#include<iostream> using namespace std; #define maxsize 10 int STACK[maxsize],top; int initStack() // stack initiallisation { top=-1; } int isFull() // checking stack is full or not { if(top==maxsize-1) return 1; else return 0; } int isEmpty() // checking stack is empty or not { if(top==-1) { return 1; } else return 0; } void push(int num) // for inserting number { if(isFull()) { cout<<"Stack is full"<<endl; } else { top=top+1; STACK[top]=num; cout<<"Number has been inserted \n"; } } void pop() // for deleting the elements { if(isEmpty()) cout<<"Stack is Empty\n"; else { int temp; temp=STACK[top]; top--; } } void display() { if(isEmpty()) cout<<"Stack is Empty\n "; else { for(int i=top;i>=0;i--) cout<<STACK[i]<<endl; } } int main() { int num; initStack(); char ch; do{ int a; cout<<"Choose option\n 1.push \n 2.pop \n 3.display"<<endl; cin>>a; switch(a) { case 1: cout<<"Enter number to be inserted\n"; cin>>num; push(num); break; case 2: pop(); break; case 3: display(); break; default: cout<<"Invalid Option"<<endl; } cout<<"Do You Want to continue ? "<<endl; cin>>ch; } while(ch=='Y' || ch=='y'); return 0; } <file_sep>#include<iostream> using namespace std; class bank { protected: char name[50],type[50]; double acc_no; float deposit,withdrawl,balance; public: bank() { char *name= new char[60]; char *type=new char[60]; acc_no=0; balance=0; } void get_details() { cout<<"enter account holder name :"; cin>>name; cout<<"\n Enter account type "; cin>>type; cout<<"\n Enter account number "; cin>>acc_no; cout<<"\n Enter Initial amount : "; cin>>balance; } void put_details() { cout<<" Name : "<<name<<endl; cout<<"Account type :"<<type<<endl; cout<<"Account Number : "<<endl; } }; class saving : public bank { public: void credit_saving() { cout<<"enter amount to be credited :"; cin>>deposit; balance=balance+deposit; cout<<" \n your account has been succesfully creditted with :"<<deposit; cout<<"\n available balance in your account after credit is : "<<balance; } void debit_saving() { cout<<"enter amount to be debitted\n"; cin>>withdrawl; if(balance<withdrawl) { cout<<"you don't have suifficient balance in your account\n"; cout<<"available balance in your account is :"<<balance<<endl; } else { balance=balance-withdrawl; cout<<"\n your account has been succesfuilly debitted with :"<<withdrawl; cout<<"\n after debit available balance in account is : "<<balance; } } }; class current: public bank { public: void current_credit() { cout<<"enter amount to be credited :"; cin>>deposit; balance=balance+deposit; cout<<" \n your account has been succesfully creditted with :"<<deposit; cout<<"\n available balance in your account after credit is : "<<balance; } void current_debit() { cout<<"enter amount to be debitted\n"; cin>>withdrawl; if(balance<withdrawl) { cout<<"you don't have suifficient balance in your account\n"; cout<<"available balance in your account is :"<<balance<<endl; } else { balance=balance-withdrawl; cout<<"\n your account has been succesfuilly debitted with :"<<withdrawl; cout<<"\n after debit available balance in account is : "<<balance; } } void penalty() { if(balance<1000) balance=balance-100; } }; int main() { int n,i;; cout<<"******************************Banking*********************"<<endl; cout<<"\n 1. Saving n\n 2.Current "<<endl; cin>>n; saving s; current c; switch(n) { case 1: s.get_details(); s.put_details(); int choice; cout<<"\n 1.Credit \n 2. Debit"<<endl; cin>>choice; if(choice==1) { s.credit_saving(); break; } else if(choice==2) { s.debit_saving(); break;} else { cout<<"envalid option"<<endl; break; } break; case 2: c.get_details(); c.put_details(); c.penalty(); cout<<"\n 1.Credit \n 2. Debit"<<endl; cin>>choice; if(choice==1) { c.current_credit(); break; } else if(choice==2) { c.current_debit(); break; } else { cout<<"envalid option"<<endl; break; } cout<<"Check Book facility available;"; break; } } <file_sep>#include<iostream> using namespace std; class xyz; class abc { int a; public: void setvalue(int x) { a=x; } friend void max( abc,xyz); }; class xyz { int b; public: void setvalue(int y) { b=y; } friend void max(abc,xyz); }; void max( abc p,xyz q) { if(p.a>q.b) cout<<"\nClass abc Variable has greater value and value is : "<<p.a<<endl; else cout<<"\nClass xyz Variable has greater value and value is : "<<q.b<<endl; }; int main() { abc d; xyz e; d.setvalue(54); e.setvalue(87); max(d,e); d.setvalue(65); e.setvalue(32); max(d,e); } <file_sep>#include<iostream> using namespace std; class sample { float a,b; public: void setvalue() { a=25; b=75; } friend float mean(sample s ); }; float mean(sample s) { return float (s.a+s.b)/2; } int main() { sample c; c.setvalue(); cout<<" mean value: "<<mean(c); } <file_sep>#include<iostream> using namespace std; class student { protected: char name[40]; int roll_number; public: void get_student_details() { cout<<"Enter Name : "<<endl; cin>>name; cout<<"Enter Roll Number : "<<endl; cin>>roll_number; } void put_students_details() { cout<<" Name : "<<name<<endl; cout<<"Roll number : "<<roll_number<<endl; } }; class test: public student { protected: float sub1,sub2; public: void get_marks(float x,float y) { sub1=x;sub2=y; } void put_marks() { cout<<"Marks in Subject 1 : "<<sub1<<endl; cout<<"Marks in Subject 2 : "<<sub2<<endl; } }; class sports { protected: float score; public: void get_score(float s) { score=s; } void put_score() { cout<<"Score Weightage is : "<<score; } }; class result: public test,public sports { private: float total; public: void get_result() { total=sub1+sub2+score; cout<<"Total Marks Obtained is : "<<total<<endl; } }; int main() { result r; r.get_student_details(); r.get_marks(65.99,34.01); r.get_score(56.0); r.put_students_details(); r.put_marks(); r.put_score(); r.get_result(); } <file_sep>#include<iostream> #include<iomanip> #include<string.h> using namespace std; class library { private: char title[50][50]; char author[50][50]; char publisher[50][50]; float price[50],total; int stock[50],n,copies; public: void getdata() { cout<<"enter the no of books to be feeded\n "; cin>>n; for(int i=0;i<n;i++) { cout<<"Enter Title of the book :"; cin>>title[i]; cout<<"\n enter the Author of the book :"; cin>>author[i]; cout<<"\n Enter publisher of the book : "; cin>>publisher[i]; cout<<"\n Enter Price of the book : "; cin>>price[i]; cout<<"\n enter available stock of book :"; cin>>stock[i]; } } void putdata() { cout<<"Title "<<setw(15)<<"Author"<<setw(15)<<"Publisher"<<setw(15)<<"Price"<<setw(15)<<"Stock"<<endl; for(int i=0;i<n;i++) { cout<<title[i]<<setw(15)<<author[i]<<setw(15)<<publisher[i]<<setw(15)<<price[i]<<setw(15)<<stock[i]<<endl; } } void search(char a[],char b[]) { for(int i=0;i<n;i++) { if(strcmp(title[i],a)==0 && strcmp(author[i],b)==0) { cout<<"\nBooks availble "<<endl; cout<<"\n Title "<<setw(15)<<"Author"<<setw(15)<<"Publisher"<<setw(15)<<"Price"<<setw(15)<<"Stock"<<endl; cout<<title[i]<<setw(15)<<author[i]<<setw(15)<<publisher[i]<<setw(15)<<price[i]<<setw(15)<<stock[i]<<endl; cout<<"\n Enter the number of books you want"; cin>>copies; if(stock[i]<copies) { cout<<"\n Sorry This much stock is not available"; cout<<"\n We have only : "<<stock[i]<<" copies "; } else { cout<<"\n We have available Stock"; total=copies*price[i]; cout<<"\n Total Price of book is : "<<total; } } } cout<<" \n Sorry We Don't have this book in our shop"; } }; int main() { library b; char search_title[50],search_author[50]; b.getdata(); b.putdata(); cout<<"\n Enter title and author name to be searched : "; cin>>search_title>>search_author; b.search(search_title,search_author); } <file_sep>#include<iostream> #include<string.h> #include<stdlib.h> using namespace std; class book { private: char author[50],title[50],publisher[50]; float price,total; int size,stock,copies; public: book() { char *author= new char[60]; char *title=new char [60]; char *publisher=new char [60]; price=0; stock=0; } void get_data() { cout<<"\n Enter Title,Author and Publisher Name :"; cin>>title>>author>>publisher; cout<<"\n Enter Price and Stock of the Book :"; cin>>price>>stock; } void put_data() { cout<<title<<endl<<"\t \t :"<<author<<"\t \t :"<<publisher<<"\t \t"<<price<<"\t \t "<<stock<<endl; } int search_book(char a[],char b[]) { if (strcmp(title,a) && strcmp(author,b)) return 0; else return 1; } void nocopies(int n) { if(stock>n) { cout<<"\n Book available "; cout<<" price : "<<price<<"\n total : "<<n*price; } else { cout<<"\n Book Not available "; } } }; int main() { book b[100]; char key_title[50],key_author[60]; int n,size,flag=0,key=0,i,copies; do{ cout<<"******************Book Store ********************\n"; cout<<"press \n"<<" 1. Insert Book \n 2. Display \n 3. Search \n 4. Exit "<<endl; cin>>n; switch(n) { case 1: cout<<"\n enter no of books to be feed"; cin>>size; for(i=0;i<size;i++) { b[i].get_data(); } break; case 2: cout<<"\n "<<"Title "<<"\t \t "<<"Author "<<"\t \t"<<"Publisher"<<"\t \t "<<"Price"<<"\t \t "<<"Stock"; for(i=0;i<size;i++) { cout<<endl; b[i].put_data(); } break; case 3: cout<<"enter title and author name to be searched"<<endl; cin>>key_title>>key_author; for(i=0;i<size;i++) { if(b[i].search_book(key_title,key_author)) { flag=1; cout<<"\n "<<"Title "<<"\t \t "<<"Author "<<"\t \t"<<"Publisher"<<"\t \t "<<"Price"<<"\t \t "<<"Stock"; b[i].put_data(); key=i; } } if(flag==1) { cout<<"Book available"<<endl; cout<<"enter no of copies"<<endl; cin>>copies; b[key].nocopies(copies); } else cout<<"Book not available"<<endl; break; case 4: exit(EXIT_SUCCESS); break; default: cout<<"Wrong Choice "; } } while(n!=5); return 0; } <file_sep># Lab-Programs Lab Programs of my college You will find here lab programs of my college College Name : Cochin University College Of Engineering kuttanad University Name : Cochin University Of Science and Technology ( CUSAT ) Professor Name : <NAME> <file_sep>#include<iostream> using namespace std; class B { int a; public: int b; void get_ab() { a=5; b=10; } int get_a() { return a; } void put_ab() { cout<<" a: "<<a<<endl; cout<<" b: "<<b<<endl; } }; class D : public B { int c; public: void mull() { c=b*get_a(); } void display() { cout<<"a= "<<get_a()<<endl; cout<<"b= "<<b<<endl; cout<<" c= "<<c<<endl; } }; int main() { D d; d.get_ab(); d.mull(); d.display(); d.b=200; d.mull(); d.display(); return 0; } <file_sep>#include<iostream> using namespace std; class M { protected: int m; public: void get_m() { m=5; } }; class N { protected: int n; public: void get_n() { n=10; } }; class P: public M, public N { public: void display() { cout<<" M = "<<m<<endl; cout<<" N = "<<n<<endl; cout<<" M*N = "<<m*n<<endl; } }; int main() { P p; p.get_m(); p.get_n(); p.display(); } <file_sep>#include<iostream> #include<iomanip> using namespace std; class student { private: int age; char name[50]; public: void getdata() { cout<<"Enter name and age \n"; cin>>name>>age; } void putdata() { cout<<"Name : "<<setw(25)<< " Age : "<<endl; cout<<name<<setw(25)<<age; } }; int main() { student s1; s1.getdata(); s1.putdata(); }
819a1c2715e0b226dc6df595078d120be7199577
[ "Markdown", "C++" ]
13
C++
Trmpsanjay/Lab-Programs
13fa9d7ba277a78865ce161abbcf4bd738ad8aad
2b7b3efd3a1461c8f0b78e7be3fa3585405c77b7
refs/heads/master
<repo_name>zerokun1999/Test<file_sep>/Class_Demo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BTH2 { public class Class_Demo { public static double Power(double x, int n) { if (n == 0) return 1.0; else if (n > 0) return x * Power(x, n - 1); else return Power(x, n + 1) / x; } } }
7a024fa4d67c27f7e92d6eced62cfcbef5159865
[ "C#" ]
1
C#
zerokun1999/Test
1bb1e2afc861be97afd2a8aa9b794c58ed61c590
fa35020fe798cd15f8f774f195d297b7a60de5a4
refs/heads/master
<repo_name>acidburn0zzz/nativefier<file_sep>/src/infer/inferOs.ts import * as os from 'os'; import * as log from 'loglevel'; // Ideally we'd get this list directly from electron-packager, but it's not // accessible in the package without importing its private js files, which felt // dirty. So if those change, we'll update these as well. // https://electron.github.io/electron-packager/master/interfaces/electronpackager.options.html#platform // https://electron.github.io/electron-packager/master/interfaces/electronpackager.options.html#arch export const supportedArchs = ['ia32', 'x64', 'armv7l', 'arm64', 'universal']; export const supportedPlatforms = [ 'darwin', 'linux', 'mac', 'mas', 'osx', 'win32', 'windows', ]; export function inferPlatform(): string { const platform = os.platform(); if (['darwin', 'linux', 'win32'].includes(platform)) { log.debug('Inferred platform', platform); return platform; } throw new Error(`Untested platform ${platform} detected`); } export function inferArch(): string { const arch = os.arch(); if (!supportedArchs.includes(arch)) { throw new Error(`Incompatible architecture ${arch} detected`); } log.debug('Inferred arch', arch); return arch; } <file_sep>/CATALOG.md # Build Commands Catalog Below you'll find a list of build commands contributed by the Nativefier community. They are here as examples, to help you nativefy "complicated" apps that need a bit of elbow grease to work. We need your help to enrich it, as long as you follow these two guidelines: 1. Only add sites that require something special! No need to document here that `simplesite.com` works with a simple `nativefier simplesite.com` 🙂. 2. Please add commands with the _strict necessary_ to make an app work. For example, - Yes to mention that `--widevine` or some `--browserwindow-options` are necessary... - ... but don't add other flags that are pure personal preference (e.g. `--disable-dev-tools` or `--disk-cache-size`). --- ## General recipes ### Window size and position This allows the last set window size and position to be remembered and applied after your app is restarted. Note: PR welcome for a built-in fix for that :) . ```sh nativefier 'https://open.google.com/' --inject window.js ``` Note: [Inject](https://github.com/nativefier/nativefier/blob/master/API.md#inject) the following javascript as `windows.js` to prevent the window size and position to reset. ```javascript function storeWindowPos() { window.localStorage.setItem('windowX', window.screenX); window.localStorage.setItem('windowY', window.screenY); } window.moveTo(window.localStorage.getItem('windowX'), window.localStorage.getItem('windowY')); setInterval(storeWindowPos, 250); ``` ## Google apps (This example documents Google Sheets, but is applicable to other Google apps, e.g. Google Calendar) ```sh nativefier 'https://docs.google.com/spreadsheets' \ --user-agent firefox ``` Note: lying about the User Agent is required, else Google will notice your "Chrome" isn't a real Chrome, and will: 1. Refuse login 2. Break notifications ## Outlook ```sh nativefier 'https://outlook.office.com/mail' --internal-urls '.*?(outlook.live.com|outlook.office365.com).*?' --file-download-options '{"saveAs": true}' --browserwindow-options '{"webPreferences": { "webviewTag": true, "nodeIntegration": true, "nodeIntegrationInSubFrames": true } }' ``` Note: `--browserwindow-options` is needed to allow pop-outs when creating/editing an email. ## Udemy ```sh nativefier 'https://www.udemy.com/' --internal-urls '.*?udemy.*?' --file-download-options '{"saveAs": true}' --widevine ``` Note: most videos will work, but to play some DRMed videos you must pass `--widevine` AND [sign the app](https://github.com/nativefier/nativefier/issues/1147#issuecomment-828750362). ## HBO Max ```sh nativefier 'https://play.hbomax.com/' --widevine --enable-es3-apis && python -m castlabs_evs.vmp sign-pkg 'name_of_the_generated_hbo_app' ``` Note: as for Udemy, `--widevine` + [app signing](https://github.com/nativefier/nativefier/issues/1147#issuecomment-828750362) is necessary. ## WhatsApp ```sh nativefier 'https://web.whatsapp.com/' --inject whatsapp.js ``` With this `--inject` in `whatsapp.js` (and maybe more, see [#1112](https://github.com/nativefier/nativefier/issues/1112)): ```javascript if ('serviceWorker' in navigator) { caches.keys().then(function (cacheNames) { cacheNames.forEach(function (cacheName) { caches.delete(cacheName); }); }); } ``` ## Spotify ```sh nativefier 'https://open.spotify.com/' --widevine --inject spotify.js --inject spotify.css ``` Notes: - You might have to pass `--user-agent firefox` to circumvent Spotify's detection that your browser isn't a real Chrome. But [maybe not](https://github.com/nativefier/nativefier/issues/1195#issuecomment-855003776). - [Inject](https://github.com/nativefier/nativefier/blob/master/API.md#inject) the following javascript as `spotify.js` to prevent "Unsupported Browser" messages. ```javascript function dontShowBrowserNoticePage() { const browserNotice = document.getElementById('browser-support-notice'); console.log({ browserNotice }); if (browserNotice) { // When Spotify displays the browser notice, it's not just the notice, // but the entire page is focused on not allowing you to proceed. // So in this case, we hide the body element (so nothing shows) // until our JS deletes the service worker and reload (which will actually load the player) document.getElementsByTagName('body')[0].style.display = 'none'; } } function reload() { window.location.href = window.location.href; } function nukeWorkers() { dontShowBrowserNoticePage(); if ('serviceWorker' in navigator) { caches.keys().then(function (cacheNames) { cacheNames.forEach(function (cacheName) { console.debug('Deleting cache', cacheName); caches.delete(cacheName); }); }); navigator.serviceWorker.getRegistrations().then((registrations) => { registrations.forEach((worker) => worker .unregister() .then((u) => { console.debug('Unregistered worker', worker); reload(); }) .catch((e) => console.error('Unable to unregister worker', error, { worker }), ), ); }); } } document.addEventListener('DOMContentLoaded', () => { nukeWorkers(); }); if (document.readyState === 'interactive') { nukeWorkers(); } ``` - It is also required to [sign the app](https://github.com/nativefier/nativefier/blob/master/API.md#widevine), or many songs will not play. - To hide all download links (as if you were in the actual app), [inject](https://github.com/nativefier/nativefier/blob/master/API.md#inject) the following CSS as `spotify.css`: ```css a[href='/download'] { display: none; } ``` <file_sep>/README.md # Nativefier ![Example of Nativefier app in the macOS dock](.github/dock-screenshot.png) You want to make a native-looking wrapper for WhatsApp Web (or any web page). ```bash nativefier 'web.whatsapp.com' ``` ![Walkthrough animation](.github/nativefier-walkthrough.gif) You're done. ## Introduction Nativefier is a command-line tool to easily create a “desktop app” for any web site with minimal fuss. Apps are wrapped by [Electron](https://www.electronjs.org/) (which uses Chromium under the hood) in an OS executable (`.app`, `.exe`, etc) usable on Windows, macOS and Linux. I built this because I grew tired of having to Alt-Tab to my browser and then search through numerous open tabs when using Messenger or Whatsapp Web ([HN thread](https://news.ycombinator.com/item?id=10930718)). Nativefier features: - Automatically retrieval of app icon / name - Injection of custom JS & CSS - Many more, see the [API docs](API.md) or `nativefier --help` ## Installation Install Nativefier globally with `npm install -g nativefier` . Requirements: - macOS 10.10+ / Windows / Linux - [Node.js](https://nodejs.org/) ≥ 12.9 and npm ≥ 6.9 Optional dependencies: - [ImageMagick](http://www.imagemagick.org/) or [GraphicsMagick](http://www.graphicsmagick.org/) to convert icons. Be sure `convert` + `identify` or `gm` are in your `$PATH`. - [Wine](https://www.winehq.org/) to build Windows apps from non-Windows platforms. Be sure `wine` is in your `$PATH`. ## Usage To create a desktop app for medium.com, simply `nativefier 'medium.com'` Nativefier will try to determine the app name, and well as lots of other options. If desired, these options can be overwritten. For example, to override the name, `nativefier --name 'My Medium App' 'medium.com'` **Read the [API docs](API.md) or run `nativefier --help`** to learn about command-line flags usable to configure your app. To have high-quality icons used by default for an app/domain, please contribute to the [icon repository](https://github.com/nativefier/nativefier-icons). ### Catalog See [CATALOG.md](CATALOG.md) for build commands & workarounds contributed by the community. ## Docker Nativefier is also usable from Docker: - Pull the image from [Docker Hub](https://hub.docker.com/r/nativefier/nativefier): `docker pull nativefier/nativefier` - ... or build it yourself: `docker build -t local/nativefier .` (in this case, replace `nativefier/` in the below examples with `local/`) By default, `nativefier --help` will be executed. To build e.g. a Gmail app into `~/nativefier-apps`, ```bash docker run --rm -v ~/nativefier-apps:/target/ nativefier/nativefier https://mail.google.com/ /target/ ``` You can pass Nativefier flags, and mount volumes to pass local files. E.g. to use an icon, ```bash docker run --rm -v ~/my-icons-folder/:/src -v $TARGET-PATH:/target nativefier/nativefier --icon /src/icon.png --name whatsApp -p linux -a x64 https://web.whatsapp.com/ /target/ ``` ## Unofficial repositories Nativefier is also available in various user-contributed software repos. These are *not* managed by Nativefier maintainers; use at your own risk. If using them, for your security, please inspect the build script. - [Snap](https://snapcraft.io/nativefier) - [AUR](https://aur.archlinux.org/packages/nodejs-nativefier) ## Development Help welcome on [bugs](https://github.com/nativefier/nativefier/issues?q=is%3Aopen+is%3Aissue+label%3Abug) and [feature requests](https://github.com/nativefier/nativefier/issues?q=is%3Aopen+is%3Aissue+label%3Afeature-request)! Docs: [Developer / build / hacking](HACKING.md), [API / flags](API.md), [Changelog](CHANGELOG.md). ## License [MIT](LICENSE.md). ## Troubleshooting Generally, see [CATALOG.md](CATALOG.md) for ideas & workarounds, and search in [existing issues](https://github.com/nativefier/nativefier/issues). ### Old/unsupported browser Some sites intentionally block Nativefier (or similar) apps, e.g. [Google](https://github.com/nativefier/nativefier/issues/831) and [WhatsApp](https://github.com/nativefier/nativefier/issues/1112). First, try setting the [`--user-agent`](https://github.com/nativefier/nativefier/blob/master/API.md#user-agent) to `firefox` or `safari`. If still broken, see [CATALOG.md](CATALOG.md) + existing issues. ### Videos won't play This issue comes up for certain sites like [HBO Max](https://github.com/nativefier/nativefier/issues/1153) and [Udemy](https://github.com/nativefier/nativefier/issues/1147). First, try [`--widevine`](API.md#widevine). If still broken, see [CATALOG.md](CATALOG.md) + existing issues. ### Settings cached between app rebuilds This can occur because app cache lives separate from the app. Try delete your app's cache, which is found at `<your_app_name_lower_case>-nativefier-<random_id>` in your OS's "App Data" directory (for Linux: `$XDG_CONFIG_HOME` or `~/.config` , for MacOS: `~/Library/Application Support/` , for Windows: `%APPDATA%` or `C:\Users\yourprofile\AppData\Roaming`)
89c272cd65a689958b8600bc4620ad39110fd39e
[ "Markdown", "TypeScript" ]
3
TypeScript
acidburn0zzz/nativefier
4c6d0b185bf3aa41d346c4ce754101666a28a5d4
58e10d3e713c4b71c7f5ec5fbb73b9dd1faa1390
refs/heads/master
<file_sep>#include <FirebaseESP8266.h> #include <ESP8266WiFi.h> #define WIFI_SSID "" // YOU SSID #define WIFI_PASSWORD "" // YOU <PASSWORD> #define FIREBASE_HOST "" // YOU HOST KEY #define FIREBASE_KEY "" // YOU FIREBASE KEY #define ledPin D0 void setup() { pinMode(ledPin, OUTPUT); Serial.begin(9600); Serial.println(WiFi.localIP()); WiFi.begin(WIFI_SSID, WIFI_PASSWORD); Serial.print("connecting"); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("connected: "); Serial.println(WiFi.localIP()); Firebase.begin(FIREBASE_HOST, FIREBASE_KEY); } void loop() { FirebaseData FB_DATA; Serial.println("========="); if(Firebase.getString(FB_DATA, "/Bed Room/LED")) { if (FB_DATA.stringData() == "1"){ Serial.println("LED IS ON !"); digitalWrite(ledPin, HIGH); } else { Serial.println("LED IS OFF !"); digitalWrite(ledPin, LOW); } } }
9b7fd0aa13098f7c1adaa2d114425754f355b3af
[ "C++" ]
1
C++
xNewz/Arduino-realtime-database-led-control
cd4d8508d2f3338481d7cc3717afdc980d730621
8c71eceb5465ef8cb3e24d2c0390782dd211a309
refs/heads/master
<repo_name>ranadeavani/bon-appetit<file_sep>/bon.sql SELECT * FROM bon.user; use bon; alter table user add constraint primary key(username); insert into user values("sheetal","rathore","srathore","jaipur","123"); select * from user; insert into item values(1,0,'Pizza',6,''); select * from user;
58eef07e48e5b69df78a28001520d1c078603478
[ "SQL" ]
1
SQL
ranadeavani/bon-appetit
6e5e8e49f2f1e4e95a0039152b6da75af6ca0c7c
cfa781101d36fe79f6c41381e627d4615e6a1fcf
refs/heads/master
<file_sep>export MOZ_USE_OMTC=1 export PATH="$HOME/.cargo/bin:$PATH" <file_sep>git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash vim +PluginInstall +qall <file_sep># ~/.bashrc: executed by bash(1) for non-login shells. # see /usr/share/doc/bash/examples/startup-files (in the package bash-doc) # for examples xclip="xclip -selection c" # If not running interactively, don't do anything case $- in *i*) ;; *) return;; esac # Use neovim alias vim='nvim' export EDITOR='nvim' # don't put duplicate lines or lines starting with space in the history. # See bash(1) for more options HISTCONTROL=ignoreboth # append to the history file, don't overwrite it shopt -s histappend # copy&paste alias pbcopy='xsel --clipboard --input' alias pbpaste='xsel --clipboard --output' # for setting history length see HISTSIZE and HISTFILESIZE in bash(1) HISTSIZE=3000 HISTFILESIZE=5000 # check the window size after each command and, if necessary, # update the values of LINES and COLUMNS. shopt -s checkwinsize # If set, the pattern "**" used in a pathname expansion context will # match all files and zero or more directories and subdirectories. #shopt -s globstar # make less more friendly for non-text input files, see lesspipe(1) [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)" # enable color support of ls and also add handy aliases if [ -x /usr/bin/dircolors ]; then test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)" alias ls='ls --color=auto' #alias dir='dir --color=auto' #alias vdir='vdir --color=auto' alias grep='grep --color=auto' alias fgrep='fgrep --color=auto' alias egrep='egrep --color=auto' fi # some more ls aliases alias ll='ls -alF' alias la='ls -A' alias l='ls -CF' # Add an "alert" alias for long running commands. Use like so: # sleep 10; alert alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"' # Alias definitions. # You may want to put all your additions into a separate file like # ~/.bash_aliases, instead of adding them here directly. # See /usr/share/doc/bash-doc/examples in the bash-doc package. if [ -f ~/.bash_aliases ]; then . ~/.bash_aliases fi # enable programmable completion features (you don't need to enable # this, if it's already enabled in /etc/bash.bashrc and /etc/profile # sources /etc/bash.bashrc). if ! shopt -oq posix; then if [ -f /usr/share/bash-completion/bash_completion ]; then . /usr/share/bash-completion/bash_completion elif [ -f /etc/bash_completion ]; then . /etc/bash_completion fi fi export JAVA_FONTS=/usr/share/fonts/TTF export PATH=/home/robert/Dropbox/scripts:$PATH export PATH=/home/robert/apps/rclone:$PATH export PATH=/home/robert/apps/todotxt:$PATH #autojump [[ -s ~/.autojump/etc/profile.d/autojump.bash ]] && . ~/.autojump/etc/profile.d/autojump.bash export JAVA_HOME=/usr/java/default # open with default app alias go='xdg-open' export PATH=/home/robert/.composer/vendor/bin:$PATH #NPM_PACKAGES="~/.npm-package" #NODE_PATH="$NPM_PACKAGES/lib/node_modules:$NODE_PATH:/home/robert/local/lib/node_modules/" #source ~/liquidprompt/liquidprompt export PATH=~/apps/sbt/bin:$PATH export PATH=~/apps:$PATH export PATH=~/bin:$PATH export PATH="$NPM_PACKAGES/bin:$PATH:/home/robert/local/bin" unset MANPATH # delete if you already modified MANPATH elsewhere in your config MANPATH="$NPM_PACKAGES/share/man:$(manpath)" ANDROID_HOME=~/Android/Sdk # Better path display #export MYPS='$(echo -n "${PWD/#$HOME/~}" | awk -F "/" '"'"'{if (length($0) > 14) { if (NF>4) print $1 "/" $2 "/.../" $(NF-1) "/" $NF; else if (NF>3) print $1 "/" $2 "/.../" $NF; else print $1 "/.../" $NF; } else print $0;}'"'"')' #PS1='$(eval "echo ${MYPS}")$ ' ## Dev scripts export PATH=/home/robert/data/87am/scripts:/home/robert/.nvm:$PATH export UID export NVM_DIR="/home/robert/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm PATH="/home/robert/perl5/bin${PATH+:}${PATH}"; export PATH; PERL5LIB="/home/robert/perl5/lib/perl5${PERL5LIB+:}${PERL5LIB}"; export PERL5LIB; PERL_LOCAL_LIB_ROOT="/home/robert/perl5${PERL_LOCAL_LIB_ROOT+:}${PERL_LOCAL_LIB_ROOT}"; export PERL_LOCAL_LIB_ROOT; PERL_MB_OPT="--install_base \"/home/robert/perl5\""; export PERL_MB_OPT; PERL_MM_OPT="INSTALL_BASE=/home/robert/perl5"; export PERL_MM_OPT; # History handling export HISTCONTROL=ignoredups:erasedups:ignorespace # no duplicate entries export HISTSIZE=100000 # big big history export HISTFILESIZE=100000 # big big history shopt -s histappend # append to history, don't overwrite it # Save and reload the history after each command finishes export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND" source ~/tools/terminal/tmuxinator.bash alias t=task set -o vi set show-mode-in-prompt On #stty -ixon if [ -f `which powerline-daemon` ]; then powerline-daemon -q POWERLINE_BASH_CONTINUATION=1 POWERLINE_BASH_SELECT=1 . /usr/share/powerline/bash/powerline.sh fi # Docker alias dc='docker-compose' alias dcu='docker-compose up' # Git alias gca="git commit -a" alias gaa="git add -A && git commit -a" # Flatpack alias signal='flatpak run org.signal.Signal/x86_64/stable' shopt -s expand_aliases eval $(thefuck --alias) unset BASH_ENV source /home/robert/apps/alacritty/alacritty-completions.bash <file_sep>dnf -y copr enable wyvie/i3blocks dnf install i3 \ redshift-gtk \ autojump \ dunst \ vifm \ mc \ vim \ neovim \ unar \ git \ docker \ docker-compose \ geary \ filezilla \ keepassx \ sshfs \ zathura \ zathura-pdf-mupdf \ i3blocks \ firefox \ python3-devel \ python3-pip \ gnome-terminal \ pcmanfm \ volumeicon cp ~/data/files/pragmata /usr/share/fonts fc-cache -v pip3 install thefuck # Configure docker for non-root groupadd docker gpasswd -a robert docker service docker restart # Install fedy dnf install https://dl.folkswithhats.org/fedora/$(rpm -E %fedora)/RPMS/fedy-release.rpm dnf install https://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-$(rpm -E %fedora).noarch.rpm https://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-$(rpm -E %fedora).noarch.rpm dnf install fedy # Atom-beta rpm -i https://atom.io/download/rpm?channel=beta # Rofi dnf copr enable yaroslav/i3desktop dnf install compton rofi # Signal sudo dnf copr enable luminoso/Signal-Desktop sudo dnf install signal-desktop
bdb09238e8f51c40441db017a703498e8663fae2
[ "Shell" ]
4
Shell
robertbak/linuxconfig
11a5a44370c70c73fd633f758d4b56af56946c76
5c99863804d8c4d415d1b9557c0181eeed2e0391
refs/heads/master
<repo_name>jerseypaint/red-llama<file_sep>/src/components/projects/index.js export * from "./projectsList" export * from "./projectsBody"<file_sep>/src/components/common/layout.js /** * Layout component that queries for data * with Gatsby's useStaticQuery component * * See: https://www.gatsbyjs.org/docs/use-static-query/ */ import React, { useState, useEffect } from "react" import PropTypes from "prop-types" import { useStaticQuery, graphql } from "gatsby" import { ThemeProvider } from 'styled-components' import "animate.css/animate.min.css" import { GlobalStyle } from "../../styles/global" import darkTheme from "../../styles/darkTheme" import lightTheme from "../../styles/lightTheme" import Header from "./header/header" import Footer from "./footer" const Layout = props => { const data = useStaticQuery(graphql` query { site { siteMetadata { title menuLinks { name link } } } image: file(relativePath: { eq: "logo.png" }) { childImageSharp { fluid (maxHeight: 100) { ...GatsbyImageSharpFluid } } } } `) const [theme, setTheme] = useState() function toggleTheme() { if (theme === `dark`) { localStorage.setItem('theme', 'light') } else { localStorage.setItem('theme', 'dark') } setTheme(localStorage.getItem(`theme`)) } useEffect(() => { if (typeof window !== `undefined` && localStorage.getItem(`theme`) === null ) { if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches){ localStorage.setItem('theme', 'dark') } else { localStorage.setItem('theme', 'light') } setTheme(localStorage.getItem(`theme`)) } else if (typeof window !== `undefined` && localStorage.getItem(`theme`) !== null) { setTheme(localStorage.getItem(`theme`)) } }) return ( <ThemeProvider theme={theme === `dark` ? darkTheme : lightTheme}> <GlobalStyle /> <> <Header siteTitle={data.site.siteMetadata.title} theme={theme} toggleTheme={toggleTheme} currentPage={props.currentPage} /> <main>{props.children}</main> <Footer logo={data.image} siteTitle={data.site.siteMetadata.title} menu={data.site.siteMetadata.menuLinks} /> </> </ThemeProvider> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout <file_sep>/src/components/services/index.js export * from "./servicesList"<file_sep>/src/components/common/header/mobileHeader.js import React, { useEffect, useState } from "react" import styled from "styled-components" import { css } from "styled-components" import Img from "gatsby-image" import { NavLink, NavButton } from "../nav" import media from "../../../styles/media" import theme from "../../../styles/theme" import { Bars } from "../icons" const MobileHeaderWrapper = styled.div` position: fixed; top:0; width: 100%; max-height: 80px; padding: 0.5rem; z-index: 99; ${media.tablet` display: none; `} ` const MobileNav = styled.div` display: flex; align-items: center; justify-content: space-between; a { color: #fff; } ` const LogoLink = styled(NavLink)` align-items: center; .gatsby-image-wrapper { min-width: calc(80px - 1rem); } ` const NavDrawer = styled.div` position: absolute; top: 80px; left:0; display: flex; flex-direction: column; width: 100%; background-color: #333; a { padding: 1rem; } ` const scrolledStyle = css` background-color: ${theme.darkGrey}; ` const MobileHeader = ({isScrolled, menu, logo, siteTitle}) => { const [showDrawer, setShowDrawer] = useState(false) return ( <MobileHeaderWrapper isScrolled={isScrolled} css={ isScrolled ? scrolledStyle : undefined} > <MobileNav> <LogoLink to={`/`}><Img fluid={logo.childImageSharp.fluid} alt="red llama logo" /><span>{siteTitle}</span></LogoLink> <NavButton onClick={() => setShowDrawer(!showDrawer)}><Bars /></NavButton> </MobileNav> {showDrawer && (<NavDrawer> {menu.map(menuLink => ( <NavLink to={menuLink.link} >{menuLink.name}</NavLink> ))} </NavDrawer>)} </MobileHeaderWrapper> ) } export default MobileHeader<file_sep>/src/components/common/footer.js import React from "react" import styled from "styled-components" import { css } from "styled-components" import Img from "gatsby-image" import { Nav, NavLink, NavButton } from "./nav" import media from "../../styles/media" import Section from "./section" import { gridContainer, GridContainer } from "./gridContainer" const LogoWrapper = styled.div` grid-column: 1 / span 4; ${media.tablet` grid-column: 1; `} ` const LogoLink = styled(NavLink)` flex-direction: column; align-items: center; padding: 0; text-transform: lowercase; height: 100px; .gatsby-image-wrapper { min-width: 80px; } ` const styleNav = css` display: block; grid-column: 1 / span 4; ${media.tablet` grid-column: 2; `} ` const styleFooter = css` background-color: #000; ` const Footer = props => ( <footer css={styleFooter}> <Section> <GridContainer> <LogoWrapper> <LogoLink to={`/`}><Img fluid={props.logo.childImageSharp.fluid} alt="red llama logo" /><span>{props.siteTitle}</span></LogoLink> </LogoWrapper> <Nav css={styleNav}> {props.menu.map(menuLink => ( <NavLink to={menuLink.link} >{menuLink.name}</NavLink> ))} </Nav> </GridContainer> </Section> </footer> ) export default Footer<file_sep>/src/components/home/work.js import React, { useState, useEffect, useRef } from "react" import styled, { css } from "styled-components" import Image from "gatsby-image" import { StyledLink } from "../common/styledLink" const GridContainer = styled.div` display: flex; align-items: center; height: 100%; ` const Container = styled.div` transition: all 600ms linear; padding: 0 2rem; ` const Child = styled.div` transition: all 600ms linear; position: relative; height: 100vh; padding: 0; ` const GalleryWrapper = styled.div` position: relative; width: 50%; .gatsby-image-wrapper { max-width: ${props => (props.inView ? `100%` : `500px`)}; margin: ${props => (props.inView ? `0` : `30%`)}; transition: all 600ms ease-in-out; } ` const ContentWrapper = styled.div` position: relative; width: 50%; ` const Content = styled.div` max-width: 500px; margin: 0 auto; p { height: ${props => (props.inView ? `15rem` : `0`)}; overflow: hidden; transition: all 600ms ease-in-out; } ` const activeStyles = css` background-color: ${props => props.theme.bg2Color}; ` const WorkItem = ({handleActive, title, description, link, linkText, fluid}) => { const [inView, setInView] = useState(false) const ref = useRef() let prevRatio = 0.0 useEffect(() => { const observer = new IntersectionObserver( ([entry]) => { if (entry.intersectionRatio > prevRatio){ setInView(true) handleActive(true) // ref.current.scrollIntoView({blcok: "start", behavior: 'smooth'}) } else { setInView(false) handleActive(false) } prevRatio = entry.intersectionRatio }, { root: null, rootMargin: "0px", threshold: 0.4 } ) if (ref.current) { observer.observe(ref.current) } }, [ref]); return ( <Child ref={ref} inView={inView} > <GridContainer> <GalleryWrapper inView={inView} > <Image fluid={fluid} /> </GalleryWrapper> <ContentWrapper> <Content inView={inView}> <h2>{title}</h2> <p>{description}</p> <StyledLink to={link}>{linkText}</StyledLink> </Content> </ContentWrapper> </GridContainer> </Child> ) } export const Work = (props) => { const [active, setActive] = useState(false) function handleActive(value) { setActive(value) } return ( <Container css={active ? activeStyles : undefined}> {props.projects.map( project => ( <WorkItem handleActive={handleActive} fluid={project.node.frontmatter.featuredImage.childImageSharp.fluid} title={project.node.frontmatter.title} description={project.node.frontmatter.description} link={project.node.frontmatter.path} linkText={`view project`} /> ))} </Container> ) }<file_sep>/src/components/common/pageHeader.js import React from "react" import styled from "styled-components" import { css } from "styled-components" import Section from "../common/section" import media from "../../styles/media" const TitleWrapper = styled.div` margin: 0 auto; padding: calc(80px + 3rem) 0; max-width: 800px; height: 100%; h1 { font-size: 2.4rem; } ${media.tablet` padding: 8rem 0; h1 { font-size: 5rem; } `} ` export const PageHeader = props => { const bgImageStyle = css` background-image: url(${props.bgImage}); background-size: cover; div { height: calc(100vh - 8rem); display: flex; flex-direction: column; justify-content: flex-end; width: 100%; } ` return ( <Section css={props.bgImage ? bgImageStyle : undefined}> <TitleWrapper> <h1>{props.title}</h1> </TitleWrapper> </Section> ) } <file_sep>/src/styles/darkTheme.js import theme from "./theme" const darkTheme = { bgColor: theme.darkGrey, textColor: theme.white, accentColor: theme.brand, bg2Color: theme.black } export default darkTheme<file_sep>/src/components/common/cta.js import React from "react" import styled from "styled-components" import ScrollAnimation from 'react-animate-on-scroll' import Section from "./section" import {StyledLink} from "../common/styledLink" const BigLinkWrapper = styled.div` a { font-size: 4rem; margin-left: 10%; } ` const CTA = props => ( <Section> <BigLinkWrapper> <ScrollAnimation animateIn="fadeInUp"> <StyledLink>Let's Talk</StyledLink> </ScrollAnimation> </BigLinkWrapper> </Section> ) export default CTA<file_sep>/src/components/home/services.js import React from "react" import { StyledLink } from "../common/styledLink" import styled from "styled-components" import ScrollAnimation from 'react-animate-on-scroll' import media from "../../styles/media" import theme from "../../styles/theme" import { GridContainer } from "../common/gridContainer" import Section from "../common/section" const StyledGridContainer = styled(GridContainer)` align-items: center; justify-items: center; ` const ContentWrapper = styled.div` grid-column: 1 / span 4; ${media.tablet` grid-column: 2 / span 4; `} ` const Content = styled.div` ` const ListWrapper = styled.div` grid-column: 1 / span 4; ul { list-style: none; .animated { border-bottom: solid 1px ${theme.darkGrey2}; font-weight: bold; &:last-of-type { border: none; } } li { margin: .5rem 0; padding: 1rem 2rem; font-size: 2.4rem; font-weight: bold; } } ${media.tablet` grid-column: 7 / span 6; `} ` const Services = props => ( <Section> <StyledGridContainer> <ContentWrapper> <Content> <ScrollAnimation animateIn="fadeInUp"> <p>{props.description}</p> <StyledLink to={`/services`}>View Services</StyledLink> </ScrollAnimation> </Content> </ContentWrapper> <ListWrapper> <ul> {props.services.map( service => ( <ScrollAnimation animateIn="fadeInUp"> <li>{service.title}</li> </ScrollAnimation> ))} </ul> </ListWrapper> </StyledGridContainer> </Section> ) export default Services<file_sep>/src/styles/lightTheme.js import theme from "./theme" const lightTheme = { bgColor: theme.white, textColor: theme.darkGrey, accentColor: theme.brand, bg2Color: theme.white } export default lightTheme<file_sep>/src/components/common/header/header.js import PropTypes from "prop-types" import React, { useEffect, useState } from "react" import { useStaticQuery, graphql } from "gatsby" import { debounce } from "lodash" import styled from "styled-components" import DesktopHeader from "./desktopHeader" import MobileHeader from "./mobileHeader" const HeaderWrapper = styled.div` a, button { font-family: "IBM Plex Sans"; } ` const Header = ({toggleTheme, currentPage}) => { const data = useStaticQuery(graphql` query headerQuery { site { siteMetadata { title menuLinks { name link } } } image: file(relativePath: { eq: "logo.png" }) { childImageSharp { fluid (maxHeight: 100) { ...GatsbyImageSharpFluid } } } } `) const [isScrolled, setIsScrolled] = useState(false) const scrollThreshold = 200 useEffect(() => { const handleScroll = debounce(e => { if (!isScrolled & (window.scrollY > scrollThreshold)) { setIsScrolled(true) } if (isScrolled & (window.scrollY < scrollThreshold)) { setIsScrolled(false) } }, 20) window.addEventListener("scroll", handleScroll) return () => window.removeEventListener("scroll", handleScroll) }) return ( <HeaderWrapper isScrolled={isScrolled}> <DesktopHeader logo={data.image} siteTitle={data.site.siteMetadata.title} menu={data.site.siteMetadata.menuLinks} isScrolled={isScrolled} toggleTheme={toggleTheme} currentPage={currentPage} /> <MobileHeader logo={data.image} siteTitle={data.site.siteMetadata.title} menu={data.site.siteMetadata.menuLinks} isScrolled={isScrolled} /> </HeaderWrapper> )} Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header <file_sep>/src/components/projects/projectsList.js import React, { useState, useEffect, useRef } from "react" import styled from "styled-components" import { css } from "styled-components" import { flatten } from "lodash" import Section from "../common/section" import { GridContainer } from "../common/gridContainer" import media from "../../styles/media" import theme from "../../styles/theme" import { StyledLink } from "../common/styledLink" const TagWrapper = styled.ul` position: relative; list-style: none; text-transform: uppercase; ${media.tablet` padding-right: 2rem; `} ` const Content = styled.div` grid-column: span 4; grid-row: span 2; align-self: end; display: flex; ${media.tablet` grid-column: 7 / span 5 ; `} ` const ImageWrapper = styled.div` grid-column: 1 / span 4 ; grid-row: span 1; img { object-fit: cover; height: 100%; width: 100%; margin-bottom: 0; } ${media.tablet` grid-column: 1 / span 5 ; `} ` const ProjectsWrapper = styled.div` ` const ProjectItemWrapper = styled.div` height: calc(100vh - 100px); ` const sticky = css` position: sticky; top: 100px; height: calc(100vh - 100px); padding: 3em 2em; background:linear-gradient(160deg, ${theme.brand}, ${theme.brand} 30%, transparent 10%, transparent); ` const ProjectItem = ({ updateProject, description, title, link, image, tags, color}) => { const [inView, setInView] = useState(false) const ref = useRef() useEffect(() => { let prevRatio = 0.0 const observer = new IntersectionObserver( ([entry]) => { if (entry.intersectionRatio > prevRatio){ setInView(true) updateProject( { title: title, description: description, link: link, image: image, tags: tags, color: color } ) } else { setInView(false) } prevRatio = entry.intersectionRatio }, { root: null, rootMargin: "0px", threshold: 0.4 } ) if (ref.current) { observer.observe(ref.current) } }, [ref]); return ( <ProjectItemWrapper ref={ref} title={title} description={description} link={link} tags={tags} /> ) } export const ProjectsList = ({projects}) => { const initialProject = projects[0].node.frontmatter const [currentProject, setCurrentProject] = useState({ title: initialProject.title, description: initialProject.description, link: initialProject.link, image: initialProject.featuredImage.childImageSharp.fluid.src, tags: initialProject.tags, color: theme.brand }) function updateProject(value) { setCurrentProject(value) } return ( <Section> <ProjectsWrapper currentProject={currentProject} projects={projects}> <GridContainer css={css` ${sticky}; background:linear-gradient(160deg, ${currentProject.color}, ${currentProject.color} 30%, transparent 10%, transparent); `}> <ImageWrapper> <img src={currentProject.image} /> </ImageWrapper> <Content> <TagWrapper> {currentProject.tags.map(tag => ( <li>{tag}</li> ))} </TagWrapper> <div> <h2>{currentProject.title}</h2 > <p>{currentProject.description}</p> <StyledLink to={currentProject.link}>Learn More</StyledLink> </div> </Content> </GridContainer> {projects.map(project => ( <ProjectItem title={project.node.frontmatter.title} description={project.node.frontmatter.description} link={project.node.frontmatter.path} image={project.node.frontmatter.featuredImage.childImageSharp.fluid.src} tags={project.node.frontmatter.tags} color={project.node.frontmatter.color} updateProject={updateProject} /> ))} </ProjectsWrapper> </Section> ) } <file_sep>/src/pages/services.js import React from "react" import { graphql } from "gatsby" import Layout from "../components/common/layout" import SEO from "../components/common/seo" import { PageHeader } from "../components/common/pageHeader" import { ServicesList } from "../components/services" const ServicesPage = ({data}) => ( <Layout> <SEO title="Services" /> <PageHeader title={`Full stack development`} /> <ServicesList services={data.servicesJson.services} /> </Layout> ) export const query = graphql` query { servicesJson { services { title description } } } ` export default ServicesPage <file_sep>/src/templates/project.js import React from "react" import { graphql } from "gatsby" import Layout from "../components/common/layout" import SEO from "../components/common/seo" import { PageHeader } from "../components/common/pageHeader" import { ProjectsBody } from "../components/projects" const ProjectTemplate = ({data}) => { const { markdownRemark } = data const { frontmatter, html } = markdownRemark return ( <Layout> <SEO title={frontmatter.title} /> <PageHeader title={frontmatter.title} bgImage={frontmatter.featuredImage.childImageSharp.original.src} /> <ProjectsBody html={html} tags={frontmatter.tags} /> </Layout> )} export const query = graphql` query($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { frontmatter { title description tags featuredImage { childImageSharp { original { src } } } } html } } ` export default ProjectTemplate <file_sep>/src/pages/index.js import React, { useState, useEffect, useRef } from "react" import Layout from "../components/common/layout" import SEO from "../components/common/seo" import { Work } from "../components/home/work" import { WorkMobile } from "../components/home/workMobile" import Hero from "../components/home/hero" import Services from "../components/home/services" import CTA from "../components/common/cta" import { media, sizes } from "../styles/media" const IndexPage = ({data, theme}) => { const [isMobile, setIsMobile] = useState(false) useEffect(() => { if (window.innerWidth <= sizes.mobile) { setIsMobile(true) } }) return ( <Layout currentPage={`index`}> <SEO title="Home" /> <Hero doing={data.homeJson.hero.doing} what={data.homeJson.hero.what} whom={data.homeJson.hero.whom} /> <Services description={data.homeJson.services.description} services={data.servicesJson.services} /> {isMobile ? <WorkMobile theme={({theme}) => theme} projects={data.allMarkdownRemark.edges} /> : <Work theme={theme} projects={data.allMarkdownRemark.edges} /> } <CTA /> </Layout> ) } export default IndexPage export const query = graphql` query { homeJson { hero { doing what whom } services { description } } servicesJson { services { title } } allMarkdownRemark(sort: {order: DESC, fields: [frontmatter___date]}, limit: 3, filter: {frontmatter: {type: {eq: "project"}}}) { edges { node { frontmatter { path title description tags featuredImage { childImageSharp { fluid { ...GatsbyImageSharpFluid } } } } } } } } `<file_sep>/src/components/common/header/desktopHeader.js import React from "react" import styled, { css } from "styled-components" import Img from "gatsby-image" import { Nav, NavLink, NavButton } from "../nav" import { Eclipse } from "../icons" import media from "../../../styles/media" const DesktopHeaderWrapper = styled.div` display: none; ${media.tablet` position: fixed; display: flex; justify-content: space-between; width: 100%; padding: 0.6rem; z-index: 99; transition: all 600ms ease-in-out; a, button { font-size: 1.2rem; color: ${props => props.currentPage === `index` && !props.isScrolled ? `#fff` : props.theme.textColor}; &:hover::after { background-color: ${props => props.currentPage === `index` && !props.isScrolled ? `#fff` : props.theme.accentColor}; } } `} ` const LogoWrapper = styled.div` max-width: 300px; ` const SubNavWrapper = styled.div` display: flex; align-items: center; ` const LogoLink = styled(NavLink)` align-items: center; padding: 0; text-transform: lowercase; transition: all 600ms ease-in-out; .gatsby-image-wrapper { min-width: 80px; } &:hover { color: ${props => props.theme.accentColor} } &:after { display: none; } ` const scrolledStyle = css` background-color: ${props => props.theme.bgColor}; ${LogoLink} { color: ${props => props.theme.accentColor}; &:hover { color: ${props => props.theme.textColor}; } } ` const Toggle = styled(NavButton)` --fa-primary-color: ${props => props.theme.textColor === `#FFFFFF` ? `inherit` : props.theme.accentColor} ; --fa-secondary-color: ${props => props.theme.textColor === `#FFFFFF` ? props.theme.accentColor : `inherit` }; transition: all 600ms ease-in-out; button& { font-size: 1.6rem; } &:hover { --fa-secondary-opacity: 1; &::after { display: none; } } ` const DesktopHeader = ({toggleTheme, isScrolled, logo, siteTitle, menu, currentPage }) => ( <DesktopHeaderWrapper currentPage={currentPage} isScrolled={isScrolled} css={ isScrolled ? scrolledStyle : undefined} > <LogoWrapper> <LogoLink to={`/`}><Img fluid={logo.childImageSharp.fluid} alt="red llama logo" /><span>{siteTitle}</span></LogoLink> </LogoWrapper> <Nav> {menu.map(menuLink => ( <NavLink to={menuLink.link} >{menuLink.name}</NavLink> ))} </Nav> <SubNavWrapper> <Toggle onClick={toggleTheme}> <Eclipse /> </Toggle> <NavLink>Login</NavLink> </SubNavWrapper> </DesktopHeaderWrapper> ) export default DesktopHeader<file_sep>/gatsby-config.js module.exports = { siteMetadata: { title: `red llama`, description: `A web app development group.`, twitter: `@redllama`, url: `https://redllamagroup.com`, logo: `src/images/logo.png`, menuLinks:[ { name:'home', link:'/' }, { name:'services', link:'/services' }, { name:'projects', link:'/projects' }, { name:'contact', link:'/contact' } ] }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/static/images`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `data`, path: `${__dirname}/static/data`, }, }, { resolve: `gatsby-source-filesystem`, options: { path: `${__dirname}/static/projects`, name: `projects`, }, }, "gatsby-transformer-json", `gatsby-transformer-remark`, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, // this (optional) plugin enables Progressive Web App + Offline functionality // To learn more, visit: https://gatsby.dev/offline // `gatsby-plugin-offline`, `gatsby-plugin-styled-components`, { resolve: `gatsby-plugin-typography`, options: { pathToConfigModule: `src/utils/typography`, }, }, ], } <file_sep>/src/styles/theme.js const theme = { black: "#000000", white: "#FFFFFF", lightGrey: "#A9A9A9", lightGrey2: "#C7C7C7", lightGrey3: "#959595", darkGrey: "#121212", darkGrey2: "#424242", darkGrey3: "#616161", brand: "#C11432", yellow: "#FDD10A" } export default theme<file_sep>/src/components/common/nav/index.js export * from "./nav" export * from "./navButton" export * from "./navLink" <file_sep>/src/components/common/gridContainer.js import styled from "styled-components" import media from "../../styles/media" export const GridContainer = styled.div` display: grid; grid-gap: 20px; grid-template-columns: repeat(4, 1fr); ${media.tablet` grid-gap: 28px; grid-template-columns: repeat(12, 1fr); `} ` <file_sep>/README.md A rough draft of a new site for an amazing dev agency. <file_sep>/src/components/home/hero.js import React, { useState, useEffect, useRef } from "react" import styled from "styled-components" import { random, divide } from "lodash" import { css } from "styled-components" import theme from "../../styles/theme" import media from "../../styles/media" const HeroWrapper = styled.div` width: 100%; background-color: ${theme.brand}; padding: 8rem 0; ${media.tablet` padding: 14rem 0; `} ` const Content = styled.div` margin: 0 auto; text-align: center; ` const Title = styled.h2` color: #fff; font-size: 2.4rem; margin-bottom: 0; ${media.tablet` font-size: 4.6rem; `} ` const Span = styled.span` border-bottom: 3px #212121 solid; display: inline-block; font-size: 1.8rem; ${media.tablet` font-size: 4.6rem; `} ` const Hero = props => { const doing = props.doing const what = props.what const whom = props.whom const longestVerb = Math.max(...(doing.map(el => el.length))) const longestProduct = Math.max(...(what.map(el => el.length))) const longestVertical = Math.max(...(whom.map(el => el.length))) const [verb, setVerb] = useState(doing[0]) const [product, setProduct] = useState(what[0]) const [vertical, setVertical] = useState(whom[0]) const verbWidth = css` min-width: ${divide(longestVerb, 1.8)}em; ` const productWidth = css` min-width: ${divide(longestProduct, 1.8)}em; ` const verticalWidth = css` min-width: ${divide(longestVertical, 1.8)}em; ` useEffect(() => { let VerbIndex = 1 let ProductIndex = 1 let verticalIndex = 1 const verbTimer = setInterval(() => { setVerb(doing[VerbIndex]) VerbIndex = (VerbIndex + 1)%(doing.length) }, random(4,10)*1000) const productTimer = setInterval(() => { setProduct(what[ProductIndex]) ProductIndex = (ProductIndex + 1)%(what.length) }, random(4,10)*1000) const verticalTimer = setInterval(() => { setVertical(whom[verticalIndex]) verticalIndex = (verticalIndex + 1)%(whom.length) }, random(4,10)*1000) return () => { clearInterval(verbTimer) clearInterval(productTimer) clearInterval(verticalTimer) } }, []) return ( <HeroWrapper current={verb}> <Content> <Title> We <Span css={verbWidth}>{verb}</Span></Title> <Title><Span css={productWidth}>{product}</Span> for </Title> <Title><Span css={verticalWidth}>{vertical}</Span> companies.</Title> </Content> </HeroWrapper> )} export default Hero<file_sep>/static/projects/next-hous.md --- type: "project" path: "/projects/next-hous" date: "2020-04-010" title: "Next Hous" description: "Chocolate lollipop cheesecake pudding soufflé jujubes carrot cake. Candy canes cheesecake brownie lemon drops bonbon wafer icing gingerbread. Jelly-o lollipop topping liquorice chocolate bar chupa chups. Jelly pastry cheesecake jelly beans lollipop candy canes biscuit." featuredImage: "../images/next-hous.png" tags: ["web design", "web app", "hosting and maintenance"] color: "#9cb200" --- Pie jelly brownie. Pudding marzipan chupa chups carrot cake. Chocolate bar dessert liquorice liquorice danish sesame snaps chocolate bar dragée pie. Cookie tootsie roll wafer sugar plum chocolate. Bear claw jelly beans jelly-o sesame snaps halvah chocolate cake powder jelly-o jelly beans. Toffee caramels marshmallow. Donut icing bear claw marzipan. Chocolate pie jelly danish. Cookie liquorice chocolate. Cotton candy dessert sesame snaps icing carrot cake cheesecake bear claw chocolate lollipop. Gummi bears jelly beans powder. Marshmallow pastry gummies sweet roll cupcake fruitcake. Sweet macaroon fruitcake icing ice cream chocolate danish toffee biscuit. Tootsie roll lollipop fruitcake candy canes caramels. Chocolate brownie candy canes dessert. Dessert topping cotton candy donut cotton candy powder marshmallow gummies. Sugar plum donut jelly-o brownie dragée bonbon muffin macaroon. Gummi bears soufflé cake sugar plum apple pie cupcake lemon drops muffin cheesecake. Tootsie roll pudding lollipop sweet roll bear claw. Chocolate pudding fruitcake halvah jelly cotton candy candy dragée. Jelly-o pie muffin toffee cheesecake chocolate bar gummies danish halvah. Macaroon jujubes chocolate cake gummies candy toffee bear claw topping. Marshmallow chupa chups dessert tootsie roll tiramisu. Jelly jelly cake cheesecake powder cookie. Croissant bonbon tart. Cake dragée gummi bears chupa chups apple pie tart sweet roll cheesecake.<file_sep>/src/styles/global.js import React from "react" import { createGlobalStyle } from "styled-components" export const GlobalStyle = createGlobalStyle` body { margin: 0; padding: 0; background-color: ${props => props.theme.bgColor}; color: ${props => props.theme.textColor}; } p { font-size: 1.2rem; line-height: 1.4; letter-spacing: 0.8px; } `<file_sep>/src/pages/projects.js import React from "react" import { graphql } from "gatsby" import Layout from "../components/common/layout" import SEO from "../components/common/seo" import { ProjectsList } from "../components/projects" import { PageHeader } from "../components/common/pageHeader" const ProjectsPage = ({data}) => ( <Layout> <SEO title="Projects" /> <PageHeader title={`Projects`} /> <ProjectsList projects={data.allMarkdownRemark.edges} /> </Layout> ) export const query = graphql` query { allMarkdownRemark(filter: {frontmatter: {type: {eq: "project"}}}) { edges { node { frontmatter { title description path tags color featuredImage { childImageSharp { fluid { ...GatsbyImageSharpFluid } } } } } } } } ` export default ProjectsPage <file_sep>/static/projects/dr-sofa.md --- type: "project" path: "/projects/dr-sofa" date: "2020-01-04" title: "Dr. Sofa" description: "Chocolate cake bonbon jelly danish caramels. Marzipan candy sweet. Liquorice toffee oat cake marzipan carrot cake. Pie tart marzipan toffee danish chocolate cake toffee chupa chups. Danish dessert icing sweet candy canes caramels. Gingerbread chupa chups muffin caramels lemon drops liquorice candy canes." featuredImage: "../images/dr-sofa.jpg" tags: ["web design", "web app", "process automation", "software integration"] color: "#bb171d" --- Pie jelly brownie. Pudding marzipan chupa chups carrot cake. Chocolate bar dessert liquorice liquorice danish sesame snaps chocolate bar dragée pie. Cookie tootsie roll wafer sugar plum chocolate. Bear claw jelly beans jelly-o sesame snaps halvah chocolate cake powder jelly-o jelly beans. Toffee caramels marshmallow. Donut icing bear claw marzipan. Chocolate pie jelly danish. Cookie liquorice chocolate. Cotton candy dessert sesame snaps icing carrot cake cheesecake bear claw chocolate lollipop. Gummi bears jelly beans powder. Marshmallow pastry gummies sweet roll cupcake fruitcake. Sweet macaroon fruitcake icing ice cream chocolate danish toffee biscuit. Tootsie roll lollipop fruitcake candy canes caramels. Chocolate brownie candy canes dessert. Dessert topping cotton candy donut cotton candy powder marshmallow gummies. Sugar plum donut jelly-o brownie dragée bonbon muffin macaroon. Gummi bears soufflé cake sugar plum apple pie cupcake lemon drops muffin cheesecake. Tootsie roll pudding lollipop sweet roll bear claw. Chocolate pudding fruitcake halvah jelly cotton candy candy dragée. Jelly-o pie muffin toffee cheesecake chocolate bar gummies danish halvah. Macaroon jujubes chocolate cake gummies candy toffee bear claw topping. Marshmallow chupa chups dessert tootsie roll tiramisu. Jelly jelly cake cheesecake powder cookie. Croissant bonbon tart. Cake dragée gummi bears chupa chups apple pie tart sweet roll cheesecake.<file_sep>/src/components/projects/projectsBody.js import React from "react" import styled from "styled-components" import { css } from "styled-components" import Section from "../common/section" import media from "../../styles/media" import { GridContainer } from "../common/gridContainer" const Sidebar = styled.div` grid-column: 1 / span 4; ${media.tablet` grid-column: 2 / span 3; `} ` const Article = styled.article` margin: 0 auto; max-width: 600px; grid-column: 1 / span 4; ${media.tablet` grid-column: 5 / span 4; `} ` export const ProjectsBody = props => { return ( <Section> <GridContainer> <Sidebar> <ul> {props.tags.map(tag => ( <li>{tag}</li> ))} </ul> </Sidebar> <Article dangerouslySetInnerHTML={{ __html: props.html }}> </ Article> </GridContainer> </Section> ) } <file_sep>/src/components/home/workMobile.js import React from "react" import styled from "styled-components" import ScrollAnimation from 'react-animate-on-scroll'; import Image from "gatsby-image" import { StyledLink } from "../common/styledLink" const Container = styled.div` color: #fff; padding: 0 2rem; ` const Child = styled.div` padding: 3rem 0; ` const Content = styled.div` padding-top: 4rem; ` const WorkItem = ({title, description, link, linkText, fluid}) => { return ( <Child> <ScrollAnimation animateIn="fadeInUp"> <Image fluid={fluid} /> </ScrollAnimation> <ScrollAnimation animateIn="fadeInUp"> <Content> <h2>{title}</h2> <p>{description}</p> <StyledLink to={link}>{linkText}</StyledLink> </Content> </ScrollAnimation> </Child> ) } export const WorkMobile = ({projects}) => { return ( <Container> {projects.map( project => ( <WorkItem fluid={project.node.frontmatter.featuredImage.childImageSharp.fluid} title={project.node.frontmatter.title} description={project.node.frontmatter.description} link={project.node.frontmatter.path} linkText={`view project`} /> ))} </Container> ) }<file_sep>/src/components/common/section.js import React from "react" import styled from "styled-components" import { css } from "styled-components" import media from "../../styles/media" const Section = styled.section` padding: 4rem 1rem; position: relative; ${media.tablet` padding: 4rem 0rem; `} ` const Container = styled.div` margin: 0 auto; max-width: 100%; ` export default props => ( <Section className={props.className} style={props.style}> <Container>{props.children}</Container> </Section> )
28bd6d8b1e53f13aded6f1948f8d92e280884dc3
[ "JavaScript", "Markdown" ]
30
JavaScript
jerseypaint/red-llama
588583cdd77da4a06fc53705e085065a2a4a37e3
c5cdeb4f23d656abb3a8944924e3d20d3a5897e5
refs/heads/master
<repo_name>vinodphilip/seleniumcrawler<file_sep>/webcrawl.py import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import TimeoutException from selenium.webdriver.remote.webelement import WebElement countries = ['India', 'Germany', 'Singapore', 'South Africa'] for country in countries: driver = webdriver.Firefox() driver.wait = WebDriverWait(driver, 5) driver.get("http://international.o2.co.uk/internationaltariffs/calling_abroad_from_uk") try: box = driver.wait.until(EC.presence_of_element_located( (By.ID, "countryName"))) box.send_keys(country) button = driver.wait.until(EC.element_to_be_clickable( (By.PARTIAL_LINK_TEXT, "Pay Monthly"))) button.click() driver.find_element_by_xpath('//*[@id="paymonthly"]').click() except TimeoutException: print("Box or Button not found in google.com") continue time.sleep(2) element = driver.find_element_by_id("standardRatesTable") print element.text driver.quit()
349b0ccae8671962e4aba8da130213e6689e8494
[ "Python" ]
1
Python
vinodphilip/seleniumcrawler
bc4dafa588cd4bdf27483e175fa928f242fe2394
92602db43cf148e35ac589a8e51180f1a6753faf
refs/heads/main
<file_sep>import java.util.InputMismatchException; public class ValidaCPF { public static boolean validarCPF (String CPF) { if (CPF.length() != 11) { return (false); } char digito10, digito11; int soma, i, resultado, num, peso; try { // Calculo do primeiro digito verificador. soma = 0; peso = 10; // transforma o i-esimo caractere do CPF em um número. for (i = 0; i < 9 ; i ++) { num = (int)(CPF.charAt(i) - 48); soma = soma + (num * peso); peso -= 1; } resultado = 11 - (soma % 11); if ((resultado == 10) || (resultado == 11)) { digito10 = '0'; }else digito10 = (char)(resultado + 48); // Calculo do segundo digito verificador. soma = 0; peso = 11; for (i = 0; i < 10; i ++) { num = (int)(CPF.charAt(i) - 48); soma = soma + (num * peso); peso -= 1; } resultado = 11 - (soma % 11); if ((resultado == 10) || (resultado == 11)) { digito11 = '0'; }else digito11 = (char)(resultado + 48); if ((digito10 == CPF.charAt(9)) && (digito11 == CPF.charAt(10))) { return (true); } else return false; } catch (InputMismatchException e) { return (false); // TODO: handle exception } } } <file_sep>import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.Scanner; public class Sender { public static void main(String[] args) { // TODO Auto-generated method stub Socket conn; try { conn = new Socket("127.0.0.1", 1010); Scanner entrada = new Scanner(System.in); ObjectOutputStream outputMessage = new ObjectOutputStream(conn.getOutputStream()); ObjectInputStream inputMessage = new ObjectInputStream(conn.getInputStream()); System.out.println("========================================================="); System.out.println("================= INICIANDO PROGRAMA ===================="); System.out.println("========================================================="); System.out.println("INSTRUÇÕES — DIGITE APENAS NUMEROS, 99999999999"); System.out.println("Digite seu CPF: "); outputMessage.writeObject(entrada.nextLine()); outputMessage.flush(); System.out.println("Receveid message: " + inputMessage.readObject().toString()); } catch (IOException e) { // TODO: handle exception e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
6ef8d39c9f7473e561c33abf7bb704760582400b
[ "Java" ]
2
Java
alexfferro/SD_PLE
db401a5d0ee614497ac104cbdc2036ece540d0b8
1590cea99c568a93f2f32bb692646f8d10c82118
refs/heads/main
<repo_name>JiangWeibeta/Answers-to-Codeforces-Problemset<file_sep>/1472C.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int size = 0; cin >> size; vector<int> vc(size + 1); for (int j = 1; j <= size; j++) { cin >> vc[j]; } for (int j = size; j >= 1; j--) { if (j + vc[j] <= size) { vc[j] += vc[j + vc[j]]; } } int maxn = 0; for (int j = 1; j <= size; j++) { if (vc[j] > maxn) { maxn =vc[j]; } } cout << maxn << endl; } system("pause"); return 0; } <file_sep>/1567C.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; int main() { int t = 0; cin >> t; while (t--) { int n = 0; cin >> n; string str = to_string(n); int even = 0, odd = 0; for (int i = 0; i < str.size(); i += 2) even = even * 10 + str[i] - '0'; for (int i = 1; i < str.size(); i += 2) odd = odd * 10 + str[i] - '0'; cout << (even + 1) * (odd + 1) - 2 << endl; } system("pause"); return 0; } <file_sep>/1466B.cpp #include <algorithm> #include <iostream> #include <set> #include <vector> #include <map> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int size = 0; cin >> size; vector<int> vc(size); int ans = 0; map<int, int> mm; for (int j = 0; j < size; j++) { cin >> vc[j]; if (!mm[vc[j]]) { mm[vc[j]]++; ans++; } else { if (!mm[vc[j] + 1]) { mm[vc[j] + 1]++; ans++; } } } cout << ans << endl; } system("pause"); return 0; } <file_sep>/dynamic programming/777C.cpp #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n = 0, m = 0; cin >> n >> m; vector<vector<int>> arr(n + 1, vector<int>(m + 1)); vector<vector<int>> mark(n + 1, vector<int>(m + 1, 0)); for (int i = 1; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { cin >> arr[i][j]; } } for (int i = 2; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { if (arr[i][j] >= arr[i - 1][j]) mark[i][j] = mark[i - 1][j] + 1; else mark[i][j] = 0; } } vector<int> ans(n + 1, 0); for (int i = 2; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) ans[i] = max(ans[i], mark[i][j]); } int k = 0; cin >> k; while (k--) { int l = 0, r = 0; cin >> l >> r; if (ans[r] >= r - l) cout << "Yes" << endl; else cout << "No" << endl; } return 0; } <file_sep>/777B.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; int max_flick(vector<char>& s, vector<char>& m) { int i = 0, j = 0, ans = 0; while (i < s.size() && j < m.size()) { if (s[i] < m[j]) { i++; j++; ans++; } else j++; } return ans; } int min_flick(vector<char> s, vector<char> m, int n) { vector<char> left_s, left_m; int i = 0, j = 0, ans = 0; while (i < n && j < n) { if (s[i] == m[j]) { s[i] = ' '; m[j] = ' '; i++; j++; } else if (s[i] < m[j]) { i++; } else { j++; } } for (char& ch : s) if (ch != ' ') left_s.push_back(ch); for (char& ch : m) if (ch != ' ') left_m.push_back(ch); return left_s.size() - max_flick(left_s, left_m); } int main() { int n = 0; cin >> n; vector<char> s(n), m(n); for (char& ch : s) cin >> ch; for (char& ch : m) cin >> ch; sort(s.begin(), s.end()); sort(m.begin(), m.end()); cout << min_flick(s, m, n) << endl; cout << max_flick(s, m); system("pause"); return 0; } <file_sep>/1559B.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <string> #include <vector> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int size = 0; cin >> size; vector<char> vc(size + 1); for (int j = 0; j < size; j++) { cin >> vc[j]; } vc[size] = 'B'; for (int j = 0; j < size + 1; j++) { if (vc[j] != '?') { for (int k = j - 1; k >= 0 && vc[k] == '?'; k--) { if (vc[k + 1] == 'R') { vc[k] = 'B'; } else { vc[k] = 'R'; } } for (int k = j + 1; k <= size && vc[k] == '?'; k++) { if (vc[k - 1] == 'R') { vc[k] = 'B'; } else { vc[k] = 'R'; } } } } vc.pop_back(); for (char c : vc) cout << c; cout << endl; } system("pause"); return 0; } <file_sep>/1097B.cpp #include <iostream> #include <algorithm> #include <stdlib.h> #include <vector> using namespace std; int main() { int n = 0; cin >> n; vector<int> arr(n); for (int i = 0; i < n; i++) { cin >> arr[i]; } bool can = false; for (int i = 0; i < (1 << n); i++) { int sum = 0; for (int j = 0; j < n; j++) { if (i & (1 << j)) { sum += arr[j]; } else { sum -= arr[j]; } } if (sum % 360 == 0) { can = true; break; } } if (can) cout << "YES" << endl; else cout << "NO" << endl; system("pause"); return 0; } <file_sep>/dynamic programming/1288C.cpp #include <algorithm> #include <iostream> using namespace std; typedef long long ll; const ll mod = 1e9 + 7; ll dp[1011][1011]; void init() { dp[0][0] = 1; dp[1][0] = 1; dp[1][1] = 1; for (int i = 2; i < 1011; i++) { dp[i][0] = 1; dp[i][1] = i; dp[i][i] = 1; for (int j = 2; j < i; j++) { dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1]; dp[i][j] %= mod; } } } int main() { int n = 0, m = 0; cin >> n >> m; init(); ll ans = 0; int pre = 0; for (int i = 1; i <= n; i++) { ans += ((dp[i + m - 1][m] - pre + mod) % mod) * (dp[m + n - i][m] % mod) % mod; ans %= mod; pre = dp[i + m - 1][m]; } cout << ans; return 0; } <file_sep>/1272C.cpp #include <iostream> #include <algorithm> #include <string> #include <map> using namespace std; int main() { int n = 0, k = 0; cin >> k >> n; string str; cin >> str; map<char, bool> can_use; for (int i = 0; i < n; i++) { char ch; cin >> ch; can_use[ch] = true; } long long left = -1; long long ans = 0; str += ' '; for (long long i = 0; i < str.size(); i++) { if (!can_use[str[i]]) { ans += (i - left) * (i - left - 1) / 2; left = i; } } cout << ans << endl; system("pause"); return 0; } <file_sep>/331C1.cpp #include <iostream> #include <algorithm> using namespace std; int arr[1000001]; int main() { int tmp = 0; cin >> tmp; for (int i = 1; i < 1000001; i++) { } } <file_sep>/1472B.cpp #include <iostream> #include <vector> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int n = 0; cin >> n; bool can_divide = true; int num_1 = 0, num_2 = 0, sum = 0; for (int j = 0; j < n; j++) { int tmp = 0; cin >> tmp; sum += tmp; if (tmp == 1) { num_1++; } else { num_2++; } } if (sum % 2) { can_divide = false; } else { if (num_1 == 0 && num_2 % 2 == 1) { can_divide = false; } } if (can_divide) { cout << "YES" << endl; } else { cout << "NO" << endl; } } system("pause"); return 0; } <file_sep>/1478.cpp #include <iostream> #include <algorithm> #include <stdlib.h> #include <vector> using namespace std; bool check(int t, int q) { if (t >= q * 10) { return true; } else { while (t >= 0) { t -= q; if (t % 10 == 0) { return true; } } } return false; } int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int size = 0, d = 0; cin >> size >> d; for (int j = 0; j < size; j++) { int t = 0; cin >> t; if (check(t, d)) { cout << "YES" << endl; } else { cout << "NO" << endl; } } } system("pause"); return 0; } <file_sep>/1042B.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; struct juice { int price = 0; string vitamin; }; int main() { int num = 0; cin >> num; vector<juice> vc(num); for (int i = 0; i < num; i++) { cin >> vc[i].price >> vc[i].vitamin; } long long min_cost = 223372036854775807; for (int i = 1; i < (1 << num); i++) { int cost = 0; bool a = false; bool b = false; bool c = false; for (int j = 0; j < num; j++) { if (i & (1 << j)) { cost += vc[j].price; for (int k = 0; k < vc[j].vitamin.size(); k++) { if (vc[j].vitamin[k] == 'A') a = true; else if (vc[j].vitamin[k] == 'B') b = true; else c = true; } if (a && b && c) break; } } if (cost < min_cost && a && b && c) min_cost = cost; } if (min_cost != 223372036854775807) cout << min_cost; else cout << -1; system("pause"); return 0; } <file_sep>/628B.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <string> #include <vector> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); string str; cin >> str; vector<ll> dp(str.size()); fill(dp.begin(), dp.end(), 0); if ((str[0] - '0') % 4 == 0) dp[0] = 1; for (int i = 1; i < str.size(); i++) { ll tmp = dp[i - 1]; ll n1 = str[i] - '0'; ll n2 = (str[i - 1] - '0') * 10 + n1; if (n1 % 4 == 0) tmp++; if (n2 % 4 == 0) tmp += i; dp[i] = tmp; } cout << dp[str.size() - 1]; system("pause"); return 0; } <file_sep>/566F.cpp #include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n = 0; int ans = 1; cin >> n; vector<int> arr(n + 1); for (int i = 1; i < n + 1; i++) { cin >> arr[i]; } vector<int> dp(arr[n] + 1, 1); for (int i = 1; i < n + 1; i++) { for (int j = 2 * arr[i]; j <= arr[n]; j += arr[i]) { dp[j] = max(dp[j], dp[arr[i]] + 1); } ans = max(ans, dp[arr[i]]); } cout << ans << endl; return 0; } <file_sep>/README.md # Answers-to-Codeforces-Problems Reference https://codeforces.com/ https://oi-wiki.org/ <file_sep>/998B.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; struct node { int bitcoin = 0; int odd = 0; }; bool cmp(node& a, node& b) { if (a.bitcoin != b.bitcoin) return a.bitcoin < b.bitcoin; else return a.odd < b.odd; } int main() { int n = 0, b = 0; cin >> n >> b; vector<int> vc(n); vector<node> arr; int odd_num = 0; int even_num = 0; for (int i = 0; i < n; i++) { cin >> vc[i]; } for (int i = 0; i < n - 1; i++) { if (vc[i] % 2) odd_num++; else even_num++; if (odd_num == even_num) { node tmp; tmp.odd = odd_num; tmp.bitcoin = abs(vc[i + 1] - vc[i]); arr.push_back(tmp); } } sort(arr.begin(), arr.end(), cmp); int ans = 0; int tmp = 0; for (int i = 0; i < arr.size(); i++) { tmp += arr[i].bitcoin; if (tmp > b) break; else ans++; } cout << ans; system("pause"); return 0; } <file_sep>/1485B.cpp #include <cmath> #include <iostream> #include <vector> using namespace std; int main() { int n = 0, q = 0, k = 0; cin >> n >> q >> k; vector<int> vc(n + 2); vc[0] = 1; vc[n + 1] = k; for (int i = 1; i < n + 1; i++) cin >> vc[i]; for (int i = 0; i < q; i++) { int l = 0, r = 0, ans = 0; cin >> l >> r; if (l != r) for (int j = l; j <= r; j++) { if (j != l && j != r) ans += vc[j + 1] - vc[j - 1] - 2; else if (j == l) ans += vc[j + 1] - 2; else ans += k - vc[j - 1] - 1; } else ans = k - 1; cout << ans << endl; } system("pause"); return 0; } <file_sep>/two pointers/1519D.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; int main() { int n = 0; cin >> n; vector<ll> a(n + 1, 0); vector<ll> b(n + 1, 0); for (int i = 1; i < n + 1; i++) cin >> a[i]; for (int i = 1; i < n + 1; i++) cin >> b[i]; vector<ll> front(n + 2, 0); vector<ll> back(n + 2, 0); ll sum = 0; ll ans = 0; for (int i = 1; i <= n; i++) { sum += (a[i] * b[i]); front[i] = sum; } sum = 0; for (int i = n; i >= 1; i--) { sum += (a[i] * b[i]); back[i] = sum; } ans = back[1]; for (int i = 1; i < n; i++) { sum = a[i] * b[i + 1] + a[i + 1] * b[i]; for (int k = 0; i - k >= 1 && i + k + 1 <= n; k++) { if (k) sum += (a[i - k] * b[i + k + 1] + a[i + k + 1] * b[i - k]); ans = max(ans, sum + front[i - k - 1] + back[i + k + 2]); } } for (int i = 2; i < n; i++) { sum = a[i] * b[i]; for (int k = 1; i - k >= 1 && i + k <= n; k++) { sum += (a[i - k] * b[i + k] + a[i + k] * b[i - k]); ans = max(ans, sum + front[i - k - 1] + back[i + k + 1]); } } cout << ans; return 0; } <file_sep>/dynamic programming/1476C.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; int main() { ll t = 0; cin >> t; while (t--) { ll n = 0; cin >> n; vector<ll> c(n), a(n), b(n); for (auto& i : c) cin >> i; for (auto& i : a) cin >> i; for (auto& i : b) cin >> i; vector<ll> dp(n, 0); ll ans = 0; for (ll i = 1; i < n; i++) { if (a[i] == b[i] || i == 1) dp[i] = 1 + c[i] + abs(b[i] - a[i]); else { dp[i] = max(abs(b[i] - a[i]) + 2 + (c[i] - 1), dp[i - 1] - abs(b[i] - a[i]) + 2 + (c[i] - 1)); } ans = max(ans, dp[i]); } cout << ans << endl; } return 0; } <file_sep>/72G.cpp #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int n0 = 1, n1 = 1, n = 0; cin >> n; if (n == 1) cout << 1; else { int cnt = 1; while (1) { n0 += n1; cnt++; if (cnt == n) { cout << n0; } n1 += n0; cnt++; if (cnt == n) { cout << n1; } } } system("pause"); return 0; } <file_sep>/327A.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int size = 0; cin >> size; vector<int> vc(size + 1); vector<vector<int>> dp; int sum = 0; int max_sum = 0; for (int i = 0; i < size + 1; i++) { vector<int> tmp(size + 1); dp.push_back(tmp); } for (int i = 1; i < size + 1; i++) { cin >> vc[i]; sum += vc[i]; } for (int i = 1; i < size + 1; i++) { dp[i][i] = sum + 1 - 2 * vc[i]; if (dp[i][i] > max_sum) { max_sum = dp[i][i]; } } for (int i = 1; i < size + 1; i++) { for (int j = i + 1; j < size + 1; j++) { dp[i][j] = dp[i][j - 1] + 1 - 2 * vc[j]; if (dp[i][j] > max_sum) { max_sum = dp[i][j]; } } } cout << max_sum; system("pause"); return 0; } <file_sep>/1475B.cpp #include <iostream> #include <stdlib.h> using namespace std; int main() { int t = 0; cin >> t; for (int i = 0; i < t; i++) { int num = 0; cin >> num; int n1 = num % 2020; int n2 = num / 2020; if (n1 <= n2) { cout << "YES" << endl; } else { cout << "NO" << endl; } } system("pause"); return 0; } <file_sep>/1469B.cpp #include <iostream> #include <algorithm> #include <stdlib.h> #include <vector> using namespace std; bool mark[1001]; int main() { int n = 0; cin >> n; int max_num = 0; int num = 0; for (int i = 1;; i++) { if (n - i >= 0) { mark[i] = true; num++; max_num = i; n -= i; } else { mark[max_num] = false; mark[max_num + n] = true; break; } } cout << num << endl; for (int i = 1; i < 1001; i++) { if (mark[i]) { cout << i << " "; } } system("pause"); return 0; } <file_sep>/1338A.cpp #include <algorithm> #include <cmath> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int size = 0; int difference = 0; cin >> size; vector<int> vc(size); int max_num = 0x80000000; for (int j = 0; j < size; j++) { cin >> vc[j]; if (vc[j] > max_num) { max_num = vc[j]; } else { difference = max(difference, max_num - vc[j]); }} for (int j = 0;; j++) { if (pow(2, j) - 1 >= difference) { cout << j << endl; break; } } } system("pause"); return 0; } <file_sep>/greedy/1389B.cpp #include <algorithm> #include <array> #include <iostream> #include <vector> using namespace std; int main() { int t = 0; cin >> t; while (t--) { int n = 0, k = 0, z = 0; cin >> n >> k >> z; vector<int> arr(n); for (int i = 0; i < n; i++) cin >> arr[i]; int sum = 0; int front = 0; int mx = 0; for (int i = 0; i < k + 1; i++) { mx = max(mx, arr[i] + arr[i + 1]); front += arr[i]; sum = max(sum, front + min((k - i) / 2, z) * mx); } cout << sum << endl; } return 0; } <file_sep>/1553B.cpp #include <algorithm> #include <iostream> #include <string> using namespace std; int main() { int t = 0; cin >> t; for (int i = 0; i < t; i++) { string s1, s2; cin >> s1 >> s2; bool found = false; for (int j = 0; j < s1.size(); j++) { int len = 0; for (len = 0; len < s2.size() && len < s1.size(); len++) { if (s1[j + len] != s2[len]) break; int _len = len + 1; for (int k = j + _len - 2; k >= 0 && _len < s2.size(); k--, _len++) { if (s1[k] != s2[_len]) break; } if (_len == s2.size()) { found = true; break; } } if (found) break; } cout << (found ? "YES" : "NO") << endl; } system("pause"); return 0; } <file_sep>/1547E.cpp #include <algorithm> #include <iostream> #include <stdint.h> #include <vector> #include <climits> using namespace std; typedef long long ll; constexpr ll inf = INT64_MAX / 2; int main() { int q = 0; cin >> q; while (q--) { int n = 0, k = 0; cin >> n >> k; vector<ll> arr(n + 1, inf); vector<ll> front(n + 2, inf); vector<ll> back(n + 2, inf); vector<ll> position(k); for (auto& p : position) cin >> p; for (int i = 0; i < k; i++) cin >> arr[position[i]]; front[1] = arr[1] - 1; back[n] = arr[n] + n; for (int i = n - 1; i > 0; i--) back[i] = min(back[i + 1], arr[i] + i); for (int i = 2; i < n + 1; i++) front[i] = min(front[i - 1], arr[i] - i); for (int i = 1; i <= n; i++) { cout << min(min(front[i - 1] + i, back[i + 1] - i), arr[i]) << " "; } cout << endl; } return 0; } <file_sep>/dynamic programming/407B.cpp #include <algorithm> #include <vector> #include <iostream> using namespace std; typedef long long ll; constexpr ll mod = 1e9 + 7; int dp[1010][1010]; int p[1010]; // dp[i][j] = dp[i][j - 1] + dp[p[j - 1]][j - 1] int dfs(int i, int j) { if (i == j) { dp[i][j] = 1; } if (dp[i][j] == 0) { dp[i][j] = dfs(i, j - 1) + dfs(p[j - 1], j - 1) + 1; } return dp[i][j] % mod; } int main() { int n = 0; cin >> n; for (int i = 1; i <= n; i++) cin >> p[i]; cout << dfs(1, n + 1) - 1 << endl; return 0; } <file_sep>/1354B_3.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <string> using namespace std; void solve() { string str; cin >> str; int arr[4] = {0, 0, 0, 0}; int i = 0, j = 0; int ans = 0x3FFFFFFF; while (j < str.size()) { arr[str[j] - '0']++; if (arr[1] && arr[2] && arr[3]) { for (; i <= j - 2; i++) { if (arr[str[i] - '0'] == 1) { if (ans > j - i + 1) ans = j - i + 1; break; } else { arr[str[i] - '0']--; } } } j++; } if (ans != 0x3FFFFFFF) cout << ans << endl; else cout << 0 << endl; } int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { solve(); } system("pause"); return 0; } <file_sep>/dynamic programming/165C.cpp // Warning! TLE #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; typedef long long ll; vector<vector<ll>> dp(100, vector<ll>(100, 0)); int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int k = 0; cin >> k; string str; cin >> str; if (k > str.size()) { cout << 0; return 0; } if (str[0] == '1') dp[1][0] = 1; else dp[0][0] = 1; ll ans = dp[k % 100][0]; int len = str.size(); for (int i = 1; i < len; i++) { if (str[i] == '1') { for (int j = 1; j <= k; j++) dp[j % 100][i % 100] = dp[(j - 1) % 100][(i - 1) % 100] + (j == 1); } else { for (int j = 0; j <= k; j++) dp[j % 100][i % 100] = dp[j % 100][(i - 1) % 100] + (j == 0); } ans += dp[k % 100][i % 100]; } cout << ans; return 0; } <file_sep>/798.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; int main() { int n = 0; cin >> n; vector<string> vc(n); for (auto& s : vc) cin >> s; bool can = true; int ans = 0x3FFFFFFF; for (int i = 0; i < n; i++) { string tmp = vc[i] + vc[i]; int sum = 0; vector<int> idx; for (int j = 0; j < n; j++) { if (tmp.find(vc[j]) != tmp.npos) { idx.push_back(tmp.find(vc[j])); } else { can = false; break; } } int max_num = 0; for (auto& i : idx) if (i > max_num) max_num = i; for (auto& i : idx) sum += (max_num - i); ans = min(ans, sum); } cout << (can ? ans : -1); system("pause"); return 0; } <file_sep>/1029B.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n = 0; cin >> n; vector<int> vc(n); for (int i = 0; i < n; i++) { cin >> vc[i]; } vector<int> dp(n); fill(dp.begin(), dp.end(), 1); int ans = 1; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (vc[i] * 2 >= vc[j] && dp[i] + 1 > dp[j]) { dp[j] = dp[i] + 1; if (dp[j] > ans) { ans = dp[j]; } break; } } } cout << ans << endl; system("pause"); return 0; } <file_sep>/1539B.cpp #include <iostream> #include <stdlib.h> #include <string> #include <algorithm> using namespace std; int main() { int n = 0, q = 0; string str; cin >> n >> q >> str; int* arr = new int[n + 1]; arr[0] = 0; int ans = 0; for (int i = 0; i < str.size(); i++) { ans += (str[i] - 'a' + 1); arr[i + 1] = ans; } for (int i = 0; i < q; i++) { int l = 0, r = 0; cin >> l >> r; cout << arr[r] - arr[l - 1] << endl; } system("pause"); return 0; } <file_sep>/626B.cpp #include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; int main() { int len = 0; cin >> len; string str; cin >> str; int r_num = 0, g_num = 0, b_num = 0; for (auto& ch : str) { if (ch == 'R') r_num++; else if (ch == 'G') g_num++; else b_num++; } if ((b_num && g_num == 0 && r_num == 0) || (b_num == 0 && g_num == 1 && r_num == 1)) cout << 'B'; else if ((g_num && b_num == 0 && r_num == 0) || (g_num == 0 && b_num == 1 && r_num == 1)) cout << 'G'; else if ((r_num && g_num == 0 && b_num == 0) || (r_num == 0 && g_num == 1 && b_num == 1)) cout << 'R'; else if ((b_num == 1 && r_num == len - 1) || (g_num == 1 && r_num == len - 1)) cout << "BG"; else if ((b_num == 1 && g_num == len - 1) || (r_num == 1 && g_num == len - 1)) cout << "BR"; else if ((g_num == 1 && b_num == len - 1) || (r_num == 1 && b_num == len - 1)) cout << "GR"; else cout << "BGR"; system("pause"); return 0; } <file_sep>/bitwise operation/1151B.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int n = 0, m = 0; cin >> n >> m; vector<vector<int>> matrix(n, vector<int>(m, 0)); for (auto& mm : matrix) for (auto& i : mm) cin >> i; int tmp = 0; for (auto& mm : matrix) tmp ^= mm[0]; if (tmp) { cout << "TAK" << endl; for (int i = 0; i < n; i++) cout << 1 << " "; return 0; } else { for (int i = 0; i < n; i++) { for (int j = 1; j < m; j++) { if (matrix[i][j] != matrix[i][0]) { cout << "TAK" << endl; for (int k = 0; k < i; k++) cout << 1 << " "; cout << j + 1 << " "; for (int k = i + 1; k < n; k++) cout << 1 << " "; return 0; } } } } cout << "NIE" << endl; return 0; } <file_sep>/greedy/913C.cpp #include <algorithm> #include <climits> #include <cmath> #include <iostream> #include <vector> using namespace std; typedef long long ll; constexpr ll inf = LONG_LONG_MAX / 2; int main() { ll n = 0; ll l = 0; ll ans = inf, tmp = 0; cin >> n >> l; vector<ll> cost(n); for (auto& c : cost) cin >> c; for (int i = 0; i < n - 1; i++) { if (cost[i] * 2 < cost[i + 1]) cost[i + 1] = 2 * cost[i]; } for (int i = n - 1; i >= 0; i--) { ll num = ll(ceil(l / pow(2, i))); ans = min(ans, num * cost[i] + tmp); tmp += ll(l / pow(2, i)) * cost[i]; l -= ll(l / pow(2, i)) * pow(2, i); } ans = min(ans, tmp); cout << ans << endl; return 0; } <file_sep>/1345B.cpp #include <algorithm> #include <iostream> #include <stdlib.h> using namespace std; int arr[25821]; void cal(int tmp, int& ans) { if (tmp <= 1) return; int lo = 1, hi = 25821; while (lo <= hi) { int mid = (lo + hi) / 2; if (arr[mid] <= tmp && arr[mid + 1] > tmp) { ans++; cal(tmp - arr[mid], ans); break; } else if (arr[mid] > tmp) { hi = mid; } else { lo = mid + 1; } } } int main() { arr[1] = 2; for (int i = 2; i < 25821; i++) { arr[i] = arr[i - 1] + 3 * i - 1; } int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int tmp = 0; cin >> tmp; int ans = 0; cal(tmp, ans); cout << ans << endl; } system("pause"); return 0; } <file_sep>/729B.cpp #include <iostream> #include <vector> using namespace std; int main() { int n = 0, m = 0; cin >> n >> m; int** graph = new int*[n + 2]; for (int i = 0; i < n + 2; i++) { graph[i] = new int[m + 2]; fill(graph[i], graph[i] + m + 2, 0); } for (int i = 1; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { cin >> graph[i][j]; if (graph[i][j]) { graph[i][m + 1]++; graph[n + 1][j]++; } } } int ans = 0; for (int i = 1; i < n + 1; i++) { for (int j = 1; j < m + 1; j++) { if (graph[i][j] == 0) ans += (graph[i][m + 1] + graph[n + 1][j]); } } cout << ans; system("pause"); return 0; } <file_sep>/dynamic programming/159D.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; typedef long long ll; int main() { string str; cin >> str; vector<vector<int>> dp(str.size(), vector<int>(str.size(), 0)); for (int i = 0; i < str.size(); i++) { dp[i][i] = 1; if (i + 1 < str.size() && str[i] == str[i + 1]) dp[i][i + 1] = 1; } for (int k = 2; k < str.size(); k++) { for (int i = 0; i + k < str.size(); i++) { dp[i][i + k] = (str[i] == str[i + k] && dp[i + 1][i + k - 1] ? 1 : 0); } } vector<ll> back(str.size(), 0); vector<ll> front(str.size(), 0); back[str.size() - 1] = 1; front[0] = 1; for (int i = str.size() - 2; i >= 0; i--) { for (int j = i; j < str.size(); j++) back[i] += dp[i][j]; back[i] += back[i + 1]; } for (int i = 1; i < str.size(); i++) { for (int j = 0; j <= i; j++) front[i] += dp[j][i]; } ll ans = 0; for (int i = 0; i < str.size() - 1; i++) { ans += front[i] * back[i + 1]; } cout << ans << endl; return 0; } <file_sep>/1406B.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { long long cnt = 0; cin >> cnt; for (long long i = 0; i < cnt; i++) { long long size = 0; cin >> size; vector<long long> vc(size); for (long long j = 0; j < size; j++) { cin >> vc[j]; } sort(vc.begin(), vc.end()); long long ans = -9223372036854775807; for (long long i = 0; i < 5; i++) { long long a1 = 1; for (long long j = 0; j < i; j++) { a1 *= vc[j]; } for (long long j = vc.size() - 1; j >= size - 5 + i; j--) { a1 *= vc[j]; } if (a1 > ans) ans = a1; } cout << ans << endl; } system("pause"); return 0; } <file_sep>/368B.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int arr[100001]; int main() { int n = 0, m = 0; cin >> n >> m; vector<int> vc(n + 1); vector<int> dp(n + 1); dp[n] = 1; for (int i = 1; i <= n; i++) { cin >> vc[i]; } arr[vc[n]] = 1; for (int i = n - 1; i >= 1; i--) { if (arr[vc[i]]) { dp[i] = dp[i + 1]; } else { dp[i] = dp[i + 1] + 1; arr[vc[i]] = 1; } } for (int i = 0; i < m; i++) { int tmp = 0; cin >> tmp; cout << dp[tmp] << endl; } system("pause"); return 0; } <file_sep>/strings/1555D.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> /* 字符串循环节 前缀和 */ using namespace std; string pattern[6] = {"abc", "acb", "cba", "cab", "bac", "bca"}; int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n = 0, m = 0; cin >> n >> m; string str; cin >> str; vector<vector<int>> arr(6, vector<int>(str.size() + 1, 0)); for (int i = 0; i < 6; i++) { int tmp = 0; for (int j = 0; j < str.size(); j++) { if (pattern[i][j % 3] != str[j]) tmp++; arr[i][j + 1] = tmp; } } while (m--) { int l = 0, r = 0; cin >> l >> r; int ans = 0x3FFFFFFF; for (int i = 0; i < 6; i++) { ans = min(ans, arr[i][r] - arr[i][l - 1]); } cout << ans << endl; } return 0; } <file_sep>/1178B.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; int main() { string str; cin >> str; int start = 0; for (; start < str.size(); start++) if (str[start] != 'o') break; vector<long long> vc; vector<long long> zc; long long v_num = 0; int cnt = 0; for (int i = start; i < str.size(); i++) { if (str[i] == 'v') v_num++; else { if (cnt == 0 && v_num > 1) { start = i; cnt++; } if (v_num > 1) vc.push_back(v_num - 1); else { if (str[i - 1] == 'v') str[i - 1] = ' '; } v_num = 0; } } long long z_num = 0; for (int i = start; i < str.size(); i++) { if (str[i] == 'o') z_num++; else if (str[i] == 'v') { if (z_num) { zc.push_back(z_num); z_num = 0; } } } if (v_num - 1 > 0) vc.push_back(v_num - 1); vector<long long> cv; long long sum = 0; for (int j = vc.size() - 1; j >= 0; j--) { sum += vc[j]; cv.push_back(sum); } long long ans = 0; if (!cv.empty() && !zc.empty()) { reverse(cv.begin(), cv.end()); for (int j = 1; j < vc.size(); j++) vc[j] += vc[j - 1]; for (int i = 0; i < vc.size() - 1; i++) { ans += vc[i] * cv[i + 1] * zc[i]; } } cout << ans; return 0; } <file_sep>/trees/763A.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int n = 0; cin >> n; vector<int> color(n + 1); vector<int> u(n - 1); vector<int> v(n - 1); vector<int> degree(n + 1); for (int i = 0; i < n - 1; i++) { cin >> u[i] >> v[i]; } for (int i = 1; i < n + 1; i++) cin >> color[i]; int num = 0; for (int i = 0; i < n - 1; i++) { if (color[u[i]] != color[v[i]]) { num++; degree[u[i]]++; degree[v[i]]++; } } for (int i = 1; i < n + 1; i++) { if (degree[i] == num) { cout << "YES" << endl << i; return 0; } } cout << "NO" << endl; return 0; } <file_sep>/961B.cpp #include <algorithm> #include <iostream> #include <map> #include <set> #include <vector> using namespace std; int main() { int n = 0, k = 0; cin >> n >> k; int sum = 0; int k_sum = 0; vector<pair<int, int>> vc(n); for (int i = 0; i < n; i++) cin >> vc[i].first; for (int i = 0; i < n; i++) { cin >> vc[i].second; if (vc[i].second == 1) sum += vc[i].first; } vector<int> dp(n); fill(dp.begin(), dp.end(), 0); for (int i = 0; i < k; i++) { if (vc[i].second == 0) dp[k - 1] += vc[i].first; } k_sum = dp[k - 1]; for (int i = k; i < n; i++) { dp[i] += dp[i - 1]; if (vc[i].second == 0) dp[i] += vc[i].first; if (vc[i - k].second == 0) dp[i] -= vc[i - k].first; if (dp[i] > k_sum) k_sum = dp[i]; } cout << k_sum + sum << endl; system("pause"); return 0; } <file_sep>/bitwise operation/1109A.cpp #include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; typedef long long ll; struct node { int odd = 0; int even = 0; }; int main() { int n = 0; cin >> n; vector<int> arr(n + 1, 0); for (int i = 1; i < n + 1; i++) { cin >> arr[i]; } map<int, node> mm; mm[0].even = 1; int tmp = 0; long long ans = 0; for (int i = 1; i < n + 1; i++) { tmp ^= arr[i]; if (i % 2) { ans += mm[tmp].odd; mm[tmp].odd++; } else { ans += mm[tmp].even; mm[tmp].even++; } } cout << ans << endl; return 0; } <file_sep>/1519B.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int n = 0, m = 0, k = 0; cin >> n >> m >> k; if (k == n - 1 + n * (m - 1) || k == m - 1 + m * (n - 1)) { cout << "YES" << endl; } else { cout << "NO" << endl; } } system("pause"); return 0; } <file_sep>/1355B.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int t = 0; cin >> t; for (int i = 0; i < t; i++) { int n = 0; cin >> n; vector<int> arr(n + 1); arr[0] = 0; for (int j = 1; j < n + 1; j++) { cin >> arr[j]; } int cnt = 0, ans = 0; sort(arr.begin(), arr.end()); for (int j = 1; j < n + 1; j++) { cnt++; if (cnt >= arr[j]) { ans++; cnt = 0; } } cout << ans << endl; } system("pause"); return 0; } <file_sep>/416B.cpp #include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int m = 0, n = 0; cin >> m >> n; vector<vector<int>> vc(m + 1); for (auto& v : vc) { v = vector<int>(n + 1); fill(v.begin(), v.end(), 0); } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) cin >> vc[i][j]; } for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { vc[i][j] = max(vc[i - 1][j], vc[i][j - 1]) + vc[i][j]; } cout << vc[i][n] << " "; } system("pause"); return 0; } <file_sep>/1180A.cpp #include <algorithm> #include <iostream> using namespace std; int main() { int n = 0; cin >> n; if (n == 1) { cout << 1; } else if (n == 2) { cout << 5; } else { int* dp = new int[n + 1]; dp[1] = 1; dp[2] = 5; for (int i = 3; i < n + 1; i++) { dp[i] = dp[i - 1] + 4 * (i - 1); } cout << dp[n]; } return 0; } <file_sep>/math/number theory/1452D.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; constexpr ll mod = 998244353; inline ll qpow(ll a, ll b) { ll ans = 1; while (b) { if (b & 1) ans = ans * a % mod; a = a * a % mod; b >>= 1; } return ans; } int main() { int n = 0; cin >> n; vector<ll> dp(n + 2); dp[1] = 1; dp[2] = 1; for (int i = 3; i < n + 2; i++) { dp[i] = (dp[i - 1] + dp[i - 2]) % mod; } ll y_ = qpow(qpow(2, n), mod - 2) % mod; cout << (dp[n] % mod) * (y_ % mod) % mod; system("pause"); return 0; } <file_sep>/1042B_2.cpp #include <iostream> #include <algorithm> #include <stdlib.h> #include <string> #include <vector> using namespace std; const int inf = 0x3FFFFFFF; int main() { int num = 0; cin >> num; vector<int> dp(8); fill(dp.begin(), dp.end(), inf); dp[0] = 0; for (int i = 0; i < num; i++) { int price = 0; string vitamin; cin >> price >> vitamin; int juice = 0; for (int j = 0; j < vitamin.size(); j++) { juice |= (1 << (vitamin[j] - 'A')); } for (int j = 0; j < 8; j++) { dp[j | juice] = min(dp[j | juice], dp[j] + price); } } cout << ((dp[7] == inf) ? -1 : dp[7]); system("pause"); return 0; } <file_sep>/919B.cpp #include <algorithm> #include <cmath> #include <iostream> #include <stdlib.h> using namespace std; int main() { int k = 0; cin >> k; int cnt = 0; int i = 19; for (; ; i++) { int sum = 0; int tmp = i; while (tmp) { sum += tmp % 10; tmp /= 10; } if (sum == 10) { cnt++; if (cnt == k) { break; } } } cout << i; system("pause"); return 0; } <file_sep>/522A.cpp #include <cctype> #include <iostream> #include <string> #include <algorithm> #include <map> #include <vector> using namespace std; int dfs(vector<vector<int>>& graph, int idx, int len) { int max_len = len; for (int i = 0; i < graph[idx].size(); i++) { int l = dfs(graph, graph[idx][i], len + 1); if (l > max_len) max_len = l; } return max_len; } int main() { int cnt = 0; cin >> cnt; vector<vector<int>> graph(2 * cnt + 1); int rank = 1; map<string, int> get_rank; for (int i = 0; i < cnt; i++) { string name1, reposted, name2; cin >> name1 >> reposted >> name2; transform(name1.begin(), name1.end(), name1.begin(), ::tolower); transform(name2.begin(), name2.end(), name2.begin(), ::tolower); if (get_rank[name1] == 0) get_rank[name1] = rank++; if (get_rank[name2] == 0) get_rank[name2] = rank++; graph[get_rank[name1]].push_back(get_rank[name2]); } int max_len = 0; for (int i = 1; i < rank; i++) { int len = dfs(graph, i, 0); if (len > max_len) max_len = len; } cout << max_len + 1; system("pause"); return 0; } <file_sep>/brute force/10B.cpp #include <algorithm> #include <climits> #include <iostream> #include <vector> using namespace std; constexpr int inf = INT_MAX / 2; int m, n, k; int matrix[1001][1001]; void solve() { int xc = (k + 1) / 2, yc = (k + 1) / 2; int sum = inf; int x = -1, yl = 0, yr = 0; for (int i = 1; i <= k; i++) { for (int j = 1; j + m - 1 <= k; j++) { int tmp = 0; bool can = true; for (int t = 0; t < m; t++) { if (matrix[i][j + t] == 1) { can = false; break; } tmp += abs(i - xc) + abs(j + t - yc); } if (can) { if (sum > tmp) { sum = tmp; x = i; yl = j; yr = j + m - 1; } } } } if (x != -1) { cout << x << " " << yl << " " << yr << endl; for (int i = yl; i <= yr; i++) matrix[x][i] = 1; } else cout << x << endl; } int main() { cin >> n >> k; for (int i = 0; i < n; i++) { cin >> m; solve(); } return 0; } <file_sep>/1538A.cpp #include <iostream> #include <vector> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int size = 0; cin >> size; int max_num = 0; int max_index = 0; int min_num = 0x3FFFFFFF; int min_index = 0; vector<int> arr(size); for (int j = 0; j < size; j++) { cin >> arr[j]; if (arr[j] > max_num) { max_num = arr[j]; max_index = j; } if (arr[j] < min_num) { min_num = arr[j]; min_index = j; } } if (min_index > max_index) { swap(min_index, max_index); } int x1 = min_index; int x2 = max_index - min_index - 1; int x3 = size - max_index - 1; cout << min(x1 + x2, min(x1 + x3, x2 + x3)) + 2 << endl; } system("pause"); return 0; } <file_sep>/search/binary search/817C.cpp // // Created by 姜伟 on 2022/1/30. // #include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; typedef long long ll; ll sum_of_digits(ll num) { ll sum = 0; while (num) { sum += num % 10; num /= 10; } return sum; } int main() { ll n = 0, s = 0; cin >> n >> s; ll l = s, r = n; ll ans = 0; while (l <= r) { ll mid = (l + r) / 2; ll diff = mid - sum_of_digits(mid); if (diff < s) { l = mid + 1; } else { r = mid - 1; } } ans = n - r; cout << ans; return 0; } <file_sep>/1200B.cpp #include <cmath> #include <cstdint> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int n = 0, m = 0, k = 0; cin >> n >> m >> k; vector<int> vc(n); for (int j = 0; j < n; j++) cin >> vc[j]; bool can = true; for (int j = 0; j < n - 1; j++) { int lo = max(vc[j + 1] - k, 0); if (vc[j] >= lo) m += vc[j] - lo; else { if (vc[j] + m >= lo) m = m - lo + vc[j]; else { can = false; break; } } } cout << (can ? "YES" : "NO") << endl; } system("pause"); return 0; } <file_sep>/dynamic programming/1489C.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; constexpr ll mod = 1e9 + 7; ll dp[1001][1001]; int t = 0, n = 0, k = 0; void solve(int n, int k) { for (int i = 0; i <= n; i++) for (int j = 0; j <= k; j++) dp[i][j] = 0; for (int i = 0; i <= n; i++) dp[i][1] = 1; for (int i = 1; i <= k; i++) dp[0][i] = 1; for (int j = 1; j <= k; j++) { for (int i = 1; i <= n; i++) { dp[i][j] = dp[i - 1][j] + dp[n - i][j - 1]; dp[i][j] %= mod; } } } int main() { cin >> t; while (t--) { cin >> n >> k; solve(n, k); cout << dp[n][k] << endl; } return 0; } <file_sep>/433B.cpp #include <iostream> #include <algorithm> #include <vector> using namespace std; typedef long long ll; int main() { ll n = 0; cin >> n; vector<ll> vc(n + 1); vector<ll> sum(n + 1); sum[0] = 0; vc[0] = 0; for (ll i = 1; i < n + 1; i++) { cin >> vc[i]; sum[i] = vc[i] + sum[i - 1]; } ll m = 0; cin >> m; sort(vc.begin(), vc.end()); vector<ll> sorted_sum(n + 1); sorted_sum[0] = 0; for (ll i = 1; i < n + 1; i++) { sorted_sum[i] = sorted_sum[i - 1] + vc[i]; } for (ll i = 0; i < m; i++) { ll type = 0, l = 0, r = 0; cin >> type >> l >> r; if (type == 1) { cout << sum[r] - sum[l - 1] << endl; } else { cout << sorted_sum[r] - sorted_sum[l - 1] << endl; } } system("pause"); return 0; } <file_sep>/1461C.cpp #include <algorithm> #include <iomanip> #include <iostream> #include <vector> using namespace std; int main() { int t = 0; cin >> t; while (t--) { int n = 0, m = 0; cin >> n >> m; vector<int> arr(n); vector<int> tmp(n); for (int i = 0; i < n; i++) { cin >> arr[i]; tmp[i] = arr[i]; } sort(tmp.begin(), tmp.end()); double ans = 0; bool sorted = true; int len = 0; for (int i = n - 1; i >= 0; i--) { if (tmp[i] != arr[i]) { sorted = false; len = i; break; } } double last = 1; for (int i = 0; i < m; i++) { int idx = 0; double prob = 0; cin >> idx >> prob; idx--; if (idx >= len) { ans += prob * last; last = (1 - prob) * last; } } if (sorted) ans = 1; cout << fixed << setprecision(6) << ans << endl; } return 0; } <file_sep>/1443B.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; ll solve(vector<ll>& diff, ll n) { ll ans = 0; for (ll i = 1; i <= n; i++) { if (diff[i] > 0) ans += diff[i]; } return ans; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll t = 0; cin >> t; for (ll i = 0; i < t; i++) { ll n = 0, q = 0; cin >> n >> q; vector<ll> vc(n + 1); vector<ll> diff(n + 1); diff[0] = 0; for (ll j = 1; j <= n; j++) cin >> vc[j]; vc.push_back(0); for (ll j = 1; j <= n; j++) diff[j] = vc[j] - vc[j + 1]; ll ans = solve(diff, n); cout << ans << endl; for (ll j = 0; j < q; j++) { ll a = 0, b = 0; cin >> a >> b; if (a > b) swap(a, b); swap(vc[a], vc[b]); if (diff[a] > 0) ans -= diff[a]; if (diff[b] > 0) ans -= diff[b]; if (diff[a - 1] > 0 && a > 1) ans -= diff[a - 1]; if (diff[b - 1] > 0 && b > 1 && b != a + 1) ans -= diff[b - 1]; diff[a] = vc[a] - vc[a + 1]; diff[a - 1] = vc[a - 1] - vc[a]; diff[b] = vc[b] - vc[b + 1]; diff[b - 1] = vc[b - 1] - vc[b]; if (diff[a] > 0) ans += diff[a]; if (diff[b] > 0) ans += diff[b]; if (diff[a - 1] > 0 && a > 1) ans += diff[a - 1]; if (diff[b - 1] > 0 && b > 1 && b - 1 != a) ans += diff[b - 1]; cout << ans << endl; } } system("pause"); return 0; } <file_sep>/trees/1336A.cpp #include <algorithm> #include <climits> #include <iostream> #include <queue> #include <vector> using namespace std; typedef long long ll; void level_order(vector<vector<ll>>& graph, vector<ll>& distance) { queue<ll> qq; distance[1] = 0; qq.push(1); vector<bool> visited(distance.size(), false); visited[1] = true; while (!qq.empty()) { ll tmp = qq.front(); qq.pop(); for (ll i = 0; i < graph[tmp].size(); i++) { if (!visited[graph[tmp][i]]) { distance[graph[tmp][i]] = distance[tmp] + 1; qq.push(graph[tmp][i]); visited[graph[tmp][i]] = true; } } } } int tree_size(vector<vector<ll>>& graph, vector<int>& child, vector<bool>& visited, int root) { visited[root] = true; for (int i = 0; i < graph[root].size(); i++) { if (!visited[graph[root][i]]) child[root] += tree_size(graph, child, visited, graph[root][i]); } return child[root]; } int main() { ll n = 0, k = 0; cin >> n >> k; vector<vector<ll>> graph(n + 1); for (ll i = 1; i < n; i++) { ll v1 = 0, v2 = 0; cin >> v1 >> v2; graph[v1].push_back(v2); graph[v2].push_back(v1); } vector<ll> distance(n + 1, INT_MAX); vector<bool> visited(n + 1, false); vector<int> child(n + 1, 1); tree_size(graph, child, visited, 1); level_order(graph, distance); for (ll i = 1; i < n + 1; i++) { distance[i] -= (child[i] - 1); } // sort(distance.begin(), distance.end(), [&g = graph](ll& a, ll& b) { // if (a != b) // { // return a < b; // } // else // { // return g[a].size() < g[b].size(); // } // }); sort(distance.begin(), distance.end(), [](ll& a, ll& b){return a > b;}); ll ans = 0; for (ll i = 1; i <= k; i++) { ans += distance[i]; } cout << ans << endl; return 0; } <file_sep>/dynamic programming/615B.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; int main() { int n = 0, m = 0; cin >> n >> m; vector<vector<ll>> graph(n + 1); for (int i = 0; i < m; i++) { int v1 = 0, v2 = 0; cin >> v1 >> v2; if (v1 > v2) swap(v1, v2); graph[v1].push_back(v2); graph[v2].push_back(v1); } vector<int> dp(n + 1, 1); ll ans = 0; for (int i = 1; i < n + 1; i++) { ans = max(ans, ll(graph[i].size())); for (int j = 0; j < graph[i].size(); j++) { if (graph[i][j] > i) { dp[graph[i][j]] = max(dp[graph[i][j]], dp[i] + 1); ans = max(ans, dp[graph[i][j]] * ll(graph[graph[i][j]].size())); } } } cout << ans << endl; return 0; } <file_sep>/dynamic programming/1513C.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; constexpr int mod = 1e9 + 7; ll arr[10][200001]; void init() { for (int i = 0; i < 200001; i++) { for (int j = 0; j < 10; j++) arr[j][i] = 1; if (i) { for (int j = 9; j >= 0; j--) { if (j == 9) arr[j][i] = arr[0][i - 1] + arr[1][i - 1]; else arr[j][i] = arr[j + 1][i - 1]; arr[j][i] %= mod; } } } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 0; cin >> t; init(); while (t--) { string n; int m = 0; cin >> n >> m; ll ans = 0; for (auto& c : n) { ans += arr[c - '0'][m]; ans %= mod; } cout << ans << endl; } return 0; } <file_sep>/1466C.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { string str; int ans = 0; cin >> str; for (int j = 0; j < str.size(); j++) { if (str[j] != ' ') { if (j + 1 < str.size() && str[j] == str[j + 1]) { ans++; str[j + 1] = ' '; } if (j + 2 < str.size() && str[j] == str[j + 2]) { ans++; str[j + 2] = ' '; } } } cout << ans << endl; } system("pause"); return 0; } <file_sep>/1415B.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int test_cases = 0; cin >> test_cases; for (int i = 0; i < test_cases; i++) { int size = 0; int queries = 0; cin >> size >> queries; vector<char> vc(size); for (int j = 0; j < size; j++) { cin >> vc[j]; } for (int j = 0; j < queries; j++) { int l = 0, r = 0; cin >> l >> r; vector<int> tmp; int rank = l - 1; int count = 0; for (int k = 0; k < size && rank < r; k++) { if (vc[k] == vc[rank]) { count++; } else { if (count) tmp.push_back(count); count = 0; k--; rank++; } } if (count) { tmp.push_back(count); } bool mark = false; if (tmp.size() == r - l + 1) for (int n : tmp) { if (n != 1) { mark = true; break; } } cout << (mark ? "YES" : "NO") << endl; } } system("pause"); return 0; } <file_sep>/1420C1.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; int solve(vector<int>& vc, vector<vector<int>>& list, int& n, int start) { int max_sum = 0; for (int i = start; i < n; i++) { int tmp = vc[i]; for (int j = 0; j < list[i].size(); j++) { int sum = solve(vc, list, n, list[i][j] + 1); if (sum + vc[i] - vc[list[i][j]] > tmp) tmp = sum + vc[i] - vc[list[i][j]]; } if (tmp > max_sum) max_sum = tmp; } return max_sum; } int main() { int t = 0; cin >> t; for (int i = 0; i < t; i++) { int n = 0, q = 0; cin >> n >> q; vector<int> vc(n); for (auto& v : vc) cin >> v; vc.push_back(0); int ans = 0; vector<vector<int>> list(n + 1); for (int j = 0; j < n; j++) { for (int k = j + 1; k < n + 1; k++) { if (vc[j] > vc[k]) list[j].push_back(k); } } cout << solve(vc, list, n, ans) << endl; } system("pause"); return 0; } <file_sep>/1499B.cpp #include <algorithm> #include <iostream> #include <string> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { string str; cin >> str; bool one_one = false; bool can = true; for (int j = 0; j + 1 < str.size(); j++) { if (str[j] == '1' && str[j + 1] == '1') { one_one = true; } if (str[j] == '0' && str[j + 1] == '0' && one_one) { can = false; } } if (can) { cout << "YES" << endl; } else { cout << "NO" << endl; } } system("pause"); return 0; } <file_sep>/1344A.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> #include <queue> using namespace std; void bfs(bool** graph, int n) { queue<int> qq; qq.push(1); bool* visited = new bool[n + 1]; fill(visited, visited + n + 1, false); int* time = new int[n + 1]; fill(time, time + n + 1, 0); visited[1] = true; while (!qq.empty()) { int tmp = qq.front(); qq.pop(); for (int i = 1; i < n + 1; i++) { if (graph[tmp][i] && !visited[i]) { qq.push(i); time[i] = time[tmp] + 1; visited[i] = true; } } } if (time[n]) cout << time[n]; else cout << -1; } int main() { int n = 0, m = 0; cin >> n >> m; bool** graph_rail = new bool*[n + 1]; bool** graph_road = new bool*[n + 1]; for (int i = 0; i < n + 1; i++) { graph_rail[i] = new bool[n + 1]; graph_road[i] = new bool[n + 1]; fill(graph_rail[i], graph_rail[i] + n + 1, false); fill(graph_road[i], graph_road[i] + n + 1, true); } for (int i = 0; i < m; i++) { int v1 = 0, v2 = 0; cin >> v1 >> v2; graph_rail[v1][v2] = true; graph_rail[v2][v1] = true; graph_road[v1][v2] = false; graph_road[v2][v1] = false; } if (graph_rail[1][n]) { bfs(graph_road, n); } else { bfs(graph_rail, n); } system("pause"); return 0; } <file_sep>/702A.cpp #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int size = 0; cin >> size; vector<int> arr(size); vector<int> dp(size); dp[0] = 1; for (int i = 0; i < size; i++) { cin >> arr[i]; } int max_len = 1; for (int i = 1; i < size; i++) { if (arr[i] > arr[i - 1]) { dp[i] = dp[i - 1] + 1; if (dp[i] > max_len) { max_len = dp[i]; } } else { dp[i] = 1; } } cout << max_len; system("pause"); return 0; } <file_sep>/dynamic programming/573B.cpp // // Created by 姜伟 on 2022/2/2. // #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int n = 0; cin >> n; vector<int> arr(n); for (int i = 0; i < n; i++) cin >> arr[i]; vector<int> front(n, 0), back(n, 0); int height = 0; for (int i = 0; i < n; i++) { if (arr[i] > height) front[i] = ++height; else { height = min(front[i - 1], arr[i]) - 1; if (arr[i] > height) { front[i] = ++height; } } } height = 0; for (int i = n - 1; i >= 0; i--) { if (arr[i] > height) back[i] = ++height; else { height = min(back[i + 1], arr[i]) - 1; if (arr[i] > height) { back[i] = ++height; } } } int ans = 0; for (int i = 0; i < n; i++) { ans = max(ans, min(front[i], back[i])); } cout << ans << endl; return 0; } <file_sep>/313B.cpp #include <algorithm> #include <iostream> #include <vector> #include <string> using namespace std; int main() { string str; cin >> str; vector<int> dp(str.size() + 1); dp[1] = 1; for (int i = 1; i < str.size(); i++) { if (str[i] == str[i - 1]) { dp[i + 1] = dp[i] + 1; } else { dp[i + 1] = dp[i]; } } int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int left = 0, right = 0; cin >> left >> right; cout << dp[right] - dp[left] << endl; } system("pause"); return 0; } <file_sep>/1598C.cpp #include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; typedef long long ll; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { double size = 0; cin >> size; map<ll, ll> mm; vector<ll> vc(size); double sum = 0; for (auto& l : vc) { cin >> l; sum += l; mm[l]++; } double avg = sum / size; ll ans = 0; if (avg - int(avg) != 0.5 && avg - int(avg) != 0) { cout << ans << endl; } else { for (auto it = mm.begin(); it != mm.end(); it++) { int l = it->first; if (mm[l]) { if (l != avg) ans += (mm[2 * avg - l] * mm[l]); else ans += (mm[l] * (mm[l] - 1)); } } cout << ans / 2 << endl; } } system("pause"); return 0; } <file_sep>/search/dfs/1528A.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef long long ll; struct node { int lo = 0; int hi = 0; vector<int> child; }; void dfs(vector<node>& tree, vector<vector<ll>>& dp, int root, int parent) { for (int i = 0; i < tree[root].child.size(); i++) { if (tree[root].child[i] != parent) { dfs(tree, dp, tree[root].child[i], root); dp[0][root] += max(abs(tree[root].lo - tree[tree[root].child[i]].lo) + dp[0][tree[root].child[i]], abs(tree[root].lo - tree[tree[root].child[i]].hi) + dp[1][tree[root].child[i]]); dp[1][root] += max(abs(tree[root].hi - tree[tree[root].child[i]].lo) + dp[0][tree[root].child[i]], abs(tree[root].hi - tree[tree[root].child[i]].hi) + dp[1][tree[root].child[i]]); } } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int t = 0; cin >> t; while (t--) { int n = 0; cin >> n; vector<node> tree(n + 1); for (int i = 1; i < n + 1; i++) cin >> tree[i].lo >> tree[i].hi; for (int i = 1; i < n; i++) { int u = 0, v = 0; cin >> u >> v; tree[u].child.push_back(v); tree[v].child.push_back(u); } vector<vector<ll>> dp(2, vector<ll>(n + 1, 0)); dfs(tree, dp, 1, -1); cout << max(dp[1][1], dp[0][1]) << endl; } return 0; } <file_sep>/1382.cpp #include <iostream> #include <vector> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int size = 0; cin >> size; vector<int> vc(size); for (int j = 0; j < size; j++) cin >> vc[j]; bool first = true; bool win = false; for (int j = 0; j < size; j++) { if (vc[j] != 1 || j == size - 1) { if (first) { win = true; } break; } else { first = !first; } } cout << (win ? "First" : "Second") << endl; } system("pause"); return 0; } <file_sep>/two pointers/814C.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; int solve(vector<char>& ch, int m, char c) { int i = 1, j = 1; int tmp = 0; int ans = 0; if (ch[j] != c) tmp = 1; while (1) { while (tmp <= m) { if (tmp == m) { if (j + 1 < ch.size() && ch[j + 1] == c) j++; else break; } else { if (j + 1 < ch.size()) { j++; if (ch[j] != c) tmp++; } } if (j == ch.size() - 1) break; } ans = max(ans, j - i + 1); while (tmp == m) { if (ch[i] != c) tmp--; i++; } if (j == ch.size() - 1) break; } return ans; } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); int n = 0; cin >> n; vector<char> ch(n + 1); for (int i = 1; i <= n; i++) { cin >> ch[i]; } int q = 0; cin >> q; for (int i = 0; i < q; i++) { int m = 0; char c; cin >> m >> c; cout << solve(ch, m, c) << endl; } return 0; } <file_sep>/761C.cpp #include <iostream> #include <algorithm> #include <string> #include <vector> using namespace std; int main() { int n = 0, m = 0; cin >> n >> m; vector<string> vc(n); for (auto& v : vc) cin >> v; vector<vector<int>> mark(n, vector<int>(3, m)); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (isdigit(vc[i][j])) mark[i][0] = min(mark[i][0], min(j, m - j)); else if (vc[i][j] >= 'a' && vc[i][j] <= 'z') mark[i][1] = min(mark[i][1], min(j, m - j)); else mark[i][2] = min(mark[i][2], min(j, m - j)); } } int ans = 0x3FFFFFFF; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { for (int k = 0; k < n; k++) { if (i != j && j != k) { ans = min(ans, mark[i][0] + mark[j][1] + mark[k][2]); } } } } cout << ans; return 0; } <file_sep>/1343C.cpp #include <algorithm> #include <iostream> #include <map> #include <stdlib.h> #include <vector> using namespace std; typedef long long ll; struct ans { ll len = 0; ll sum = 0; ll last_element = 0; }; void solve() { int size = 0; cin >> size; ans p_start, n_start; vector<ll> vc(size + 1); for (int i = 1; i < size + 1; i++) { cin >> vc[i]; } int p = 0, n = 0; for (int i = 1; i < size + 1; i++) { if (vc[i] > 0) { p_start.len = 1; p_start.sum = vc[i]; p_start.last_element = vc[i]; p = i; break; } } for (int i = 1; i < size + 1; i++) { if (vc[i] < 0) { n_start.len = 1; n_start.sum = vc[i]; n_start.last_element = vc[i]; n = i; break; } } for (int j = p + 1; j < size + 1; j++) { if (vc[j] * p_start.last_element < 0) { p_start.len++; p_start.sum += vc[j]; p_start.last_element = vc[j]; } else { if (vc[j] > p_start.last_element) { p_start.sum = p_start.sum - p_start.last_element + vc[j]; p_start.last_element = vc[j]; } } } for (int j = n + 1; j < size + 1; j++) { if (vc[j] * n_start.last_element < 0) { n_start.len++; n_start.sum += vc[j]; n_start.last_element = vc[j]; } else { if (vc[j] > n_start.last_element) { n_start.sum = n_start.sum - n_start.last_element + vc[j]; n_start.last_element = vc[j]; } } } if (p_start.len > n_start.len) { cout << p_start.sum << endl; } else { cout << n_start.sum << endl; } } int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { solve(); } system("pause"); return 0; } <file_sep>/dynamic programming/1196D2.cpp #include <algorithm> #include <iostream> #include <string> #include <vector> using namespace std; int main() { int t = 0; cin >> t; while (t--) { int n = 0, k = 0; cin >> n >> k; string str; cin >> str; string rgb = "RGB"; string gbr = "GBR"; string brg = "BRG"; vector<int> dpr(str.size(), 0); vector<int> dpg(str.size(), 0); vector<int> dpb(str.size(), 0); if (str[0] == 'R') dpr[0] = 1; else if (str[0] == 'G') dpg[0] = 1; else dpb[0] = 1; for (int i = 1; i < str.size(); i++) { int m = i % 3; if (str[i] == rgb[m]) { dpr[i] = dpr[i - 1] + 1; dpg[i] = dpg[i - 1]; dpb[i] = dpb[i - 1]; } else if (str[i] == gbr[m]) { dpg[i] = dpg[i - 1] + 1; dpb[i] = dpb[i - 1]; dpr[i] = dpr[i - 1]; } else { dpb[i] = dpb[i - 1] + 1; dpg[i] = dpg[i - 1]; dpr[i] = dpr[i - 1]; } } int ans = k; for (int i = 0; i + k - 1 < str.size(); i++) { if (i == 0) { ans = min(k - dpr[i + k - 1], ans); ans = min(k - dpg[i + k - 1], ans); ans = min(k - dpb[i + k - 1], ans); } else { ans = min(k - dpr[i + k - 1] + dpr[i - 1], ans); ans = min(k - dpg[i + k - 1] + dpg[i - 1], ans); ans = min(k - dpb[i + k - 1] + dpb[i - 1], ans); } } cout << ans << endl; } return 0; } <file_sep>/706B.cpp #include <algorithm> #include <iostream> #include <stdlib.h> #include <vector> using namespace std; int main() { int len = 0; cin >> len; vector<int> vc(len); for (int i = 0; i < len; i++) { cin >> vc[i]; } sort(vc.begin(), vc.end()); int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int tmp = 0; cin >> tmp; int left = 0, right = len; int ans = 0; while (left < right) { int mid = (left + right) / 2; if (vc[mid] <= tmp) { left = mid + 1; } else { right = mid; } } ans = left; cout << ans << endl; } system("pause"); return 0; } <file_sep>/1462B.cpp #include <iostream> #include <string> #include <algorithm> using namespace std; int main() { int cnt = 0; cin >> cnt; for (int i = 0; i < cnt; i++) { int size = 0; cin >> size; string str; cin >> str; if (str.substr(0, 4) == "2020" || str.substr(size - 4, size) == "2020") { cout << "YES" << endl; } else { if (str[0] == '2' && str.substr(size - 3, size) == "020") { cout << "YES" << endl; } else if (str.substr(0, 2) == "20" && str.substr(size - 2, size) == "20") { cout << "YES" << endl; } else if (str[size - 1] == '0' && str.substr(0, 3) == "202") { cout << "YES" << endl; } else { cout << "NO" << endl; } } } system("pause"); return 0; } <file_sep>/1206B.cpp #include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int size = 0; cin >> size; long long ans = 0; int multi = 1; bool has_zero = false; for (int i = 0; i < size; i++) { int tmp = 0; cin >> tmp; if (tmp == 0) { has_zero = true; } if (abs(tmp + 1) < abs(tmp - 1)) { multi *= -1; ans += abs(tmp + 1); } else { ans += abs(tmp - 1); } } if (multi == -1 && !has_zero) { ans += 2; } cout << ans << endl; system("pause"); return 0; } <file_sep>/651A.cpp #include <algorithm> #include <iostream> #include <stdlib.h> using namespace std; void cal(int& a1, int& a2) { a2 -= 2; a1 += 1; } int main() { int a1 = 0, a2 = 0; cin >> a1 >> a2; if (a1 < a2) swap(a1, a2); int time = 0; if (a1 < 2 && a2 < 2) { cout << 0; return 0; } while (a1 > 0 && a2 > 0) { if (a2 > 2) cal(a1, a2); else { swap(a1, a2); cal(a1, a2); } time++; } cout << time; system("pause"); return 0; } <file_sep>/games/74B.cpp #include <algorithm> #include <iostream> #include <string> using namespace std; int main() { int n = 0, m = 0, k = 0; cin >> n >> m >> k; string direction, state; cin.get(); getline(cin, direction); getline(cin, state); bool tmp = true; if (direction != "to head") tmp = false; for (int i = 0; i < state.size(); i++) { if (state[i] == '0') { if (m < k) { if (m > 1) m--; } else if (m > k) { if (m < n) m++; } } else { if (tmp == true) m = n; if (tmp == false) m = 1; } if (tmp) { if (k > 1) k--; if (k == 1) tmp = false; } else { if (k < n) k++; if (k == n) tmp = true; } if (k == m) { cout << "Controller " << i + 1 << endl; return 0; } } cout << "Stowaway" << endl; return 0; } <file_sep>/1113A.cpp #include <algorithm> #include <iostream> #include <stdlib.h> using namespace std; int main() { int n = 0, v = 0; cin >> n >> v; int ans = 0; int rest = 0; int to_go = n - 1; for (int i = 1; i <= n; i++) { if (i != 1) { rest--; } int capacity = v - rest; if (capacity <= to_go) { ans += capacity * i; rest = v; to_go -= capacity; } else { ans += to_go * i; to_go = 0; rest += to_go; } } cout << ans; system("pause"); return 0; }
03865b47085ede07ac03511541b9d9f054076c26
[ "Markdown", "C++" ]
87
C++
JiangWeibeta/Answers-to-Codeforces-Problemset
f258ed0d441f587551ae0fc55215dca189a9dcef
23bb39c88ecca3070dc0358784d18497bb826040
refs/heads/master
<file_sep>import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; /** * Created by AFrangopoulos on 4/22/2017. */ public class PrimeNumberTest { private final int EVEN_BOTTOM = 4; private final int EVEN_TOP = 100;//Pick any even number you want to test to. private PrimeNumber number; private List<Integer> list; @Before //do any initializations or any ctor work here public void before(){ number = new PrimeNumber(); list = new ArrayList<>(); } //Primality Tests @Test public void isANaturalNumber(){ //0 to infinity are Natural. Negative numbers are not. Must be positive counting number, but 'int' takes care of that. Assert.assertFalse("-7 is not a natural number and therefore not prime.",number.isPrime(-7)); } @Test public void zeroAndOneAreNotPrime(){ Assert.assertFalse("0 is not prime", number.isPrime(0)); Assert.assertFalse("1 is not prime", number.isPrime(1)); } @Test public void twoIsPrime(){ Assert.assertTrue("2 is a prime number.", number.isPrime(2)); } @Test//check arbitrary amount of even numbers for primality public void evenNumbersExceptTwoAreNotPrime(){ for(int i = EVEN_BOTTOM; i <= EVEN_TOP; i += 2) { String s = String.valueOf(i) + " is not prime."; Assert.assertFalse(s, number.isPrime(i)); } } @Test public void isOnlyDivisibleByOneAndItself(){ //even numbers have been checked already, so let's check some odd numbers that are not prime Assert.assertFalse("21 is not prime", number.isPrime(21)); Assert.assertFalse("35 is not prime", number.isPrime(35)); } //generate() Tests @Test public void generateReturnsANonEmptyListStandardRange(){ list = number.generate(7900,7920); Assert.assertTrue("generate did not add primes to list",!list.isEmpty()); } @Test public void generateReturnsValuesWithInclusiveRange(){ list = number.generate(1,11);//11 should be last element in the list. Assert.assertTrue("not inclusive", list.contains(11)); } @Test public void generateReturnsNonEmptyListWithInvertedRange(){ list = number.generate(10,1); Assert.assertFalse("list should not be empty", list.isEmpty()); } @Test public void generateReturnsSameListForStdAndInvertedRange(){ list = number.generate(1,100); List<Integer> tempList = number.generate(100,1); Assert.assertTrue("Lists are not equal with same range", list.equals(tempList)); } @Test public void generateReturnsEmptyListWhenNoValidPrimesInRange(){ list = number.generate(-100,-1); Assert.assertTrue("",list.isEmpty()); list = number.generate(-2,1); Assert.assertTrue("",list.isEmpty()); list = number.generate(1,-3); Assert.assertTrue("",list.isEmpty()); list = number.generate(1,1); Assert.assertTrue("",list.isEmpty()); } }
1bb872b7d47bbe38cfa1bac99dc3c29ab148c59e
[ "Java" ]
1
Java
AMF1107/PrimeNumberGenerator
3fd227ae2489376ae1c3d3952dd9838611b14211
aa557a7f5aab0e9fe39dca2dd91714ceb9884a2f
refs/heads/master
<repo_name>ZeeCoder/vk-elso-epizod<file_sep>/game/Scripts/Mirror_effect.rb # NOT UPDATED ! #============================================================================== # ■ Sprite_Mirror # Based on Sprite_Shadow, modified by Rataime #============================================================================== class Sprite_Mirror < RPG::Sprite attr_accessor :character attr_accessor :events attr_accessor :event_y def initialize(viewport=nil) super(viewport) @character = $game_player @events=0 @event_y=0 self.opacity=0 update end def update super if @tile_id != @character.tile_id or @character_name != @character.character_name or @character_hue != @character.character_hue @tile_id = @character.tile_id @character_name = @character.character_name @character_hue = @character.character_hue if @tile_id >= 384 self.bitmap = RPG::Cache.tile($game_map.tileset_name, @tile_id, @character.character_hue) self.src_rect.set(0, 0, 32, 32) self.ox = 16 self.oy = 32 else self.bitmap = RPG::Cache.character(@character.character_name, @character.character_hue) @cw = bitmap.width / 4 @ch = bitmap.height / 4 self.ox = @cw / 2 self.oy = @ch end end self.visible = (not @character.transparent) if @tile_id == 0 sx = (@character.pattern) * @cw sy = (@character.direction - 2) / 2 * @ch if @character.direction==8 sy = 0 * @ch end if @character.direction==2 sy = 3 * @ch end self.src_rect.set(sx, sy, @cw, @ch) end self.x = @character.screen_x self.y = self.event_y-($game_player.screen_y-self.event_y).abs+30 self.z = 10 self.blend_type = @character.blend_type self.bush_depth = @character.bush_depth if @character.animation_id != 0 animation = $data_animations[@character.animation_id] animation(animation, true) @character.animation_id = 0 end end end #=================================================== # ▼ CLASS Sprite_Character edit #=================================================== class Sprite_Character < RPG::Sprite alias mirror_initialize initialize def initialize(viewport, character = nil) @character = character super(viewport) if character.is_a?(Game_Player) $game_map.mirror=Sprite_Mirror.new(viewport) end mirror_initialize(viewport, @character) end alias mirror_update update def update mirror_update if (@mirror!=nil and character.is_a?(Game_Event) and character.list!=nil and character.list[0].code == 108 and character.list[0].parameters == ["m"]) if $game_player.screen_y-self.y<80 and self.y<$game_player.screen_y and ($game_player.screen_x-self.x).abs<17 if (character.list[1]!=nil and character.list[1].code == 108) @mirror.opacity=character.list[1].parameters[0].to_f else @mirror.opacity=$game_player.opacity end @mirror.events=self.id @mirror.event_y=self.y else if @mirror.events==self.id @mirror.events=0 else if @mirror.events==0 @mirror.opacity=0 end end end end @mirror=$game_map.mirror if character.is_a?(Game_Player) @mirror.update end end end #=================================================== # ▼ CLASS Scene_Save edit #=================================================== class Scene_Save < Scene_File alias mirror_write_save_data write_save_data def write_save_data(file) $game_map.mirror = nil mirror_write_save_data(file) end end #=================================================== # ▼ CLASS Game_Map edit #=================================================== class Game_Map attr_accessor :mirror end #=================================================== # ▼ CLASS Scene_Map edit #=================================================== class Spriteset_Map alias mirror_map_initialize initialize def initialize $game_map.mirror=nil mirror_map_initialize end end <file_sep>/game/Scripts/Message.rb #=================================================== # ■ AMS - Advanced Message Script - R4 [Update #2] #=================================================== # For more infos and update, visit: # www.dubealex.com (Creation Asylum) # # Edited, Fixed and Enhanced by: Dubealex # Original Script Core by: XRXS Scripter (<NAME>) # HTML Hexadecimal color feature from: Phylomorphis # # Special Thanks: # Rabu: For enabling the Show Face feature in an encrypted project # # To found all my new features, search the following: #NEW # To configure the button to skip the dialog, search: #SKIP_TEXT_CODE # # May 18, 2005 #=================================================== LETTER_BY_LETTER_MODE = true #Set the letter by letter mode ON/OFF #=================================================== # ▼ CLASS AMS Begins #=================================================== class AMS attr_accessor :name_box_x_offset attr_accessor :name_box_y_offset attr_accessor :font_type attr_accessor :name_font_type attr_accessor :font_size attr_accessor :name_font_size attr_accessor :message_box_opacity attr_accessor :name_box_skin attr_accessor :name_box_text_color attr_accessor :message_box_text_color attr_accessor :message_box_skin attr_accessor :name_box_width attr_accessor :name_box_height attr_accessor :message_width attr_accessor :message_height attr_accessor :message_x attr_accessor :message_y_bottom attr_accessor :message_y_middle attr_accessor :message_y_top attr_accessor :event_message_x_ofset attr_accessor :event_message_y_ofset def initialize @name_box_x_offset = 0 #Choose the X axis offset of the name bos. default= 0 @name_box_y_offset = -10 #Choose the Y axis offset of the name bos. default= -10 @name_box_width = 8 #Choose the width of the Name Box. default= 8 @name_box_height = 26 #Choose the height of the Name Box. default= 26 @font_type = "Tahoma" #Choose the Font Name (Case Sensitive) for message box @name_font_type = "Tahoma" #Choose the Font Name (Case Sensitive) for Name Box @font_size = 22 #Choose the default Font Size for message box text @name_font_size = 22 #Choose the deafault Font Size for Name Box text @name_box_text_color=0 #Choose the Text Color of the Name Box @message_box_text_color=0 #Choose the Text Color of the Message Box @message_box_opacity = 160 #Choose the opacity of the message window. Default=160 @message_box_skin = "001-Blue01" #Choose the WindowSkin for the Message Box @name_box_skin = "001-Blue01" #Choose the WindowSkin for the Name Box @message_width = 480 #Choose the width size of the message box. Default=480 @message_height = 160 #Choose the height size of the message box. Default=160 @message_x = 80 #Choose the X position of the message box. Default=80 @message_y_bottom = 304 #Choose the Y bottom position of the message box. Default=304 @message_y_middle = 160 #Choose the Y middle position of the message box. Default=160 @message_y_top = 16 #Choose the Y top position of the message box. Default=16 @event_message_x_ofset = 0 #Choose the X position offset of the event message. Default=0 @event_message_y_ofset = 48 #Choose the Y position offset of the event message. Default=48 end end #=================================================== # ▲ CLASS AMS Ends #=================================================== #=================================================== # ▼ Class Window_Message Begins #=================================================== class Window_Message < Window_Selectable alias xrxs9_initialize initialize def initialize @alex_skip = false xrxs9_initialize if $soundname_on_speak == nil then $soundname_on_speak = "" end $gaiji_file = "./Graphics/Gaiji/sample.png" if FileTest.exist?($gaiji_file) @gaiji_cache = Bitmap.new($gaiji_file) else @gaigi_cache = nil end @opacity_text_buf = Bitmap.new(32, 32) end #-------------------------------------------------------------------------- alias xrxs9_terminate_message terminate_message def terminate_message if @name_window_frame != nil @name_window_frame.dispose @name_window_frame = nil end if @name_window_text != nil @name_window_text.dispose @name_window_text = nil end xrxs9_terminate_message end #-------------------------------------------------------------------------- def refresh self.contents.clear self.contents.font.color = text_color($ams.message_box_text_color) self.contents.font.name = $ams.font_type self.contents.font.size = $ams.font_size self.windowskin = RPG::Cache.windowskin($ams.message_box_skin) @x = @y = @max_x = @max_y = @indent = @lines = 0 @face_indent = 0 @opacity = 255 @cursor_width = 0 @write_speed = 0 @write_wait = 0 @mid_stop = false @face_file = nil @popchar = -2 if $game_temp.choice_start == 0 @x = 8 end if $game_temp.message_text != nil @now_text = $game_temp.message_text if (/\A\\[Ff]\[(.+?)\]/.match(@now_text))!=nil then @face_file = $1 + ".png" @x = @face_indent = 128 if FileTest.exist?("Graphics/Pictures/" + $1 + ".png") self.contents.blt(16, 16, RPG::Cache.picture(@face_file), Rect.new(0, 0, 96, 96)) end @now_text.gsub!(/\\[Ff]\[(.*?)\]/) { "" } end begin last_text = @now_text.clone @now_text.gsub!(/\\[Vv]\[([IiWwAaSs]?)([0-9]+)\]/) { convart_value($1, $2.to_i) } end until @now_text == last_text @now_text.gsub!(/\\[Nn]\[([0-9]+)\]/) do $game_actors[$1.to_i] != nil ? $game_actors[$1.to_i].name : "" end #NEW #Dubealex's Stop Skip Text ON-OFF @now_text.gsub!(/\\[%]/) { "\100" } #End new command #NEW #Dubealex's Show Monster Name Feature @now_text.gsub!(/\\[Mm]\[([0-9]+)\]/) do $data_enemies[$1.to_i] != nil ? $data_enemies[$1.to_i].name : "" end #End new command #NEW #Dubealex's Show Item Price Feature @now_text.gsub!(/\\[Pp]rice\[([0-9]+)\]/) do $data_items[$1.to_i] != nil ? $data_items[$1.to_i].price : "" end #End new command #NEW #Dubealex's Show Hero Class Name Feature @now_text.gsub!(/\\[Cc]lass\[([0-9]+)\]/) do $data_classes[$data_actors[$1.to_i].class_id] != nil ? $data_classes[$data_actors[$1.to_i].class_id].name : "" end #End new command #NEW #Dubealex's Show Current Map Name Feature @now_text.gsub!(/\\[Mm]ap/) do $game_map.name != nil ? $game_map.name : "" end #End new command #NEW #Dubealex's Choose Name Box Text Color @now_text.gsub!(/\\[Zz]\[([0-9]+)\]/) do $ams.name_box_text_color=$1.to_i @now_text.sub!(/\\[Zz]\[([0-9]+)\]/) { "" } end #End new command name_window_set = false if (/\\[Nn]ame\[(.+?)\]/.match(@now_text)) != nil name_window_set = true name_text = $1 @now_text.sub!(/\\[Nn]ame\[(.*?)\]/) { "" } end if (/\\[Pp]\[([-1,0-9]+)\]/.match(@now_text))!=nil then @popchar = $1.to_i if @popchar == -1 @x = @indent = 48 @y = 4 end @now_text.gsub!(/\\[Pp]\[([-1,0-9]+)\]/) { "" } end @max_choice_x = 0 if @popchar >= 0 @text_save = @now_text.clone @max_x = 0 @max_y = 4 for i in 0..3 line = @now_text.split(/\n/)[3-i] @max_y -= 1 if line == nil and @max_y <= 4-i next if line == nil line.gsub!(/\\\w\[(\w+)\]/) { "" } cx = contents.text_size(line).width @max_x = cx if cx > @max_x if i >= $game_temp.choice_start @max_choice_x = cx if cx > @max_choice_x end end self.width = @max_x + 32 + @face_indent self.height = (@max_y - 1) * 32 + 64 @max_choice_x -= 68 @max_choice_x -= @face_indent*216/128 else @max_x = self.width - 32 - @face_indent for i in 0..3 line = @now_text.split(/\n/)[i] next if line == nil line.gsub!(/\\\w\[(\w+)\]/) { "" } cx = contents.text_size(line).width if i >= $game_temp.choice_start @max_choice_x = cx if cx > @max_choice_x end end @max_choice_x += 8 end @cursor_width = 0 @now_text.gsub!(/\\\\/) { "\000" } @now_text.gsub!(/\\[Cc]\[([0123456789ABCDEF#]+)\]/) { "\001[#{$1}]" } @now_text.gsub!(/\\[Gg]/) { "\002" } @now_text.gsub!(/\\[Ss]\[([0-9]+)\]/) { "\003[#{$1}]" } @now_text.gsub!(/\\[Aa]\[(.*?)\]/) { "\004[#{$1}]" } #NEW #Dubealex's Permanent Color Change @now_text.gsub!(/\\[Cc]olor\[([0-9]+)\]/) do $ams.message_box_text_color= $1.to_i @now_text.sub!(/\\[Cc]\[([0-9]+)\]/) { "" } end #End of new command #NEW #Dubealex's Font Change Feature @now_text.gsub(/\\[Tt]\[(.*?)\]/) do buftxt = $1.to_s $ams.font_type = buftxt @now_text.sub!(/\\[Tt]\[(.*?)\]/) { "" } end #End of new command @now_text.gsub!(/\\[.]/) { "\005" } @now_text.gsub!(/\\[|]/) { "\006" } @now_text.gsub!(/\\[>]/) { "\016" } @now_text.gsub!(/\\[<]/) { "\017" } @now_text.gsub!(/\\[!]/) { "\020" } @now_text.gsub!(/\\[~]/) { "\021" } @now_text.gsub!(/\\[Ee]\[([0-9]+)\]/) { "\022[#{$1}]" } @now_text.gsub!(/\\[Ii]/) { "\023" } @now_text.gsub!(/\\[Oo]\[([0-9]+)\]/) { "\024[#{$1}]" } @now_text.gsub!(/\\[Hh]\[([0-9]+)\]/) { "\025[#{$1}]" } @now_text.gsub!(/\\[Bb]\[([0-9]+)\]/) { "\026[#{$1}]" } @now_text.gsub!(/\\[Rr]\[(.*?)\]/) { "\027[#{$1}]" } reset_window if name_window_set color=$ams.name_box_text_color off_x = $ams.name_box_x_offset off_y = $ams.name_box_y_offset space = 2 x = self.x + off_x - space / 2 y = self.y + off_y - space / 2 w = self.contents.text_size(name_text).width + $ams.name_box_width + space h = $ams.name_box_height + space @name_window_frame = Window_Frame.new(x, y, w, h) @name_window_frame.z = self.z + 1 x = self.x + off_x + 4 y = self.y + off_y @name_window_text = Air_Text.new(x, y, name_text, color) @name_window_text.z = self.z + 2 end end reset_window if $game_temp.choice_max > 0 @item_max = $game_temp.choice_max self.active = true self.index = 0 end if $game_temp.num_input_variable_id > 0 digits_max = $game_temp.num_input_digits_max number = $game_variables[$game_temp.num_input_variable_id] @input_number_window = Window_InputNumber.new(digits_max) @input_number_window.number = number @input_number_window.x = self.x + 8 @input_number_window.y = self.y + $game_temp.num_input_start * 32 end end #-------------------------------------------------------------------------- def update super if @fade_in self.contents_opacity += 24 if @input_number_window != nil @input_number_window.contents_opacity += 24 end if self.contents_opacity == 255 @fade_in = false end return end @now_text = nil if @now_text == "" if @now_text != nil and @mid_stop == false if @write_wait > 0 @write_wait -= 1 return end text_not_skip = LETTER_BY_LETTER_MODE while true @max_x = @x if @max_x < @x @max_y = @y if @max_y < @y if (c = @now_text.slice!(/./m)) != nil if c == "\000" c = "\\" end if c == "\001" @now_text.sub!(/\[([0123456789ABCDEF#]+)\]/, "") temp_color = $1 color = temp_color.to_i leading_x = temp_color.to_s.slice!(/./m) if leading_x == "#" self.contents.font.color = hex_color(temp_color) next end if color >= 0 and color <= 7 self.contents.font.color = text_color(color) end next end if c == "\002" if @gold_window == nil and @popchar <= 0 @gold_window = Window_Gold.new @gold_window.x = 560 - @gold_window.width if $game_temp.in_battle @gold_window.y = 192 else @gold_window.y = self.y >= 128 ? 32 : 384 end @gold_window.opacity = self.opacity @gold_window.back_opacity = self.back_opacity end c = "" end if c == "\003" @now_text.sub!(/\[([0-9]+)\]/, "") speed = $1.to_i if speed >= 0 and speed <= 19 @write_speed = speed end c = "" end if c == "\004" @now_text.sub!(/\[(.*?)\]/, "") buftxt = $1.dup.to_s if buftxt.match(/\//) == nil and buftxt != "" then $soundname_on_speak = "Audio/SE/" + buftxt else $soundname_on_speak = buftxt.dup end c = "" elsif c == "\004" c = "" end if c == "\005" @write_wait += 5 c = "" end if c == "\006" @write_wait += 20 c = "" end if c == "\016" text_not_skip = false c = "" end if c == "\017" text_not_skip = true c = "" end if c == "\020" @mid_stop = true c = "" end if c == "\021" terminate_message return end if c == "\023" @indent = @x c = "" end if c == "\024" @now_text.sub!(/\[([0-9]+)\]/, "") @opacity = $1.to_i color = self.contents.font.color self.contents.font.name = $ams.font_type self.contents.font.size = $ams.font_size self.contents.font.color = Color.new(color.red, color.green, color.blue, color.alpha * @opacity / 255) c = "" end if c == "\025" @now_text.sub!(/\[([0-9]+)\]/, "") self.contents.font.size = [[$1.to_i, 6].max, 32].min c = "" end if c == "\026" @now_text.sub!(/\[([0-9]+)\]/, "") @x += $1.to_i c = "" end if c == "\027" @now_text.sub!(/\[(.*?)\]/, "") @x += ruby_draw_text(self.contents, @x, @y * line_height + (line_height - self.contents.font.size), $1, @opacity) if $soundname_on_speak != "" Audio.se_play($soundname_on_speak) end c = "" end if c == "\030" @now_text.sub!(/\[(.*?)\]/, "") self.contents.blt(@x , @y * line_height + 8, RPG::Cache.icon($1), Rect.new(0, 0, 24, 24)) if $soundname_on_speak != "" Audio.se_play($soundname_on_speak) end @x += 24 c = "" end if c == "\n" @lines += 1 @y += 1 @x = 0 + @indent + @face_indent if @lines >= $game_temp.choice_start @x = 8 + @indent + @face_indent @cursor_width = @max_choice_x end c = "" end if c == "\022" @now_text.sub!(/\[([0-9]+)\]/, "") @x += gaiji_draw(4 + @x, @y * line_height + (line_height - self.contents.font.size), $1.to_i) c = "" end #NEW #Dubealex's Text Skip On/OFF Command if c == "\100" if @alex_skip==false @alex_skip=true else @alex_skip=false end c = "" end #end of new command if c != "" self.contents.draw_text(0+@x, 32 * @y, 40, 32, c) @x += self.contents.text_size(c).width if $soundname_on_speak != "" then Audio.se_play($soundname_on_speak) end end #SKIP_TEXT_CODE # B = Escape, 0 (On The NumPad), X # C = Enter, Space Bar and C # A = Shift, Z if Input.press?(Input::C) # <-- Change the value on that line if @alex_skip==false text_not_skip = false end end else text_not_skip = true break end if text_not_skip break end end @write_wait += @write_speed return end if @input_number_window != nil @input_number_window.update if Input.trigger?(Input::C) $game_system.se_play($data_system.decision_se) $game_variables[$game_temp.num_input_variable_id] = @input_number_window.number $game_map.need_refresh = true @input_number_window.dispose @input_number_window = nil terminate_message end return end if @contents_showing if $game_temp.choice_max == 0 self.pause = true end if Input.trigger?(Input::B) if $game_temp.choice_max > 0 and $game_temp.choice_cancel_type > 0 $game_system.se_play($data_system.cancel_se) $game_temp.choice_proc.call($game_temp.choice_cancel_type - 1) terminate_message end end if Input.trigger?(Input::C) if $game_temp.choice_max > 0 $game_system.se_play($data_system.decision_se) $game_temp.choice_proc.call(self.index) end if @mid_stop @mid_stop = false return else terminate_message end end return end if @fade_out == false and $game_temp.message_text != nil @contents_showing = true $game_temp.message_window_showing = true refresh Graphics.frame_reset self.visible = true self.contents_opacity = 0 if @input_number_window != nil @input_number_window.contents_opacity = 0 end @fade_in = true return end if self.visible @fade_out = true self.opacity -= 48 if self.opacity == 0 self.visible = false @fade_out = false $game_temp.message_window_showing = false end return end end #-------------------------------------------------------------------------- def get_character(parameter) case parameter when 0 return $game_player else events = $game_map.events return events == nil ? nil : events[parameter] end end #-------------------------------------------------------------------------- def reset_window #MESSAGE_SIZE #MESSAGE_POSITION if @popchar >= 0 events = $game_map.events if events != nil character = get_character(@popchar) x = [[character.screen_x - $ams.event_message_x_ofset - self.width / 2, 4].max, 636 - self.width].min y = [[character.screen_y - $ams.event_message_y_ofset - self.height, 4].max, 476 - self.height].min self.x = x self.y = y end elsif @popchar == -1 self.x = -4 self.y = -4 self.width = 648 self.height = 488 else if $game_temp.in_battle self.y = 16 else case $game_system.message_position when 0 self.y = $ams.message_y_top when 1 self.y = $ams.message_y_middle when 2 self.y = $ams.message_y_bottom end self.x = $ams.message_x if @face_file == nil self.width = $ams.message_width self.x = $ams.message_x else if self.width <= 600 self.width = 600 self.x -=60 end end self.height = $ams.message_height end end self.contents = Bitmap.new(self.width - 32, self.height - 32) self.contents.font.color = text_color($ams.message_box_text_color) self.contents.font.name = $ams.font_type self.contents.font.size = $ams.font_size if @face_file != nil self.contents.blt(16, 16, RPG::Cache.picture(@face_file), Rect.new(0, 0, 96, 96)) end if @popchar == -1 self.opacity = 255 self.back_opacity = 0 elsif $game_system.message_frame == 0 self.opacity = 255 self.back_opacity = $ams.message_box_opacity else self.opacity = 0 self.back_opacity = $ams.message_box_opacity end end #-------------------------------------------------------------------------- def gaiji_draw(x, y, num) if @gaiji_cache == nil return 0 else if @gaiji_cache.width < num * 24 return 0 end if self.contents.font.size >= 20 and self.contents.font.size <= 24 size = 24 else size = self.contents.font.size * 100 * 24 / 2200 end self.contents.stretch_blt(Rect.new(x, y, size, size), @gaiji_cache, Rect.new(num * 24, 0, 24, 24)) if $soundname_on_speak != "" then Audio.se_play($soundname_on_speak) end return size end end #-------------------------------------------------------------------------- def line_height return 32 if self.contents.font.size >= 20 and self.contents.font.size <= 24 return 32 else return self.contents.font.size * 15 / 10 end end #-------------------------------------------------------------------------- def ruby_draw_text(target, x, y, str,opacity) sizeback = target.font.size target.font.size * 3 / 2 > 32 ? rubysize = 32 - target.font.size : rubysize = target.font.size / 2 rubysize = [rubysize, 6].max opacity = [[opacity, 0].max, 255].min split_s = str.split(/,/) split_s[0] == nil ? split_s[0] = "" : nil split_s[1] == nil ? split_s[1] = "" : nil height = sizeback + rubysize width = target.text_size(split_s[0]).width target.font.size = rubysize ruby_width = target.text_size(split_s[1]).width target.font.size = sizeback buf_width = [target.text_size(split_s[0]).width, ruby_width].max width - ruby_width != 0 ? sub_x = (width - ruby_width) / 2 : sub_x = 0 if opacity == 255 target.font.size = rubysize target.draw_text(x + sub_x, y - target.font.size, target.text_size(split_s[1]).width, target.font.size, split_s[1]) target.font.size = sizeback target.draw_text(x, y, width, target.font.size, split_s[0]) return width else if @opacity_text_buf.width < buf_width or @opacity_text_buf.height < height @opacity_text_buf.dispose @opacity_text_buf = Bitmap.new(buf_width, height) else @opacity_text_buf.clear end @opacity_text_buf.font.size = rubysize @opacity_text_buf.draw_text(0 , 0, buf_width, rubysize, split_s[1], 1) @opacity_text_buf.font.size = sizeback @opacity_text_buf.draw_text(0 , rubysize, buf_width, sizeback, split_s[0], 1) if sub_x >= 0 target.blt(x, y - rubysize, @opacity_text_buf, Rect.new(0, 0, buf_width, height), opacity) else target.blt(x + sub_x, y - rubysize, @opacity_text_buf, Rect.new(0, 0, buf_width, height), opacity) end return width end end #-------------------------------------------------------------------------- def convart_value(option, index) option == nil ? option = "" : nil option.downcase! case option when "i" unless $data_items[index].name == nil r = sprintf("\030[%s]%s", $data_items[index].icon_name, $data_items[index].name) end when "w" unless $data_weapons[index].name == nil r = sprintf("\030[%s]%s", $data_weapons[index].icon_name, $data_weapons[index].name) end when "a" unless $data_armors[index].name == nil r = sprintf("\030[%s]%s", $data_armors[index].icon_name, $data_armors[index].name) end when "s" unless $data_skills[index].name == nil r = sprintf("\030[%s]%s", $data_skills[index].icon_name, $data_skills[index].name) end else r = $game_variables[index] end r == nil ? r = "" : nil return r end #-------------------------------------------------------------------------- def dispose terminate_message if @gaiji_cache != nil unless @gaiji_cache.disposed? @gaiji_cache.dispose end end unless @opacity_text_buf.disposed? @opacity_text_buf.dispose end $game_temp.message_window_showing = false if @input_number_window != nil @input_number_window.dispose end super end #-------------------------------------------------------------------------- def update_cursor_rect if @index >= 0 n = $game_temp.choice_start + @index self.cursor_rect.set(8 + @indent + @face_indent, n * 32, @cursor_width, 32) else self.cursor_rect.empty end end end #========================================= # ▲ CLASS Window_Message Ends #========================================= #========================================= # ▼ Class Window_Frame Begins #========================================= class Window_Frame < Window_Base def initialize(x, y, width, height) super(x, y, width, height) self.windowskin = RPG::Cache.windowskin($ams.name_box_skin) self.contents = nil end #-------------------------------------------------------------------------- def dispose super end end #========================================= # ▲ CLASS Window_Frame Ends #========================================= #========================================= # ▼ CLASS Game_Map Additional Code Begins #========================================= class Game_Map #Dubealex's Addition (from XRXS) to show Map Name on screen def name $map_infos[@map_id] end end #========================================= # ▲ CLASS Game_Map Additional Code Ends #========================================= #========================================= # ▼ CLASS Scene_Title Additional Code Begins #========================================= class Scene_Title #Dubealex's Addition (from XRXS) to show Map Name on screen $map_infos = load_data("Data/MapInfos.rxdata") for key in $map_infos.keys $map_infos[key] = $map_infos[key].name end #Dubealex's addition to save data from the AMS in the save files $ams = AMS.new end #========================================= # ▲ CLASS Scene_Title Additional Code Ends #========================================= #========================================= # ▼ CLASS Window_Base Additional Code Begins #========================================= class Window_Base < Window #Dubealex Addition (from Phylomorphis) to use HTML Hex Code Colors def hex_color(string) red = 0 green = 0 blue = 0 if string.size != 6 print("Hex strings must be six characters long.") print("White text will be used.") return Color.new(255, 255, 255, 255) end for i in 1..6 s = string.slice!(/./m) if s == "#" print("Hex color string may not contain the \"#\" character.") print("White text will be used.") return Color.new(255, 255, 255, 255) end value = hex_convert(s) if value == -1 print("Error converting hex value.") print("White text will be used.") return Color.new(255, 255, 255, 255) end case i when 1 red += value * 16 when 2 red += value when 3 green += value * 16 when 4 green += value when 5 blue += value * 16 when 6 blue += value end end return Color.new(red, green, blue, 255) end #-------------------------------------------------------------------------- def hex_convert(character) case character when "0" return 0 when "1" return 1 when "2" return 2 when "3" return 3 when "4" return 4 when "5" return 5 when "6" return 6 when "7" return 7 when "8" return 8 when "9" return 9 when "A" return 10 when "B" return 11 when "C" return 12 when "D" return 13 when "E" return 14 when "F" return 15 end return -1 end end #========================================= # ▲ CLASS Window_Base Additional Code Ends #========================================= #========================================= # ▼ Class Air_Text Begins #========================================= class Air_Text < Window_Base def initialize(x, y, designate_text, color=0) super(x-16, y-16, 32 + designate_text.size * 12, 56) self.opacity = 0 self.back_opacity = 0 self.contents = Bitmap.new(self.width - 32, self.height - 32) w = self.contents.width h = self.contents.height self.contents.font.name = $ams.name_font_type self.contents.font.size = $ams.name_font_size self.contents.font.color = text_color(color) self.contents.draw_text(0, 0, w, h, designate_text) end #-------------------------------------------------------------------------- def dispose self.contents.clear super end end #========================================== # ▲ CLASS Air_Text Ends #========================================== #=================================================== # ▼ CLASS Scene_Save Additional Code Begins #=================================================== class Scene_Save < Scene_File alias ams_original_write_save_data write_save_data def write_save_data(file) ams_original_write_save_data(file) Marshal.dump($ams, file) end end #=================================================== # ▲ CLASS Scene_Save Additional Code Ends #=================================================== #=================================================== # ▼ CLASS Scene_Load Additional Code Begins #=================================================== class Scene_Load < Scene_File alias ams_original_read_save_data read_save_data def read_save_data(file) ams_original_read_save_data(file) $ams = Marshal.load(file) end end #=================================================== # ▲ CLASS Scene_Load Additional Code Ends #=================================================== <file_sep>/game/Scripts/Reflection_effect.rb # NOT UPDATED ! #============================================================================== # ■ Sprite_Reflection # Based on Sprite_Mirror, Modified By: JmsPlDnl, rewritten entirely by Rataime #============================================================================== CATERPILLAR_COMPATIBLE = true class Game_Party attr_reader :characters end class Sprite_Reflection < RPG::Sprite attr_accessor :character def initialize(viewport=nil, character=nil,self_angle = 180) super(viewport) @character = character @self_angle=self_angle self.opacity=0 @reflected=false @former=false @moving=false if $game_map.terrain_tag(@character.real_x/128,@character.real_y/128+1)==7 @reflected=true @former=true end update end def update super if @tile_id != @character.tile_id or @character_name != @character.character_name or @character_hue != @character.character_hue @tile_id = @character.tile_id @character_name = @character.character_name @character_hue = @character.character_hue if @tile_id >= 384 self.bitmap = RPG::Cache.tile($game_map.tileset_name, @tile_id, @character.character_hue) self.src_rect.set(0, 0, 32, 32) self.ox = 16 self.oy = 32 else self.bitmap = RPG::Cache.character(@character.character_name, @character.character_hue) @cw = bitmap.width / 4 @ch = bitmap.height / 4 self.ox = @cw / 2 self.oy = @ch end end self.visible = (not @character.transparent) if @tile_id == 0 sx = (@character.pattern) * @cw sy = (@character.direction - 2) / 2 * @ch if @character.direction== 6 sy = ( 4- 2) / 2 * @ch end if @character.direction== 4 sy = ( 6- 2) / 2 * @ch end if @character.direction != 4 and @character.direction != 6 sy = (@character.direction - 2) / 2 * @ch end end self.x = @character.screen_x self.y = @character.screen_y-5 @moving=!(@character.real_x%128==0 and @character.real_y%128==0) @d=@character.direction @rect=[sx, sy, @cw, @ch] if !(@moving) if $game_map.terrain_tag(@character.real_x/128,@character.real_y/128+1)==7 @reflected=true @former=true else @reflected=false @former=false end else case @d when 2 if $game_map.terrain_tag(@character.real_x/128,@character.real_y/128+2)==7 @reflected=true if @former==false @offset = (@character.screen_y%32)*@ch/32 @rect=[sx, sy, @cw, @offset] self.y=@character.screen_y-5 end else @reflected=false end when 4 if $game_map.terrain_tag(@character.real_x/128,@character.real_y/128+1)!=7 @offset = ((@character.screen_x-@cw/2)%32)*@cw/32 @rect=[sx, sy, @offset, @ch] self.x=@character.screen_x else @reflected=true if @former==false @offset = ((@character.screen_x-@cw/2)%32)*@cw/32 @rect=[sx+@offset, sy, @cw-@offset, @ch] self.x=@character.screen_x-@offset end end when 6 if $game_map.terrain_tag(@character.real_x/128+1,@character.real_y/128+1)!=7 @offset = ((@character.screen_x-@cw/2)%32)*@cw/32 @rect=[sx+@offset, sy, @cw-@offset, @ch] self.x=@character.screen_x-@offset else @reflected=true if @former==false @offset = ((@character.screen_x-@cw/2)%32)*@cw/32 @rect=[sx, sy, @offset, @ch] self.x=@character.screen_x end end when 8 if $game_map.terrain_tag(@character.real_x/128,@character.real_y/128+2)==7 @reflected=true if $game_map.terrain_tag(@character.real_x/128,@character.real_y/128+1)!=7 @offset = (@character.screen_y%32)*@ch/32 @rect=[sx, sy, @cw, @offset] self.y=@character.screen_y-5 end else @reflected=false end end end if @reflected self.opacity=128 else @rect=[sx, sy, @cw, @ch] self.opacity=0 end if $game_map.terrain_tag((@character.real_x+64)/128,@character.real_y/128+2)!=7 if $game_map.terrain_tag((@character.real_x+64)/128,@character.real_y/128+2)!=7 @rect[1]= @rect[1]+@ch/2 @rect[3]= @rect[3]/2 self.y = self.y - @ch/2 else @reflected=false end end self.src_rect.set(@rect[0],@rect[1],@rect[2],@rect[3]) @character.is_a?(Game_Player) ? self.z = 9 : self.z = 5 self.blend_type = @character.blend_type self.bush_depth = @character.bush_depth if @character.animation_id != 0 animation = $data_animations[@character.animation_id] animation(animation, true) @character.animation_id = 0 end self.angle = @self_angle end end #=================================================== # ▼ CLASS Sprite_Character edit #=================================================== class Sprite_Character < RPG::Sprite alias reflect_initialize initialize def initialize(viewport, character = nil) @character = character @reflection = [] super(viewport) if (character.is_a?(Game_Event) and character.list!=nil and character.list[0].code == 108 and character.list[0].parameters == ["r"]) @reflection.push(Sprite_Reflection.new(viewport,@character)) end if (character.is_a?(Game_Event) and character.list!=nil and character.list[0].code == 108 and character.list[0].parameters == ["hero_r"]) @reflection.push(Sprite_Reflection.new(viewport,$game_player)) #=================================================== # ● Compatibility with fukuyama's caterpillar script #=================================================== if CATERPILLAR_COMPATIBLE and $game_party.characters!=nil for member in $game_party.characters @reflection.push(Sprite_Reflection.new(viewport,member)) end end #=================================================== # ● End of the compatibility #=================================================== end reflect_initialize(viewport, @character) end alias reflect_update update def update reflect_update if @reflection!=nil for reflect in @reflection reflect.update end end end end <file_sep>/rebuild.sh #!/bin/bash # rm game/Save*.rxdata rvpacker -a pack -d ./game -t xp echo 'Done rebuilding the project into Data/ binaries.' <file_sep>/extract.sh #!/bin/bash if ls game/Save*.rxdata &> /dev/null; then echo 'Deleted save files.' rm game/Save*.rxdata fi rvpacker -a unpack -d ./game -t xp echo 'Done extracting the project binaries into text files.' <file_sep>/game/Scripts/Character_Shadow.rb #============================================================================== # ** Dynamic Shadows #------------------------------------------------------------------------------ # Rataime # Version 4.0 # 06/05/2007 (2007-05-06) # Version 1.0 was based on <NAME>'s shadows, extra features Boushy #============================================================================== #============================================================================== # Here's the brand new free configuration feature # The comments will be compared to the pattern using Regexp, except that I did # the entire work for you, so you don't have to know regexps at all. # Just choose the trigger ('s', 'begin shadow' or whatever), and the pattern # The pattern can be one line or a list to use multiple comment lines. # arg1 is the minimum angle # arg2 is the maximum angle # arg3 is the maximum distance # The only thing you must do is using 'trigger' before the arguments # Examples : # # SHADOWS_SOURCE_COMMENT_TRIGGER = 's' # SHADOWS_SOURCE_COMMENT_PATTERN = ['trigger','arg1','arg2','arg3'] # SHADOWS_CHAR_COMMENT_TRIGGER = 'o' # SHADOWS_CHAR_COMMENT_PATTERN = 'trigger' # is the old way to use shadows, with a single 's' in the first line, and the # arguments in following lines # # SHADOWS_SOURCE_COMMENT_TRIGGER = 'begin shadow source' # SHADOWS_SOURCE_COMMENT_PATTERN = # ['trigger','anglemin arg1','anglemax arg2','distancemax arg3'] # SHADOWS_CHAR_COMMENT_TRIGGER = 'begin shadow' # SHADOWS_CHAR_COMMENT_PATTERN = 'trigger' # will work with : # Comment "begin shadow source" # Comment "anglemin 0" # Comment "anglemax 0" # Comment "distancemax 250" # # Take the time to choose something you like, and something compatible with other # scripts. # Note that the comments will be detected even if they aren't in the beginning # of the event's action list. Ah, and you can switch the arguments if you like #============================================================================== #============================================================================== # Here is the method I like best, because of its compatibility with other # scripts. But don't hesitate to change it. # It will react to something like Shadow|0|0|250 #============================================================================== SHADOWS_SOURCE_COMMENT_TRIGGER = 'Shadow' SHADOWS_SOURCE_COMMENT_PATTERN = 'trigger|arg1|arg2|arg3' SHADOWS_CHAR_COMMENT_TRIGGER = 'o' SHADOWS_CHAR_COMMENT_PATTERN = 'trigger' #============================================================================== # An important option : if you set it to true, the shadows will get longer if # you are far from the source. Nice, but induces lag : it will eat your CPU, # and quite possibly your first born if you try that on a big map. #============================================================================== SHADOW_GETS_LONGER = true #============================================================================== # Misc options # If an event has its opacity below SHADOWS_OPACITY_THRESHOLD, no shadow will # be displayed. # Set SHADOWS_CATERPILLAR_COMPATIBLE to true if you uses the caterpillar script #============================================================================== SHADOWS_OPACITY_THRESHOLD = 254 SHADOWS_CATERPILLAR_COMPATIBLE = true #============================================================================== # You probably won't need to touch this : it's the 'map' of how to display the # shadow depending on the event's direction and his relative position to the # source. a minus means the shadow is mirrored. It seems complex, and it is. # Complain to Enterbrain (why didn't they use something clockwise or counter- # clockwise ? I suspect it's because of the rm2k legacy. More explanations # below. #============================================================================== SHADOWS_DIRECTION_ARRAY = Array.new SHADOWS_DIRECTION_ARRAY[2] = [ -3, 4, -2, 1 ] SHADOWS_DIRECTION_ARRAY[4] = [ 4, -2, 1, -3 ] SHADOWS_DIRECTION_ARRAY[6] = [ 1, -3, 4, -2 ] SHADOWS_DIRECTION_ARRAY[8] = [ -2, 1, -3, 4 ] #------------------------------------------------------------------------------ # * SDK Log Script and Check requirements #------------------------------------------------------------------------------ SDK.log('Shadows', 'rataime', 1.00, '05.06.2007') SDK.check_requirements(2, [1,2]) #============================================================================== # ** Game_Party, for compatibility with the caterpillar script. #============================================================================== class Game_Party attr_reader :characters end #============================================================================== # ** Sprite_Shadow, the meat of this script #============================================================================== class Sprite_Shadow < RPG::Sprite attr_accessor :character #-------------------------------------------------------------------------- # * Initialize #-------------------------------------------------------------------------- def initialize(viewport, character = nil,source = nil,anglemin=0, \ anglemax=0,distancemax=700) super(viewport) @anglemin=anglemin.to_f @anglemax=anglemax.to_f @distancemax=distancemax.to_f @character = character @source = source self.color = Color.new(0, 0, 0) update end #-------------------------------------------------------------------------- # * Update #-------------------------------------------------------------------------- def update if @character.transparent or @character.opacity <= SHADOWS_OPACITY_THRESHOLD self.visible = false return end @deltax=(@source.real_x-@character.real_x)/4 @deltay= (@source.real_y-@character.real_y)/4 @distance = (((@deltax ** 2) + (@deltay ** 2))** 0.5) if @distancemax !=0 and @distance>@distancemax self.visible = false return end self.angle = 57.3*Math.atan2(@deltax, @deltay ) @angle_trigo= (self.angle+90) % 360 if @anglemin !=0 or @anglemax !=0 if (@angle_trigo<@anglemin or @angle_trigo>@anglemax) and \ @anglemin<@anglemax self.visible = false return elsif (@angle_trigo<@anglemin and @angle_trigo>@anglemax) and \ @anglemin>@anglemax self.visible = false return end end super if @tile_id != @character.tile_id or @character_name != @character.character_name or @character_hue != @character.character_hue @tile_id = @character.tile_id @character_name = @character.character_name @character_hue = @character.character_hue if @tile_id >= 384 self.bitmap = RPG::Cache.tile($game_map.tileset_name, @tile_id, @character.character_hue) self.src_rect.set(0, 0, 32, 32) self.ox = 16 self.oy = 32 else self.bitmap = RPG::Cache.character(@character.character_name, @character.character_hue) @cw = bitmap.width / 4 @ch = bitmap.height / 4 self.ox = @cw / 2 self.oy = @ch end end self.visible = true self.x = @character.screen_x self.y = @character.screen_y-8 self.z = @character.screen_z(@ch)-1 if @character.animation_id != 0 animation = $data_animations[@character.animation_id] animation(animation, true) @character.animation_id = 0 end if @tile_id == 0 sx = @character.pattern * @cw quarter = ((@angle_trigo/90+0.5).floor)%4 # The quarter is the position of the event relative to the source. # Imagine the source is the o point (0,0). Trace the 2 lines # y=x and y=-x : you get something like a big X # On the right, quarter=0. Up, quarter = 1, and so on # Take the @character.direction row (2,4,6,8), and the quarter # column (0,1,2,3) (remember, it starts at 0), and you'll get # a number between 1 and 4. It correspond to the row of the charset # the shadow will be, and mirrored if negative. # Yes, it isn't obvious, but I didn't find any simple operation to # get those. magic = SHADOWS_DIRECTION_ARRAY[@character.direction][quarter] magic = -magic if magic < 0 self.mirror = true magic = -magic else self.mirror = false end sy = (magic-1)*@ch self.src_rect.set(sx, sy, @cw, @ch) end # This is the formula of the opacity in function of the distance # ** 2 means square self.opacity = 600/((@distance ** 2)/ 1000 + 6) # This is the formula of the size in function of the distance # The 0.75 is here so you have a size of 1:1 when next to the source. self.zoom_y=0.75 + @distance / 256 if SHADOW_GETS_LONGER end end #====================================================================== # ** Sprite_Character EDIT #====================================================================== # All those things could go somewhere else, but they # work quite well here. #====================================================================== class Sprite_Character < RPG::Sprite @@regexp_source = nil @@regexp_source_short = nil @@regexp_char = nil @@regexp_char_short = nil alias rataime_shadow_initialize initialize #-------------------------------------------------------------------------- # * Initialize #-------------------------------------------------------------------------- def initialize(viewport, character = nil) if @@regexp_source == nil regexp_initialize end @character = character super(viewport) @ombrelist=[] if (character.is_a?(Game_Event) and character.list!=nil) # Let's check the comments in our event list for j_list in 0..character.list.size-1 #p [@@regexp_source_short, character.list[j_list].parameters[0]] if (character.list[j_list].code == 108 and \ @@regexp_source_short.match(character.list[j_list].parameters[0])!= nil) # Haha ! We found a trigger tag ! Time to retrieve the parameters ! parameter_string = character.list[j_list].parameters[0] j_list += 1 while j_list < character.list.size and \ (character.list[j_list].code == 108 or \ character.list[j_list].code == 408) parameter_string = parameter_string + "\n" + \ character.list[j_list].parameters[0] j_list += 1 end # The following line is a nifty piece of code. Really. @anglemin,@anglemax,@distancemax = \ (regexp_get_parameters(parameter_string, true)+[nil]*3)[0..2] # We have our source parameters. Let's find which events we should # make have a shadow for i in $game_map.events.keys.sort if ($game_map.events[i].is_a?(Game_Event) and \ $game_map.events[i].list!=nil) for i_list in 0..$game_map.events[i].list.size-1 if (($game_map.events[i].list[i_list].code == 108 or \ $game_map.events[i].list[i_list].code == 408 )and \ @@regexp_char_short.match( \ $game_map.events[i].list[i_list].parameters[0])!= nil) @ombrelist[i+1] = Sprite_Shadow.new(viewport, $game_map.events[i],\ self,@anglemin,@anglemax,@distancemax) break # no need to add more than one shadow per source per event end end # end for end end # end for @ombrelist[1] = Sprite_Shadow.new(viewport, $game_player,self,@anglemin,\ @anglemax,@distancemax) #=================================================== # Compatibility with fukuyama's caterpillar script #=================================================== if SHADOWS_CATERPILLAR_COMPATIBLE and $game_party.characters!=nil for member in $game_party.characters @ombrelist.push(Sprite_Shadow.new(viewport, member,self,@anglemin,\ @anglemax,@distancemax)) end end #=================================================== # End of the compatibility #=================================================== end break # We don't need to go further in the source's list end # end for end rataime_shadow_initialize(viewport, @character) end alias rataime_shadow_update update #-------------------------------------------------------------------------- # * Update #-------------------------------------------------------------------------- def update rataime_shadow_update if @ombrelist!=[] for i in 1..@ombrelist.size if @ombrelist[i]!=nil @ombrelist[i].update end end end end #-------------------------------------------------------------------------- # * Real_x : it just returns the character's real_x #-------------------------------------------------------------------------- def real_x return @character.real_x end #-------------------------------------------------------------------------- # * Real_y : it just returns the character's real_y #-------------------------------------------------------------------------- def real_y return @character.real_y end #-------------------------------------------------------------------------- # * regexp_initialize : the brand new configuration function # This function generate the regexps based on the configuration #-------------------------------------------------------------------------- def regexp_initialize @@regexp_source = regexp_generate(true) @@regexp_char = regexp_generate(false) @@regexp_source_short = @@regexp_source @@regexp_char_short = @@regexp_char if SHADOWS_SOURCE_COMMENT_PATTERN.is_a?(Array) @@regexp_source_short = regexp_generate_short(@@regexp_source) end if SHADOWS_CHAR_COMMENT_PATTERN.is_a?(Array) @@regexp_char_short = regexp_generate_short(@@regexp_char) end end #-------------------------------------------------------------------------- # * regexp_generate generate a full length regexp including the arguments # detection. #-------------------------------------------------------------------------- def regexp_generate(source = false) if source pattern = SHADOWS_SOURCE_COMMENT_PATTERN trigger = SHADOWS_SOURCE_COMMENT_TRIGGER @@argument_indexes_source = [] indexes = @@argument_indexes_source else pattern = SHADOWS_CHAR_COMMENT_PATTERN trigger = SHADOWS_CHAR_COMMENT_TRIGGER @@argument_indexes_char = [] indexes = @@argument_indexes_char end if pattern.is_a?(Array) string = Regexp.escape(pattern.join("\n")) else string = Regexp.escape(pattern) end string = string.gsub('trigger',')('+trigger+')(') splitted = string.split('arg') regexp = '\A(' + splitted[0] + '(\d+)){0,1}' for i in 1..splitted.size-1 if splitted[i][0..0].to_i == 0 p 'Error : You probably forgot a digit after an arg' raise else indexes.push(splitted[i][0..0].to_i) regexp = regexp + '(' + splitted[i][1..splitted[i].size-1] + '(\d+)){0,1}' end end return Regexp.new(regexp.chomp('(\d+)){0,1}') + ')') end #-------------------------------------------------------------------------- # * Will return a shorter regexp, but still able to identify the trigger #-------------------------------------------------------------------------- def regexp_generate_short(regexp) string = regexp.inspect string = string.split('\n')[0] string = string[1..string.size-2] return Regexp.new(string) end #-------------------------------------------------------------------------- # * regexp_get_parameters is called whenever a trigger has been identify, # and the script wants to know the arguments. It returns an array in the # right orger [arg1,arg2,arg3] #-------------------------------------------------------------------------- def regexp_get_parameters(string, source = false) if source regexp = @@regexp_source indexes = @@argument_indexes_source.dup else regexp = @@regexp_char indexes = @@argument_indexes_char.dup end indexes = indexes.reverse! match_array = regexp.match(string).captures return_array = Array.new if match_array.size > 3 for i in 2..match_array.size-1 if ((i.to_f/2).ceil)*2 != i and match_array[i]!=nil return_array[indexes.pop-1] = match_array[i] end end end return return_array end end<file_sep>/game/Scripts/Window_ShopCommand.rb #============================================================================== # ■ Window_ShopCommand #------------------------------------------------------------------------------ #  ショップ画面で、用件を選択するウィンドウです。 #============================================================================== class Window_ShopCommand < Window_Selectable #-------------------------------------------------------------------------- # ● オブジェクト初期化 #-------------------------------------------------------------------------- def initialize super(0, 64, 480, 64) self.contents = Bitmap.new(width - 32, height - 32) self.contents.font.name = $defaultfonttype # "Shop Commands" window font self.contents.font.size = $defaultfontsize @item_max = 3 @column_max = 3 @commands = ["Vesz", "Elad", "Távoz"] refresh self.index = 0 end #-------------------------------------------------------------------------- # ● リフレッシュ #-------------------------------------------------------------------------- def refresh self.contents.clear for i in 0...@item_max draw_item(i) end end #-------------------------------------------------------------------------- # ● 項目の描画 # index : 項目番号 #-------------------------------------------------------------------------- def draw_item(index) x = 4 + index * 160 self.contents.draw_text(x, 0, 128, 32, @commands[index]) end end <file_sep>/game/Scripts/Window_NameInput.rb #============================================================================== # ■ Window_NameInput #------------------------------------------------------------------------------ #  名前入力画面で、文字を選択するウィンドウです。 #============================================================================== class Window_NameInput < Window_Base CHARACTER_TABLE = [ "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", " ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", " ", "+", "-", ";", ":", "'", ",", ".", "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", " ", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", " ", "[", "]", "{", "}", "<", ">", "?", ] #-------------------------------------------------------------------------- # ● オブジェクト初期化 #-------------------------------------------------------------------------- def initialize super(160, 128, 320, 352) self.contents = Bitmap.new(width - 32, height - 32) self.contents.font.name = $defaultfonttype # "Name Input" window font self.contents.font.size = $defaultfontsize @index = 0 refresh update_cursor_rect end #-------------------------------------------------------------------------- # ● 文字の取得 #-------------------------------------------------------------------------- def character return CHARACTER_TABLE[@index] end #-------------------------------------------------------------------------- # ● リフレッシュ #-------------------------------------------------------------------------- def refresh self.contents.clear for i in 0..89 x = 4 + i / 5 / 9 * 152 + i % 5 * 28 y = i / 5 % 9 * 32 self.contents.draw_text(x, y, 28, 32, CHARACTER_TABLE[i], 1) end self.contents.draw_text(225, 9 * 32, 64, 32, "Accept", 1) end #-------------------------------------------------------------------------- # ● カーソルの矩形更新 #-------------------------------------------------------------------------- def update_cursor_rect # カーソル位置が [決定] の場合 if @index >= 90 self.cursor_rect.set(225, 9 * 32, 64, 32) # カーソル位置が [決定] 以外の場合 else x = 4 + @index / 5 / 9 * 152 + @index % 5 * 28 y = @index / 5 % 9 * 32 self.cursor_rect.set(x, y, 28, 32) end end #-------------------------------------------------------------------------- # ● フレーム更新 #-------------------------------------------------------------------------- def update super # カーソル位置が [決定] の場合 if @index >= 90 # カーソル下 if Input.trigger?(Input::DOWN) $game_system.se_play($data_system.cursor_se) @index -= 90 end # カーソル上 if Input.repeat?(Input::UP) $game_system.se_play($data_system.cursor_se) @index -= 90 - 40 end # カーソル位置が [決定] 以外の場合 else # 方向ボタンの右が押された場合 if Input.repeat?(Input::RIGHT) # 押下状態がリピートでない場合か、 # カーソル位置が右端ではない場合 if Input.trigger?(Input::RIGHT) or @index / 45 < 3 or @index % 5 < 4 # カーソルを右に移動 $game_system.se_play($data_system.cursor_se) if @index % 5 < 4 @index += 1 else @index += 45 - 4 end if @index >= 90 @index -= 90 end end end # 方向ボタンの左が押された場合 if Input.repeat?(Input::LEFT) # 押下状態がリピートでない場合か、 # カーソル位置が左端ではない場合 if Input.trigger?(Input::LEFT) or @index / 45 > 0 or @index % 5 > 0 # カーソルを左に移動 $game_system.se_play($data_system.cursor_se) if @index % 5 > 0 @index -= 1 else @index -= 45 - 4 end if @index < 0 @index += 90 end end end # 方向ボタンの下が押された場合 if Input.repeat?(Input::DOWN) # カーソルを下に移動 $game_system.se_play($data_system.cursor_se) if @index % 45 < 40 @index += 5 else @index += 90 - 40 end end # 方向ボタンの上が押された場合 if Input.repeat?(Input::UP) # 押下状態がリピートでない場合か、 # カーソル位置が上端ではない場合 if Input.trigger?(Input::UP) or @index % 45 >= 5 # カーソルを上に移動 $game_system.se_play($data_system.cursor_se) if @index % 45 >= 5 @index -= 5 else @index += 90 end end end # L ボタンか R ボタンが押された場合 if Input.repeat?(Input::L) or Input.repeat?(Input::R) # ひらがな / カタカナ 移動 $game_system.se_play($data_system.cursor_se) if @index / 45 < 2 @index += 90 else @index -= 90 end end end update_cursor_rect end end <file_sep>/game/Scripts/SDK.rb #============================================================================== # ** RMXP Standard Development Kit (SDK) #------------------------------------------------------------------------------ # Build Date - 2005-11-22 # Version 1.0 - Near Fantastica - 2005-11-22 # Version 1.1 - SephirothSpawn - 2005-12-18 - (Near Fantastica) # Version 1.2 - Near Fantastica - 2005-12-18 - (Wachunga) # Version 1.3 - Wachunga - 2005-12-19 - (Near Fantastica) # Version 1.4 - Prexus - 2006-03-02 - (SephirothSpawn) # Version 1.5 - <NAME> - 2006-03-25 - (Near Fantastica) # Version 2.0 - SephirothSpawn / Trickster / # <NAME> / Sandgolem - 2007-02-22 - (SDK Team) # Version 2.1 - tibuda /alexanderpas / Mr. Mo - 2007-02-25 - (SephirothSpawn) # Version 2.2 - SephirothSpawn / Trickster / # tibuda - 2007-04-04 - (SDK Team) # Version 2.3 - Rataime / SephirothSpawn / # Trickster / vgvgf - 2007-07-22 - (SDK Team) # Version 2.4 - SephirothSpawn / Trickster - 2008-07-13 - (SephirothSpawn) #============================================================================== #============================================================================== # ** SDK #============================================================================== module SDK #-------------------------------------------------------------------------- # * Include Parts # # When a SDK Part, all classes and methods within that class are # included, even if they are not in the individual parts. # # Individual Parts allow you to include just a individual method split # from a certain part. This allows you to only use part of a SDK Part, # to allow further compatability. # # * Individual Part Listings: # # Part 2 # - 'RPG::Sprite#update' # - 'Game_Map#setup' # - 'Game_Map#update' # - 'Game_Battler#attack_effect' # - 'Game_Battler#skill_effect' # - 'Game_Battler#item_effect' # - 'Game_Battler#slip_damage_effect' # - 'Game_Actor#exp=' # - 'Game_Character#update' # - 'Game_Event#refresh' # - 'Game_Player#update' # - 'Sprite_Battler#update' # - 'Spriteset_Map#initialize' # - 'Spriteset_Map#update' # - 'Spriteset_Battle#initialize' # - 'Spriteset_Battle#update' # - 'Window_SaveFile#initialize' # # Part 3 # - 'Part 3#Scene_Title' # - 'Part 3#Scene_Map' # - 'Part 3#Scene_Menu' # - 'Part 3#Scene_Item' # - 'Part 3#Scene_Skill' # - 'Part 3#Scene_Equip' # - 'Part 3#Scene_Status' # - 'Part 3#Scene_File' # - 'Part 3#Scene_Save' # - 'Part 3#Scene_Load' # - 'Part 3#Scene_End' # - 'Part 3#Scene_Battle' # - 'Part 3#Scene_Shop' # - 'Part 3#Scene_Name' # - 'Part 3#Scene_Gameover' # - 'Part 3#Scene_Debug' # # Part 4 # - 'Part 4#Scene_Title' # - 'Part 4#Scene_Menu' # - 'Part 4#Scene_End' # - 'Part 4#Scene_Battle' # - 'Part 4#Scene_Shop' #-------------------------------------------------------------------------- Parts = [1, 2, 3, 4, 5] Individual_Parts = [] #-------------------------------------------------------------------------- # * Show Disable Messages #-------------------------------------------------------------------------- Show_Error_Disable_Message = true Show_Method_Overwrite_Error = true end #============================================================================== # ** SDK Scene Commands #------------------------------------------------------------------------------ # This module contains all scene commands. This is only needed to be configured # if you use Part 4 of the SDK, or an individual part that uses part 4. #============================================================================== module SDK::Scene_Commands #-------------------------------------------------------------------------- # * Load Data System #-------------------------------------------------------------------------- DataSystem = load_data('Data/System.rxdata') #============================================================================ # ** Scene_Title #============================================================================ module Scene_Title New_Game = 'Új játék' Continue = 'Betöltés' Shutdown = 'Kilépés' end #============================================================================ # ** Scene_Menu #============================================================================ module Scene_Menu Item = DataSystem.words.item Skill = DataSystem.words.skill Equip = DataSystem.words.equip Status = 'Státusz' Save = 'Mentés' End_Game = 'Kilépés' end #============================================================================ # ** Scene_End #============================================================================ module Scene_End To_Title = 'Menübe' Shutdown = 'Kilépés' Cancel = 'Mégsem' end #============================================================================ # ** Scene_Battle #============================================================================ module Scene_Battle Fight = 'Fight' Escape = 'Escape' Attack = DataSystem.words.attack Skill = DataSystem.words.skill Guard = DataSystem.words.guard Item = DataSystem.words.item end #============================================================================ # ** Scene_Shop #============================================================================ module Scene_Shop Buy = 'Vesz' Sell = 'Elad' Exit = 'Kilép' end end #============================================================================== # ** RMXP Standard Development Kit (SDK) - Documentation #============================================================================== =begin ** 1.0 - SDK Definition & Information The Standard Development Kit (SDK) aims to increase compatibility between RGSS scripts by: a) defining a set of scripting standards (see section 4) b) restructuring often-used default classes and methods (see section 5) c) providing a scripting tools module (see section 6) The SDK has been divided up into individual parts, to allow more users to use only part of or the complete SDK. It is recommended to use all 4 parts of the SDK but is not required. All SDK scripts must use at least part I, but this should not interfer with any other scripts. The Parts are divided up as follows : Part I : SDK Module ; Standard RGSS Fixes Part II : SDK Modifications - Hidden, Game, Sprite & Spriteset Classes Part III : SDK Modifications - Scene Classes Part IV : SDK Modifications - Scene Input Handeling Using Part I will not cause problems with non-SDK scripts. Parts II - IV split up default methods into specialized methods allowing easier modification. Part IV requires Part III. #------------------------------------------------------------------------------ * 1.1 - Terms & Conditions for the RMXP Standard Development Kit The RMXP SDK Kit is open for any commerical or non-commerical game usage. It is required to credit the SDK and all authors found in the SDK script heading. #============================================================================== ** 2.0 - Modifications to the RMXP Standard Development Kit Since edits to the SDK may cause massive capability errors, any and all modifications must first be approved by a member of the RMXP SDK Team. The author of any modifications must be sure to update all relevant documentation. This also includes the header, where the author is to put the next version number with his or her name and the name of the approval member (from the SDK Team) under the latest version in the following format. Version # - Name - Date - (Approval Member Name) #============================================================================== ** 3.0 - Instructions & FAQ Q) How do I install the SDK? A) Copy and Paste The RMXP SDK Complete code into your script editor below Scene_Debug, and above all other scripts. Q) What order do I place my scripts? A) There is no simple answer for this. Some scripts overwrite methods or other problems may arise. The most common order of placement is * Default Scripts * The SDK * Non-SDK Scripts * SDK Scripts * Main However, non-SDK scripts could overwrite SDK methods rendering them uselss. If a problem arises, feel free to ask for help here : SDK General Support - http://www.rmxp.org/forums/showthread.php?t=17691 SDK Conversion Request Shop - http://www.rmxp.org/forums/showthread.php?t=1985 Q) What is the SDK Patch? A) The SDK Patch is for upgrading purpose only. Old SDK methods were renamed, deleted, replaced, etc. with new, better methods. This patch is to redirect old scripts to use the new methods as the old one. Unless you are using a script that requires a previous version of the SDK, you do not need to include the patch. Q) What is compliant? Compatible? A) Compliant means that the script you are using follows all guidelines set in the coding standards of the SDK. Compatible is scripts that use SDK created methods and will not conflict with other SDK scripts (in theory). Q) I only want to use a certain part of the SDK. Do I need all of them? A) No. Only if you are using a script that uses elements of a certain part of the SDK are you required to use that part. However, Part I is required for use with any other part and part III is required for part IV. Have more questions? Post them here : - http://www.rmxp.org/forums/showthread.php?t=1802 #============================================================================== ** 4.0 - Coding Standards To be compliant with the SDK, a script must comply with the following coding standards: 4.1 - Commenting 4.2 - Classes 4.3 - Variables 4.4 - Aliases 4.5 - Strings 4.6 - Line Length 4.7 - White Space 4.8 - Constants 4.9 - Parentheses 4.10 - Versions #------------------------------------------------------------------------------ * 4.1 - Commenting Scripts must begin with the following header : #============================================================================== # ** Script Name #------------------------------------------------------------------------------ # Your Name # Version # Date # SDK Version : (SDK Version Number) - Parts #s #============================================================================== All classes and methods must have a comment describing the process or what was added. All code added to methods that can not be aliased must be formatted as follows: #---------------------------------------------------------------------------- # Begin Script Name Edit #---------------------------------------------------------------------------- [Code] #---------------------------------------------------------------------------- # End Script Name Edit #---------------------------------------------------------------------------- Single line comments should precede the described block of code and should be indented at the same level. Code that is not self-documenting should be commented. However, very short comments can appear on the same line as the described code, but should be shifted far enough to separate them from the statements. If more than one short comment appears in a chunk of code, they should all be indented to the same tab setting. Attribute declarations should always have a trailing comment. #------------------------------------------------------------------------------ * 4.2 - Classes All classes must be named consistently with the default code, namely: Data - Any class that defines database information Game - Any class that defines specific game data for specific session Sprite - Any class that defines a specialized sprite class Spriteset - Any class that defines multiple sprites Window - Any class that defines a specialized window class Arrow - Any class that defines a specialized arrow class Scene - Any class that defines a specialized scene class #------------------------------------------------------------------------------ * 4.3 - Variables All variable names must be reasonably descriptive. Use of class and global variables should be limited. Any variable used by the default system can not have its use changed. #------------------------------------------------------------------------------ * 4.4 - Aliases Aliasing a method is preferable to overriding it; an alias should be used whenever possible to increase compatibility with other scripts. All aliased method names must either be logged, or by using the alias_method method in class Module. All alias names must have the following format: alias new_method_name old_method_name SDK.log_alias(:class_name, :old_method_name, :new_method_name) - or - alias_method :new_method_name, :old_method_name * Format for New Method Name should be: yourname_scriptname_classname_methodname / yourname_scriptname_methodname ** Note : When Aliasing the same method in parent / child-class, it is required for you to put class name in the alias naming. #------------------------------------------------------------------------------ * 4.5 – Strings Strings should normally be defined with single quotes ('example'); this decreases the processing time of the engine. Double quotes are useful when using the following features: a) substitutions, i.e. sequences that start with a backslash character (e.g. \n for the newline character) b) expression interpolation, i.e. #{ expression } is replaced by the value of expression #------------------------------------------------------------------------------ * 4.6 - Line Length Lines should not cause the the viewer to have to scroll sideways to view them in the script editor. When the line needs to be broken, it should follow the following guidelines, in preferential order: Break after a comma. Break before an operator. Prefer higher-level breaks to lower-level breaks. Align the new line with the beginning of the expression at the same level on the previous line. If the above rules lead to confusing code or to code that’s squished up against the right margin, just indent 4 spaces instead. #------------------------------------------------------------------------------ * 4.7 - White Space A blank line(s) should be used in the following places: Between sections of a source file Between class and module definitions Between attributes and the class definition Between methods Between the local variables in a method and its first statement Before a block or single-line comment Between logical sections inside a method to improve readability Blank spaces should be used in the following places: A keyword followed by a parenthesis, e.g. if (some_boolean_statements) After commas in argument lists, e.g. def method (arg1, arg2, ...) All binary operators except '.', e.g. a + b; c = 1 #------------------------------------------------------------------------------ * 4.8 - Constants Numercial values that are used constantly and have the same purpose for being used, is encouraged to be made a constant value instead of being hard coded. Also if a numericial value has a important function that can be changed then it is also encouraged for it to be made a constant. #------------------------------------------------------------------------------ * 4.9 - Parentheses It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems. Even if the operator precedence seems clear to you, it might not be to others -— you shouldn’t assume that other programmers know precedence as well as you do. #------------------------------------------------------------------------------ * 4.10 - Versions You are required to document the script with the current version. Here is a general guideline to recording this. (Thanks to Ccoa) Format : A.BC (A.B.C is fine except when logging) A = Main Version or Rewrites B = Additions or Modifications C = Bug Fixes Due to the version checking, A.B.C will result in an error if used to log your script. Please use the A.BC method when logging script. #============================================================================== ** 5.0 - Engine Updates The following is a list of classes and methods that have been updated by the SDK to help improve compatibility: #------------------------------------------------------------------------------ * 5.0.1 - Part I * New Classes : - SDK::Scene_Base - Window_HorizCommand * Created Methods : - Object#disable_dispose, #disable_dispose= & #disable_dispose? - Object#disable_update, #disable_update= & #disable_update? - RPG::Event::Page::Condition#conditions_met? - RPG::Event::Page::Condition#conditions_met? - Window_Command#command - Window_Command#commands - Window_Command#commands= * Bug & Bug Prevention Fixes : - Window_Base#dispose - Window_SaveFile#initialize - Interpreter#command_355 * Deprecated Methods : - SDK#print -> SDK#return_log - SDK#state -> SDK#enabled? #------------------------------------------------------------------------------ * 5.0.2 - Part II * Split Methods : - RPG::Sprite#update - update_whiten # Update Whiten - update_appear # Update Appear - update_escape # Update Escape - update_collapse # Update Collapse - update_damage # Update Damage - update_animation_duration # Update Animation Duration - update_loop_animation_index # Update Loop Animation - update_blink # Update Blink - Window_SaveFile#initialize - init_filename # Initialize Filename - init_filedata # Initialize Filedata - init_gamedata # Initialize Gamedata - Game_Map#setup - setup_map_id # Setup Map ID - setup_load # Setup Map Data - setup_tileset # Setup Tileset Data - setup_display # Setup Display - setup_refresh # Setup Refresh - setup_events # Setup Events - setup_common_events # Setup Common Events - setup_fog # Setup Fog - setup_scroll # Setup Scroll - Game_Battler#attack_effect - attack_effect_setup - attack_effect_first_hit_result - attack_effect_base_damage - attack_effect_element_correction - attack_effect_critical_correction - attack_effect_guard_correction - attack_effect_dispersion - attack_effect_second_hit_result - attack_effect_damage - attack_effect_miss - Game_Battler#skill_effect - skill_effect_setup - skill_effect_scope - skill_effect_effective_setup - skill_effect_first_hit_result - skill_effect_effective_correction - skill_effect_power - skill_effect_rate - skill_effect_base_damage - skill_effect_element_correction - skill_effect_guard_correction - skill_effect_disperation - skill_effect_second_hit_result - skill_effect_physical_hit_result - skill_effect_damage - skill_effect_power0 - skill_effect_miss - skill_effect_damagefix - Game_Battler#item_effect - item_effect_setup - item_effect_scope - item_effect_effective_setup - item_effect_hit_result - item_effect_effective_correction - item_effect_recovery - item_effect_element_correction - item_effect_guard_correction - item_effect_dispersion - item_effect_damage - item_effect_parameter_points - item_effect_no_recovery - item_effect_miss - item_effect_damagefix - Game_Battler#slip_damage_effect - slip_damage_effect_base_damage - slip_damage_effect_dispersion - slip_damage_effect_damage - Game_Map#update - update_refresh # Update Refresh Flag - update_scrolling # Update Scrolling - update_events # Update Events - update_common_events # Update Common Events - update_fog_scroll # Update Fog Scrolling - update_fog_color # Update Fog Color - update_fog # Update Fog - Game_Actor#exp= - level_up # Level Actor Up - level_down # Level Actor Down - Game_Character#update - update_movement_type # Update Movement Type - update_animation # Update Animation Counters - update_wait? # Update Wait Test - update_force? # Update Force Route Test - update_startlock? # Update Start/Lock Test - update_movement # Update Movement - Game_Event#refresh - refresh_new_page # Refresh New Page - refresh_page_change? # Refresh Page Change Test - refresh_page_reset? # Refresh Page Reset Test - refresh_set_page # Refresh Set page variables - refresh_check_process # Check parallel processing - Game_Player#update - update_player_movement # Update Player Movement - update_plyrmvttest? # Update Can Move Test - update_scroll_down # Update Scroll Down - update_scroll_left # Update Scroll Left - update_scroll_right # Update Scroll Right - update_scroll_up # Update Scroll Up - update_nonmoving # Update Non-Moving - Sprite_Battler#update - redraw_battler # Redraw Battler - loop_anim # Loop Animaiton - adjust_actor_opacity # Adjust Actor Opacity - adjust_blink # Adjust Blink - adjust_visibility # Adjust Visibility - sprite_escape # Sprite Escape - sprite_white_flash # Sprite White Flash - sprite_animation # Sprite Animation - sprite_damage # Sprite Damage - sprite_collapse # Sprite Collapse - sprite_position # Sprite Position - Spriteset_Map#initialize - init_viewports # Initialize Viewports - init_tilemap # Initialize Tilemap - init_panorama # Initialize Panorama - init_fog # Initialize Fog - init_characters # Initialize Characters - init_player # Initialize Player - init_weather # Initialize Weather - init_pictures # Initialize Pictures - init_timer # Initialize Timer - Spriteset_Map#update - update_panorama # Update Panorama - update_fog # Update Fog - update_tilemap # Update Tilemap - update_panorama_plane # Update Panorama Plane - update_fog_plane # Update Fog Plane - update_character_sprites # Update Character Sprites - update_weather # Update Weather - update_picture_sprites # Update Picture Sprites - update_timer # Update Timer Sprite - update_viewports # Update Viewports - Spriteset_Battle#initialize - init_viewport # Initialize Viewports - init_battleback # Initialize Battleback - init_enemysprites # Initialize Enemy Sprites - init_actorsprites # Initialize Actor Sprites - init_picturesprites # Initialize Picture Sprites - init_weather # Initialize Weather - init_timer # Initialize Timer - Spriteset_Battle#update - update_battleback # Update Battleback - update_battlers # Update Actor Battlers - update_sprites # Update Sprites - update_weather # Update Weather - update_timer # Update Timer - update_viewports # Update Viewports * Deprecated Methods : - Game_Map : update_fog_colour -> update_fog_color - Game_Character : update_wait -> update_wait? - Game_Character : update_event_execution? -> update_startlock? #------------------------------------------------------------------------------ * 5.0.3 - Part III All scenes are now child classes of SDK::Scene_Base. You still must alias every Scene_Base method even if not defined below. * Created Methods : - Window_EquipItem#disable_update? - Window_Message#disable_update? * Split Methods : - Scene_Title#main - main_battle_test? # Main Battle Test Mode Test - main_variable # Main Variable Initialization - main_database # Main Database Initialization - main_test_continue # Test For Saved Files - main_sprite # Main Sprite Initialization - main_window # Main Window Initialization - main_audio # Main Audio Initialization - Scene_Title#command_new_game - commandnewgame_audio # Audio Control - commandnewgame_gamedata # Game Data Setup - commandnewgame_partysetup # Party Setup - commandnewgame_mapsetup # Map Setup - commandnewgame_sceneswitch # Scene Switch - Scene_Title#battle_test - battletest_database # Setup Battletest Database - commandnewgame_gamedata # Game Data Setup - battletest_setup # Battletest Setup - battletest_sceneswitch # Scene Switch - Scene_Map#main - main_spriteset # Main Spriteset Initialization - main_window # Main Window Initialization - main_end # Main End - Scene_Map#update - update_systems # Update Systems - update_transferplayer? # Break if Transfer Player - update_transition? # Break if Transition - update_game_over? # Exit If Gameover - update_to_title? # Exit if Title - update_message? # Exit If Message - update_transition # Update Transition - update_encounter # Update Encounter - update_call_menu # Update Menu Call - update_call_debug # Update Debug Call - update_calling # Update Calls - Scene_Menu#main - main_window # Main Window Initialization - main_command_window # Main Command Window Setup - Scene_Item#main - main_window # Main Window Initialization - Scene_Skill#main - main_variable # Main Variable Initialization - main_window # Main Window Initialization - Scene_Equip#main - main_variable # Main Variable Initialization - main_window # Main Window Initialization - Scene_Status#main - main_variable # Main Variable Initialization - main_window # Main Window Initialization - Scene_File#main - main_variable # Main Variable Initialization - main_window # Main Window Initialization - Scene_Save#write_save_data - write_characters(file) # Write Characters - write_frame(file) # Write Frame Count - write_setup(file) # Write Setup Data - write_data(file) # Write Game Data - Scene_Load#read_save_data - read_characters(file) # Read Characters - read_frame(file) # Read Frame Count - read_data(file) # Read Game Data - read_edit # Read Edit - read_refresh # Read Refresh - Scene_End#main - main_window # Main Window Initialization - main_end # Main End - Scene_Battle#main - main_variable # Main Variable Initialization - main_battledata # Setup Battle Temp Data & Interpreter - main_troopdata # Setup Troop Data - main_spriteset # Main Spriteset Initialization - main_window # Main Window Initialization - main_transition # Main Transition Initialization - main_end # Main End - Scene_Battle#update - update_interpreter # Update Battle Interpreter - update_systems # Update Screen & Timer - update_transition # Update Transition - update_message? # Update Message Test - update_sseffect? # Update Spriteset Effect Test - update_gameover? # Update Gameover Test - update_title? # Update Title Test - update_abort? # Update Abort Test - update_wait? # Update Wait Test - update_forcing? # Update Forcing Test - update_battlephase # Update Battle Phase - Scene_Shop#main - main_window # Main Window Initialization - Scene_Name#main - main_variable # Main Variable Initialization - main_window # Main Window Initialization - Scene_Gameover#main - main_sprite # Main Sprite Initialization - main_audio # Main Audio Initialization - main_transition # Main Transition Initialization - main_end # Main End - Scene_Debug#main - main_window # Main Window Initialization * Deprecated Methods : - Scene_Title : main_background -> main_sprite - Scene_Title : main_scenechange? -> main_break? - Scene_Map : main_draw -> main_spriteset ; main_window - Scene_Map : main_scenechange? -> main_break? - Scene_Map : main_tiletrigger -> main_end - Scene_Map : update_graphics -> nil - Scene_Map : update_scene -> update_calling - Scene_Title : main_windows -> main_window - Scene_Title : main_scenechange? -> main_break? - Scene_Battle : main_temp -> main_battledata - Scene_Battle : main_troop -> main_troopdata - Scene_Battle : main_command -> main_windows - Scene_Battle : main_windows -> main_window - Scene_Battle : main_scenechange? -> main_break? #------------------------------------------------------------------------------ * 5.0.4 - Part IV * Altered Classes : - Window_ShopCommand # Child-class of Window_HorizCommand - Window_PartyCommand # Child-class of Window_HorizCommand * Rewrote Methods (Methods Created In Part III) : - Scene_Title#main_window # Assigns Commands with SDK Commands - Scene_Menu#main_command_window # Assigns Commands with SDK Commands - Scene_End#main_window # Assigns Commands with SDK Commands - Scene_Battle#main_window # Assigns Commands with SDK Commands * Command Methods : - Scene_Title#update - main_command_input # Command Branch - disabled_main_command? # Test For Disabled Command - Scene_Menu#update_command - disabled_main_command? # Test For Disabled Command - main_command_input # Command Branch - command_item # Item Command - command_skill # Skill Command - command_equip # Equip Command - command_status # Status Command - command_save # Save Command - command_endgame # End Game Command - active_status_window # Activate Status Method - Scene_Menu#update_status - disabled_sub_command? # Test For Disabled Command - sub_command_input # Command Branch - command_skill # Skill Command - command_equip # Equip Command - command_status # Status Command - Scene_End#update - disabled_main_command? # Test For Disabled Command - main_command_input # Branch Command - command_to_title # To Title Command - command_shutdown # Shutdown Command - command_cancel # Cancel Command - Scene_Battle#update_phase2 - phase2_command_disabled? # Test For Disabled Command - phase2_command_input # Command Branch - phase2_command_fight # Fight Command - phase2_command_escape # Escape Command - Scene_Battle#update_phase3_basic_command - phase3_basic_command_disabled? # Test for Disabled Command - phase3_basic_command_input # Command Branch - phase3_command_attack # Attack Command - phase3_command_skill # Skill Command - phase3_command_guard # Guard Command - phase3_command_item # Item Command - Scene_Shop#update_command - disabled_main_command? # Test for Disabled Command - main_command_input # Command Branch - command_main_buy # Command Buy - command_main_sell # Command Sell - command_exit # Command Exit - Scene_Shop#update_number - number_cancel_command_input # Command Branch - number_command_input # Command Branch - command_number_buy # Command Buy - command_number_sell # Command Sell * Deprecated Methods : - Scene_Menu : buzzer_check -> disabled_main_command? - Scene_Menu : update_command_check -> main_command_input - Scene_Menu : update_status_check -> sub_command_input - Scene_Menu : command_start_skill -> command_skill - Scene_Menu : command_start_equip -> command_equip - Scene_Menu : command_start_status -> command_status - Scene_Battle : check_commands -> phase3_basic_command_input - Scene_Battle : update_phase3_command_attack -> phase3_command_attack - Scene_Battle : update_phase3_command_skill -> phase3_command_skill - Scene_Battle : update_phase3_command_guard -> phase3_command_guard - Scene_Battle : update_phase3_command_item -> phase3_command_item * Removed Methods : - Scene_Menu#commands_init -> See SDK::Scene_Commands::Scene_Menu - Scene_Battle#commands_init -> See SDK::Scene_Commands::Scene_Battle - Scene_Battle#make_basic_action_result_attack - Scene_Battle#make_basic_action_result_guard - Scene_Battle#make_basic_action_result_escape - Scene_Battle#make_basic_action_result_nothing #------------------------------------------------------------------------------ * 5.0.5 - Individual Parts Listing Part 2 - 'RPG::Sprite#update' - 'Game_Map#setup' - 'Game_Map#update' - 'Game_Battler#attack_effect' - 'Game_Battler#skill_effect' - 'Game_Battler#item_effect' - 'Game_Battler#slip_damage_effect' - 'Game_Actor#exp=' - 'Game_Character#update' - 'Game_Event#refresh' - 'Game_Player#update' - 'Sprite_Battler#update' - 'Spriteset_Map#initialize' - 'Spriteset_Map#update' - 'Spriteset_Battle#initialize' - 'Spriteset_Battle#update' - 'Window_SaveFile#initialize' Part 3 - 'Part 3#Scene_Title' - 'Part 3#Scene_Map' - 'Part 3#Scene_Menu' - 'Part 3#Scene_Item' - 'Part 3#Scene_Skill' - 'Part 3#Scene_Equip' - 'Part 3#Scene_Status' - 'Part 3#Scene_File' - 'Part 3#Scene_Save' - 'Part 3#Scene_Load' - 'Part 3#Scene_End' - 'Part 3#Scene_Battle' - 'Part 3#Scene_Shop' - 'Part 3#Scene_Name' - 'Part 3#Scene_Gameover' - 'Part 3#Scene_Debug' Part 4 - 'Part 4#Scene_Title' - 'Part 4#Scene_Menu' - 'Part 4#Scene_End' - 'Part 4#Scene_Battle' - 'Part 4#Scene_Shop' #------------------------------------------------------------------------------ * 5.1 - SDK Module ~ Constants - Version : Specifies SDK Version (Float) - Parts : Specifies SDK Parts (Array of Integers) - Show_Error_Disable_Message : Show Error Messages (Boolean) - Show_Method_Overwrite_Error : Show Method Errors (Boolean) ~ Method Instances - @list : Specifies Logged Scripts (Hash) Setup : script_name => [ scripter, version, date ] script_name : Script Name (String) scripter : Scripter Name (String) version : Version Number (Numeric) date : Script Date (String) Default : nil - @enabled : Specifies Enabled Scripts (Hash) Setup : script_name => boolean script_name : Script Name (String) boolean : true or false Default : false - @aliases : Specifies Aliased Methods (Hash) Setup : script_name => [ [class, old_method, new_method], ... ] script_name : Script Name (String) class : Class Name (Symbol) old_method : Method Name (Symbol) new_method : Method Name (Symbol) Default : [] - @overwrites : Specifies Overwrote Methods (Hash) Setup : script_name => [ [class, method], ... ] script_name : Script Name (String) method : Method Name (Symbol) Default : [] - @method_branch_log : Specifies SDK Method Branches (Hash) Setup : [class, method] => [method, ... ] class : Class Name (Symbol) method : Method Name (Symbol) - @last_script : Specifies Last Logged Scripts (String) ~ Methods - SDK.log(script, name, ver, date) script : Script Name (String) name : Scripter Name (String) ver : Version (Float) date : Date (String) - SDK.log_alias(classname, oldmethodname, newmethodname) classname : Class Name (Symbol) oldmethodname : Old Method Name (Symbol) newmethodname : New Method Name (Symbol) - SDK.log_overwrite(classname, methodname) classname : Class Name (Symbol) methodname : Method Name (Symbol) - self.log_branch(classname, methodname, *sub_methods) classname : Class Name (Symbol) methodname : Method Name (Symbol) submethods : Method Name (Symbol) - self.check_requirements(version = 2.3, parts = [1], scripts = []) version : Required SDK Version or greater (Float) parts : Required SDK Parts (Array of Integers) scripts : Script Name (String) Array of Script Names (Strings) Hash of Script Name => Version (Hash) - self.check_individual_parts(*individual_parts) individual_parts : Part Name (String) - self.enable(script) script : Script Name (String) - self.disable(script) script : Script Name (String) - self.write(scripts = self.sorted_log, filename = 'Scripts List.txt') scripts : Array of Script Info filename : Filename of Log - self.write_enabled - self.write_aliases - self.write_overwrites - self.return_log(script = '') script : Script Name or No Argument - self.return_enabled_log(script = '') script : Script Name or No Argument - self.return_alias_log(script = '') script : Script Name or No Argument - self.return_overwrite_log(script = '') script : Script Name or No Argument - self.text_box_input(element, index) - self.event_comment_input(*args) #============================================================================== 6.0 - SDK Tools The following tools are included in the SDK to help improve the development process: 6.1 - Logging Scripts 6.2 - Checking Script Requirements (Script Dependencies) 6.3 - Logging Aliased & Overwrote Methods 6.4 - Enabling/Disabling Scripts 6.5 - Standard Text Box Input 6.6 - Standard Event Comment Input 6.7 - Scene_Base 6.8 - Scene Command Input #------------------------------------------------------------------------------ * 6.1 – Logging Scripts All SDK-compliant scripts should be logged. This is done by calling the SDK.log(script, name, ver, date) method, where script = script name name = your name ver = version date = date last updated #------------------------------------------------------------------------------ * 6.2 - Checking SDK Requirements All SDK-compliant scripts must check for for the current SDK version and required SDK parts. This is done by calling : SDK.check_requirements(version, [parts], [scripts]) or SDK.check_requirements(version, [parts], {scripts}) version = Required Version of SDK (or greater) parts = Array of all SDK required parts (part 1 is not required) scripts = Array of required script names or scripts = Hash with script names as key and required min version as values If the requirements are not met, the script will be disabled and an error will be given on why the script was disabled. * 6.2.1 - Checking SDK individual parts You may check individual parts instead of entire parts using the following method: SDK.check_individual_parts(*individual_parts) This is none-case sensitive, but be sure to one of the individual part names outlined in 5.0.5 #------------------------------------------------------------------------------ * 6.3 - Logging Aliased & Overwrote Methods Aliased methods must be logged using : alias_method :yourname_scriptname_classname_methodname, :oldmethodname or alias yourname_scriptname_classname_methodname oldmethodname SDK.log_alias(:classname, :oldmethodname, :newmethodname) Overwrote methods must be logged using : SDK.log_overwrite(:classname, :methodname) The reason for this is there is an auto-error detection system that will check method overwrites for compatability issues. #------------------------------------------------------------------------------ * 6.4 – Enabling/Disabling Scripts When a script is logged it is also enabled. A script can be enabled and disabled using the following calls: SDK.enable('Script Name') SDK.disable('Script Name') All non-default scripts (and code added to default scripts) must be enclosed in an if statement that checks whether or not they have been enabled, as follows: #-------------------------------------------------------------------------- # Begin SDK Enabled Check #-------------------------------------------------------------------------- if SDK.enabled?('Script Name') [Script or Code] end #-------------------------------------------------------------------------- # End SDK Enabled Test #-------------------------------------------------------------------------- Keep in mind that this if statement can not continue on to other pages and every page needs its own if statement testing the state of the script. As well every script should have its own test. #------------------------------------------------------------------------------ * 6.5 – Standard Text Box Input Any script that requires input from a database text field should use the following: SDK.text_box_input(element, index) where: element = an object of the text field index = the index in which your script call falls The text field should be formatted in the following way: "Default value | script call | script call" #------------------------------------------------------------------------------ * 6.6 – Standard Event Comment Input Any script that requires input from an event comment should use the following: SDK.event_comment_input(event, elements, trigger) where: event = an object of the event elements = the number of elements the method is to process trigger = the text value triggering the script to start processing or SDK.event_comment_input(page, elements, trigger) where: page = an object of the event.page elements = the number of elements the method is to process trigger = the text value triggering the script to start processing The method returns nil if the trigger can not be found; otherwise, it returns a list of the parameters from the event. #------------------------------------------------------------------------------ * 6.7 – Scene Base (Part I) This script was designed to act as a parent class for all scenes. It provides 2 major purposes : a) Give the Main Processing Method a Common Structure b) Automatically Update & Dispose All Spritesets, Sprites, Windows or any other instance variable that responds to :update or :dispose This is a script for developers, not non-scripters. If you do not plan to create scenes in RMXP, this isn't needed. The SDK::Scene_Base class divides the main processing method into : main_variable main_spriteset main_sprite main_window main_audio main_transition main_loop main_update main_breaktest main_dispose main_end When making scenes, make Scene_Base the parent class. Organize the creation of variables, spritesets, sprites, windows and audio within these methods: main_variable Used for Variables Non-Sprite or Window Related main_spriteset Used for spriteset setup main_sprite Used for sprite setsup main_window Used for window setup main_audio Used for Audio setup You need to only use methods needed and others may be leftout. It is advised to place super calls within these methods, in case of further updates or additions to the SDK::Scene_Base class. ** Notes ** main_transition This method can can be left alone unless you are wanting to alter from the default Graphics.transition call. main_loop / main_update This method updates the Graphics and Input modules. It is advised to add other module updates directly to the Scene_Base class (such as the Keyboard or Mouse Module). The sub-method to this is main_update, where the automatic update takes place of objects. ** Special Note On Automatic Update & Dispose The autoupdate and autodispose method will test every instance object to check if it responds to the method names list below. This will pass through arrays and hashes as well. Basic Update Processing if object responds to :update if object responds to :disable_update? return if object :disable_update? end update object end Basic Dispose Processing if object responds to :dispose if object responds to :disposed? return if object :disposed? end dispose object end main_breaktest This method test to break the scene loop. By default, it returns true only when the $scene changes to another scene class. main_dispose Like the main_update method, this method is designed to automatically dispose all instance variables. main_end This method was added on in the event you are wanting to add additional coding after the scene has been executed and exited. #------------------------------------------------------------------------------ * 5.8 - Scene Command Input (Part IV) The SDK has a sub-module (SDK::Scene_Commands) that holds more sub-modules containing constants for scene commands. Each sub-module of Scene_Commands should match the name of the scene you are adding commands to. If you add any commands to the default scenes, the commands are to be placed with here. It is advised that any custom scenes you create with command windows are added here as well. Each C trigger branch is set up as the following : if Input.trigger?(Input::C) if <phasename>_command_disabled? <play_buzzer_se> return end <phasename>_command_input end Commands are not to be branched by the index, but the command using <your_command_window>.command Each command is to have its own method, for simpler modification. * Changes in the Window_Command class The window command class now has added methods, Window_Command#command and Window_Command#commands=. The #command method returns the current command depending upon the index (by default ; can pass alternate index). The #commands= method allows you to reset the commands. This method automatically resets the windows contents, item max, etc. if a change occurs. * Changes in Horizontal Command classes The creation of a Window_HorizCommand class has been created to match the Window_Command class, just horizonatally. All methods of Window_Command are found in this class (default and SDK created methods). The default classes Window_ShopCommand and Window_PartyCommand have been rewrote, using this class. * For more information, refer to Part IV =end #========================================================================= #============================================================================== # ** RMXP Standard Development Kit (SDK) - Update Patch #------------------------------------------------------------------------------ # ** Patch Details # # This patch was created to fix method renames, deprecated methods, etc. to # make scripts specifically designed with an older version of the SDK to # work with the new updated version. # # However, the the commands initialization and command input have been # completely removed, so if any of the scripts use these methods, the # script will be removed until a later date. We are considering an improved # way of handeling, adding and customizing options to scenes. # # If you do not use old scripts that require previous versions, it is # suggested to not have this patch in your project. #============================================================================== #============================================================================== # ** Enable Part V Check #============================================================================== if SDK::Parts.include?(5) #============================================================================== # ** SDK #============================================================================== module SDK #-------------------------------------------------------------------------- def self.print(script = '') return self.return_log(script) end #-------------------------------------------------------------------------- def self.state(script) return self.enabled?(script) end #-------------------------------------------------------------------------- def self.using_old_method p 'You are using a script that uses an old element of the SDK. Using ' + 'this script will cause incompatibility with new versoins of the ' + 'SDK. You must either modify, remove or request for the script to ' + 'be made compatable with the new SDK. We are sorry for the trouble.' end #-------------------------------------------------------------------------- def self.part_included_for_patch?(part_required, method) # Return true If Part Include return true if Parts.include?(part_required) # If Part Not Included p 'You are trying to use the method ' + method + ', which is an ' + 'old SDK method. You need to either enable part ' + part_required.to_s + ' of the SDK, or modify your script using this method.' # Return False return false end end #============================================================================== # ** Game_Map #============================================================================== class Game_map #-------------------------------------------------------------------------- def update_fog_colour method = 'Game_Map#update_fog_colour' update_fog_color if SDK.part_included_for_patch?(2, method) end end #============================================================================== # ** Game_Character #============================================================================== class Game_Character #-------------------------------------------------------------------------- def update_wait method = 'Game_Character#update_wait' return update_wait? if SDK.part_included_for_patch?(2, method) end #-------------------------------------------------------------------------- def update_event_execution? method = 'Game_Character#update_event_execution?' return update_startlock? if SDK.part_included_for_patch?(2, method) end end #============================================================================== # ** Scene_Title #============================================================================== class Scene_Title #-------------------------------------------------------------------------- def main_background method = 'Scene_Title#main_background' main_sprite if SDK.part_included_for_patch?(3, method) end #-------------------------------------------------------------------------- def main_windows method = 'Scene_Title#main_windows' main_window if SDK.part_included_for_patch?(3, method) end #-------------------------------------------------------------------------- def main_scenechange? method = 'Scene_Title#main_scenechange?' return main_break? if SDK.part_included_for_patch?(3, method) end end #============================================================================== # ** Scene_Map #============================================================================== class Scene_Map #-------------------------------------------------------------------------- def main_draw if SDK.part_included_for_patch?(3, 'Scene_Map#main_draw') main_spriteset main_window end end #-------------------------------------------------------------------------- def main_scenechange? method = 'Scene_Map#main_scenechange?' return main_break? if SDK.part_included_for_patch?(3, method) end #-------------------------------------------------------------------------- def main_tiletrigger main_end if SDK.part_included_for_patch?(3, 'Scene_Map#main_tiletrigger') end #-------------------------------------------------------------------------- def update_graphics end #-------------------------------------------------------------------------- def update_scene method = 'Scene_Map#main_scenechange?' update_calling if SDK.part_included_for_patch?(3, method) end end #============================================================================== # ** Scene_Battle #============================================================================== class Scene_Battle #-------------------------------------------------------------------------- def main_temp method = 'Scene_Battle#main_temp' main_battledata if SDK.part_included_for_patch?(3, method) end #-------------------------------------------------------------------------- def main_troop method = 'Scene_Battle#main_troop' main_troopdata if SDK.part_included_for_patch?(3, method) end #-------------------------------------------------------------------------- def main_command method = 'Scene_Battle#main_command' main_windows if SDK.part_included_for_patch?(3, method) end #-------------------------------------------------------------------------- def main_windows method = 'Scene_Battle#main_windows' main_window if SDK.part_included_for_patch?(3, method) end #-------------------------------------------------------------------------- def main_scenechange? method = 'Scene_Battle#main_scenechange?' return main_break? if SDK.part_included_for_patch?(3, method) end end #============================================================================== # ** Scene_Menu #============================================================================== class Scene_Menu #-------------------------------------------------------------------------- def buzzer_check method = 'Scene_Menu#buzzer_check' return disabled_main_command? if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def update_command_check method = 'Scene_Menu#update_command_check' main_command_input if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def update_status_check method = 'Scene_Menu#update_status_check' sub_command_input if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def command_start_skill method = 'Scene_Menu#command_start_skill' command_skill if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def command_start_equip method = 'Scene_Menu#command_start_equip' command_equip if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def command_start_status method = 'Scene_Menu#command_start_status' command_status if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def commands_init SDK.using_old_method end end #============================================================================== # ** Scene_Battle #============================================================================== class Scene_Battle #-------------------------------------------------------------------------- def check_commands method = 'Scene_Battle#check_commands' phase3_basic_command_input if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def update_phase3_command_attack method = 'Scene_Battle#update_phase3_command_attack' phase3_command_attack if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def update_phase3_command_skill method = 'Scene_Battle#update_phase3_command_skill' phase3_command_skill if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def update_phase3_command_guard method = 'Scene_Battle#update_phase3_command_guard' phase3_command_guard if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def update_phase3_command_item method = 'Scene_Battle#update_phase3_command_item' phase3_command_item if SDK.part_included_for_patch?(4, method) end #-------------------------------------------------------------------------- def commands_init SDK.using_old_method end #-------------------------------------------------------------------------- def make_basic_action_result_attack SDK.using_old_method end #-------------------------------------------------------------------------- def make_basic_action_result_guard SDK.using_old_method end #-------------------------------------------------------------------------- def make_basic_action_result_escape SDK.using_old_method end #-------------------------------------------------------------------------- def make_basic_action_result_nothing SDK.using_old_method end end #============================================================================== # ** Ends Enable Part V Check #============================================================================== end #============================================================================== # ** SDK Vocab #------------------------------------------------------------------------------ # This module is the same as SDK::Scene_Commands. #============================================================================== module SDK::Vocab include SDK::Scene_Commands end #============================================================================== # ** SDK #============================================================================== module SDK #-------------------------------------------------------------------------- # * Version & Parts Log Correction #-------------------------------------------------------------------------- Version = 2.4 Parts << 1 unless Parts.include?(1) Parts.delete(4) if Parts.include?(4) && !Parts.include?(3) Individual_Parts.collect! {|i| i.upcase} #-------------------------------------------------------------------------- # * Individual Parts - Part Section #-------------------------------------------------------------------------- Individual_Parts_Sections = {} for ind in ['RPG::Sprite#update', 'Game_Map#setup', 'Game_Map#update', 'Game_Battler#attack_effect', 'Game_Battler#skill_effect', 'Game_Battler#item_effect', 'Game_Battler#slip_damage_effect', 'Game_Actor#exp=', 'Game_Character#update', 'Game_Event#refresh', 'Game_Player#update', 'Sprite_Battler#update', 'Spriteset_Map#initialize', 'Spriteset_Map#update', 'Spriteset_Battle#initialize', 'Spriteset_Battle#update', 'Window_SaveFile#initialize'] Individual_Parts_Sections[ind.upcase] = 2 end for ind in ['Part 3#Scene_Title', 'Part 3#Scene_Map', 'Part 3#Scene_Menu', 'Part 3#Scene_Item', 'Part 3#Scene_Skill', 'Part 3#Scene_Equip', 'Part 3#Scene_Status', 'Part 3#Scene_File', 'Part 3#Scene_Save', 'Part 3#Scene_Load', 'Part 3#Scene_End', 'Part 3#Scene_Battle', 'Part 3#Scene_Shop', 'Part 3#Scene_Name', 'Part 3#Scene_Gameover', 'Part 3#Scene_Debug'] Individual_Parts_Sections[ind.upcase] = 3 end for ind in ['Part 4#Scene_Title', 'Part 4#Scene_Menu', 'Part 4#Scene_End', 'Part 4#Scene_Battle', 'Part 4#Scene_Shop'] Individual_Parts_Sections[ind.upcase] = 4 end #-------------------------------------------------------------------------- # * Script, Alias, Overwrite & Method Branch Log Logging #-------------------------------------------------------------------------- @list = {} @enabled = {} @enabled.default = false @aliases = {} @aliases.default = [] @overwrites = {} @overwrites.default = [] @method_branch_log = {} @last_script = 'SDK' #-------------------------------------------------------------------------- # * Logs a custom script #-------------------------------------------------------------------------- def self.log(script, name, ver, date) # Logs Script @list[script] = [name, ver, date] # Enables Script @enabled[script] = true # Sets Last Script @last_script = script end #-------------------------------------------------------------------------- # * Logs an alias #-------------------------------------------------------------------------- def self.log_alias(classname, oldmethodname, newmethodname) # Gets Value value = [classname, oldmethodname, newmethodname] # Convert Values to Symbols value.collect! { |x| (x.is_a?(Symbol) ? x : x.to_s.to_sym) } # Creates Array @aliases[@last_script] = [] unless @aliases.has_key?(@last_script) # Logs Alias @aliases[@last_script] << value # Check for overwrites self.check_for_overwrites(value) if Show_Method_Overwrite_Error end #-------------------------------------------------------------------------- # * Logs an overwrite #-------------------------------------------------------------------------- def self.log_overwrite(classname, methodname) # Gets Value value = [classname, methodname] # Convert Values to Symbols value.collect! { |x| (x.is_a?(Symbol) ? x : x.to_s.to_sym)} # Creates Array @overwrites[@last_script] = [] unless @overwrites.has_key?(@last_script) # Stop if Overwrite Logged return if @overwrites[@last_script].include?(value) # Log Overwrite @overwrites[@last_script] << value # Check for aliases self.check_for_aliases(value) if Show_Method_Overwrite_Error end #-------------------------------------------------------------------------- # * Logs an method branch #-------------------------------------------------------------------------- def self.log_branch(classname, methodname, *sub_methods) # Creates Key key = [classname, methodname] # Convert Values to Symbols key.collect! { |x| (x.is_a?(Symbol) ? x : x.to_s.to_sym)} # Creates Sub Method List (if none yet recorded) @method_branch_log[key] = [] unless @method_branch_log.has_key?(key) # Adds New Sub Methods @method_branch_log[key] << sub_methods # Organize Sub Method List @method_branch_log[key].flatten! @method_branch_log[key].uniq! end #-------------------------------------------------------------------------- # * Check Requirements #-------------------------------------------------------------------------- def self.check_requirements(version = 2.3, parts = [1], scripts = []) # Start Missing Requirements missing_reqs = {} # Checks Version missing_reqs[0] = version unless Version >= version # Checks Required Part for part in parts unless Parts.include?(part) missing_reqs[1] = parts break end end # Checks Required Scripts if scripts.is_a?(String) unless self.enabled?(scripts) missing_reqs[2] = [] unless missing_reqs.has_key?(2) missing_reqs[2] << scripts end elsif scripts.is_a?(Array) for script in scripts unless self.enabled?(script) missing_reqs[2] = [] unless missing_reqs.has_key?(2) missing_reqs[2] << script end end elsif scripts.is_a?(Hash) scripts.each do |script, v| if self.enabled?(script) == false missing_reqs[2] = [] unless missing_reqs.has_key?(2) missing_reqs[2] << script elsif self.enabled?(script, v) == false missing_reqs[3] = {} unless missing_reqs.has_key?(3) missing_reqs[3][script] = v end end end # If Script Needing Disabled unless missing_reqs.size == 0 # Disable Script self.disable(@last_script) # If Show Auto Disable Script Message if Show_Error_Disable_Message # Show Error Message self.auto_disable_script_message(@last_script, missing_reqs) end end end #-------------------------------------------------------------------------- # * Check Individual Parts #-------------------------------------------------------------------------- def self.check_individual_parts(*ind_parts) # Starts Empty Missing Array missing = [] # Pass through methods ind_parts.each do |ind_part| # Skip if Individual Part Include next if Individual_Parts.include?(ind_part.upcase) # Skip if Complete Part Included next if Parts.include?(Individual_Parts_Sections[ind_part.upcase]) # Add Missing Part missing << ind_part.upcase end # If Script Needing Disabled unless missing_reqs.size == 0 # Disable Script self.disable(@last_script) # If Show Auto Disable Script Message if Show_Error_Disable_Message # Print message p 'The following individual sections are needed for the script ' + @last_script + ' to work: ' + missing.join(', ') end end end #-------------------------------------------------------------------------- # * Enables the passed script #-------------------------------------------------------------------------- def self.enable(script) @enabled[script] = true end #-------------------------------------------------------------------------- # * Disables the passed script #-------------------------------------------------------------------------- def self.disable(script) @enabled[script] = false end #-------------------------------------------------------------------------- # * Enabled Test #-------------------------------------------------------------------------- def self.enabled?(script, version = nil) # If Version Specified & List Included if version != nil && @list.has_key?(script) # Return False Unless Script Version High Enough return false unless @list[script][1] >= version end # Return Enabled return @enabled[script] end #-------------------------------------------------------------------------- # * Writes a list of the custom scripts to a file #-------------------------------------------------------------------------- def self.write(scripts = self.sorted_log, filename = 'Scripts List.txt') # Opens / Creates File & Writes Script Listings file = File.open(filename, 'wb') for script in scripts l = "#{script[0]} : #{script[1]} Version #{script[2]} (#{script[3]})\n" file.write(l) end file.close end #-------------------------------------------------------------------------- # * Writes a list of the enabled scripts to a file #-------------------------------------------------------------------------- def self.write_enabled self.write(self.sorted_enabled_log, 'Enabled Script List.txt') end #-------------------------------------------------------------------------- # * Writes a list of the aliases #-------------------------------------------------------------------------- def self.write_aliases # Opens / Creates File & Writes Script Listings file = File.open('Alias List.txt', 'wb') for line in self.sorted_alias_log file.write("#{line}\n") end file.close end #-------------------------------------------------------------------------- # * Writes a list of the overwrites #-------------------------------------------------------------------------- def self.write_overwrites # Opens / Creates File & Writes Script Listings file = File.open('Overwrites List.txt', 'wb') for line in self.sorted_overwrite_log file.write("#{line}\n") end file.close end #-------------------------------------------------------------------------- # * Returns a list of custom scripts #-------------------------------------------------------------------------- def self.return_log(script = '') return script == '' || @list.include?(script) == false ? self.sorted_log : @list[script] end #-------------------------------------------------------------------------- # * Returns a list of enabled scripts #-------------------------------------------------------------------------- def self.return_enabled_log(script = '') return script == '' || self.enabled?(script) == false ? self.sorted_enabled_log : @enabled[script] end #-------------------------------------------------------------------------- # * Returns alias log #-------------------------------------------------------------------------- def self.return_alias_log(script = '') return script == '' || @list.include?(script) == false ? self.sorted_alias_log : @aliases[script] end #-------------------------------------------------------------------------- # * Returns overwrite log #-------------------------------------------------------------------------- def self.return_overwrite_log(script = '') return script == '' || @list.include?(script) == false ? self.sorted_overwrite_log : @overwrites[script] end #-------------------------------------------------------------------------- # * Sort Script List # # sort_type : 0 - Scripter, 1 - Script Name #-------------------------------------------------------------------------- def self.sorted_log(sort_type = 0) # Creates Sorted Nested Array nested = @list.sort do |a, b| sort_type == 0 ? a[1][0] <=> b [1][0] : a[0] <=> b[0] end # Creates Sorted List lst = [] nested.each do |x| x.flatten! lst << ((sort_type == 0 ? [x[1], x[0]] : [x[0], x[1]]) << x[2] << x[3]) end # Return List return lst end #-------------------------------------------------------------------------- # * Sort Enabled Script List # # sort_type : 0 - Scripter, 1 - Script Name #-------------------------------------------------------------------------- def self.sorted_enabled_log(sort_type = 0) # Creates Sorted Nested Array nested = @list.sort do |a, b| sort_type == 0 ? a[1][0] <=> b [1][0] : a[0] <=> b[0] end # Creates Sorted List lst = [] nested.each do |x| next unless @enabled[x[0]] x.flatten! lst << ((sort_type == 0 ? [x[1], x[0]] : [x[0], x[1]]) << x[2] << x[3]) end # Return List return lst end #-------------------------------------------------------------------------- # * Sort Alias List #-------------------------------------------------------------------------- def self.sorted_alias_log # Creates Sorted List lst = [] for sname in @aliases.keys.sort for a in @aliases[sname] c, o, n = "Class: #{a[0]}", "Old Name: #{a[1]}", "New Name: #{a[2]}" lst << "#{sname} - #{c} - #{o} - #{n}" end end # Return List return lst end #-------------------------------------------------------------------------- # * Sort Overwrite List #-------------------------------------------------------------------------- def self.sorted_overwrite_log # Creates Sorted List lst = [] for sname in @overwrites.keys.sort lst << "#{sname} - Class: #{o[0]} - Method:#{o[1]}" end # Return List return lst end #-------------------------------------------------------------------------- # * Show Auto Disable Error Message # # Missing Reqs = { type => parameters } # # Type 0 : Not High Enough Version # Parameters : [version_required] # # Type 1 : SDK Parts Missing # Parameters : [part, ...] # # Type 2 : Missing Script # Parameters : [script, ...] # # Type 3 : Not High Enough Script Version # Parameters : {script => version, ...} #-------------------------------------------------------------------------- def self.auto_disable_script_message(script, missing_reqs) # Start Message Text t = 'The following script has been disabled : ' + script # If Missing Reqs Specified unless missing_reqs.size == 0 # Adds Message Text t += ' for the following reasons : ' ta = [] # Pass Through Missing Reqs missing_reqs.each do |type, parameters| # Branch By Type case type when 0 # Not High Enough SDK Version ta << 'SDK version not high enough version. Please update to ' + 'at least version ' + parameters.to_s when 1 # Missing SDK Part ta << 'You are missing part of the SDK. Please add the following ' + 'parts - ' + parameters.join(' & ') when 2 # Missing Scripts parameters.each do |script| ta << 'Script missing - ' + script end when 3 # Not High Enough Version parameters.each do |script, v| ta << 'Script not high enough version - ' + script + ' (Required ' + v.to_s + ' or higher)' end end end # Add Message Text t += ta.join(' ; ') end # Print Error Message p t end #-------------------------------------------------------------------------- # * Check for Overwrites # # Value = [classname, oldmethodname, newmethodname] #-------------------------------------------------------------------------- def self.check_for_overwrites(value) # Pass Through All Method Branches @method_branch_log.each do |classmethod, submethods| # If Class name matches & Sub Methods Include Method if classmethod[0] == value[0] && submethods.include?(value[1]) # Pass Throug All Script Overwrites @overwrites.each do |script, overwrites| # Pass Through Overwrite List overwrites.each do |cm| # If Method Matches if classmethod == cm # Print Error p 'The following script will not work : ' + @last_script, 'Reason : The (' + script + ') overwrites the ' + 'method ' + cm[1].to_s + ' erasing the branched method ' + value[1].to_s + ' branched from ' + value[0].to_s + ' that ' + 'the ' + script + ' uses' return end end end end end end #-------------------------------------------------------------------------- # * Check for Aliases # # Value = [classname, methodname] #-------------------------------------------------------------------------- def self.check_for_aliases(value) # Check If Method Ever Aliased @aliases.each do |script, list| # Pass Through Alias List list.each do |con| # If Class & Method Match if con[0] == value[0] && con[1] == value[1] # Print Error p 'The following script will not work : ' + script, 'Reason : The (' + @last_script + ') overwrites the method ' + value[1].to_s + ' aliased from ' + "#{con[1]} to #{con[2]}" + 'found in class ' + value[0] end end end # Pass Through All Method Branches @method_branch_log.each do |classmethod, submethods| # If Class name matches & Sub Methods Include Method if classmethod == value # Pass Through Aliases @aliases.each do |script, list| # Pass Through Alias List list.each do |con| # If Sub Methods Include Old Method if submethods.include?(con[1]) # Print Error p 'The following script will not work : ' + script, 'Reason : The (' + @last_script + ') overwrites the ' + 'method ' + con[1].to_s + ' erasing the branched method ' + value[1].to_s + ' branched from ' + value[0].to_s + ' that '+ 'the ' + script + ' uses' end end end end end end #-------------------------------------------------------------------------- # * Evals text from an input source #-------------------------------------------------------------------------- def self.text_box_input(element, index) return if index == 0 commands = element.split('|') eval(commands[index]) end #-------------------------------------------------------------------------- # * Returns a list of parameters from an event's comments #-------------------------------------------------------------------------- def self.event_comment_input(*args) parameters = [] list = *args[0].list elements = *args[1] trigger = *args[2] return nil if list == nil return nil unless list.is_a?(Array) for item in list next unless item.code == 108 || item.code == 408 if item.parameters[0] == trigger start = list.index(item) + 1 finish = start + elements for id in start...finish next if !list[id] parameters.push(list[id].parameters[0]) end return parameters end end return nil end end #============================================================================== # ** SDK::Scene Base #============================================================================== class SDK::Scene_Base #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize @previous_scene = $scene.class end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main main_variable # Main Variable Initialization main_spriteset # Main Spriteset Initialization main_sprite # Main Sprite Initialization main_window # Main Window Initialization main_audio # Main Audio Initialization main_transition # Main Transition Initialization loop do # Scene Loop main_loop # Main Loop break if main_break? # Break If Breakloop Test end # End Scene Loop Graphics.freeze # Prepare for transition main_dispose # Main Dispose main_end # Main End end #-------------------------------------------------------------------------- # * Main Processing : Variable Initialization #-------------------------------------------------------------------------- def main_variable ; end #-------------------------------------------------------------------------- # * Main Processing : Spriteset Initialization #-------------------------------------------------------------------------- def main_spriteset ; end #-------------------------------------------------------------------------- # * Main Processing : Sprite Initialization #-------------------------------------------------------------------------- def main_sprite ; end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window ; end #-------------------------------------------------------------------------- # * Main Processing : Audio Initialization #-------------------------------------------------------------------------- def main_audio ; end #-------------------------------------------------------------------------- # * Main Processing : Transition #-------------------------------------------------------------------------- def main_transition Graphics.transition end #-------------------------------------------------------------------------- # * Main Processing : Loop #-------------------------------------------------------------------------- def main_loop Graphics.update # Update game screen Input.update # Update input information main_update # Update scene objects update # Update Processing end #-------------------------------------------------------------------------- # * Main Processing : Break Loop Test #-------------------------------------------------------------------------- def main_break? return $scene != self # Abort loop if sceen is changed end #-------------------------------------------------------------------------- # * Main Processing : Disposal #-------------------------------------------------------------------------- def main_dispose # Passes Through All Instance Variables self.instance_variables.each do |object_name| # Evaluates Object object = eval object_name # Pass Object To Auto Dispose auto_dispose(object) end end #-------------------------------------------------------------------------- # * Main Processing : Ending #-------------------------------------------------------------------------- def main_end ; end #-------------------------------------------------------------------------- # * Main Processing : Update #-------------------------------------------------------------------------- def main_update # Passes Through All Instance Variables self.instance_variables.each do |object_name| # Evaluates Object object = eval object_name # Pass Object To Auto Update auto_update(object) end end #-------------------------------------------------------------------------- # * Main Processing : Auto Update #-------------------------------------------------------------------------- def auto_update(object) # Return If Object isn't a Hash, Array or Respond to Update return unless object.is_a?(Hash) || object.is_a?(Array) || object.respond_to?(:update) # If Hash Object if object.is_a?(Hash) object.each do |key, value| # Pass Key & Value to Auto Update auto_update(key) ; auto_update(value) end return end # If Array Object if object.is_a?(Array) # Pass All Object to Auto Update object.each {|obj| auto_update(obj)} return end # If Responds to Dispose if object.respond_to?(:dispose) # If Responds to Disposed? && is Disposed or Responds to Disable # Dispose and dispose is disabled if (object.respond_to?(:disposed?) && object.disposed?) || (object.respond_to?(:disable_dispose?) && object.disable_dispose?) # Return return end end # If Responds to Update if object.respond_to?(:update) # If Responds to Disable Update & Update Disabled if object.respond_to?(:disable_update?) && object.disable_update? # Return return end # Update Object object.update end end #-------------------------------------------------------------------------- # * Main Processing : Auto Dispose #-------------------------------------------------------------------------- def auto_dispose(object) # Return If Object isn't a Hash, Array or Respond to Dispose return unless object.is_a?(Hash) || object.is_a?(Array) || object.respond_to?(:dispose) # If Hash Object if object.is_a?(Hash) object.each do |key, value| # Pass Key & Value to Auto Dispose auto_dispose(key) ; auto_dispose(value) end return end # If Array Object if object.is_a?(Array) # Pass All Object to Auto Dispose object.each {|obj| auto_dispose(obj)} return end # If Responds to Dispose if object.respond_to?(:dispose) # If Responds to Disposed? && is Disposed or Responds to Disable # Dispose and dispose is disabled if (object.respond_to?(:disposed?) && object.disposed?) || (object.respond_to?(:disable_dispose?) && object.disable_dispose?) # Return return end # Dispose Object object.dispose end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update ; end end #============================================================================== # ** Module #============================================================================== class Module #-------------------------------------------------------------------------- # * Alias Log #-------------------------------------------------------------------------- @@aliases = {} #-------------------------------------------------------------------------- # * Alias Listings #-------------------------------------------------------------------------- alias_method :sdk_aliaslog_aliasmethod, :alias_method #-------------------------------------------------------------------------- # * Alias Method #-------------------------------------------------------------------------- def alias_method(newmethodname, oldmethodname, prevent_stack = true) # Create Key If not already created @@aliases[self] = [] unless @@aliases.has_key?(self) # Return if new method name included return if @@aliases[self].include?(newmethodname) && prevent_stack # Add new method name @@aliases[self] << newmethodname # Log Alias SDK.log_alias(self, oldmethodname, newmethodname) # Original Alias Method sdk_aliaslog_aliasmethod(newmethodname, oldmethodname) end end #============================================================================== # ** Object #============================================================================== class Object #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_accessor :disable_dispose, :disable_update #-------------------------------------------------------------------------- # * Alias Listings #-------------------------------------------------------------------------- alias_method :sdk_disableupdate_object_init, :initialize #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize # Original Initialization sdk_disableupdate_object_init # Turn Disable Flags Off @disable_dispose, @disable_update = false, false end #-------------------------------------------------------------------------- # * Disable Dispose #-------------------------------------------------------------------------- def disable_dispose? return @disable_dispose end #-------------------------------------------------------------------------- # * Disable Update #-------------------------------------------------------------------------- def disable_update? return @disable_update end end #============================================================================== # ** Bitmap #============================================================================== class Bitmap #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_accessor :disable_dispose #-------------------------------------------------------------------------- # * Alias Listings #-------------------------------------------------------------------------- alias_method :sdk_bitmap_init, :initialize #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize(*args) # Original Initialization sdk_bitmap_init(*args) # Turn Disable Dispose ON @disable_dispose = true end end #============================================================================== # ** RPG::Event::Page::Condition #============================================================================== class RPG::Event::Page::Condition #-------------------------------------------------------------------------- # * Conditions Met? #-------------------------------------------------------------------------- def conditions_met?(map_id, event_id) # Switch 1 condition confirmation if @switch1_valid && $game_switches[@switch1_id] == false return false end # Switch 2 condition confirmation if @switch2_valid && $game_switches[@switch2_id] == false return false end # Variable condition confirmation if @variable_valid && $game_variables[@variable_id] < @variable_value return false end # Self switch condition confirmation if @self_switch_valid key = [map_id, event_id, @self_switch_ch] if $game_self_switches[key] == false return false end end # Returns True return true end end #============================================================================== # ** RPG::Troop::Page::Condition #============================================================================== class RPG::Troop::Page::Condition #-------------------------------------------------------------------------- # * Conditions Met? #-------------------------------------------------------------------------- def conditions_met?(page_index) # Return False if no conditions appointed unless @turn_valid || @enemy_valid || @actor_valid || @switch_valid return false end # Return False if page already completed if $game_temp.battle_event_flags[page_index] return false end # Confirm turn conditions if @turn_valid n = $game_temp.battle_turn a = @turn_a b = @turn_b if (b == 0 && n != a) || (b > 0 && (n < 1 or n < a or n % b != a % b)) return false end end # Confirm enemy conditions if @enemy_valid enemy = $game_troop.enemies[@enemy_index] if enemy == nil or enemy.hp * 100.0 / enemy.maxhp > @enemy_hp return false end end # Confirm actor conditions if @actor_valid actor = $game_actors[@actor_id] if actor == nil or actor.hp * 100.0 / actor.maxhp > @actor_hp return false end end # Confirm switch conditions if @switch_valid if $game_switches[@switch_id] == false return false end end # Return True return true end end #============================================================================== # ** Window_Base #------------------------------------------------------------------------------ # This class is for all in-game windows. #============================================================================== class Window_Base #-------------------------------------------------------------------------- # * Dispose #-------------------------------------------------------------------------- def dispose return if self.disposed? # Dispose if window contents bit map is set if self.contents != nil self.contents.dispose end super end end #============================================================================== # ** Window_Command #------------------------------------------------------------------------------ # This window deals with general command choices. #============================================================================== class Window_Command < Window_Selectable #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_reader :commands #-------------------------------------------------------------------------- # * Command #-------------------------------------------------------------------------- def command(index = self.index) return @commands[index] end #-------------------------------------------------------------------------- # * Commands #-------------------------------------------------------------------------- def commands=(commands) # Return if Commands Are Same return if @commands == commands # Reset Commands @commands = commands # Resets Item Max item_max = @item_max @item_max = @commands.size # If Item Max Changes unless item_max == @item_max # Deletes Existing Contents (If Exist) unless self.contents.nil? self.contents.dispose self.contents = nil end # Recreates Contents self.contents = Bitmap.new(width - 32, @item_max * 32) end # Refresh Window refresh end end #============================================================================== # ** Window_HorizCommand #------------------------------------------------------------------------------ # This window deals with general command choices. (Horizontal) #============================================================================== class Window_HorizCommand < Window_Selectable #-------------------------------------------------------------------------- # * Public Instance Variables #-------------------------------------------------------------------------- attr_reader :commands attr_accessor :c_spacing attr_accessor :alignment #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize(width, commands, c_spacing = (width - 32) / commands.size) # Compute window height from command quantity super(0, 0, width, 64) @commands = commands @item_max = commands.size @column_max = @item_max @c_spacing = c_spacing @alignment = 1 self.contents = Bitmap.new(@item_max * @c_spacing, height - 32) refresh self.index = 0 end #-------------------------------------------------------------------------- # * Command #-------------------------------------------------------------------------- def command(index = self.index) return @commands[index] end #-------------------------------------------------------------------------- # * Commands #-------------------------------------------------------------------------- def commands=(commands) # Return if Commands Are Same return if @commands == commands # Reset Commands @commands = commands # Resets Item Max item_max = @item_max @item_max = @commands.size @column_max = @item_max # If Item Max Changes unless item_max == @item_max # Deletes Existing Contents (If Exist) unless self.contents.nil? self.contents.dispose self.contents = nil end # Recreates Contents self.contents = Bitmap.new(@item_max * @c_spacing, height - 32) end # Refresh Window refresh end #-------------------------------------------------------------------------- # * Refresh #-------------------------------------------------------------------------- def refresh self.contents.clear for i in 0...@item_max draw_item(i, normal_color) end end #-------------------------------------------------------------------------- # * Draw Item #-------------------------------------------------------------------------- def draw_item(index, color) command = commands[index] x = index * @c_spacing + 4 self.contents.font.color = color self.contents.draw_text(x, 0, @c_spacing - 8, 32, command, @alignment) end #-------------------------------------------------------------------------- # * Disable Item #-------------------------------------------------------------------------- def disable_item(index) draw_item(index, disabled_color) end #-------------------------------------------------------------------------- # * Cursor Rectangle Update #-------------------------------------------------------------------------- def update_cursor_rect if @index < 0 self.cursor_rect.empty else self.cursor_rect.set(@c_spacing * @index, 0, @c_spacing, 32) end end end #============================================================================== # ** Window_SaveFile #------------------------------------------------------------------------------ # This window displays save files on the save and load screens. #============================================================================== class Window_SaveFile < Window_Base #-------------------------------------------------------------------------- # * Object Initialization # file_index : save file index (0-3) # filename : file name #-------------------------------------------------------------------------- def initialize(file_index, filename) super(0, 64 + file_index % 4 * 104, 640, 104) self.contents = Bitmap.new(width - 32, height - 32) @file_index = file_index @filename = filename @time_stamp = Time.at(0) @file_exist = FileTest.exist?(@filename) if @file_exist file = File.open(@filename, "r") @time_stamp = file.mtime @characters = Marshal.load(file) @frame_count = Marshal.load(file) @game_system = Marshal.load(file) @game_switches = Marshal.load(file) @game_variables = Marshal.load(file) @total_sec = @frame_count / Graphics.frame_rate file.close end refresh @selected = false end end #============================================================================== # ** Interpreter #------------------------------------------------------------------------------ # This interpreter runs event commands. This class is used within the # Game_System class and the Game_Event class. #============================================================================== class Interpreter #-------------------------------------------------------------------------- # * Script #-------------------------------------------------------------------------- def command_355 # Set first line to script script = @list[@index].parameters[0] + "\n" # Loop loop do # If next event command is second line of script or after if @list[@index+1].code == 655 # Add second line or after to script script += @list[@index+1].parameters[0] + "\n" # If event command is not second line or after else # Abort loop break end # Advance index @index += 1 end # Evaluation result = eval(script) # If return value is false if result == FalseClass # End return false end # Continue return true end end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('RPG::SPRITE#UPDATE') #============================================================================== # ** RPG::Sprite #============================================================================== class RPG::Sprite #-------------------------------------------------------------------------- SDK.log_branch(RPG::Sprite.to_s.to_sym, :update, :update_whiten, :update_appear, :update_escape, :update_collapse, :update_damage, :update_animation_duration, :update_loop_animation_index, :update_blink) #-------------------------------------------------------------------------- # * Update #-------------------------------------------------------------------------- def update super update_whiten # Update Whiten update_appear # Update Appear update_escape # Update Escape update_collapse # Update Collapse update_damage # Update Damage update_animation_duration # Update Animation Duration update_loop_animation_index # Update Loop Animation update_blink # Update Blink @@_animations.clear # Clear Animations end #-------------------------------------------------------------------------- # * Update Whiten #-------------------------------------------------------------------------- def update_whiten if @_whiten_duration > 0 @_whiten_duration -= 1 self.color.alpha = 128 - (16 - @_whiten_duration) * 10 end end #-------------------------------------------------------------------------- # * Update Appear #-------------------------------------------------------------------------- def update_appear if @_appear_duration > 0 @_appear_duration -= 1 self.opacity = (16 - @_appear_duration) * 16 end end #-------------------------------------------------------------------------- # * Update Escape #-------------------------------------------------------------------------- def update_escape if @_escape_duration > 0 @_escape_duration -= 1 self.opacity = 256 - (32 - @_escape_duration) * 10 end end #-------------------------------------------------------------------------- # * Update Collapse #-------------------------------------------------------------------------- def update_collapse if @_collapse_duration > 0 @_collapse_duration -= 1 self.opacity = 256 - (48 - @_collapse_duration) * 6 end end #-------------------------------------------------------------------------- # * Update Damage #-------------------------------------------------------------------------- def update_damage if @_damage_duration > 0 @_damage_duration -= 1 case @_damage_duration when 38..39 @_damage_sprite.y -= 4 when 36..37 @_damage_sprite.y -= 2 when 34..35 @_damage_sprite.y += 2 when 28..33 @_damage_sprite.y += 4 end @_damage_sprite.opacity = 256 - (12 - @_damage_duration) * 32 if @_damage_duration == 0 dispose_damage end end end #-------------------------------------------------------------------------- # * Update Animation Duration #-------------------------------------------------------------------------- def update_animation_duration if @_animation != nil and (Graphics.frame_count % 2 == 0) @_animation_duration -= 1 update_animation end end #-------------------------------------------------------------------------- # * Update Loop Animation Index #-------------------------------------------------------------------------- def update_loop_animation_index if @_loop_animation != nil and (Graphics.frame_count % 2 == 0) update_loop_animation @_loop_animation_index += 1 @_loop_animation_index %= @_loop_animation.frame_max end end #-------------------------------------------------------------------------- # * Update Blink #-------------------------------------------------------------------------- def update_blink if @_blink @_blink_count = (@_blink_count + 1) % 32 if @_blink_count < 16 alpha = (16 - @_blink_count) * 6 else alpha = (@_blink_count - 16) * 6 end self.color.set(255, 255, 255, alpha) end end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_MAP#SETUP') #============================================================================== # ** Game_Map #------------------------------------------------------------------------------ # This class handles the map. It includes scrolling and passable determining # functions. Refer to "$game_map" for the instance of this class. #============================================================================== class Game_Map #-------------------------------------------------------------------------- SDK.log_branch(:Game_Map, :setup, :setup_map_id, :setup_load, :setup_tileset, :setup_display, :setup_refresh, :setup_events, :setup_common_events, :setup_fog, :setup_scroll) #-------------------------------------------------------------------------- # * Setup # map_id : map ID #-------------------------------------------------------------------------- def setup(map_id) setup_map_id(map_id) # Setup Map ID setup_load # Setup Map Data setup_tileset # Setup Tileset Data setup_display # Setup Display setup_refresh # Setup Refresh setup_events # Setup Events setup_common_events # Setup Common Events setup_fog # Setup Fog setup_scroll # Setup Scroll end #-------------------------------------------------------------------------- # * Setup Map ID #-------------------------------------------------------------------------- def setup_map_id(map_id) # Put map ID in @map_id memory @map_id = map_id end #-------------------------------------------------------------------------- # * Load Map Data #-------------------------------------------------------------------------- def setup_load # Load map from file and set @map @map = load_data(sprintf("Data/Map%03d.rxdata", @map_id)) end #-------------------------------------------------------------------------- # * Setup Tileset #-------------------------------------------------------------------------- def setup_tileset # set tile set information in opening instance variables tileset = $data_tilesets[@map.tileset_id] @tileset_name = tileset.tileset_name @autotile_names = tileset.autotile_names @panorama_name = tileset.panorama_name @panorama_hue = tileset.panorama_hue @fog_name = tileset.fog_name @fog_hue = tileset.fog_hue @fog_opacity = tileset.fog_opacity @fog_blend_type = tileset.fog_blend_type @fog_zoom = tileset.fog_zoom @fog_sx = tileset.fog_sx @fog_sy = tileset.fog_sy @battleback_name = tileset.battleback_name @passages = tileset.passages @priorities = tileset.priorities @terrain_tags = tileset.terrain_tags end #-------------------------------------------------------------------------- # * Setup Display #-------------------------------------------------------------------------- def setup_display # Initialize displayed coordinates @display_x = 0 @display_y = 0 end #-------------------------------------------------------------------------- # * Setup Refresh #-------------------------------------------------------------------------- def setup_refresh # Clear refresh request flag @need_refresh = false end #-------------------------------------------------------------------------- # * Setup Events #-------------------------------------------------------------------------- def setup_events # Set map event data @events = {} for i in @map.events.keys @events[i] = Game_Event.new(@map_id, @map.events[i]) end end #-------------------------------------------------------------------------- # * Setup Common Events #-------------------------------------------------------------------------- def setup_common_events # Set common event data @common_events = {} for i in 1...$data_common_events.size @common_events[i] = Game_CommonEvent.new(i) end end #-------------------------------------------------------------------------- # * Setup Fog #-------------------------------------------------------------------------- def setup_fog # Initialize all fog information @fog_ox = 0 @fog_oy = 0 @fog_tone = Tone.new(0, 0, 0, 0) @fog_tone_target = Tone.new(0, 0, 0, 0) @fog_tone_duration = 0 @fog_opacity_duration = 0 @fog_opacity_target = 0 end #-------------------------------------------------------------------------- # * Setup Scroll #-------------------------------------------------------------------------- def setup_scroll # Initialize scroll information @scroll_direction = 2 @scroll_rest = 0 @scroll_speed = 4 end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_MAP#UPDATE') #============================================================================== # ** Game_Map #------------------------------------------------------------------------------ # This class handles the map. It includes scrolling and passable determining # functions. Refer to "$game_map" for the instance of this class. #============================================================================== class Game_Map #-------------------------------------------------------------------------- SDK.log_branch(:Game_Map, :update, :update_refresh, :update_scrolling, :update_events, :update_common_events, :update_fog_scroll, :update_fog_color, :update_fog) #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update update_refresh # Update Refresh Flag update_scrolling # Update Scrolling update_events # Update Events update_common_events # Update Common Events update_fog_scroll # Update Fog Scrolling update_fog_color # Update Fog Color update_fog # Update Fog end #-------------------------------------------------------------------------- # * Refresh Game Map #-------------------------------------------------------------------------- def update_refresh # Refresh map if necessary if $game_map.need_refresh refresh end end #-------------------------------------------------------------------------- # * Update Scrolling #-------------------------------------------------------------------------- def update_scrolling # If scrolling if @scroll_rest > 0 # Change from scroll speed to distance in map coordinates distance = 2 ** @scroll_speed # Execute scrolling case @scroll_direction when 2 # Down scroll_down(distance) when 4 # Left scroll_left(distance) when 6 # Right scroll_right(distance) when 8 # Up scroll_up(distance) end # Subtract distance scrolled @scroll_rest -= distance end end #-------------------------------------------------------------------------- # * Update Events #-------------------------------------------------------------------------- def update_events # Update map event for event in @events.values event.update end end #-------------------------------------------------------------------------- # * Update Common Events #-------------------------------------------------------------------------- def update_common_events # Update common event for common_event in @common_events.values common_event.update end end #-------------------------------------------------------------------------- # * Update Fog Scroll #-------------------------------------------------------------------------- def update_fog_scroll # Manage fog scrolling @fog_ox -= @fog_sx / 8.0 @fog_oy -= @fog_sy / 8.0 end #-------------------------------------------------------------------------- # * Update Fog Color #-------------------------------------------------------------------------- def update_fog_color # Manage change in fog color tone if @fog_tone_duration >= 1 d = @fog_tone_duration target = @fog_tone_target @fog_tone.red = (@fog_tone.red * (d - 1) + target.red) / d @fog_tone.green = (@fog_tone.green * (d - 1) + target.green) / d @fog_tone.blue = (@fog_tone.blue * (d - 1) + target.blue) / d @fog_tone.gray = (@fog_tone.gray * (d - 1) + target.gray) / d @fog_tone_duration -= 1 end end #-------------------------------------------------------------------------- # * Update Fog #-------------------------------------------------------------------------- def update_fog # Manage change in fog opacity level if @fog_opacity_duration >= 1 d = @fog_opacity_duration @fog_opacity = (@fog_opacity * (d - 1) + @fog_opacity_target) / d @fog_opacity_duration -= 1 end end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_BATTLER#ATTACK_EFFECT') #============================================================================== # ** Game_Battler (part 3) #------------------------------------------------------------------------------ # This class deals with battlers. It's used as a superclass for the Game_Actor # and Game_Enemy classes. #============================================================================== class Game_Battler #-------------------------------------------------------------------------- SDK.log_branch(:Game_Battler, :attack_effect, :attack_effect_setup, :attack_effect_first_hit_result, :attack_effect_base_damage, :attack_effect_element_correction, :attack_effect_critical_correction, :attack_effect_guard_correction, :attack_effect_dispersion, :attack_effect_second_hit_result, :attack_effect_damage, :attack_effect_miss) #-------------------------------------------------------------------------- # * Applying Normal Attack Effects #-------------------------------------------------------------------------- def attack_effect(attacker) # Setup Attack Effect attack_effect_setup # First Hit Detection hit_result = attack_effect_first_hit_result(attacker) # If hit occurs if hit_result # Calculate Basic Damage attack_effect_base_damage(attacker) # Element Correction attack_effect_element_correction(attacker) # If damage value is strictly positive if self.damage > 0 # Critical correction attack_effect_critical_correction(attacker) # Guard correction attack_effect_guard_correction end # Dispersion attack_effect_dispersion # Second Hit Detection hit_result = attack_effect_second_hit_result(attacker) end # If hit occurs if hit_result # State Removed by Shock remove_states_shock # Substract damage from HP attack_effect_damage # State change @state_changed = false states_plus(attacker.plus_state_set) states_minus(attacker.minus_state_set) # When missing else # Apply Miss Results attack_effect_miss end # End Method return true end #-------------------------------------------------------------------------- # * Attack Effect : Setup #-------------------------------------------------------------------------- def attack_effect_setup self.critical = false end #-------------------------------------------------------------------------- # * Attack Effect : First Hit Detection #-------------------------------------------------------------------------- def attack_effect_first_hit_result(attacker) return (rand(100) < attacker.hit) end #-------------------------------------------------------------------------- # * Attack Effect : Base Damage #-------------------------------------------------------------------------- def attack_effect_base_damage(attacker) atk = [attacker.atk - self.pdef / 2, 0].max self.damage = atk * (20 + attacker.str) / 20 end #-------------------------------------------------------------------------- # * Attack Effect : Element Correction #-------------------------------------------------------------------------- def attack_effect_element_correction(attacker) self.damage *= elements_correct(attacker.element_set) self.damage /= 100 end #-------------------------------------------------------------------------- # * Attack Effect : Critical Correction #-------------------------------------------------------------------------- def attack_effect_critical_correction(attacker) if rand(100) < 4 * attacker.dex / self.agi self.damage *= 2 self.critical = true end end #-------------------------------------------------------------------------- # * Attack Effect : Guard Correction #-------------------------------------------------------------------------- def attack_effect_guard_correction self.damage /= 2 if self.guarding? end #-------------------------------------------------------------------------- # * Attack Effect : Dispersion #-------------------------------------------------------------------------- def attack_effect_dispersion if self.damage.abs > 0 amp = [self.damage.abs * 15 / 100, 1].max self.damage += rand(amp+1) + rand(amp+1) - amp end end #-------------------------------------------------------------------------- # * Attack Effect : Second Hit Detection #-------------------------------------------------------------------------- def attack_effect_second_hit_result(attacker) eva = 8 * self.agi / attacker.dex + self.eva hit = self.damage < 0 ? 100 : 100 - eva hit = self.cant_evade? ? 100 : hit return (rand(100) < hit) end #-------------------------------------------------------------------------- # * Attack Effect : Deal Damage #-------------------------------------------------------------------------- def attack_effect_damage self.hp -= self.damage end #-------------------------------------------------------------------------- # * Attack Effect : Miss #-------------------------------------------------------------------------- def attack_effect_miss self.damage = 'Miss' self.critical = false end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_BATTLER#SKILL_EFFECT') #============================================================================== # ** Game_Battler (part 3) #------------------------------------------------------------------------------ # This class deals with battlers. It's used as a superclass for the Game_Actor # and Game_Enemy classes. #============================================================================== class Game_Battler #-------------------------------------------------------------------------- SDK.log_branch(:Game_Battler, :skill_effect, :skill_effect_setup, :skill_effect_scope, :skill_effect_effective_setup, :skill_effect_first_hit_result, :skill_effect_effective_correction, :skill_effect_power, :skill_effect_rate, :skill_effect_base_damage, :skill_effect_element_correction, :skill_effect_guard_correction, :skill_effect_disperation, :skill_effect_second_hit_result, :skill_effect_physical_hit_result, :skill_effect_damage, :skill_effect_power0, :skill_effect_miss, :skill_effect_damagefix) #-------------------------------------------------------------------------- # * Apply Skill Effects #-------------------------------------------------------------------------- def skill_effect(user, skill) # Skill Effects Setup skill_effect_setup # Return False If Out of Scope return false if skill_effect_scope(skill) # Setup Effective effective = skill_effect_effective_setup(skill) # First hit detection hit, hit_result = skill_effect_first_hit_result(user, skill) # Set effective flag if skill is uncertain effective = skill_effect_effective_correction(effective, hit) # If hit occurs if hit_result # Calculate power power = skill_effect_power(user, skill) # Calculate rate rate = skill_effect_rate(user, skill) # Calculate basic damage skill_effect_base_damage(power, rate) # Element correction skill_effect_element_correction(skill) # If damage value is strictly positive if self.damage > 0 # Guard correction skill_effect_guard_correction end # Dispersion skill_effect_disperation(skill) # Second hit detection hit, hit_result = skill_effect_second_hit_result(user, skill) # Set effective flag if skill is uncertain effective = skill_effect_effective_correction(effective, hit) end # If hit occurs if hit_result # Physical Hit Detection effective = true if skill_effect_physical_hit_result(skill) # Deal Damage effective = skill_effect_damage # State change @state_changed = false effective |= states_plus(skill.plus_state_set) effective |= states_minus(skill.minus_state_set) # Skill Effect 0 Power Test skill_effect_power0(skill) # If miss occurs else # Apply Miss Effects skill_effect_miss end # Skill Effect Damage Fix skill_effect_damagefix # End Method return effective end #-------------------------------------------------------------------------- # * Skill Effect : Setup #-------------------------------------------------------------------------- def skill_effect_setup self.critical = false end #-------------------------------------------------------------------------- # * Skill Effect : Scope Test #-------------------------------------------------------------------------- def skill_effect_scope(skill) # If skill scope is for ally with 1 or more HP, and your own HP = 0, # or skill scope is for ally with 0, and your own HP = 1 or more return (((skill.scope == 3 or skill.scope == 4) and self.hp == 0) or ((skill.scope == 5 or skill.scope == 6) and self.hp >= 1)) end #-------------------------------------------------------------------------- # * Skill Effect : Effective Setup #-------------------------------------------------------------------------- def skill_effect_effective_setup(skill) effective = false return effective |= skill.common_event_id > 0 end #-------------------------------------------------------------------------- # * Skill Effect : First Hit Result #-------------------------------------------------------------------------- def skill_effect_first_hit_result(user, skill) hit = skill.hit if skill.atk_f > 0 hit *= user.hit / 100 end return hit, (rand(100) < hit) end #-------------------------------------------------------------------------- # * Skill Effect : Skill Effective #-------------------------------------------------------------------------- def skill_effect_effective_correction(effective, hit) return effective |= hit < 100 end #-------------------------------------------------------------------------- # * Skill Effect : Power #-------------------------------------------------------------------------- def skill_effect_power(user, skill) power = skill.power + user.atk * skill.atk_f / 100 if power > 0 power -= self.pdef * skill.pdef_f / 200 power -= self.mdef * skill.mdef_f / 200 power = [power, 0].max end return power end #-------------------------------------------------------------------------- # * Skill Effect : Rate #-------------------------------------------------------------------------- def skill_effect_rate(user, skill) # Calculate rate rate = 20 rate += (user.str * skill.str_f / 100) rate += (user.dex * skill.dex_f / 100) rate += (user.agi * skill.agi_f / 100) rate += (user.int * skill.int_f / 100) # Return Rate return rate end #-------------------------------------------------------------------------- # * Skill Effect : Base Damage #-------------------------------------------------------------------------- def skill_effect_base_damage(power, rate) self.damage = power * rate / 20 end #-------------------------------------------------------------------------- # * Skill Effect : Element Correction #-------------------------------------------------------------------------- def skill_effect_element_correction(skill) self.damage *= elements_correct(skill.element_set) self.damage /= 100 end #-------------------------------------------------------------------------- # * Skill Effect : Guard Correction #-------------------------------------------------------------------------- def skill_effect_guard_correction self.damage /= 2 if self.guarding? end #-------------------------------------------------------------------------- # * Skill Effect : Disperation #-------------------------------------------------------------------------- def skill_effect_disperation(skill) if skill.variance > 0 and self.damage.abs > 0 amp = [self.damage.abs * skill.variance / 100, 1].max self.damage += rand(amp+1) + rand(amp+1) - amp end end #-------------------------------------------------------------------------- # * Skill Effect : Second Hit Detection #-------------------------------------------------------------------------- def skill_effect_second_hit_result(user, skill) eva = 8 * self.agi / user.dex + self.eva hit = self.damage < 0 ? 100 : 100 - eva * skill.eva_f / 100 hit = self.cant_evade? ? 100 : hit return hit, (rand(100) < hit) end #-------------------------------------------------------------------------- # * Skill Effect : Physical Hit Result #-------------------------------------------------------------------------- def skill_effect_physical_hit_result(skill) # If physical attack has power other than 0 if skill.power != 0 and skill.atk_f > 0 # State Removed by Shock remove_states_shock # Return True return true end # Return False return false end #-------------------------------------------------------------------------- # * Skill Effect : Damage #-------------------------------------------------------------------------- def skill_effect_damage # Substract damage from HP last_hp = self.hp self.hp -= self.damage return self.hp != last_hp end #-------------------------------------------------------------------------- # * Skill Effect : Power 0 Test #-------------------------------------------------------------------------- def skill_effect_power0(skill) # If power is 0 if skill.power == 0 # Set damage to an empty string self.damage = "" # If state is unchanged unless @state_changed # Set damage to "Miss" self.damage = 'Miss' end end end #-------------------------------------------------------------------------- # * Skill Effect : Miss #-------------------------------------------------------------------------- def skill_effect_miss self.damage = 'Miss' end #-------------------------------------------------------------------------- # * Skill Effect : Damage Fix #-------------------------------------------------------------------------- def skill_effect_damagefix self.damage = nil unless $game_temp.in_battle end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_BATTLER#ITEM_EFFECT') #============================================================================== # ** Game_Battler (part 3) #------------------------------------------------------------------------------ # This class deals with battlers. It's used as a superclass for the Game_Actor # and Game_Enemy classes. #============================================================================== class Game_Battler #-------------------------------------------------------------------------- SDK.log_branch(:Game_Battler, :item_effect, :item_effect_setup, :item_effect_scope, :item_effect_effective_setup, :item_effect_hit_result, :item_effect_effective_correction, :item_effect_recovery, :item_effect_element_correction, :item_effect_guard_correction, :item_effect_dispersion, :item_effect_damage, :item_effect_parameter_points, :item_effect_no_recovery, :item_effect_miss, :item_effect_damagefix) #-------------------------------------------------------------------------- # * Application of Item Effects #-------------------------------------------------------------------------- def item_effect(item) # Item Effect Setup item_effect_setup # Return False If Out of Scope return false if item_effect_scope(item) # Setup Effective effective = item_effect_effective_setup(item) # First hit detection hit_result = item_effect_hit_result(item) # Set effective flag if skill is uncertain effective = item_effect_effective_correction(effective, item) # If hit occurs if hit_result # Calculate amount of recovery recover_hp, recover_sp = item_effect_recovery(item) # Element correction recover_hp, recover_sp = item_effect_element_correction(recover_hp, recover_sp, item) # If recovery code is negative if recover_hp < 0 # Guard correction recover_hp = item_effect_guard_correction(recover_hp) end # Dispersion recover_hp, recover_sp = item_effect_dispersion(recover_hp, recover_sp, item) # Damage & Recovery effective = item_effect_damage(recover_hp, recover_sp, effective) # State change @state_changed = false effective |= states_plus(item.plus_state_set) effective |= states_minus(item.minus_state_set) # If parameter value increase is effective if item.parameter_type > 0 and item.parameter_points != 0 # Item Effect Parameter Points item_effect_parameter_points(item) # Set to effective flag effective = true end # Item effect no recovery item_effect_no_recovery(item) # If miss occurs else # Item effect miss item_effect_miss end # Item effect damage fix item_effect_damagefix # End Method return effective end #-------------------------------------------------------------------------- # * Item Effect : Setup #-------------------------------------------------------------------------- def item_effect_setup self.critical = false end #-------------------------------------------------------------------------- # * Item Effect : Scope #-------------------------------------------------------------------------- def item_effect_scope(item) return (((item.scope == 3 or item.scope == 4) and self.hp == 0) or ((item.scope == 5 or item.scope == 6) and self.hp >= 1)) end #-------------------------------------------------------------------------- # * Item Effect : Effective #-------------------------------------------------------------------------- def item_effect_effective_setup(item) effective = false return effective |= item.common_event_id > 0 end #-------------------------------------------------------------------------- # * Item Effect : Hit Result #-------------------------------------------------------------------------- def item_effect_hit_result(item) return (rand(100) < item.hit) end #-------------------------------------------------------------------------- # * Item Effect : Item Effective #-------------------------------------------------------------------------- def item_effect_effective_correction(effective, item) return effective |= item.hit < 100 end #-------------------------------------------------------------------------- # * Item Effect : Recovery #-------------------------------------------------------------------------- def item_effect_recovery(item) recover_hp = maxhp * item.recover_hp_rate / 100 + item.recover_hp recover_sp = maxsp * item.recover_sp_rate / 100 + item.recover_sp if recover_hp < 0 recover_hp += self.pdef * item.pdef_f / 20 recover_hp += self.mdef * item.mdef_f / 20 recover_hp = [recover_hp, 0].min end return recover_hp, recover_sp end #-------------------------------------------------------------------------- # * Item Effect : Element Correction #-------------------------------------------------------------------------- def item_effect_element_correction(recover_hp, recover_sp, item) # Element correction recover_hp *= elements_correct(item.element_set) recover_hp /= 100 recover_sp *= elements_correct(item.element_set) recover_sp /= 100 return recover_hp, recover_sp end #-------------------------------------------------------------------------- # * Item Effect : Guard Correction #-------------------------------------------------------------------------- def item_effect_guard_correction(recover_hp) return self.guarding? ? recover_hp /= 2 : recover_hp end #-------------------------------------------------------------------------- # * Item Effect : Disperation #-------------------------------------------------------------------------- def item_effect_dispersion(recover_hp, recover_sp, item) if item.variance > 0 and recover_hp.abs > 0 amp = [recover_hp.abs * item.variance / 100, 1].max recover_hp += rand(amp+1) + rand(amp+1) - amp end if item.variance > 0 and recover_sp.abs > 0 amp = [recover_sp.abs * item.variance / 100, 1].max recover_sp += rand(amp+1) + rand(amp+1) - amp end return recover_hp, recover_sp end #-------------------------------------------------------------------------- # * Item Effect : Damage #-------------------------------------------------------------------------- def item_effect_damage(recover_hp, recover_sp, effective) # Set Damage self.damage = -recover_hp # HP and SP recovery last_hp = self.hp last_sp = self.sp self.hp += recover_hp self.sp += recover_sp effective |= self.hp != last_hp effective |= self.sp != last_sp # Return Effectiveness return effective end #-------------------------------------------------------------------------- # * Item Effect : Parameter Points #-------------------------------------------------------------------------- def item_effect_parameter_points(item) # Branch by parameter case item.parameter_type when 1 # Max HP @maxhp_plus += item.parameter_points when 2 # Max SP @maxsp_plus += item.parameter_points when 3 # Strength @str_plus += item.parameter_points when 4 # Dexterity @dex_plus += item.parameter_points when 5 # Agility @agi_plus += item.parameter_points when 6 # Intelligence @int_plus += item.parameter_points end end #-------------------------------------------------------------------------- # * Item Effect : No Recovery #-------------------------------------------------------------------------- def item_effect_no_recovery(item) # If HP recovery rate and recovery amount are 0 if item.recover_hp_rate == 0 and item.recover_hp == 0 # Set damage to empty string self.damage = '' # If SP recovery rate / recovery amount are 0, and parameter increase # value is ineffective. if item.recover_sp_rate == 0 and item.recover_sp == 0 and (item.parameter_type == 0 or item.parameter_points == 0) # If state is unchanged unless @state_changed # Set damage to "Miss" self.damage = 'Miss' end end end end #-------------------------------------------------------------------------- # * Item Effect : Miss #-------------------------------------------------------------------------- def item_effect_miss self.damage = 'Miss' end #-------------------------------------------------------------------------- # * Item Effect : Damage Fix #-------------------------------------------------------------------------- def item_effect_damagefix self.damage = nil unless $game_temp.in_battle end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_BATTLER#SLIP_DAMAGE_EFFECT') #============================================================================== # ** Game_Battler (part 3) #------------------------------------------------------------------------------ # This class deals with battlers. It's used as a superclass for the Game_Actor # and Game_Enemy classes. #============================================================================== class Game_Battler #-------------------------------------------------------------------------- SDK.log_branch(:Game_Battler, :slip_damage_effect, :slip_damage_effect_base_damage, :slip_damage_effect_dispersion, :slip_damage_effect_damage) #-------------------------------------------------------------------------- # * Application of Slip Damage Effects #-------------------------------------------------------------------------- def slip_damage_effect # Set damage slip_damage_effect_base_damage # Dispersion slip_damage_effect_dispersion # Subtract damage from HP slip_damage_effect_damage # End Method return true end #-------------------------------------------------------------------------- # * Slip Damage Effects : Base Damage #-------------------------------------------------------------------------- def slip_damage_effect_base_damage self.damage = self.maxhp / 10 end #-------------------------------------------------------------------------- # * Slip Damage Effects : Dispersion #-------------------------------------------------------------------------- def slip_damage_effect_dispersion # Dispersion if self.damage.abs > 0 amp = [self.damage.abs * 15 / 100, 1].max self.damage += rand(amp+1) + rand(amp+1) - amp end end #-------------------------------------------------------------------------- # * Slip Damage Effects : Damage #-------------------------------------------------------------------------- def slip_damage_effect_damage self.hp -= self.damage end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_ACTOR#EXP=') #============================================================================== # ** Game_Actor #------------------------------------------------------------------------------ # This class handles the actor. It's used within the Game_Actors class # ($game_actors) and refers to the Game_Party class ($game_party). #============================================================================== class Game_Actor < Game_Battler #-------------------------------------------------------------------------- SDK.log_branch(:Game_Actor, :exp=, :level_up, :level_down) #-------------------------------------------------------------------------- # * Change EXP #-------------------------------------------------------------------------- def exp=(exp) @exp = [[exp, 9999999].min, 0].max # Level up while @exp >= @exp_list[@level+1] and @exp_list[@level+1] > 0 level_up end # Level down while @exp < @exp_list[@level] level_down end # Correction if exceeding current max HP and max SP @hp = [@hp, self.maxhp].min @sp = [@sp, self.maxsp].min end #-------------------------------------------------------------------------- # * Level Up #-------------------------------------------------------------------------- def level_up @level += 1 # Learn skill for j in $data_classes[@class_id].learnings if j.level == @level learn_skill(j.skill_id) end end end #-------------------------------------------------------------------------- # * Level Down #-------------------------------------------------------------------------- def level_down @level -= 1 end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_CHARACTER#UPDATE') #============================================================================== # ** Game_Character #------------------------------------------------------------------------------ # This class deals with characters. It's used as a superclass for the # Game_Player and Game_Event classes. #============================================================================== class Game_Character #-------------------------------------------------------------------------- SDK.log_branch(:Game_Character, :update, :update_movement_type, :update_animation, :update_wait?, :update_force?, :update_startlock?, :update_movement) #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update update_movement_type # Update Movement Type update_animation # Update Animation Counters return if update_wait? # Update Wait Test return if update_force? # Update Force Route Test return if update_startlock? # Update Start/Lock Test update_movement # Update Movement end #-------------------------------------------------------------------------- # * Frame Update : Movement Type #-------------------------------------------------------------------------- def update_movement_type # Branch with jumping, moving, and stopping if jumping? update_jump elsif moving? update_move else update_stop end end #-------------------------------------------------------------------------- # * Frame Update : Animation Counters #-------------------------------------------------------------------------- def update_animation # If animation count exceeds maximum value # * Maximum value is move speed * 1 taken from basic value 18 if @anime_count > 18 - @move_speed * 2 # If stop animation is OFF when stopping if not @step_anime and @stop_count > 0 # Return to original pattern @pattern = @original_pattern # If stop animation is ON when moving else # Update pattern @pattern = (@pattern + 1) % 4 end # Clear animation count @anime_count = 0 end end #-------------------------------------------------------------------------- # * Frame Update : Wait Test #-------------------------------------------------------------------------- def update_wait? # If waiting if @wait_count > 0 # Reduce wait count @wait_count -= 1 return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Force Route Test #-------------------------------------------------------------------------- def update_force? # If move route is forced if @move_route_forcing # Custom move move_type_custom return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Starting or Lock Test #-------------------------------------------------------------------------- def update_startlock? # When waiting for event execution or locked return (@starting or lock?) end #-------------------------------------------------------------------------- # * Frame Update : Movement #-------------------------------------------------------------------------- def update_movement # If stop count exceeds a certain value (computed from move frequency) if @stop_count > (40 - @move_frequency * 2) * (6 - @move_frequency) # Branch by move type case @move_type when 1 # Random move_type_random when 2 # Approach move_type_toward_player when 3 # Custom move_type_custom end end end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_EVENT#REFRESH') #============================================================================== # ** Game_Event #------------------------------------------------------------------------------ # This class deals with events. It handles functions including event page # switching via condition determinants, and running parallel process events. # It's used within the Game_Map class. #============================================================================== class Game_Event < Game_Character #-------------------------------------------------------------------------- SDK.log_branch(:Game_Event, :refresh, :refresh_new_page, :refresh_page_change?, :refresh_page_reset?, :refresh_set_page, :refresh_check_process) #-------------------------------------------------------------------------- # * Refresh #-------------------------------------------------------------------------- def refresh new_page = refresh_new_page # Get New Page return if refresh_page_change?(new_page) # Return if No Page Change clear_starting # Clear starting flag return if refresh_page_reset? # Return if Nil Page Reset refresh_set_page # Set page variables refresh_check_process # Check parallel processing check_event_trigger_auto # Auto event start determinant end #-------------------------------------------------------------------------- # * Refresh : New Page #-------------------------------------------------------------------------- def refresh_new_page return @erased ? nil : refresh_trigger_conditions end #-------------------------------------------------------------------------- # * Refresh Trigger Conditions #-------------------------------------------------------------------------- def refresh_trigger_conditions # Check in order of large event pages for page in @event.pages.reverse # Skips If Page Conditions Not Met next unless page.condition.conditions_met?(@map_id, @id) # Set local variable: new_page new_page = page # Remove loop break end # Return new page return new_page end #-------------------------------------------------------------------------- # * Refresh : Page Change #-------------------------------------------------------------------------- def refresh_page_change?(new_page) # If event page is the same as last time if new_page == @page # End method return true end # Set @page as current event page @page = new_page return false end #-------------------------------------------------------------------------- # * Refresh : Page Reset #-------------------------------------------------------------------------- def refresh_page_reset? # If no page fulfills conditions if @page == nil # Reset values refresh_reset # End method return true end return false end #-------------------------------------------------------------------------- # * Refresh Reset #-------------------------------------------------------------------------- def refresh_reset # Set each instance variable @tile_id = 0 @character_name = "" @character_hue = 0 @move_type = 0 @through = true @trigger = nil @list = nil @interpreter = nil end #-------------------------------------------------------------------------- # * Refresh Set Page #-------------------------------------------------------------------------- def refresh_set_page # Set each instance variable @tile_id = @page.graphic.tile_id @character_name = @page.graphic.character_name @character_hue = @page.graphic.character_hue if @original_direction != @page.graphic.direction @direction = @page.graphic.direction @original_direction = @direction @prelock_direction = 0 end if @original_pattern != @page.graphic.pattern @pattern = @page.graphic.pattern @original_pattern = @pattern end @opacity = @page.graphic.opacity @blend_type = @page.graphic.blend_type @move_type = @page.move_type @move_speed = @page.move_speed @move_frequency = @page.move_frequency @move_route = @page.move_route @move_route_index = 0 @move_route_forcing = false @walk_anime = @page.walk_anime @step_anime = @page.step_anime @direction_fix = @page.direction_fix @through = @page.through @always_on_top = @page.always_on_top @trigger = @page.trigger @list = @page.list @interpreter = nil end #-------------------------------------------------------------------------- # * Refresh Check Process #-------------------------------------------------------------------------- def refresh_check_process # If trigger is [parallel process] if @trigger == 4 # Create parallel process interpreter @interpreter = Interpreter.new end end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('GAME_PLAYER#UPDATE') #============================================================================== # ** Game_Player #------------------------------------------------------------------------------ # This class handles the player. Its functions include event starting # determinants and map scrolling. Refer to "$game_player" for the one # instance of this class. #============================================================================== class Game_Player < Game_Character #-------------------------------------------------------------------------- SDK.log_branch(:Game_Player, :update, :update_player_movement, :update_plyrmvttest?, :update_scroll_down, :update_scroll_left, :update_scroll_right, :update_scroll_up, :update_nonmoving) #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update last_moving = moving? # Remember moving flag update_player_movement if update_plyrmvttest? # Update Player Movement last_real_x = @real_x # Remember Real X last_real_y = @real_y # Remember Real Y super # Parent Update Call update_scroll_down(last_real_y) # Scroll Down update_scroll_left(last_real_x) # Scroll Left update_scroll_right(last_real_x) # Scroll Right update_scroll_up(last_real_y) # Scroll Up update_nonmoving(last_moving) # Update Non-Moving end #-------------------------------------------------------------------------- # * Frame Update : Player Movement Test #-------------------------------------------------------------------------- def update_plyrmvttest? # If moving, event running, move route forcing, and message window # display are all not occurring unless moving? or $game_system.map_interpreter.running? or @move_route_forcing or $game_temp.message_window_showing return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Player Movement #-------------------------------------------------------------------------- def update_player_movement # Move player in the direction the directional button is being pressed case Input.dir4 when 2 move_down when 4 move_left when 6 move_right when 8 move_up end end #-------------------------------------------------------------------------- # * Frame Update : Scroll Down #-------------------------------------------------------------------------- def update_scroll_down(last_real_y) # If character moves down and is positioned lower than the center # of the screen if @real_y > last_real_y and @real_y - $game_map.display_y > CENTER_Y # Scroll map down $game_map.scroll_down(@real_y - last_real_y) end end #-------------------------------------------------------------------------- # * Scroll Left #-------------------------------------------------------------------------- def update_scroll_left(last_real_x) # If character moves left and is positioned more let on-screen than # center if @real_x < last_real_x and @real_x - $game_map.display_x < CENTER_X # Scroll map left $game_map.scroll_left(last_real_x - @real_x) end end #-------------------------------------------------------------------------- # * Scroll Right #-------------------------------------------------------------------------- def update_scroll_right(last_real_x) # If character moves right and is positioned more right on-screen than # center if @real_x > last_real_x and @real_x - $game_map.display_x > CENTER_X # Scroll map right $game_map.scroll_right(@real_x - last_real_x) end end #-------------------------------------------------------------------------- # * Scroll Up #-------------------------------------------------------------------------- def update_scroll_up(last_real_y) # If character moves up and is positioned higher than the center # of the screen if @real_y < last_real_y and @real_y - $game_map.display_y < CENTER_Y # Scroll map up $game_map.scroll_up(last_real_y - @real_y) end end #-------------------------------------------------------------------------- # * Frame Update : Non-Moving #-------------------------------------------------------------------------- def update_nonmoving(last_moving) # If not moving unless moving? # If player was moving last time if last_moving update_encounter end update_action_trigger end end #-------------------------------------------------------------------------- # * Frame Update : Encounter #-------------------------------------------------------------------------- def update_encounter # Event determinant is via touch of same position event result = check_event_trigger_here([1,2]) # If event which started does not exist if result == false # Disregard if debug mode is ON and ctrl key was pressed unless $DEBUG and Input.press?(Input::CTRL) # Encounter countdown if @encounter_count > 0 @encounter_count -= 1 end end end end #-------------------------------------------------------------------------- # * Frame Update : Action Trigger #-------------------------------------------------------------------------- def update_action_trigger # If C button was pressed if Input.trigger?(Input::C) # Same position and front event determinant check_event_trigger_here([0]) check_event_trigger_there([0,1,2]) end end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('SPRITE_BATTLER#UPDATE') #============================================================================== # ** Sprite_Battler #------------------------------------------------------------------------------ # This sprite is used to display the battler.It observes the Game_Character # class and automatically changes sprite conditions. #============================================================================== class Sprite_Battler #-------------------------------------------------------------------------- SDK.log_branch(:Sprite_Battler, :update, :remove_battler, :redraw_battler, :loop_anim, :adjust_actor_opacity, :adjust_blink, :adjust_visibility, :sprite_escape, :sprite_white_flash, :sprite_animation, :sprite_damage, :sprite_collapse, :sprite_position) #-------------------------------------------------------------------------- # * Update #-------------------------------------------------------------------------- def update super # If battler is nil if @battler == nil remove_battler return end # If file name or hue are different than current ones redraw_battler # If animation ID is different than current one loop_anim # If actor which should be displayed adjust_actor_opacity # Blink adjust_blink # If invisible adjust_visibility # If visible if @battler_visible # Escape sprite_escape # White flash sprite_white_flash # Animation sprite_animation # Damage sprite_damage # Collapse sprite_collapse end # Set sprite coordinates sprite_position end #-------------------------------------------------------------------------- # * Remove Battler #-------------------------------------------------------------------------- def remove_battler self.bitmap = nil loop_animation(nil) end #-------------------------------------------------------------------------- # * Redraw Battler #-------------------------------------------------------------------------- def redraw_battler if @battler.battler_name != @battler_name or @battler.battler_hue != @battler_hue # Get and set bitmap @battler_name = @battler.battler_name @battler_hue = @battler.battler_hue self.bitmap = RPG::Cache.battler(@battler_name, @battler_hue) @width = bitmap.width @height = bitmap.height self.ox = @width / 2 self.oy = @height # Change opacity level to 0 when dead or hidden if @battler.dead? or @battler.hidden self.opacity = 0 end end end #-------------------------------------------------------------------------- # * Loop Sprite Animation #-------------------------------------------------------------------------- def loop_anim if @battler.damage == nil and @battler.state_animation_id != @state_animation_id @state_animation_id = @battler.state_animation_id loop_animation($data_animations[@state_animation_id]) end end #-------------------------------------------------------------------------- # * Adjust Actor Opacity #-------------------------------------------------------------------------- def adjust_actor_opacity if @battler.is_a?(Game_Actor) and @battler_visible # Bring opacity level down a bit when not in main phase if $game_temp.battle_main_phase self.opacity += 3 if self.opacity < 255 else self.opacity -= 3 if self.opacity > 207 end end end #-------------------------------------------------------------------------- # * Adjust Blink #-------------------------------------------------------------------------- def adjust_blink if @battler.blink blink_on else blink_off end end #-------------------------------------------------------------------------- # * Adjust Visibility #-------------------------------------------------------------------------- def adjust_visibility unless @battler_visible # Appear if not @battler.hidden and not @battler.dead? and (@battler.damage == nil or @battler.damage_pop) appear @battler_visible = true end end end #-------------------------------------------------------------------------- # * Sprite: Escape #-------------------------------------------------------------------------- def sprite_escape if @battler.hidden $game_system.se_play($data_system.escape_se) escape @battler_visible = false end end #-------------------------------------------------------------------------- # * Sprite: White Flash #-------------------------------------------------------------------------- def sprite_white_flash if @battler.white_flash whiten @battler.white_flash = false end end #-------------------------------------------------------------------------- # * Sprite: Animation #-------------------------------------------------------------------------- def sprite_animation if @battler.animation_id != 0 animation = $data_animations[@battler.animation_id] animation(animation, @battler.animation_hit) @battler.animation_id = 0 end end #-------------------------------------------------------------------------- # * Sprite: Damage #-------------------------------------------------------------------------- def sprite_damage if @battler.damage_pop damage(@battler.damage, @battler.critical) @battler.damage = nil @battler.critical = false @battler.damage_pop = false end end #-------------------------------------------------------------------------- # * Sprite: Collapse #-------------------------------------------------------------------------- def sprite_collapse if @battler.damage == nil and @battler.dead? if @battler.is_a?(Game_Enemy) $game_system.se_play($data_system.enemy_collapse_se) else $game_system.se_play($data_system.actor_collapse_se) end collapse @battler_visible = false end end #-------------------------------------------------------------------------- # * Sprite: Position #-------------------------------------------------------------------------- def sprite_position self.x = @battler.screen_x self.y = @battler.screen_y self.z = @battler.screen_z end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('SPRITESET_MAP#INITIALIZE') #============================================================================== # ** Spriteset_Map #------------------------------------------------------------------------------ # This class brings together map screen sprites, tilemaps, etc. # It's used within the Scene_Map class. #============================================================================== class Spriteset_Map #-------------------------------------------------------------------------- SDK.log_branch(:Spriteset_Map, :initialize, :init_viewports, :init_tilemap, :init_panorama, :init_fog, :init_characters, :init_player, :init_weather, :init_pictures, :init_timer) #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize init_viewports # Initialize Viewports init_tilemap # Initialize Tilemap init_panorama # Initialize Panorama init_fog # Initialize Fog init_characters # Initialize Characters init_player # Initialize Player init_weather # Initialize Weather init_pictures # Initialize Pictures init_timer # Initialize Timer update # Frame update end #-------------------------------------------------------------------------- # * Viewport Initialization #-------------------------------------------------------------------------- def init_viewports # Make viewports @viewport1 = Viewport.new(0, 0, 640, 480) @viewport2 = Viewport.new(0, 0, 640, 480) @viewport3 = Viewport.new(0, 0, 640, 480) @viewport2.z = 200 @viewport3.z = 5000 end #-------------------------------------------------------------------------- # * Tilemap Initialization #-------------------------------------------------------------------------- def init_tilemap # Make tilemap @tilemap = Tilemap.new(@viewport1) @tilemap.tileset = RPG::Cache.tileset($game_map.tileset_name) for i in 0..6 autotile_name = $game_map.autotile_names[i] @tilemap.autotiles[i] = RPG::Cache.autotile(autotile_name) end @tilemap.map_data = $game_map.data.dup @tilemap.priorities = $game_map.priorities end #-------------------------------------------------------------------------- # * Panorama Initialization #-------------------------------------------------------------------------- def init_panorama # Make panorama plane @panorama = Plane.new(@viewport1) @panorama.z = -1000 end #-------------------------------------------------------------------------- # * Fog Initialization #-------------------------------------------------------------------------- def init_fog # Make fog plane @fog = Plane.new(@viewport1) @fog.z = 3000 end #-------------------------------------------------------------------------- # * Character Sprite Initialization #-------------------------------------------------------------------------- def init_characters # Make character sprites @character_sprites = [] for i in $game_map.events.keys.sort sprite = Sprite_Character.new(@viewport1, $game_map.events[i]) @character_sprites.push(sprite) end end #-------------------------------------------------------------------------- # * Player Initialization #-------------------------------------------------------------------------- def init_player @character_sprites.push(Sprite_Character.new(@viewport1, $game_player)) end #-------------------------------------------------------------------------- # * Weather Initialization #-------------------------------------------------------------------------- def init_weather # Make weather @weather = RPG::Weather.new(@viewport1) end #-------------------------------------------------------------------------- # * Picture Initialization #-------------------------------------------------------------------------- def init_pictures # Make picture sprites @picture_sprites = [] for i in 1..80 @picture_sprites.push(Sprite_Picture.new(@viewport2, $game_screen.pictures[i])) end end #-------------------------------------------------------------------------- # * Timer Initialization #-------------------------------------------------------------------------- def init_timer # Make timer sprite @timer_sprite = Sprite_Timer.new end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('SPRITESET_MAP#UPDATE') #============================================================================== # ** Spriteset_Map #------------------------------------------------------------------------------ # This class brings together map screen sprites, tilemaps, etc. # It's used within the Scene_Map class. #============================================================================== class Spriteset_Map #-------------------------------------------------------------------------- SDK.log_branch(:Spriteset_Map, :update, :update_panorama, :update_fog, :update_tilemap, :update_panorama_plane, :update_fog_plane, :update_character_sprites, :update_weather, :update_picture_sprites, :update_timer, :update_viewports) #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update update_panorama # Update Panorama update_fog # Update Fog update_tilemap # Update Tilemap update_panorama_plane # Update Panorama Plane update_fog_plane # Update Fog Plane update_character_sprites # Update Character Sprites update_weather # Update Weather update_picture_sprites # Update Picture Sprites update_timer # Update Timer Sprite update_viewports # Update Viewports end #-------------------------------------------------------------------------- # * Update Panorama #-------------------------------------------------------------------------- def update_panorama # If panorama is different from current one if @panorama_name != $game_map.panorama_name or @panorama_hue != $game_map.panorama_hue @panorama_name = $game_map.panorama_name @panorama_hue = $game_map.panorama_hue if @panorama.bitmap != nil @panorama.bitmap.dispose @panorama.bitmap = nil end if @panorama_name != "" @panorama.bitmap = RPG::Cache.panorama(@panorama_name, @panorama_hue) end Graphics.frame_reset end end #-------------------------------------------------------------------------- # * Update Fog #-------------------------------------------------------------------------- def update_fog # If fog is different than current fog if @fog_name != $game_map.fog_name or @fog_hue != $game_map.fog_hue @fog_name = $game_map.fog_name @fog_hue = $game_map.fog_hue if @fog.bitmap != nil @fog.bitmap.dispose @fog.bitmap = nil end if @fog_name != "" @fog.bitmap = RPG::Cache.fog(@fog_name, @fog_hue) end Graphics.frame_reset end end #-------------------------------------------------------------------------- # * Update Tilemap #-------------------------------------------------------------------------- def update_tilemap # Update tilemap @tilemap.ox = $game_map.display_x / 4 @tilemap.oy = $game_map.display_y / 4 @tilemap.update end #-------------------------------------------------------------------------- # * Update Panorama Plane #-------------------------------------------------------------------------- def update_panorama_plane # Update panorama plane @panorama.ox = $game_map.display_x / 8 @panorama.oy = $game_map.display_y / 8 end #-------------------------------------------------------------------------- # * Update Fog Plane #-------------------------------------------------------------------------- def update_fog_plane # Update fog plane @fog.zoom_x = $game_map.fog_zoom / 100.0 @fog.zoom_y = $game_map.fog_zoom / 100.0 @fog.opacity = $game_map.fog_opacity @fog.blend_type = $game_map.fog_blend_type @fog.ox = $game_map.display_x / 4 + $game_map.fog_ox @fog.oy = $game_map.display_y / 4 + $game_map.fog_oy @fog.tone = $game_map.fog_tone end #-------------------------------------------------------------------------- # * Update Character Sprites #-------------------------------------------------------------------------- def update_character_sprites # Update character sprites for sprite in @character_sprites sprite.update end end #-------------------------------------------------------------------------- # * Update Weather #-------------------------------------------------------------------------- def update_weather # Update weather graphic @weather.type = $game_screen.weather_type @weather.max = $game_screen.weather_max @weather.ox = $game_map.display_x / 4 @weather.oy = $game_map.display_y / 4 @weather.update end #-------------------------------------------------------------------------- # * Update Picture Sprites #-------------------------------------------------------------------------- def update_picture_sprites # Update picture sprites for sprite in @picture_sprites sprite.update end end #-------------------------------------------------------------------------- # * Frame Update : Timer #-------------------------------------------------------------------------- def update_timer # Update timer sprite @timer_sprite.update end #-------------------------------------------------------------------------- # * Frame Update : Viewports #-------------------------------------------------------------------------- def update_viewports # Set screen color tone and shake position @viewport1.tone = $game_screen.tone @viewport1.ox = $game_screen.shake # Set screen flash color @viewport3.color = $game_screen.flash_color # Update viewports @viewport1.update @viewport3.update end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('SPRITESET_BATTLE#INITIALIZE') #============================================================================== # ** Spriteset_Battle #------------------------------------------------------------------------------ # This class brings together battle screen sprites. It's used within # the Scene_Battle class. #============================================================================== class Spriteset_Battle #-------------------------------------------------------------------------- SDK.log_branch(:Spriteset_Battle, :initialize, :init_viewport, :init_battleback, :init_enemysprites, :init_actorsprites, :init_picturesprites, :init_weather, :init_timer) #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize init_viewport # Initialize Viewports init_battleback # Initialize Battleback init_enemysprites # Initialize Enemy Sprites init_actorsprites # Initialize Actor Sprites init_picturesprites # Initialize Picture Sprites init_weather # Initialize Weather init_timer # Initialize Timer update # Frame update end #-------------------------------------------------------------------------- # * Object Initialization : Viewports #-------------------------------------------------------------------------- def init_viewport # Make viewports @viewport1 = Viewport.new(0, 0, 640, 320) @viewport2 = Viewport.new(0, 0, 640, 480) @viewport3 = Viewport.new(0, 0, 640, 480) @viewport4 = Viewport.new(0, 0, 640, 480) @viewport2.z = 101 @viewport3.z = 200 @viewport4.z = 5000 end #-------------------------------------------------------------------------- # * Object Initialization : Battleback Sprite #-------------------------------------------------------------------------- def init_battleback # Make battleback sprite @battleback_sprite = Sprite.new(@viewport1) end #-------------------------------------------------------------------------- # * Object Initialization : Enemy Sprites #-------------------------------------------------------------------------- def init_enemysprites # Make enemy sprites @enemy_sprites = [] for enemy in $game_troop.enemies.reverse @enemy_sprites.push(Sprite_Battler.new(@viewport1, enemy)) end end #-------------------------------------------------------------------------- # * Object Initialization : Actor Sprites #-------------------------------------------------------------------------- def init_actorsprites # Make actor sprites @actor_sprites = [] @actor_sprites.push(Sprite_Battler.new(@viewport2)) @actor_sprites.push(Sprite_Battler.new(@viewport2)) @actor_sprites.push(Sprite_Battler.new(@viewport2)) @actor_sprites.push(Sprite_Battler.new(@viewport2)) end #-------------------------------------------------------------------------- # * Object Initialization : Pictures #-------------------------------------------------------------------------- def init_picturesprites # Make picture sprites @picture_sprites = [] for i in 81..100 @picture_sprites.push(Sprite_Picture.new(@viewport3, $game_screen.pictures[i])) end end #-------------------------------------------------------------------------- # * Object Initialization : Weather #-------------------------------------------------------------------------- def init_weather # Make weather @weather = RPG::Weather.new(@viewport1) end #-------------------------------------------------------------------------- # * Object Initialization : Timer #-------------------------------------------------------------------------- def init_timer # Make timer sprite @timer_sprite = Sprite_Timer.new end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('SPRITESET_BATTLE#UPDATE') #============================================================================== # ** Spriteset_Battle #------------------------------------------------------------------------------ # This class brings together battle screen sprites. It's used within # the Scene_Battle class. #============================================================================== class Spriteset_Battle #-------------------------------------------------------------------------- SDK.log_branch(:Spriteset_Battle, :update, :update_battleback, :update_battlers, :update_sprites, :update_weather, :update_timer, :update_viewports) #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update update_battleback # Update Battleback update_battlers # Update Actor Battlers update_sprites # Update Sprites update_weather # Update Weather update_timer # Update Timer update_viewports # Update Viewports end #-------------------------------------------------------------------------- # * Frame Update : Battleback #-------------------------------------------------------------------------- def update_battleback # If battleback file name is different from current one if @battleback_name != $game_temp.battleback_name @battleback_name = $game_temp.battleback_name if @battleback_sprite.bitmap != nil @battleback_sprite.bitmap.dispose end @battleback_sprite.bitmap = RPG::Cache.battleback(@battleback_name) @battleback_sprite.src_rect.set(0, 0, 640, 320) end end #-------------------------------------------------------------------------- # * Frame Update : Actor Battlers #-------------------------------------------------------------------------- def update_battlers # Update actor sprite contents (corresponds with actor switching) @actor_sprites[0].battler = $game_party.actors[0] @actor_sprites[1].battler = $game_party.actors[1] @actor_sprites[2].battler = $game_party.actors[2] @actor_sprites[3].battler = $game_party.actors[3] end #-------------------------------------------------------------------------- # * Frame Update : Sprites #-------------------------------------------------------------------------- def update_sprites # Update battler sprites for sprite in @enemy_sprites + @actor_sprites + @picture_sprites sprite.update end end #-------------------------------------------------------------------------- # * Frame Update : Weather #-------------------------------------------------------------------------- def update_weather # Update weather graphic @weather.type = $game_screen.weather_type @weather.max = $game_screen.weather_max @weather.update end #-------------------------------------------------------------------------- # * Frame Update : Timer #-------------------------------------------------------------------------- def update_timer # Update timer sprite @timer_sprite.update end #-------------------------------------------------------------------------- # * Frame Update : Viewports #-------------------------------------------------------------------------- def update_viewports # Set screen color tone and shake position @viewport1.tone = $game_screen.tone @viewport1.ox = $game_screen.shake # Set screen flash color @viewport4.color = $game_screen.flash_color # Update viewports @viewport1.update @viewport2.update @viewport4.update end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part II Check #============================================================================== if SDK::Parts.include?(2) || SDK::Indidual_Parts.include?('WINDOW_SAVEFILE#INITIIALIZE') #============================================================================== # ** Window_SaveFile #============================================================================== class Window_SaveFile < Window_Base #-------------------------------------------------------------------------- SDK.log_branch(:Window_SaveFile, :initialize, :init_filename, :init_filedata, :init_gamedata) #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize(file_index, filename) super(0, 64 + file_index % 4 * 104, 640, 104) self.contents = Bitmap.new(width - 32, height - 32) init_filename(file_index, filename) init_filedata(file_index) init_gamedata if @file_exist refresh end #-------------------------------------------------------------------------- # * Object Initialization : Filename #-------------------------------------------------------------------------- def init_filename(file_index, filename) @file_index = file_index @filename = filename end #-------------------------------------------------------------------------- # * Object Initialization : File Data #-------------------------------------------------------------------------- def init_filedata(file_index) @file_index = file_index @time_stamp = Time.at(0) @file_exist = FileTest.exist?(@filename) @selected = false end #-------------------------------------------------------------------------- # * Object Initialization : Game Data #-------------------------------------------------------------------------- def init_gamedata file = File.open(@filename, "r") @time_stamp = file.mtime @characters = Marshal.load(file) @frame_count = Marshal.load(file) @game_system = Marshal.load(file) @game_switches = Marshal.load(file) @game_variables = Marshal.load(file) @total_sec = @frame_count / Graphics.frame_rate file.close end end #============================================================================== # ** Ends Enable Part II Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_TITLE') #============================================================================== # ** Scene_Title #------------------------------------------------------------------------------ # This class performs title screen processing. #============================================================================== class Scene_Title < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Title, :main, :main_variable, :main_sprite, :main_window, :main_audio) SDK.log_branch(:Scene_Title, :main_variable, :main_database, :main_test_continue) SDK.log_branch(:Scene_Title, :command_new_game, :commandnewgame_audio, :commandnewgame_gamedata, :commandnewgame_partysetup, :commandnewgame_mapsetup, :commandnewgame_sceneswitch) SDK.log_branch(:Scene_Title, :battle_test, :battletest_database, :commandnewgame_gamedata, :battletest_setup, :battletest_sceneswitch) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main return if main_battle_test? # Battle Test & Return if in Battle Test Mode super end #-------------------------------------------------------------------------- # * Main Processing : Battle Test Check #-------------------------------------------------------------------------- def main_battle_test? # If battle test if $BTEST battle_test return true end return false end #-------------------------------------------------------------------------- # * Main Processing : Variable Initialization #-------------------------------------------------------------------------- def main_variable super # Load Database main_database # Continue Enabled Test main_test_continue end #-------------------------------------------------------------------------- # * Main Processing : Database Initialization #-------------------------------------------------------------------------- def main_database # Load database $data_actors = load_data("Data/Actors.rxdata") $data_classes = load_data("Data/Classes.rxdata") $data_skills = load_data("Data/Skills.rxdata") $data_items = load_data("Data/Items.rxdata") $data_weapons = load_data("Data/Weapons.rxdata") $data_armors = load_data("Data/Armors.rxdata") $data_enemies = load_data("Data/Enemies.rxdata") $data_troops = load_data("Data/Troops.rxdata") $data_states = load_data("Data/States.rxdata") $data_animations = load_data("Data/Animations.rxdata") $data_tilesets = load_data("Data/Tilesets.rxdata") $data_common_events = load_data("Data/CommonEvents.rxdata") $data_system = load_data("Data/System.rxdata") # Make system object $game_system = Game_System.new end #-------------------------------------------------------------------------- # * Main Test Initialization #-------------------------------------------------------------------------- def main_test_continue # Set Continued Enabled Flag Off @continue_enabled = false # Checks For Save Files for i in 0..3 if FileTest.exist?("Save#{i+1}.rxdata") # Sets Continued Enable Flag On @continue_enabled = true end end end #-------------------------------------------------------------------------- # * Main Processing : Sprite Initialization #-------------------------------------------------------------------------- def main_sprite super # Make title graphic @sprite = Sprite.new @sprite.bitmap = RPG::Cache.title($data_system.title_name) end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make command window s1 = "New Game" s2 = "Continue" s3 = "Shutdown" @command_window = Window_Command.new(192, [s1, s2, s3]) @command_window.back_opacity = 160 @command_window.x = 320 - @command_window.width / 2 @command_window.y = 288 # If continue is enabled, move cursor to "Continue" # If disabled, display "Continue" text in gray if @continue_enabled @command_window.index = 1 else @command_window.disable_item(1) end end #-------------------------------------------------------------------------- # * Main Processing : Audio Initialization #-------------------------------------------------------------------------- def main_audio super # Play title BGM $game_system.bgm_play($data_system.title_bgm) # Stop playing ME and BGS Audio.me_stop Audio.bgs_stop end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If C button was pressed if Input.trigger?(Input::C) # Branch by command window cursor position case @command_window.index when 0 # New game command_new_game when 1 # Continue command_continue when 2 # Shutdown command_shutdown end end end #-------------------------------------------------------------------------- # * Command: New Game #-------------------------------------------------------------------------- def command_new_game commandnewgame_audio # Audio Control commandnewgame_gamedata # Game Data Setup commandnewgame_partysetup # Party Setup commandnewgame_mapsetup # Map Setup commandnewgame_sceneswitch # Scene Switch end #-------------------------------------------------------------------------- # * Command: New Game : Audio Control #-------------------------------------------------------------------------- def commandnewgame_audio # Play decision SE $game_system.se_play($data_system.decision_se) # Stop BGM Audio.bgm_stop end #-------------------------------------------------------------------------- # * Command: New Game : Game Data Setup #-------------------------------------------------------------------------- def commandnewgame_gamedata # Reset frame count for measuring play time Graphics.frame_count = 0 # Make each type of game object $game_temp = Game_Temp.new $game_system = Game_System.new $game_switches = Game_Switches.new $game_variables = Game_Variables.new $game_self_switches = Game_SelfSwitches.new $game_screen = Game_Screen.new $game_actors = Game_Actors.new $game_party = Game_Party.new $game_troop = Game_Troop.new $game_map = Game_Map.new $game_player = Game_Player.new end #-------------------------------------------------------------------------- # * Command: New Game : Party Setup #-------------------------------------------------------------------------- def commandnewgame_partysetup # Set up initial party $game_party.setup_starting_members end #-------------------------------------------------------------------------- # * Command: New Game : Map Setup #-------------------------------------------------------------------------- def commandnewgame_mapsetup # Set up initial map position $game_map.setup($data_system.start_map_id) # Move player to initial position $game_player.moveto($data_system.start_x, $data_system.start_y) # Refresh player $game_player.refresh # Run automatic change for BGM and BGS set with map $game_map.autoplay # Update map (run parallel process event) $game_map.update end #-------------------------------------------------------------------------- # * Command: New Game : Scene Switch #-------------------------------------------------------------------------- def commandnewgame_sceneswitch # Switch to map screen $scene = Scene_Map.new end #-------------------------------------------------------------------------- # * Command: Continue #-------------------------------------------------------------------------- def command_continue # If continue is disabled unless @continue_enabled # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to load screen $scene = Scene_Load.new end #-------------------------------------------------------------------------- # * Command: Shutdown #-------------------------------------------------------------------------- def command_shutdown # Play decision SE $game_system.se_play($data_system.decision_se) # Fade out BGM, BGS, and ME Audio.bgm_fade(800) Audio.bgs_fade(800) Audio.me_fade(800) # Shutdown $scene = nil end #-------------------------------------------------------------------------- # * Battle Test #-------------------------------------------------------------------------- def battle_test battletest_database commandnewgame_gamedata battletest_setup battletest_sceneswitch end #-------------------------------------------------------------------------- # * Battle Test : Load Database #-------------------------------------------------------------------------- def battletest_database # Load database (for battle test) $data_actors = load_data("Data/BT_Actors.rxdata") $data_classes = load_data("Data/BT_Classes.rxdata") $data_skills = load_data("Data/BT_Skills.rxdata") $data_items = load_data("Data/BT_Items.rxdata") $data_weapons = load_data("Data/BT_Weapons.rxdata") $data_armors = load_data("Data/BT_Armors.rxdata") $data_enemies = load_data("Data/BT_Enemies.rxdata") $data_troops = load_data("Data/BT_Troops.rxdata") $data_states = load_data("Data/BT_States.rxdata") $data_animations = load_data("Data/BT_Animations.rxdata") $data_tilesets = load_data("Data/BT_Tilesets.rxdata") $data_common_events = load_data("Data/BT_CommonEvents.rxdata") $data_system = load_data("Data/BT_System.rxdata") end #-------------------------------------------------------------------------- # * Battle Test : Setup #-------------------------------------------------------------------------- def battletest_setup # Set up party for battle test $game_party.setup_battle_test_members # Set troop ID, can escape flag, and battleback $game_temp.battle_troop_id = $data_system.test_troop_id $game_temp.battle_can_escape = true $game_map.battleback_name = $data_system.battleback_name end #-------------------------------------------------------------------------- # * Battle Test : Scene Switch #-------------------------------------------------------------------------- def battletest_sceneswitch # Play battle start SE $game_system.se_play($data_system.battle_start_se) # Play battle BGM $game_system.bgm_play($game_system.battle_bgm) # Switch to battle screen $scene = Scene_Battle.new end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_MAP') #============================================================================== # ** Window_Message #------------------------------------------------------------------------------ # This message window is used to display text. #============================================================================== class Window_Message < Window_Selectable #-------------------------------------------------------------------------- # * Disable Update #-------------------------------------------------------------------------- def disable_update? return $scene.is_a?(Scene_Map) end end #============================================================================== # ** Spriteset_Map #------------------------------------------------------------------------------ # This class brings together map screen sprites, tilemaps, etc. # It's used within the Scene_Map class. #============================================================================== class Spriteset_Map #-------------------------------------------------------------------------- # * Disable Update #-------------------------------------------------------------------------- def disable_update? return $scene.is_a?(Scene_Map) end end #============================================================================== # ** Scene_Map #------------------------------------------------------------------------------ # This class performs map screen processing. #============================================================================== class Scene_Map < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Map, :main, :main_spriteset, :main_window, :main_end) SDK.log_branch(:Scene_Map, :update, :update_systems, :update_transferplayer?, :update_transition?, :update_game_over?, :update_to_title?, :update_transition, :update_encounter, :update_call_menu, :update_call_debug, :update_calling) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Spriteset Initialization #-------------------------------------------------------------------------- def main_spriteset super # Make sprite set @spriteset = Spriteset_Map.new end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make message window @message_window = Window_Message.new end #-------------------------------------------------------------------------- # * Main Processing : Ending #-------------------------------------------------------------------------- def main_end super # If switching to title screen if $scene.is_a?(Scene_Title) # Fade out screen Graphics.transition Graphics.freeze end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super loop do # Loop update_systems # Update Systems break if update_transferplayer? # Break if Transfer Player break if update_transition? # Break if Transition end # End Loop @message_window.update # Update message window @spriteset.update # Update Spriteset return if update_game_over? # Exit If Gameover return if update_to_title? # Exit if Title update_transition # Update Transition return if update_message? # Exit If Message update_encounter # Update Encounter update_call_menu # Update Menu Call update_call_debug # Update Debug Call update_calling # Update Calls end #-------------------------------------------------------------------------- # * Frame Update : Systems #-------------------------------------------------------------------------- def update_systems # Update map, interpreter, and player order # (this update order is important for when conditions are fulfilled # to run any event, and the player isn't provided the opportunity to # move in an instant) $game_map.update $game_system.map_interpreter.update $game_player.update # Update system (timer), screen $game_system.update $game_screen.update end #-------------------------------------------------------------------------- # * Frame Update : Transfer Player #-------------------------------------------------------------------------- def update_transferplayer? # Abort loop if player isn't place moving unless $game_temp.player_transferring return true end # Run place move transfer_player return false end #-------------------------------------------------------------------------- # * Frame Update : Transition #-------------------------------------------------------------------------- def update_transition? # Abort loop if transition processing if $game_temp.transition_processing return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Gameover Test #-------------------------------------------------------------------------- def update_game_over? # If game over if $game_temp.gameover # Switch to game over screen $scene = Scene_Gameover.new return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Title Test #-------------------------------------------------------------------------- def update_to_title? # If returning to title screen if $game_temp.to_title # Change to title screen $scene = Scene_Title.new return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Transition #-------------------------------------------------------------------------- def update_transition # If transition processing if $game_temp.transition_processing # Clear transition processing flag $game_temp.transition_processing = false # Execute transition if $game_temp.transition_name == '' Graphics.transition(20) else Graphics.transition(40, 'Graphics/Transitions/' + $game_temp.transition_name) end end end #-------------------------------------------------------------------------- # * Frame Update : Message Test #-------------------------------------------------------------------------- def update_message? # If showing message window if $game_temp.message_window_showing return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Encounter #-------------------------------------------------------------------------- def update_encounter # If encounter list isn't empty, and encounter count is 0 if $game_player.encounter_count == 0 and $game_map.encounter_list != [] # If event is running or encounter is not forbidden unless $game_system.map_interpreter.running? or $game_system.encounter_disabled # Confirm troop n = rand($game_map.encounter_list.size) troop_id = $game_map.encounter_list[n] # If troop is valid if $data_troops[troop_id] != nil # Set battle calling flag $game_temp.battle_calling = true $game_temp.battle_troop_id = troop_id $game_temp.battle_can_escape = true $game_temp.battle_can_lose = false $game_temp.battle_proc = nil end end end end #-------------------------------------------------------------------------- # * Frame Update : Menu Call #-------------------------------------------------------------------------- def update_call_menu # If B button was pressed if Input.trigger?(Input::B) # If event is running, or menu is not forbidden unless $game_system.map_interpreter.running? or $game_system.menu_disabled # Set menu calling flag or beep flag $game_temp.menu_calling = true $game_temp.menu_beep = true end end end #-------------------------------------------------------------------------- # * Frame Update : Debug Call #-------------------------------------------------------------------------- def update_call_debug # If debug mode is ON and F9 key was pressed if $DEBUG and Input.press?(Input::F9) # Set debug calling flag $game_temp.debug_calling = true end end #-------------------------------------------------------------------------- # * Frame Update : Calling #-------------------------------------------------------------------------- def update_calling # If player is not moving unless $game_player.moving? # Run calling of each screen if $game_temp.battle_calling call_battle elsif $game_temp.shop_calling call_shop elsif $game_temp.name_calling call_name elsif $game_temp.menu_calling call_menu elsif $game_temp.save_calling call_save elsif $game_temp.debug_calling call_debug end end end #-------------------------------------------------------------------------- # * Battle Call #-------------------------------------------------------------------------- def call_battle # Clear battle calling flag $game_temp.battle_calling = false # Clear menu calling flag $game_temp.menu_calling = false $game_temp.menu_beep = false # Make encounter count $game_player.make_encounter_count # Memorize map BGM and stop BGM $game_temp.map_bgm = $game_system.playing_bgm $game_system.bgm_stop # Play battle start SE $game_system.se_play($data_system.battle_start_se) # Play battle BGM $game_system.bgm_play($game_system.battle_bgm) # Straighten player position $game_player.straighten # Switch to battle screen $scene = Scene_Battle.new end #-------------------------------------------------------------------------- # * Shop Call #-------------------------------------------------------------------------- def call_shop # Clear shop call flag $game_temp.shop_calling = false # Straighten player position $game_player.straighten # Switch to shop screen $scene = Scene_Shop.new end #-------------------------------------------------------------------------- # * Name Input Call #-------------------------------------------------------------------------- def call_name # Clear name input call flag $game_temp.name_calling = false # Straighten player position $game_player.straighten # Switch to name input screen $scene = Scene_Name.new end #-------------------------------------------------------------------------- # * Menu Call #-------------------------------------------------------------------------- def call_menu # Clear menu call flag $game_temp.menu_calling = false # If menu beep flag is set if $game_temp.menu_beep # Play decision SE $game_system.se_play($data_system.decision_se) # Clear menu beep flag $game_temp.menu_beep = false end # Straighten player position $game_player.straighten # Switch to menu screen $scene = Scene_Menu.new end #-------------------------------------------------------------------------- # * Save Call #-------------------------------------------------------------------------- def call_save # Straighten player position $game_player.straighten # Switch to save screen $scene = Scene_Save.new end #-------------------------------------------------------------------------- # * Debug Call #-------------------------------------------------------------------------- def call_debug # Clear debug call flag $game_temp.debug_calling = false # Play decision SE $game_system.se_play($data_system.decision_se) # Straighten player position $game_player.straighten # Switch to debug screen $scene = Scene_Debug.new end #-------------------------------------------------------------------------- # * Player Place Move #-------------------------------------------------------------------------- def transfer_player # Clear player place move call flag $game_temp.player_transferring = false # If move destination is different than current map if $game_map.map_id != $game_temp.player_new_map_id # Set up a new map $game_map.setup($game_temp.player_new_map_id) end # Set up player position $game_player.moveto($game_temp.player_new_x, $game_temp.player_new_y) # Set player direction case $game_temp.player_new_direction when 2 # down $game_player.turn_down when 4 # left $game_player.turn_left when 6 # right $game_player.turn_right when 8 # up $game_player.turn_up end # Straighten player position $game_player.straighten # Update map (run parallel process event) $game_map.update # Remake sprite set @spriteset.dispose @spriteset = Spriteset_Map.new # If processing transition if $game_temp.transition_processing # Clear transition processing flag $game_temp.transition_processing = false # Execute transition Graphics.transition(20) end # Run automatic change for BGM and BGS set on the map $game_map.autoplay # Frame reset Graphics.frame_reset # Update input information Input.update end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_MENU') #============================================================================== # ** Scene_Menu #------------------------------------------------------------------------------ # This class performs menu screen processing. #============================================================================== class Scene_Menu < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Menu, :main, :main_window) SDK.log_branch(:Scene_Menu, :main_window, :main_command_window) #-------------------------------------------------------------------------- # * Object Initialization # menu_index : command cursor's initial position #-------------------------------------------------------------------------- def initialize(menu_index = 0) @menu_index = menu_index super() end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make main command window main_command_window # Make play time window @playtime_window = Window_PlayTime.new @playtime_window.x = 0 @playtime_window.y = 224 # Make steps window @steps_window = Window_Steps.new @steps_window.x = 0 @steps_window.y = 320 # Make gold window @gold_window = Window_Gold.new @gold_window.x = 0 @gold_window.y = 416 # Make status window @status_window = Window_MenuStatus.new @status_window.x = 160 @status_window.y = 0 end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization : Main Command #-------------------------------------------------------------------------- def main_command_window # Make command window s1 = $data_system.words.item s2 = $data_system.words.skill s3 = $data_system.words.equip s4 = "Status" s5 = "Save" s6 = "End Game" @command_window = Window_Command.new(160, [s1, s2, s3, s4, s5, s6]) @command_window.index = @menu_index # If number of party members is 0 if $game_party.actors.size == 0 # Disable items, skills, equipment, and status @command_window.disable_item(0) @command_window.disable_item(1) @command_window.disable_item(2) @command_window.disable_item(3) end # If save is forbidden if $game_system.save_disabled # Disable save @command_window.disable_item(4) end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If command window is active: call update_command if @command_window.active update_command return # If status window is active: call update_status elsif @status_window.active update_status return end end #-------------------------------------------------------------------------- # * Frame Update (when command window is active) #-------------------------------------------------------------------------- def update_command # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to map screen $scene = Scene_Map.new return end # If C button was pressed if Input.trigger?(Input::C) # If command other than save or end game, and party members = 0 if $game_party.actors.size == 0 and @command_window.index < 4 # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Branch by command window cursor position case @command_window.index when 0 # item # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to item screen $scene = Scene_Item.new when 1 # skill # Play decision SE $game_system.se_play($data_system.decision_se) # Make status window active @command_window.active = false @status_window.active = true @status_window.index = 0 when 2 # equipment # Play decision SE $game_system.se_play($data_system.decision_se) # Make status window active @command_window.active = false @status_window.active = true @status_window.index = 0 when 3 # status # Play decision SE $game_system.se_play($data_system.decision_se) # Make status window active @command_window.active = false @status_window.active = true @status_window.index = 0 when 4 # save # If saving is forbidden if $game_system.save_disabled # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to save screen $scene = Scene_Save.new when 5 # end game # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to end game screen $scene = Scene_End.new end return end end #-------------------------------------------------------------------------- # * Frame Update (when status window is active) #-------------------------------------------------------------------------- def update_status # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Make command window active @command_window.active = true @status_window.active = false @status_window.index = -1 return end # If C button was pressed if Input.trigger?(Input::C) # Branch by command window cursor position case @command_window.index when 1 # skill # If this actor's action limit is 2 or more if $game_party.actors[@status_window.index].restriction >= 2 # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to skill screen $scene = Scene_Skill.new(@status_window.index) when 2 # equipment # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to equipment screen $scene = Scene_Equip.new(@status_window.index) when 3 # status # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to status screen $scene = Scene_Status.new(@status_window.index) end return end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_ITEM') #============================================================================== # ** Scene_Item #------------------------------------------------------------------------------ # This class performs item screen processing. #============================================================================== class Scene_Item < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Item, :main, :main_window) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make help window, item window @help_window = Window_Help.new @item_window = Window_Item.new # Associate help window @item_window.help_window = @help_window # Make target window (set to invisible / inactive) @target_window = Window_Target.new @target_window.visible = false @target_window.active = false end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If item window is active: call update_item if @item_window.active update_item return # If target window is active: call update_target elsif @target_window.active update_target return end end #-------------------------------------------------------------------------- # * Frame Update (when item window is active) #-------------------------------------------------------------------------- def update_item # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to menu screen $scene = Scene_Menu.new(0) return end # If C button was pressed if Input.trigger?(Input::C) # Get currently selected data on the item window @item = @item_window.item # If not a use item unless @item.is_a?(RPG::Item) # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # If it can't be used unless $game_party.item_can_use?(@item.id) # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # If effect scope is an ally if @item.scope >= 3 # Activate target window @item_window.active = false @target_window.x = (@item_window.index + 1) % 2 * 304 @target_window.visible = true @target_window.active = true # Set cursor position to effect scope (single / all) if @item.scope == 4 || @item.scope == 6 @target_window.index = -1 else @target_window.index = 0 end # If effect scope is other than an ally else # If command event ID is valid if @item.common_event_id > 0 # Command event call reservation $game_temp.common_event_id = @item.common_event_id # Play item use SE $game_system.se_play(@item.menu_se) # If consumable if @item.consumable # Decrease used items by 1 $game_party.lose_item(@item.id, 1) # Draw item window item @item_window.draw_item(@item_window.index) end # Switch to map screen $scene = Scene_Map.new return end end return end end #-------------------------------------------------------------------------- # * Frame Update (when target window is active) #-------------------------------------------------------------------------- def update_target # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # If unable to use because items ran out unless $game_party.item_can_use?(@item.id) # Remake item window contents @item_window.refresh end # Erase target window @item_window.active = true @target_window.visible = false @target_window.active = false return end # If C button was pressed if Input.trigger?(Input::C) # If items are used up if $game_party.item_number(@item.id) == 0 # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # If target is all if @target_window.index == -1 # Apply item effects to entire party used = false for i in $game_party.actors used |= i.item_effect(@item) end end # If single target if @target_window.index >= 0 # Apply item use effects to target actor target = $game_party.actors[@target_window.index] used = target.item_effect(@item) end # If an item was used if used # Play item use SE $game_system.se_play(@item.menu_se) # If consumable if @item.consumable # Decrease used items by 1 $game_party.lose_item(@item.id, 1) # Redraw item window item @item_window.draw_item(@item_window.index) end # Remake target window contents @target_window.refresh # If all party members are dead if $game_party.all_dead? # Switch to game over screen $scene = Scene_Gameover.new return end # If common event ID is valid if @item.common_event_id > 0 # Common event call reservation $game_temp.common_event_id = @item.common_event_id # Switch to map screen $scene = Scene_Map.new return end end # If item wasn't used unless used # Play buzzer SE $game_system.se_play($data_system.buzzer_se) end return end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_SKILL') #============================================================================== # ** Scene_Skill #------------------------------------------------------------------------------ # This class performs skill screen processing. #============================================================================== class Scene_Skill < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Skill, :main, :main_variable, :main_window) #-------------------------------------------------------------------------- # * Object Initialization # actor_index : actor index #-------------------------------------------------------------------------- def initialize(actor_index = 0) @actor_index = actor_index super() end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Variable Initialization #-------------------------------------------------------------------------- def main_variable super # Get actor @actor = $game_party.actors[@actor_index] end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make help window, status window, and skill window @help_window = Window_Help.new @status_window = Window_SkillStatus.new(@actor) @skill_window = Window_Skill.new(@actor) # Associate help window @skill_window.help_window = @help_window # Make target window (set to invisible / inactive) @target_window = Window_Target.new @target_window.visible = false @target_window.active = false end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If skill window is active: call update_skill if @skill_window.active update_skill return # If skill target is active: call update_target elsif @target_window.active update_target return end end #-------------------------------------------------------------------------- # * Frame Update (if skill window is active) #-------------------------------------------------------------------------- def update_skill # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to menu screen $scene = Scene_Menu.new(1) return end # If C button was pressed if Input.trigger?(Input::C) # Get currently selected data on the skill window @skill = @skill_window.skill # If unable to use if @skill == nil or not @actor.skill_can_use?(@skill.id) # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # If effect scope is ally if @skill.scope >= 3 # Activate target window @skill_window.active = false @target_window.x = (@skill_window.index + 1) % 2 * 304 @target_window.visible = true @target_window.active = true # Set cursor position to effect scope (single / all) if @skill.scope == 4 || @skill.scope == 6 @target_window.index = -1 elsif @skill.scope == 7 @target_window.index = @actor_index - 10 else @target_window.index = 0 end # If effect scope is other than ally else # If common event ID is valid if @skill.common_event_id > 0 # Common event call reservation $game_temp.common_event_id = @skill.common_event_id # Play use skill SE $game_system.se_play(@skill.menu_se) # Use up SP @actor.sp -= @skill.sp_cost # Remake each window content @status_window.refresh @skill_window.refresh @target_window.refresh # Switch to map screen $scene = Scene_Map.new return end end return end # If R button was pressed if Input.trigger?(Input::R) # Play cursor SE $game_system.se_play($data_system.cursor_se) # To next actor @actor_index += 1 @actor_index %= $game_party.actors.size # Switch to different skill screen $scene = Scene_Skill.new(@actor_index) return end # If L button was pressed if Input.trigger?(Input::L) # Play cursor SE $game_system.se_play($data_system.cursor_se) # To previous actor @actor_index += $game_party.actors.size - 1 @actor_index %= $game_party.actors.size # Switch to different skill screen $scene = Scene_Skill.new(@actor_index) return end end #-------------------------------------------------------------------------- # * Frame Update (when target window is active) #-------------------------------------------------------------------------- def update_target # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Erase target window @skill_window.active = true @target_window.visible = false @target_window.active = false return end # If C button was pressed if Input.trigger?(Input::C) # If unable to use because SP ran out unless @actor.skill_can_use?(@skill.id) # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # If target is all if @target_window.index == -1 # Apply skill use effects to entire party used = false for i in $game_party.actors used |= i.skill_effect(@actor, @skill) end end # If target is user if @target_window.index <= -2 # Apply skill use effects to target actor target = $game_party.actors[@target_window.index + 10] used = target.skill_effect(@actor, @skill) end # If single target if @target_window.index >= 0 # Apply skill use effects to target actor target = $game_party.actors[@target_window.index] used = target.skill_effect(@actor, @skill) end # If skill was used if used # Play skill use SE $game_system.se_play(@skill.menu_se) # Use up SP @actor.sp -= @skill.sp_cost # Remake each window content @status_window.refresh @skill_window.refresh @target_window.refresh # If entire party is dead if $game_party.all_dead? # Switch to game over screen $scene = Scene_Gameover.new return end # If command event ID is valid if @skill.common_event_id > 0 # Command event call reservation $game_temp.common_event_id = @skill.common_event_id # Switch to map screen $scene = Scene_Map.new return end end # If skill wasn't used unless used # Play buzzer SE $game_system.se_play($data_system.buzzer_se) end return end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_EQUIP') #============================================================================== # ** Window_EquipItem #------------------------------------------------------------------------------ # This window displays choices when opting to change equipment on the # equipment screen. #============================================================================== class Window_EquipItem < Window_Selectable #-------------------------------------------------------------------------- # * Disable Update #-------------------------------------------------------------------------- def disable_update? return true end end #============================================================================== # ** Scene_Equip #------------------------------------------------------------------------------ # This class performs equipment screen processing. #============================================================================== class Scene_Equip < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Equip, :main, :main_variable, :main_window) #-------------------------------------------------------------------------- # * Object Initialization # actor_index : actor index # equip_index : equipment index #-------------------------------------------------------------------------- def initialize(actor_index = 0, equip_index = 0) @actor_index = actor_index @equip_index = equip_index super() end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Variable Initialization #-------------------------------------------------------------------------- def main_variable super # Get actor @actor = $game_party.actors[@actor_index] end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make windows @help_window = Window_Help.new @left_window = Window_EquipLeft.new(@actor) @right_window = Window_EquipRight.new(@actor) @item_window1 = Window_EquipItem.new(@actor, 0) @item_window2 = Window_EquipItem.new(@actor, 1) @item_window3 = Window_EquipItem.new(@actor, 2) @item_window4 = Window_EquipItem.new(@actor, 3) @item_window5 = Window_EquipItem.new(@actor, 4) # Associate help window @right_window.help_window = @help_window @item_window1.help_window = @help_window @item_window2.help_window = @help_window @item_window3.help_window = @help_window @item_window4.help_window = @help_window @item_window5.help_window = @help_window # Set cursor position @right_window.index = @equip_index refresh end #-------------------------------------------------------------------------- # * Main Update #-------------------------------------------------------------------------- def main_update super @item_window.update end #-------------------------------------------------------------------------- # * Refresh #-------------------------------------------------------------------------- def refresh # Set item window to visible @item_window1.visible = (@right_window.index == 0) @item_window2.visible = (@right_window.index == 1) @item_window3.visible = (@right_window.index == 2) @item_window4.visible = (@right_window.index == 3) @item_window5.visible = (@right_window.index == 4) # Get currently equipped item item1 = @right_window.item # Set current item window to @item_window case @right_window.index when 0 @item_window = @item_window1 when 1 @item_window = @item_window2 when 2 @item_window = @item_window3 when 3 @item_window = @item_window4 when 4 @item_window = @item_window5 end # If right window is active if @right_window.active # Erase parameters for after equipment change @left_window.set_new_parameters(nil, nil, nil) end # If item window is active if @item_window.active # Get currently selected item item2 = @item_window.item # Change equipment last_hp = @actor.hp last_sp = @actor.sp @actor.equip(@right_window.index, item2 == nil ? 0 : item2.id) # Get parameters for after equipment change new_atk = @actor.atk new_pdef = @actor.pdef new_mdef = @actor.mdef # Return equipment @actor.equip(@right_window.index, item1 == nil ? 0 : item1.id) @actor.hp = last_hp @actor.sp = last_sp # Draw in left window @left_window.set_new_parameters(new_atk, new_pdef, new_mdef) end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # Refresh Windows refresh # If right window is active: call update_right if @right_window.active update_right return # If item window is active: call update_item elsif @item_window.active update_item return end end #-------------------------------------------------------------------------- # * Frame Update (when right window is active) #-------------------------------------------------------------------------- def update_right # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to menu screen $scene = Scene_Menu.new(2) return end # If C button was pressed if Input.trigger?(Input::C) # If equipment is fixed if @actor.equip_fix?(@right_window.index) # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Activate item window @right_window.active = false @item_window.active = true @item_window.index = 0 return end # If R button was pressed if Input.trigger?(Input::R) # Play cursor SE $game_system.se_play($data_system.cursor_se) # To next actor @actor_index += 1 @actor_index %= $game_party.actors.size # Switch to different equipment screen $scene = Scene_Equip.new(@actor_index, @right_window.index) return end # If L button was pressed if Input.trigger?(Input::L) # Play cursor SE $game_system.se_play($data_system.cursor_se) # To previous actor @actor_index += $game_party.actors.size - 1 @actor_index %= $game_party.actors.size # Switch to different equipment screen $scene = Scene_Equip.new(@actor_index, @right_window.index) return end end #-------------------------------------------------------------------------- # * Frame Update (when item window is active) #-------------------------------------------------------------------------- def update_item # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Activate right window @right_window.active = true @item_window.active = false @item_window.index = -1 return end # If C button was pressed if Input.trigger?(Input::C) # Play equip SE $game_system.se_play($data_system.equip_se) # Get currently selected data on the item window item = @item_window.item # Change equipment @actor.equip(@right_window.index, item == nil ? 0 : item.id) # Activate right window @right_window.active = true @item_window.active = false @item_window.index = -1 # Remake right window and item window contents @right_window.refresh @item_window.refresh return end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_STATUS') #============================================================================== # ** Scene_Status #------------------------------------------------------------------------------ # This class performs status screen processing. #============================================================================== class Scene_Status < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Status, :main, :main_variable, :main_window) #-------------------------------------------------------------------------- # * Object Initialization # actor_index : actor index #-------------------------------------------------------------------------- def initialize(actor_index = 0) @actor_index = actor_index super() end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Variable Initialization #-------------------------------------------------------------------------- def main_variable super # Get actor @actor = $game_party.actors[@actor_index] end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make status window @status_window = Window_Status.new(@actor) end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to menu screen $scene = Scene_Menu.new(3) return end # If R button was pressed if Input.trigger?(Input::R) # Play cursor SE $game_system.se_play($data_system.cursor_se) # To next actor @actor_index += 1 @actor_index %= $game_party.actors.size # Switch to different status screen $scene = Scene_Status.new(@actor_index) return end # If L button was pressed if Input.trigger?(Input::L) # Play cursor SE $game_system.se_play($data_system.cursor_se) # To previous actor @actor_index += $game_party.actors.size - 1 @actor_index %= $game_party.actors.size # Switch to different status screen $scene = Scene_Status.new(@actor_index) return end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_FILE') #============================================================================== # ** Scene_File #------------------------------------------------------------------------------ # This is a superclass for the save screen and load screen. #============================================================================== class Scene_File < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_File, :main, :main_variable, :main_window) #-------------------------------------------------------------------------- # * Object Initialization # help_text : text string shown in the help window #-------------------------------------------------------------------------- def initialize(help_text) @help_text = help_text super() end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Variable Initialization #-------------------------------------------------------------------------- def main_variable super # Select last file to be operated @file_index = $game_temp.last_file_index end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make help window @help_window = Window_Help.new @help_window.set_text(@help_text) # Make save file window @savefile_windows = [] for i in 0..3 @savefile_windows.push(Window_SaveFile.new(i, make_filename(i))) end @savefile_windows[@file_index].selected = true end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If C button was pressed if Input.trigger?(Input::C) # Call method: on_decision (defined by the subclasses) on_decision(make_filename(@file_index)) $game_temp.last_file_index = @file_index return end # If B button was pressed if Input.trigger?(Input::B) # Call method: on_cancel (defined by the subclasses) on_cancel return end # If the down directional button was pressed if Input.repeat?(Input::DOWN) # If the down directional button pressed down is not a repeat, # or cursor position is more in front than 3 if Input.trigger?(Input::DOWN) or @file_index < 3 # Play cursor SE $game_system.se_play($data_system.cursor_se) # Move cursor down @savefile_windows[@file_index].selected = false @file_index = (@file_index + 1) % 4 @savefile_windows[@file_index].selected = true return end end # If the up directional button was pressed if Input.repeat?(Input::UP) # If the up directional button pressed down is not a repeat? # or cursor position is more in back than 0 if Input.trigger?(Input::UP) or @file_index > 0 # Play cursor SE $game_system.se_play($data_system.cursor_se) # Move cursor up @savefile_windows[@file_index].selected = false @file_index = (@file_index + 3) % 4 @savefile_windows[@file_index].selected = true return end end end #-------------------------------------------------------------------------- # * Make File Name # file_index : save file index (0-3) #-------------------------------------------------------------------------- def make_filename(file_index) return "Save#{file_index + 1}.rxdata" end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_SAVE') #============================================================================== # ** Scene_Save #------------------------------------------------------------------------------ # This class performs save screen processing. #============================================================================== class Scene_Save < Scene_File #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Save, :write_save_data, :write_characters, :write_frame, :write_setup, :write_data) #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize super("Which file would you like to save to?") end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Decision Processing #-------------------------------------------------------------------------- def on_decision(filename) # Play save SE $game_system.se_play($data_system.save_se) # Write save data file = File.open(filename, "wb") write_save_data(file) file.close # If called from event if $game_temp.save_calling # Clear save call flag $game_temp.save_calling = false # Switch to map screen $scene = Scene_Map.new return end # Switch to menu screen $scene = Scene_Menu.new(4) end #-------------------------------------------------------------------------- # * Cancel Processing #-------------------------------------------------------------------------- def on_cancel # Play cancel SE $game_system.se_play($data_system.cancel_se) # If called from event if $game_temp.save_calling # Clear save call flag $game_temp.save_calling = false # Switch to map screen $scene = Scene_Map.new return end # Switch to menu screen $scene = Scene_Map.new #$scene = Scene_Menu.new(4) end #-------------------------------------------------------------------------- # * Write Save Data # file : write file object (opened) #-------------------------------------------------------------------------- def write_save_data(file) write_characters(file) write_frame(file) write_setup(file) write_data(file) end #-------------------------------------------------------------------------- # * Make Character Data #-------------------------------------------------------------------------- def write_characters(file) # Make character data for drawing save file characters = [] for i in 0...$game_party.actors.size actor = $game_party.actors[i] characters.push([actor.character_name, actor.character_hue]) end # Write character data for drawing save file Marshal.dump(characters, file) end #-------------------------------------------------------------------------- # * Write Frame Count #-------------------------------------------------------------------------- def write_frame(file) # Wrire frame count for measuring play time Marshal.dump(Graphics.frame_count, file) end #-------------------------------------------------------------------------- # * Write Setup #-------------------------------------------------------------------------- def write_setup(file) # Increase save count by 1 $game_system.save_count += 1 # Save magic number # (A random value will be written each time saving with editor) $game_system.magic_number = $data_system.magic_number end #-------------------------------------------------------------------------- # * Write Data #-------------------------------------------------------------------------- def write_data(file) # Write each type of game object Marshal.dump($game_system, file) Marshal.dump($game_switches, file) Marshal.dump($game_variables, file) Marshal.dump($game_self_switches, file) Marshal.dump($game_screen, file) Marshal.dump($game_actors, file) Marshal.dump($game_party, file) Marshal.dump($game_troop, file) Marshal.dump($game_map, file) Marshal.dump($game_player, file) end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_LOAD') #============================================================================== # ** Scene_Load #------------------------------------------------------------------------------ # This class performs load screen processing. #============================================================================== class Scene_Load < Scene_File #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Load, :read_save_data, :read_characters, :read_frame, :read_data, :read_edit, :read_refresh) #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize # Remake temporary object $game_temp = Game_Temp.new # Timestamp selects new file $game_temp.last_file_index = 0 latest_time = Time.at(0) for i in 0..3 filename = make_filename(i) if FileTest.exist?(filename) file = File.open(filename, "r") if file.mtime > latest_time latest_time = file.mtime $game_temp.last_file_index = i end file.close end end super("Honnan szeretnél tölteni?") end #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Decision Processing #-------------------------------------------------------------------------- def on_decision(filename) # If file doesn't exist unless FileTest.exist?(filename) # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play load SE $game_system.se_play($data_system.load_se) # Read save data file = File.open(filename, "rb") read_save_data(file) file.close # Restore BGM and BGS $game_system.bgm_play($game_system.playing_bgm) $game_system.bgs_play($game_system.playing_bgs) # Update map (run parallel process event) $game_map.update # Switch to map screen $scene = Scene_Map.new end #-------------------------------------------------------------------------- # * Cancel Processing #-------------------------------------------------------------------------- def on_cancel # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to title screen $scene = Scene_Map.new # $scene = Scene_Title.new end #-------------------------------------------------------------------------- # * Read Save Data # file : file object for reading (opened) #-------------------------------------------------------------------------- def read_save_data(file) read_characters(file) read_frame(file) read_data(file) read_edit read_refresh end #-------------------------------------------------------------------------- # * Read Character Data #-------------------------------------------------------------------------- def read_characters(file) # Read character data for drawing save file characters = Marshal.load(file) end #-------------------------------------------------------------------------- # * Read Frame Count #-------------------------------------------------------------------------- def read_frame(file) # Read frame count for measuring play time Graphics.frame_count = Marshal.load(file) end #-------------------------------------------------------------------------- # * Read Data #-------------------------------------------------------------------------- def read_data(file) # Read each type of game object $game_system = Marshal.load(file) $game_switches = Marshal.load(file) $game_variables = Marshal.load(file) $game_self_switches = Marshal.load(file) $game_screen = Marshal.load(file) $game_actors = Marshal.load(file) $game_party = Marshal.load(file) $game_troop = Marshal.load(file) $game_map = Marshal.load(file) $game_player = Marshal.load(file) end #-------------------------------------------------------------------------- # * Read Edit #-------------------------------------------------------------------------- def read_edit # If magic number is different from when saving # (if editing was added with editor) if $game_system.magic_number != $data_system.magic_number # Load map $game_map.setup($game_map.map_id) $game_player.center($game_player.x, $game_player.y) end end #-------------------------------------------------------------------------- # * Refresh Game Party #-------------------------------------------------------------------------- def read_refresh # Refresh party members $game_party.refresh end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_END') #============================================================================== # ** Scene_End #------------------------------------------------------------------------------ # This class performs game end screen processing. #============================================================================== class Scene_End < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_End, :main, :main_window, :main_end) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make command window s1 = "To Title" s2 = "Shutdown" s3 = "Cancel" @command_window = Window_Command.new(192, [s1, s2, s3]) @command_window.x = 320 - @command_window.width / 2 @command_window.y = 240 - @command_window.height / 2 end #-------------------------------------------------------------------------- # * Main Processing : Ending #-------------------------------------------------------------------------- def main_end # If switching to title screen if $scene.is_a?(Scene_Title) # Fade out screen Graphics.transition Graphics.freeze end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to menu screen $scene = Scene_Menu.new(5) return end # If C button was pressed if Input.trigger?(Input::C) # Branch by command window cursor position case @command_window.index when 0 # to title command_to_title when 1 # shutdown command_shutdown when 2 # quit command_cancel end return end end #-------------------------------------------------------------------------- # * Process When Choosing [To Title] Command #-------------------------------------------------------------------------- def command_to_title # Play decision SE $game_system.se_play($data_system.decision_se) # Fade out BGM, BGS, and ME Audio.bgm_fade(800) Audio.bgs_fade(800) Audio.me_fade(800) # Switch to title screen $scene = Scene_Title.new end #-------------------------------------------------------------------------- # * Process When Choosing [Shutdown] Command #-------------------------------------------------------------------------- def command_shutdown # Play decision SE $game_system.se_play($data_system.decision_se) # Fade out BGM, BGS, and ME Audio.bgm_fade(800) Audio.bgs_fade(800) Audio.me_fade(800) # Shutdown $scene = nil end #-------------------------------------------------------------------------- # * Process When Choosing [Cancel] Command #-------------------------------------------------------------------------- def command_cancel # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to menu screen $scene = Scene_Menu.new(5) end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_BATTLE') #============================================================================== # ** Window_PartyCommand #------------------------------------------------------------------------------ # This window is used to select whether to fight or escape on the battle # screen. #============================================================================== class Window_PartyCommand < Window_HorizCommand #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize s1 = SDK::Scene_Commands::Scene_Battle::Fight s2 = SDK::Scene_Commands::Scene_Battle::Escape super(640, [s1, s2]) self.back_opacity = 160 disable_item(1) unless $game_temp.battle_can_escape self.active = false self.visible = false end end #============================================================================== # ** Scene_Battle #------------------------------------------------------------------------------ # This class performs battle screen processing. #============================================================================== class Scene_Battle < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Battle, :main, :main_variable, :main_spriteset, :main_window, :main_transition, :main_end) SDK.log_branch(:Scene_Battle, :main_variable, :main_battledata, :main_troopdata) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Variable Initialization #-------------------------------------------------------------------------- def main_variable super main_battledata # Setup Battle Temp Data & Interpreter main_troopdata # Setup Troop Data # Initialize wait count @wait_count = 0 end #-------------------------------------------------------------------------- # * Main Processing : Battle Data Initialization #-------------------------------------------------------------------------- def main_battledata # Initialize each kind of temporary battle data $game_temp.in_battle = true $game_temp.battle_turn = 0 $game_temp.battle_event_flags.clear $game_temp.battle_abort = false $game_temp.battle_main_phase = false $game_temp.battleback_name = $game_map.battleback_name $game_temp.forcing_battler = nil # Initialize battle event interpreter $game_system.battle_interpreter.setup(nil, 0) end #-------------------------------------------------------------------------- # * Main Processing : Troop Data Initialization #-------------------------------------------------------------------------- def main_troopdata # Prepare troop @troop_id = $game_temp.battle_troop_id $game_troop.setup(@troop_id) end #-------------------------------------------------------------------------- # * Main Processing : Spriteset Initialization #-------------------------------------------------------------------------- def main_spriteset super # Make sprite set @spriteset = Spriteset_Battle.new end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make actor command window s1 = $data_system.words.attack s2 = $data_system.words.skill s3 = $data_system.words.guard s4 = $data_system.words.item @actor_command_window = Window_Command.new(160, [s1, s2, s3, s4]) @actor_command_window.y = 160 @actor_command_window.back_opacity = 160 @actor_command_window.active = false @actor_command_window.visible = false # Make other windows @party_command_window = Window_PartyCommand.new @help_window = Window_Help.new @help_window.back_opacity = 160 @help_window.visible = false @status_window = Window_BattleStatus.new @message_window = Window_Message.new end #-------------------------------------------------------------------------- # * Main Processing : Transition #-------------------------------------------------------------------------- def main_transition # Execute transition if $data_system.battle_transition == "" Graphics.transition(20) else Graphics.transition(40, "Graphics/Transitions/" + $data_system.battle_transition) end # Start pre-battle phase start_phase1 end #-------------------------------------------------------------------------- # * Main Processing : Ending #-------------------------------------------------------------------------- def main_end # Refresh map $game_map.refresh # If switching to title screen if $scene.is_a?(Scene_Title) # Fade out screen Graphics.transition Graphics.freeze end # If switching from battle test to any screen other than game over screen if $BTEST and not $scene.is_a?(Scene_Gameover) $scene = nil end end #-------------------------------------------------------------------------- # * Determine Battle Win/Loss Results #-------------------------------------------------------------------------- def judge # If all dead determinant is true, or number of members in party is 0 if $game_party.all_dead? or $game_party.actors.size == 0 # If possible to lose if $game_temp.battle_can_lose # Return to BGM before battle starts $game_system.bgm_play($game_temp.map_bgm) # Battle ends battle_end(2) # Return true return true end # Set game over flag $game_temp.gameover = true # Return true return true end # Return false if even 1 enemy exists for enemy in $game_troop.enemies if enemy.exist? return false end end # Start after battle phase (win) start_phase5 # Return true return true end #-------------------------------------------------------------------------- # * Battle Ends # result : results (0:win 1:lose 2:escape) #-------------------------------------------------------------------------- def battle_end(result) # Clear in battle flag $game_temp.in_battle = false # Clear entire party actions flag $game_party.clear_actions # Remove battle states for actor in $game_party.actors actor.remove_states_battle end # Clear enemies $game_troop.enemies.clear # Call battle callback if $game_temp.battle_proc != nil $game_temp.battle_proc.call(result) $game_temp.battle_proc = nil end # Switch to map screen $scene = Scene_Map.new end #-------------------------------------------------------------------------- # * Battle Event Setup #-------------------------------------------------------------------------- def setup_battle_event # If battle event is running if $game_system.battle_interpreter.running? return end # Search for all battle event pages for index in 0...$data_troops[@<EMAIL>].pages.size # Get event pages page = $data_troops[@tro<EMAIL>].pages[index] # Make event conditions possible for reference with c c = page.condition # Next if Page Condition Not Met next unless c.conditions_met?(index) # Set up event $game_system.battle_interpreter.setup(page.list, 0) # If this page span is [battle] or [turn] if page.span <= 1 # Set action completed flag $game_temp.battle_event_flags[index] = true end return end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super update_interpreter # Update Battle Interpreter update_systems # Update Screen & Timer update_transition # Update Transition return if update_message? # Update Message Test return if update_sseffect? # Update Spriteset Effect Test return if update_gameover? # Update Gameover Test return if update_title? # Update Title Test return if update_abort? # Update Abort Test return if update_wait? # Update Wait Test return if update_forcing? # Update Forcing Test update_battlephase # Update Battle Phase end #-------------------------------------------------------------------------- # * Frame Update : Interpreter #-------------------------------------------------------------------------- def update_interpreter # If battle event is running if $game_system.battle_interpreter.running? # Update interpreter $game_system.battle_interpreter.update # If a battler which is forcing actions doesn't exist if $game_temp.forcing_battler == nil # If battle event has finished running unless $game_system.battle_interpreter.running? # Rerun battle event set up if battle continues unless judge setup_battle_event end end # If not after battle phase if @phase != 5 # Refresh status window @status_window.refresh end end end end #-------------------------------------------------------------------------- # * Frame Update : Systems #-------------------------------------------------------------------------- def update_systems # Update system (timer) and screen $game_system.update $game_screen.update # If timer has reached 0 if $game_system.timer_working and $game_system.timer == 0 # Abort battle $game_temp.battle_abort = true end end #-------------------------------------------------------------------------- # * Frame Update : Transition #-------------------------------------------------------------------------- def update_transition # If transition is processing if $game_temp.transition_processing # Clear transition processing flag $game_temp.transition_processing = false # Execute transition if $game_temp.transition_name == "" Graphics.transition(20) else Graphics.transition(40, "Graphics/Transitions/" + $game_temp.transition_name) end end end #-------------------------------------------------------------------------- # * Frame Update : Message Test #-------------------------------------------------------------------------- def update_message? # If message window is showing return $game_temp.message_window_showing end #-------------------------------------------------------------------------- # * Frame Update : Spriteset Effect Test #-------------------------------------------------------------------------- def update_sseffect? # If effect is showing return @spriteset.effect? end #-------------------------------------------------------------------------- # * Frame Update : Gamevoer Test #-------------------------------------------------------------------------- def update_gameover? # If game over if $game_temp.gameover # Switch to game over screen $scene = Scene_Gameover.new return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Title Test #-------------------------------------------------------------------------- def update_title? # If returning to title screen if $game_temp.to_title # Switch to title screen $scene = Scene_Title.new return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Abort Test #-------------------------------------------------------------------------- def update_abort? # If battle is aborted if $game_temp.battle_abort # Return to BGM used before battle started $game_system.bgm_play($game_temp.map_bgm) # Battle ends battle_end(1) return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Wait Test #-------------------------------------------------------------------------- def update_wait? # If waiting if @wait_count > 0 # Decrease wait count @wait_count -= 1 return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Forcing Test #-------------------------------------------------------------------------- def update_forcing? # If battler forcing an action doesn't exist, # and battle event is running if $game_temp.forcing_battler == nil and $game_system.battle_interpreter.running? return true end return false end #-------------------------------------------------------------------------- # * Frame Update : Battle Phase #-------------------------------------------------------------------------- def update_battlephase # Branch according to phase case @phase when 1 # pre-battle phase update_phase1 when 2 # party command phase update_phase2 when 3 # actor command phase update_phase3 when 4 # main phase update_phase4 when 5 # after battle phase update_phase5 end end #-------------------------------------------------------------------------- # * Start Pre-Battle Phase #-------------------------------------------------------------------------- def start_phase1 # Shift to phase 1 @phase = 1 # Clear all party member actions $game_party.clear_actions # Set up battle event setup_battle_event end #-------------------------------------------------------------------------- # * Frame Update (pre-battle phase) #-------------------------------------------------------------------------- def update_phase1 # Determine win/loss situation if judge # If won or lost: end method return end # Start party command phase start_phase2 end #-------------------------------------------------------------------------- # * Start Party Command Phase #-------------------------------------------------------------------------- def start_phase2 # Shift to phase 2 @phase = 2 # Set actor to non-selecting @actor_index = -1 @active_battler = nil # Enable party command window @party_command_window.active = true @party_command_window.visible = true # Disable actor command window @actor_command_window.active = false @actor_command_window.visible = false # Clear main phase flag $game_temp.battle_main_phase = false # Clear all party member actions $game_party.clear_actions # If impossible to input command unless $game_party.inputable? # Start main phase start_phase4 end end #-------------------------------------------------------------------------- # * Frame Update (party command phase) #-------------------------------------------------------------------------- def update_phase2 # If C button was pressed if Input.trigger?(Input::C) # Branch by party command window cursor position case @party_command_window.index when 0 # fight # Play decision SE $game_system.se_play($data_system.decision_se) # Start actor command phase start_phase3 when 1 # escape # If it's not possible to escape if $game_temp.battle_can_escape == false # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Escape processing update_phase2_escape end return end end #-------------------------------------------------------------------------- # * Frame Update (party command phase: escape) #-------------------------------------------------------------------------- def update_phase2_escape # Calculate enemy agility average enemies_agi = 0 enemies_number = 0 for enemy in $game_troop.enemies if enemy.exist? enemies_agi += enemy.agi enemies_number += 1 end end if enemies_number > 0 enemies_agi /= enemies_number end # Calculate actor agility average actors_agi = 0 actors_number = 0 for actor in $game_party.actors if actor.exist? actors_agi += actor.agi actors_number += 1 end end if actors_number > 0 actors_agi /= actors_number end # Determine if escape is successful success = rand(100) < 50 * actors_agi / enemies_agi # If escape is successful if success # Play escape SE $game_system.se_play($data_system.escape_se) # Return to BGM before battle started $game_system.bgm_play($game_temp.map_bgm) # Battle ends battle_end(1) # If escape is failure else # Clear all party member actions $game_party.clear_actions # Start main phase start_phase4 end end #-------------------------------------------------------------------------- # * Start After Battle Phase #-------------------------------------------------------------------------- def start_phase5 # Shift to phase 5 @phase = 5 # Play battle end ME $game_system.me_play($game_system.battle_end_me) # Return to BGM before battle started $game_system.bgm_play($game_temp.map_bgm) # Initialize EXP, amount of gold, and treasure exp = 0 gold = 0 treasures = [] # Loop for enemy in $game_troop.enemies # If enemy is not hidden unless enemy.hidden # Add EXP and amount of gold obtained exp += enemy.exp gold += enemy.gold # Determine if treasure appears if rand(100) < enemy.treasure_prob if enemy.item_id > 0 treasures.push($data_items[enemy.item_id]) end if enemy.weapon_id > 0 treasures.push($data_weapons[enemy.weapon_id]) end if enemy.armor_id > 0 treasures.push($data_armors[enemy.armor_id]) end end end end # Treasure is limited to a maximum of 6 items treasures = treasures[0..5] # Obtaining EXP for i in 0...$game_party.actors.size actor = $game_party.actors[i] if actor.cant_get_exp? == false last_level = actor.level actor.exp += exp if actor.level > last_level @status_window.level_up(i) end end end # Obtaining gold $game_party.gain_gold(gold) # Obtaining treasure for item in treasures case item when RPG::Item $game_party.gain_item(item.id, 1) when RPG::Weapon $game_party.gain_weapon(item.id, 1) when RPG::Armor $game_party.gain_armor(item.id, 1) end end # Make battle result window @result_window = Window_BattleResult.new(exp, gold, treasures) # Set wait count @phase5_wait_count = 100 end #-------------------------------------------------------------------------- # * Frame Update (after battle phase) #-------------------------------------------------------------------------- def update_phase5 # If wait count is larger than 0 if @phase5_wait_count > 0 # Decrease wait count @phase5_wait_count -= 1 # If wait count reaches 0 if @phase5_wait_count == 0 # Show result window @result_window.visible = true # Clear main phase flag $game_temp.battle_main_phase = false # Refresh status window @status_window.refresh end return end # If C button was pressed if Input.trigger?(Input::C) # Battle ends battle_end(0) end end #-------------------------------------------------------------------------- # * Start Actor Command Phase #-------------------------------------------------------------------------- def start_phase3 # Shift to phase 3 @phase = 3 # Set actor as unselectable @actor_index = -1 @active_battler = nil # Go to command input for next actor phase3_next_actor end #-------------------------------------------------------------------------- # * Go to Command Input for Next Actor #-------------------------------------------------------------------------- def phase3_next_actor # Loop begin # Actor blink effect OFF if @active_battler != nil @active_battler.blink = false end # If last actor if @actor_index == $game_party.actors.size-1 # Start main phase start_phase4 return end # Advance actor index @actor_index += 1 @active_battler = $game_party.actors[@actor_index] @active_battler.blink = true # Once more if actor refuses command input end until @active_battler.inputable? # Set up actor command window phase3_setup_command_window end #-------------------------------------------------------------------------- # * Go to Command Input of Previous Actor #-------------------------------------------------------------------------- def phase3_prior_actor # Loop begin # Actor blink effect OFF if @active_battler != nil @active_battler.blink = false end # If first actor if @actor_index == 0 # Start party command phase start_phase2 return end # Return to actor index @actor_index -= 1 @active_battler = $game_party.actors[@actor_index] @active_battler.blink = true # Once more if actor refuses command input end until @active_battler.inputable? # Set up actor command window phase3_setup_command_window end #-------------------------------------------------------------------------- # * Actor Command Window Setup #-------------------------------------------------------------------------- def phase3_setup_command_window # Disable party command window @party_command_window.active = false @party_command_window.visible = false # Enable actor command window @actor_command_window.active = true @actor_command_window.visible = true # Set actor command window position @actor_command_window.x = @actor_index * 160 # Set index to 0 @actor_command_window.index = 0 end #-------------------------------------------------------------------------- # * Frame Update (actor command phase) #-------------------------------------------------------------------------- def update_phase3 # If enemy arrow is enabled if @enemy_arrow != nil update_phase3_enemy_select # If actor arrow is enabled elsif @actor_arrow != nil update_phase3_actor_select # If skill window is enabled elsif @skill_window != nil update_phase3_skill_select # If item window is enabled elsif @item_window != nil update_phase3_item_select # If actor command window is enabled elsif @actor_command_window.active update_phase3_basic_command end end #-------------------------------------------------------------------------- # * Frame Update (actor command phase : basic command) #-------------------------------------------------------------------------- def update_phase3_basic_command # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Go to command input for previous actor phase3_prior_actor return end # If C button was pressed if Input.trigger?(Input::C) # Branch by actor command window cursor position case @actor_command_window.index when 0 # attack # Play decision SE $game_system.se_play($data_system.decision_se) # Set action @active_battler.current_action.kind = 0 @active_battler.current_action.basic = 0 # Start enemy selection start_enemy_select when 1 # skill # Play decision SE $game_system.se_play($data_system.decision_se) # Set action @active_battler.current_action.kind = 1 # Start skill selection start_skill_select when 2 # guard # Play decision SE $game_system.se_play($data_system.decision_se) # Set action @active_battler.current_action.kind = 0 @active_battler.current_action.basic = 1 # Go to command input for next actor phase3_next_actor when 3 # item # Play decision SE $game_system.se_play($data_system.decision_se) # Set action @active_battler.current_action.kind = 2 # Start item selection start_item_select end return end end #-------------------------------------------------------------------------- # * Frame Update (actor command phase : skill selection) #-------------------------------------------------------------------------- def update_phase3_skill_select # Make skill window visible @skill_window.visible = true # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # End skill selection end_skill_select return end # If C button was pressed if Input.trigger?(Input::C) # Get currently selected data on the skill window @skill = @skill_window.skill # If it can't be used if @skill == nil or not @active_battler.skill_can_use?(@skill.id) # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Set action @active_battler.current_action.skill_id = @skill.id # Make skill window invisible @skill_window.visible = false @skill_window.active = false # If effect scope is single enemy if @skill.scope == 1 # Start enemy selection start_enemy_select # If effect scope is single ally elsif @skill.scope == 3 or @skill.scope == 5 # Start actor selection start_actor_select # If effect scope is not single else # End skill selection end_skill_select # Go to command input for next actor phase3_next_actor end return end end #-------------------------------------------------------------------------- # * Frame Update (actor command phase : item selection) #-------------------------------------------------------------------------- def update_phase3_item_select # Make item window visible @item_window.visible = true # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # End item selection end_item_select return end # If C button was pressed if Input.trigger?(Input::C) # Get currently selected data on the item window @item = @item_window.item # If it can't be used unless $game_party.item_can_use?(@item.id) # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Set action @active_battler.current_action.item_id = @item.id # Make item window invisible @item_window.visible = false @item_window.active = false # If effect scope is single enemy if @item.scope == 1 # Start enemy selection start_enemy_select # If effect scope is single ally elsif @item.scope == 3 or @item.scope == 5 # Start actor selection start_actor_select # If effect scope is not single else # End item selection end_item_select # Go to command input for next actor phase3_next_actor end return end end #-------------------------------------------------------------------------- # * Frame Update (actor command phase : enemy selection) #-------------------------------------------------------------------------- def update_phase3_enemy_select # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # End enemy selection end_enemy_select return end # If C button was pressed if Input.trigger?(Input::C) # Play decision SE $game_system.se_play($data_system.decision_se) # Set action @active_battler.current_action.target_index = @enemy_arrow.index # End enemy selection end_enemy_select # If skill window is showing if @skill_window != nil # End skill selection end_skill_select end # If item window is showing if @item_window != nil # End item selection end_item_select end # Go to command input for next actor phase3_next_actor end end #-------------------------------------------------------------------------- # * Frame Update (actor command phase : actor selection) #-------------------------------------------------------------------------- def update_phase3_actor_select # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # End actor selection end_actor_select return end # If C button was pressed if Input.trigger?(Input::C) # Play decision SE $game_system.se_play($data_system.decision_se) # Set action @active_battler.current_action.target_index = @actor_arrow.index # End actor selection end_actor_select # If skill window is showing if @skill_window != nil # End skill selection end_skill_select end # If item window is showing if @item_window != nil # End item selection end_item_select end # Go to command input for next actor phase3_next_actor end end #-------------------------------------------------------------------------- # * Start Enemy Selection #-------------------------------------------------------------------------- def start_enemy_select # Make enemy arrow @enemy_arrow = Arrow_Enemy.new(@spriteset.viewport1) # Associate help window @enemy_arrow.help_window = @help_window # Disable actor command window @actor_command_window.active = false @actor_command_window.visible = false end #-------------------------------------------------------------------------- # * End Enemy Selection #-------------------------------------------------------------------------- def end_enemy_select # Dispose of enemy arrow @enemy_arrow.dispose @enemy_arrow = nil # If command is [fight] if @actor_command_window.index == 0 # Enable actor command window @actor_command_window.active = true @actor_command_window.visible = true # Hide help window @help_window.visible = false end # If Skill Window Exist unless @skill_window.nil? # Enable Skill Window @skill_window.active = true end # If Item Window Exist unless @item_window.nil? # Enable Skill Window @item_window.active = true end end #-------------------------------------------------------------------------- # * Start Actor Selection #-------------------------------------------------------------------------- def start_actor_select # Make actor arrow @actor_arrow = Arrow_Actor.new(@spriteset.viewport2) @actor_arrow.index = @actor_index # Associate help window @actor_arrow.help_window = @help_window # Disable actor command window @actor_command_window.active = false @actor_command_window.visible = false end #-------------------------------------------------------------------------- # * End Actor Selection #-------------------------------------------------------------------------- def end_actor_select # Dispose of actor arrow @actor_arrow.dispose @actor_arrow = nil # If Skill Window Exist unless @skill_window.nil? # Enable Skill Window @skill_window.active = true end # If Item Window Exist unless @item_window.nil? # Enable Skill Window @item_window.active = true end end #-------------------------------------------------------------------------- # * Start Skill Selection #-------------------------------------------------------------------------- def start_skill_select # Make skill window @skill_window = Window_Skill.new(@active_battler) # Associate help window @skill_window.help_window = @help_window # Disable actor command window @actor_command_window.active = false @actor_command_window.visible = false end #-------------------------------------------------------------------------- # * End Skill Selection #-------------------------------------------------------------------------- def end_skill_select # Dispose of skill window @skill_window.dispose @skill_window = nil # Hide help window @help_window.visible = false # Enable actor command window @actor_command_window.active = true @actor_command_window.visible = true end #-------------------------------------------------------------------------- # * Start Item Selection #-------------------------------------------------------------------------- def start_item_select # Make item window @item_window = Window_Item.new # Associate help window @item_window.help_window = @help_window # Disable actor command window @actor_command_window.active = false @actor_command_window.visible = false end #-------------------------------------------------------------------------- # * End Item Selection #-------------------------------------------------------------------------- def end_item_select # Dispose of item window @item_window.dispose @item_window = nil # Hide help window @help_window.visible = false # Enable actor command window @actor_command_window.active = true @actor_command_window.visible = true end #-------------------------------------------------------------------------- # * Start Main Phase #-------------------------------------------------------------------------- def start_phase4 # Shift to phase 4 @phase = 4 # Turn count $game_temp.battle_turn += 1 # Search all battle event pages for index in 0...$data_troops[@troop_id].pages.size # Get event page page = $data_troops[@troop_id].pages[index] # If this page span is [turn] if page.span == 1 # Clear action completed flags $game_temp.battle_event_flags[index] = false end end # Set actor as unselectable @actor_index = -1 @active_battler = nil # Enable party command window @party_command_window.active = false @party_command_window.visible = false # Disable actor command window @actor_command_window.active = false @actor_command_window.visible = false # Set main phase flag $game_temp.battle_main_phase = true # Make enemy action for enemy in $game_troop.enemies enemy.make_action end # Make action orders make_action_orders # Shift to step 1 @phase4_step = 1 end #-------------------------------------------------------------------------- # * Make Action Orders #-------------------------------------------------------------------------- def make_action_orders # Initialize @action_battlers array @action_battlers = [] # Add enemy to @action_battlers array for enemy in $game_troop.enemies @action_battlers.push(enemy) end # Add actor to @action_battlers array for actor in $game_party.actors @action_battlers.push(actor) end # Decide action speed for all for battler in @action_battlers battler.make_action_speed end # Line up action speed in order from greatest to least @action_battlers.sort! {|a,b| b.current_action.speed - a.current_action.speed } end #-------------------------------------------------------------------------- # * Frame Update (main phase) #-------------------------------------------------------------------------- def update_phase4 case @phase4_step when 1 update_phase4_step1 when 2 update_phase4_step2 when 3 update_phase4_step3 when 4 update_phase4_step4 when 5 update_phase4_step5 when 6 update_phase4_step6 end end #-------------------------------------------------------------------------- # * Frame Update (main phase step 1 : action preparation) #-------------------------------------------------------------------------- def update_phase4_step1 # Hide help window @help_window.visible = false # Determine win/loss if judge # If won, or if lost : end method return end # If an action forcing battler doesn't exist if $game_temp.forcing_battler == nil # Set up battle event setup_battle_event # If battle event is running if $game_system.battle_interpreter.running? return end end # If an action forcing battler exists if $game_temp.forcing_battler != nil # Add to head, or move @action_battlers.delete($game_temp.forcing_battler) @action_battlers.unshift($game_temp.forcing_battler) end # If no actionless battlers exist (all have performed an action) if @action_battlers.size == 0 # Start party command phase start_phase2 return end # Initialize animation ID and common event ID @animation1_id = 0 @animation2_id = 0 @common_event_id = 0 # Shift from head of actionless battlers @active_battler = @action_battlers.shift # If already removed from battle if @active_battler.index == nil return end # Slip damage if @active_battler.hp > 0 and @active_battler.slip_damage? @active_battler.slip_damage_effect @active_battler.damage_pop = true end # Natural removal of states @active_battler.remove_states_auto # Refresh status window @status_window.refresh # Shift to step 2 @phase4_step = 2 end #-------------------------------------------------------------------------- # * Frame Update (main phase step 2 : start action) #-------------------------------------------------------------------------- def update_phase4_step2 # If not a forcing action unless @active_battler.current_action.forcing # If restriction is [normal attack enemy] or [normal attack ally] if @active_battler.restriction == 2 or @active_battler.restriction == 3 # Set attack as an action @active_battler.current_action.kind = 0 @active_battler.current_action.basic = 0 end # If restriction is [cannot perform action] if @active_battler.restriction == 4 # Clear battler being forced into action $game_temp.forcing_battler = nil # Shift to step 1 @phase4_step = 1 return end end # Clear target battlers @target_battlers = [] # Branch according to each action case @active_battler.current_action.kind when 0 # basic make_basic_action_result when 1 # skill make_skill_action_result when 2 # item make_item_action_result end # Shift to step 3 if @phase4_step == 2 @phase4_step = 3 end end #-------------------------------------------------------------------------- # * Make Basic Action Results #-------------------------------------------------------------------------- def make_basic_action_result # If attack if @active_battler.current_action.basic == 0 # Set anaimation ID @animation1_id = @active_battler.animation1_id @animation2_id = @active_battler.animation2_id # If action battler is enemy if @active_battler.is_a?(Game_Enemy) if @active_battler.restriction == 3 target = $game_troop.random_target_enemy elsif @active_battler.restriction == 2 target = $game_party.random_target_actor else index = @active_battler.current_action.target_index target = $game_party.smooth_target_actor(index) end end # If action battler is actor if @active_battler.is_a?(Game_Actor) if @active_battler.restriction == 3 target = $game_party.random_target_actor elsif @active_battler.restriction == 2 target = $game_troop.random_target_enemy else index = @active_battler.current_action.target_index target = $game_troop.smooth_target_enemy(index) end end # Set array of targeted battlers @target_battlers = [target] # Apply normal attack results for target in @target_battlers target.attack_effect(@active_battler) end return end # If guard if @active_battler.current_action.basic == 1 # Display "Guard" in help window @help_window.set_text($data_system.words.guard, 1) return end # If escape if @active_battler.is_a?(Game_Enemy) and @active_battler.current_action.basic == 2 # Display "Escape" in help window @help_window.set_text("Escape", 1) # Escape @active_battler.escape return end # If doing nothing if @active_battler.current_action.basic == 3 # Clear battler being forced into action $game_temp.forcing_battler = nil # Shift to step 1 @phase4_step = 1 return end end #-------------------------------------------------------------------------- # * Set Targeted Battler for Skill or Item # scope : effect scope for skill or item #-------------------------------------------------------------------------- def set_target_battlers(scope) # If battler performing action is enemy if @active_battler.is_a?(Game_Enemy) # Branch by effect scope case scope when 1 # single enemy index = @active_battler.current_action.target_index @target_battlers.push($game_party.smooth_target_actor(index)) when 2 # all enemies for actor in $game_party.actors if actor.exist? @target_battlers.push(actor) end end when 3 # single ally index = @active_battler.current_action.target_index @target_battlers.push($game_troop.smooth_target_enemy(index)) when 4 # all allies for enemy in $game_troop.enemies if enemy.exist? @target_battlers.push(enemy) end end when 5 # single ally (HP 0) index = @active_battler.current_action.target_index enemy = $game_troop.enemies[index] if enemy != nil and enemy.hp0? @target_battlers.push(enemy) end when 6 # all allies (HP 0) for enemy in $game_troop.enemies if enemy != nil and enemy.hp0? @target_battlers.push(enemy) end end when 7 # user @target_battlers.push(@active_battler) end end # If battler performing action is actor if @active_battler.is_a?(Game_Actor) # Branch by effect scope case scope when 1 # single enemy index = @active_battler.current_action.target_index @target_battlers.push($game_troop.smooth_target_enemy(index)) when 2 # all enemies for enemy in $game_troop.enemies if enemy.exist? @target_battlers.push(enemy) end end when 3 # single ally index = @active_battler.current_action.target_index @target_battlers.push($game_party.smooth_target_actor(index)) when 4 # all allies for actor in $game_party.actors if actor.exist? @target_battlers.push(actor) end end when 5 # single ally (HP 0) index = @active_battler.current_action.target_index actor = $game_party.actors[index] if actor != nil and actor.hp0? @target_battlers.push(actor) end when 6 # all allies (HP 0) for actor in $game_party.actors if actor != nil and actor.hp0? @target_battlers.push(actor) end end when 7 # user @target_battlers.push(@active_battler) end end end #-------------------------------------------------------------------------- # * Make Skill Action Results #-------------------------------------------------------------------------- def make_skill_action_result # Get skill @skill = $data_skills[@active_battler.current_action.skill_id] # If not a forcing action unless @active_battler.current_action.forcing # If unable to use due to SP running out unless @active_battler.skill_can_use?(@skill.id) # Clear battler being forced into action $game_temp.forcing_battler = nil # Shift to step 1 @phase4_step = 1 return end end # Use up SP @active_battler.sp -= @skill.sp_cost # Refresh status window @status_window.refresh # Show skill name on help window @help_window.set_text(@skill.name, 1) # Set animation ID @animation1_id = @skill.animation1_id @animation2_id = @skill.animation2_id # Set command event ID @common_event_id = @skill.common_event_id # Set target battlers set_target_battlers(@skill.scope) # Apply skill effect for target in @target_battlers target.skill_effect(@active_battler, @skill) end end #-------------------------------------------------------------------------- # * Make Item Action Results #-------------------------------------------------------------------------- def make_item_action_result # Get item @item = $data_items[@active_battler.current_action.item_id] # If unable to use due to items running out unless $game_party.item_can_use?(@item.id) # Shift to step 1 @phase4_step = 1 return end # If consumable if @item.consumable # Decrease used item by 1 $game_party.lose_item(@item.id, 1) end # Display item name on help window @help_window.set_text(@item.name, 1) # Set animation ID @animation1_id = @item.animation1_id @animation2_id = @item.animation2_id # Set common event ID @common_event_id = @item.common_event_id # Decide on target index = @active_battler.current_action.target_index target = $game_party.smooth_target_actor(index) # Set targeted battlers set_target_battlers(@item.scope) # Apply item effect for target in @target_battlers target.item_effect(@item) end end #-------------------------------------------------------------------------- # * Frame Update (main phase step 3 : animation for action performer) #-------------------------------------------------------------------------- def update_phase4_step3 # Animation for action performer (if ID is 0, then white flash) if @animation1_id == 0 @active_battler.white_flash = true else @active_battler.animation_id = @animation1_id @active_battler.animation_hit = true end # Shift to step 4 @phase4_step = 4 end #-------------------------------------------------------------------------- # * Frame Update (main phase step 4 : animation for target) #-------------------------------------------------------------------------- def update_phase4_step4 # Animation for target for target in @target_battlers target.animation_id = @animation2_id target.animation_hit = (target.damage != "Miss") end # Animation has at least 8 frames, regardless of its length @wait_count = 8 # Shift to step 5 @phase4_step = 5 end #-------------------------------------------------------------------------- # * Frame Update (main phase step 5 : damage display) #-------------------------------------------------------------------------- def update_phase4_step5 # Hide help window @help_window.visible = false # Refresh status window @status_window.refresh # Display damage for target in @target_battlers if target.damage != nil target.damage_pop = true end end # Animation has at least 8 frames, regardless of its length @wait_count = 8 # Shift to step 6 @phase4_step = 6 end #-------------------------------------------------------------------------- # * Frame Update (main phase step 6 : refresh) #-------------------------------------------------------------------------- def update_phase4_step6 # Clear battler being forced into action $game_temp.forcing_battler = nil # If common event ID is valid if @common_event_id > 0 # Set up event common_event = $data_common_events[@common_event_id] $game_system.battle_interpreter.setup(common_event.list, 0) end # Shift to step 1 @phase4_step = 1 end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_SHOP') #============================================================================== # ** Window_ShopCommand #------------------------------------------------------------------------------ # This window is used to choose your business on the shop screen. #============================================================================== class Window_ShopCommand < Window_HorizCommand #-------------------------------------------------------------------------- # * Object Initialization #-------------------------------------------------------------------------- def initialize s1 = SDK::Scene_Commands::Scene_Shop::Buy s2 = SDK::Scene_Commands::Scene_Shop::Sell s3 = SDK::Scene_Commands::Scene_Shop::Exit super(480, [s1, s2, s3]) self.y = 64 @alignment = 0 refresh end end #============================================================================== # ** Scene_Shop #------------------------------------------------------------------------------ # This class performs shop screen processing. #============================================================================== class Scene_Shop < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Shop, :main, :main_window) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make help window @help_window = Window_Help.new # Make command window @command_window = Window_ShopCommand.new # Make gold window @gold_window = Window_Gold.new @gold_window.x = 480 @gold_window.y = 64 # Make dummy window @dummy_window = Window_Base.new(0, 128, 640, 352) # Make buy window @buy_window = Window_ShopBuy.new($game_temp.shop_goods) @buy_window.active = false @buy_window.visible = false @buy_window.help_window = @help_window # Make sell window @sell_window = Window_ShopSell.new @sell_window.active = false @sell_window.visible = false @sell_window.help_window = @help_window # Make quantity input window @number_window = Window_ShopNumber.new @number_window.active = false @number_window.visible = false # Make status window @status_window = Window_ShopStatus.new @status_window.visible = false end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If command window is active: call update_command if @command_window.active update_command return # If buy window is active: call update_buy elsif @buy_window.active update_buy return # If sell window is active: call update_sell elsif @sell_window.active update_sell return # If quantity input window is active: call update_number elsif @number_window.active update_number return end end #-------------------------------------------------------------------------- # * Frame Update (when command window is active) #-------------------------------------------------------------------------- def update_command # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to map screen $scene = Scene_Map.new return end # If C button was pressed if Input.trigger?(Input::C) # Branch by command window cursor position case @command_window.index when 0 # buy # Play decision SE $game_system.se_play($data_system.decision_se) # Change windows to buy mode @command_window.active = false @dummy_window.visible = false @buy_window.active = true @buy_window.visible = true @buy_window.refresh @status_window.visible = true when 1 # sell # Play decision SE $game_system.se_play($data_system.decision_se) # Change windows to sell mode @command_window.active = false @dummy_window.visible = false @sell_window.active = true @sell_window.visible = true @sell_window.refresh when 2 # quit # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to map screen $scene = Scene_Map.new end return end end #-------------------------------------------------------------------------- # * Frame Update (when buy window is active) #-------------------------------------------------------------------------- def update_buy # Set status window item @status_window.item = @buy_window.item # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Change windows to initial mode @command_window.active = true @dummy_window.visible = true @buy_window.active = false @buy_window.visible = false @status_window.visible = false @status_window.item = nil # Erase help text @help_window.set_text("") return end # If C button was pressed if Input.trigger?(Input::C) # Get item @item = @buy_window.item # If item is invalid, or price is higher than money possessed if @item == nil or @item.price > $game_party.gold # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Get items in possession count case @item when RPG::Item number = $game_party.item_number(@item.id) when RPG::Weapon number = $game_party.weapon_number(@item.id) when RPG::Armor number = $game_party.armor_number(@item.id) end # If 99 items are already in possession if number == 99 # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Calculate maximum amount possible to buy max = @item.price == 0 ? 99 : $game_party.gold / @item.price max = [max, 99 - number].min # Change windows to quantity input mode @buy_window.active = false @buy_window.visible = false @number_window.set(@item, max, @item.price) @number_window.active = true @number_window.visible = true end end #-------------------------------------------------------------------------- # * Frame Update (when sell window is active) #-------------------------------------------------------------------------- def update_sell # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Change windows to initial mode @command_window.active = true @dummy_window.visible = true @sell_window.active = false @sell_window.visible = false @status_window.item = nil # Erase help text @help_window.set_text("") return end # If C button was pressed if Input.trigger?(Input::C) # Get item @item = @sell_window.item # Set status window item @status_window.item = @item # If item is invalid, or item price is 0 (unable to sell) if @item == nil or @item.price == 0 # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Get items in possession count case @item when RPG::Item number = $game_party.item_number(@item.id) when RPG::Weapon number = $game_party.weapon_number(@item.id) when RPG::Armor number = $game_party.armor_number(@item.id) end # Maximum quanitity to sell = number of items in possession max = number # Change windows to quantity input mode @sell_window.active = false @sell_window.visible = false @number_window.set(@item, max, @item.price / 2) @number_window.active = true @number_window.visible = true @status_window.visible = true end end #-------------------------------------------------------------------------- # * Frame Update (when quantity input window is active) #-------------------------------------------------------------------------- def update_number # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Set quantity input window to inactive / invisible @number_window.active = false @number_window.visible = false # Branch by command window cursor position case @command_window.index when 0 # buy # Change windows to buy mode @buy_window.active = true @buy_window.visible = true when 1 # sell # Change windows to sell mode @sell_window.active = true @sell_window.visible = true @status_window.visible = false end return end # If C button was pressed if Input.trigger?(Input::C) # Play shop SE $game_system.se_play($data_system.shop_se) # Set quantity input window to inactive / invisible @number_window.active = false @number_window.visible = false # Branch by command window cursor position case @command_window.index when 0 # buy # Buy process $game_party.lose_gold(@number_window.number * @item.price) case @item when RPG::Item $game_party.gain_item(@item.id, @number_window.number) when RPG::Weapon $game_party.gain_weapon(@item.id, @number_window.number) when RPG::Armor $game_party.gain_armor(@item.id, @number_window.number) end # Refresh each window @gold_window.refresh @buy_window.refresh @status_window.refresh # Change windows to buy mode @buy_window.active = true @buy_window.visible = true when 1 # sell # Sell process $game_party.gain_gold(@number_window.number * (@item.price / 2)) case @item when RPG::Item $game_party.lose_item(@item.id, @number_window.number) when RPG::Weapon $game_party.lose_weapon(@item.id, @number_window.number) when RPG::Armor $game_party.lose_armor(@item.id, @number_window.number) end # Refresh each window @gold_window.refresh @sell_window.refresh @status_window.refresh # Change windows to sell mode @sell_window.active = true @sell_window.visible = true @status_window.visible = false end return end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_NAME') #============================================================================== # ** Scene_Name #------------------------------------------------------------------------------ # This class performs name input screen processing. #============================================================================== class Scene_Name < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Name, :main, :main_variable, :main_window) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Variable Initialization #-------------------------------------------------------------------------- def main_variable super # Get actor @actor = $game_actors[$game_temp.name_actor_id] end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make windows @edit_window = Window_NameEdit.new(@actor, $game_temp.name_max_char) @input_window = Window_NameInput.new end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If B button was pressed if Input.repeat?(Input::B) # If cursor position is at 0 if @edit_window.index == 0 return end # Play cancel SE $game_system.se_play($data_system.cancel_se) # Delete text @edit_window.back return end # If C button was pressed if Input.trigger?(Input::C) # If cursor position is at [OK] if @input_window.character == nil # If name is empty if @edit_window.name == "" # Return to default name @edit_window.restore_default # If name is empty if @edit_window.name == "" # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) return end # Change actor name @actor.name = @edit_window.name # Play decision SE $game_system.se_play($data_system.decision_se) # Switch to map screen $scene = Scene_Map.new return end # If cursor position is at maximum if @edit_window.index == $game_temp.name_max_char # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # If text character is empty if @input_window.character == "" # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Play decision SE $game_system.se_play($data_system.decision_se) # Add text character @edit_window.add(@input_window.character) return end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_GAMEOVER') #============================================================================== # ** Scene_Gameover #------------------------------------------------------------------------------ # This class performs game over screen processing. #============================================================================== class Scene_Gameover < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Gameover, :main, :main_sprite, :main_audio, :main_transition, :main_end) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Sprite Initialization #-------------------------------------------------------------------------- def main_sprite super # Make game over graphic @sprite = Sprite.new @sprite.bitmap = RPG::Cache.gameover($data_system.gameover_name) end #-------------------------------------------------------------------------- # * Main Processing : Audio Initialization #-------------------------------------------------------------------------- def main_audio super # Stop BGM and BGS $game_system.bgm_play(nil) $game_system.bgs_play(nil) # Play game over ME $game_system.me_play($data_system.gameover_me) end #-------------------------------------------------------------------------- # * Main Processing : Transition #-------------------------------------------------------------------------- def main_transition Graphics.transition(120) end #-------------------------------------------------------------------------- # * Main Processing : Ending #-------------------------------------------------------------------------- def main_end super # Execute transition Graphics.transition(40) # Prepare for transition Graphics.freeze # If battle test if $BTEST $scene = nil end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If C button was pressed if Input.trigger?(Input::C) # Switch to title screen $scene = Scene_Title.new end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part III Check #============================================================================== if SDK::Parts.include?(3) || SDK::Indidual_Parts.include?('PART 3#SCENE_DEBUG') #============================================================================== # ** Scene_Debug #------------------------------------------------------------------------------ # This class performs debug screen processing. #============================================================================== class Scene_Debug < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Debug, :main, :main_window) #-------------------------------------------------------------------------- # * Main Processing #-------------------------------------------------------------------------- def main super end #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make windows @left_window = Window_DebugLeft.new @right_window = Window_DebugRight.new @help_window = Window_Base.new(192, 352, 448, 128) @help_window.contents = Bitmap.new(406, 96) # Restore previously selected item @left_window.top_row = $game_temp.debug_top_row @left_window.index = $game_temp.debug_index @right_window.mode = @left_window.mode @right_window.top_id = @left_window.top_id end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # Update windows @right_window.mode = @left_window.mode @right_window.top_id = @left_window.top_id # Memorize selected item $game_temp.debug_top_row = @left_window.top_row $game_temp.debug_index = @left_window.index # If left window is active: call update_left if @left_window.active update_left return end # If right window is active: call update_right if @right_window.active update_right return end end #-------------------------------------------------------------------------- # * Frame Update (when left window is active) #-------------------------------------------------------------------------- def update_left # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to map screen $scene = Scene_Map.new return end # If C button was pressed if Input.trigger?(Input::C) # Play decision SE $game_system.se_play($data_system.decision_se) # Display help if @left_window.mode == 0 text1 = "C (Enter) : ON / OFF" @help_window.contents.draw_text(4, 0, 406, 32, text1) else text1 = "Left : -1 Right : +1" text2 = "L (Pageup) : -10" text3 = "R (Pagedown) : +10" @help_window.contents.draw_text(4, 0, 406, 32, text1) @help_window.contents.draw_text(4, 32, 406, 32, text2) @help_window.contents.draw_text(4, 64, 406, 32, text3) end # Activate right window @left_window.active = false @right_window.active = true @right_window.index = 0 return end end #-------------------------------------------------------------------------- # * Frame Update (when right window is active) #-------------------------------------------------------------------------- def update_right # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Activate left window @left_window.active = true @right_window.active = false @right_window.index = -1 # Erase help @help_window.contents.clear return end # Get selected switch / variable ID current_id = @right_window.top_id + @right_window.index # If switch if @right_window.mode == 0 # If C button was pressed if Input.trigger?(Input::C) # Play decision SE $game_system.se_play($data_system.decision_se) # Reverse ON / OFF $game_switches[current_id] = (not $game_switches[current_id]) @right_window.refresh return end end # If variable if @right_window.mode == 1 # If right button was pressed if Input.repeat?(Input::RIGHT) # Play cursor SE $game_system.se_play($data_system.cursor_se) # Increase variables by 1 $game_variables[current_id] += 1 # Maximum limit check if $game_variables[current_id] > 99999999 $game_variables[current_id] = 99999999 end @right_window.refresh return end # If left button was pressed if Input.repeat?(Input::LEFT) # Play cursor SE $game_system.se_play($data_system.cursor_se) # Decrease variables by 1 $game_variables[current_id] -= 1 # Minimum limit check if $game_variables[current_id] < -99999999 $game_variables[current_id] = -99999999 end @right_window.refresh return end # If R button was pressed if Input.repeat?(Input::R) # Play cursor SE $game_system.se_play($data_system.cursor_se) # Increase variables by 10 $game_variables[current_id] += 10 # Maximum limit check if $game_variables[current_id] > 99999999 $game_variables[current_id] = 99999999 end @right_window.refresh return end # If L button was pressed if Input.repeat?(Input::L) # Play cursor SE $game_system.se_play($data_system.cursor_se) # Decrease variables by 10 $game_variables[current_id] -= 10 # Minimum limit check if $game_variables[current_id] < -99999999 $game_variables[current_id] = -99999999 end @right_window.refresh return end end end end #============================================================================== # ** Ends Enable Part III Check #============================================================================== end #============================================================================== # ** Enable Part IV Check #============================================================================== if SDK::Parts.include?(4) || (SDK::Indidual_Parts.include?('PART 3#SCENE_TITLE') && SDK::Indidual_Parts.include?('PART 4#SCENE_TITLE')) #============================================================================== # ** Scene_Title #------------------------------------------------------------------------------ # This class performs title screen processing. #============================================================================== class Scene_Title < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Title, :update, :disabled_main_command?, :main_command_input) #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make command window s1 = SDK::Scene_Commands::Scene_Title::New_Game s2 = SDK::Scene_Commands::Scene_Title::Continue s3 = SDK::Scene_Commands::Scene_Title::Shutdown @command_window = Window_Command.new(192, [s1, s2, s3]) @command_window.back_opacity = 160 @command_window.x = 320 - @command_window.width / 2 @command_window.y = 288 # If continue is enabled, move cursor to "Continue" # If disabled, display "Continue" text in gray if @continue_enabled @command_window.index = 1 else @command_window.disable_item(1) end end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If C button was pressed if Input.trigger?(Input::C) # Return if Disabled Command if disabled_main_command? # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Command Input main_command_input return end end #-------------------------------------------------------------------------- # * Disabled Main Command? Test #-------------------------------------------------------------------------- def disabled_main_command? # If Continue is Selected if @command_window.command == SDK::Scene_Commands::Scene_Title::Continue return true unless @continue_enabled end return false end #-------------------------------------------------------------------------- # * Main Command Input #-------------------------------------------------------------------------- def main_command_input # Branch by command window cursor position case @command_window.command when SDK::Scene_Commands::Scene_Title::New_Game # New game command_new_game when SDK::Scene_Commands::Scene_Title::Continue # Continue command_continue when SDK::Scene_Commands::Scene_Title::Shutdown # Shutdown command_shutdown end end end #============================================================================== # ** Ends Enable Part IV Check #============================================================================== end #============================================================================== # ** Enable Part IV Check #============================================================================== if SDK::Parts.include?(4) || (SDK::Indidual_Parts.include?('PART 3#SCENE_MENU') && SDK::Indidual_Parts.include?('PART 4#SCENE_MENU')) #============================================================================== # ** Scene_Menu #------------------------------------------------------------------------------ # This class performs menu screen processing. #============================================================================== class Scene_Menu < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Menu, :update_command, :disabled_main_command?, :main_command_input) SDK.log_branch(:Scene_Menu, :update_status, :disabled_main_command?, :sub_command_input) SDK.log_branch(:Scene_Menu, :main_command_input, :command_item, :command_skill, :command_equip, :command_status, :command_save, :command_endgame) SDK.log_branch(:Scene_Menu, :sub_command_input, :command_skill, :command_equip, :command_status) #-------------------------------------------------------------------------- # * Main Processing : Window Initialization : Main Command #-------------------------------------------------------------------------- def main_command_window # Make command window s1 = SDK::Scene_Commands::Scene_Menu::Item s2 = SDK::Scene_Commands::Scene_Menu::Skill s3 = SDK::Scene_Commands::Scene_Menu::Equip s4 = SDK::Scene_Commands::Scene_Menu::Status s5 = SDK::Scene_Commands::Scene_Menu::Save s6 = SDK::Scene_Commands::Scene_Menu::End_Game @command_window = Window_Command.new(160, [s1, s2, s3, s4, s5, s6]) @command_window.index = @menu_index # If number of party members is 0 if $game_party.actors.size == 0 # Disable items, skills, equipment, and status @command_window.disable_item(0) @command_window.disable_item(1) @command_window.disable_item(2) @command_window.disable_item(3) end # If save is forbidden if $game_system.save_disabled # Disable save @command_window.disable_item(4) end end #-------------------------------------------------------------------------- # * Frame Update (when command window is active) #-------------------------------------------------------------------------- def update_command # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to map screen $scene = Scene_Map.new return end # If C button was pressed if Input.trigger?(Input::C) # Return if Disabled Command if disabled_main_command? # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Command Input main_command_input return end end #-------------------------------------------------------------------------- # * Frame Update (when status window is active) #-------------------------------------------------------------------------- def update_status # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Make command window active @command_window.active = true @status_window.active = false @status_window.index = -1 return end # If C button was pressed if Input.trigger?(Input::C) # Return if Disabled Command if disabled_main_command? # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Command Input sub_command_input return end end #-------------------------------------------------------------------------- # * Disabled Main Command? Test #-------------------------------------------------------------------------- def disabled_main_command? # Gets Current Command command = @command_window.command # Gets SDK Scene_Menu Commands c = SDK::Scene_Commands::Scene_Menu # If 0 Party Size if $game_party.actors.size == 0 # If Item, Skill, Equip or Status Selected if [c::Item, c::Skill, c::Equip, c::Status].include?(command) return true end end # If Save Disabled && Command is Save return true if $game_system.save_disabled && command == c::Save return false end #-------------------------------------------------------------------------- # * Main Command Input #-------------------------------------------------------------------------- def main_command_input # Play decision SE $game_system.se_play($data_system.decision_se) # Branch by command window cursor position case @command_window.command when SDK::Scene_Commands::Scene_Menu::Item # item command_item when SDK::Scene_Commands::Scene_Menu::Skill # skill command_skill when SDK::Scene_Commands::Scene_Menu::Equip # equipment command_equip when SDK::Scene_Commands::Scene_Menu::Status # status command_status when SDK::Scene_Commands::Scene_Menu::Save # save command_save when SDK::Scene_Commands::Scene_Menu::End_Game # end game command_endgame end end #-------------------------------------------------------------------------- # * Disabled Sub Command? Test #-------------------------------------------------------------------------- def disabled_sub_command? # If Skill Selected if @command_window.command == SDK::Scene_Commands::Scene_Menu::Skill # If this actor's action limit is 2 or more if $game_party.actors[@<EMAIL>].restriction >= 2 return true end end return false end #-------------------------------------------------------------------------- # * Sub Command Input #-------------------------------------------------------------------------- def sub_command_input # Play decision SE $game_system.se_play($data_system.decision_se) # Branch by command window cursor position case @command_window.command when SDK::Scene_Commands::Scene_Menu::Skill # skill command_skill when SDK::Scene_Commands::Scene_Menu::Equip # equipment command_equip when SDK::Scene_Commands::Scene_Menu::Status # status command_status end end #-------------------------------------------------------------------------- # * Command : Item #-------------------------------------------------------------------------- def command_item # Switch to item screen $scene = Scene_Item.new end #-------------------------------------------------------------------------- # * Command : Skill #-------------------------------------------------------------------------- def command_skill # If Main Command Active if @command_window.active # Activate Status Window active_status_window return end # Switch to skill screen $scene = Scene_Skill.new(@status_window.index) end #-------------------------------------------------------------------------- # * Command : Equip #-------------------------------------------------------------------------- def command_equip # If Main Command Active if @command_window.active # Activate Status Window active_status_window return end # Switch to equipment screen $scene = Scene_Equip.new(@status_window.index) end #-------------------------------------------------------------------------- # * Command : Status #-------------------------------------------------------------------------- def command_status # If Main Command Active if @command_window.active # Activate Status Window active_status_window return end # Switch to status screen $scene = Scene_Status.new(@status_window.index) end #-------------------------------------------------------------------------- # * Command : Save #-------------------------------------------------------------------------- def command_save # Switch to save screen $scene = Scene_Save.new end #-------------------------------------------------------------------------- # * Command : End Game #-------------------------------------------------------------------------- def command_endgame # Switch to end game screen $scene = Scene_End.new end #-------------------------------------------------------------------------- # * Activate Status Window #-------------------------------------------------------------------------- def active_status_window # Make status window active @command_window.active = false @status_window.active = true @status_window.index = 0 end end #============================================================================== # ** Ends Enable Part IV Check #============================================================================== end #============================================================================== # ** Enable Part IV Check #============================================================================== if SDK::Parts.include?(4) || (SDK::Indidual_Parts.include?('PART 3#SCENE_END') && SDK::Indidual_Parts.include?('PART 4#SCENE_END')) #============================================================================== # ** Scene_End #------------------------------------------------------------------------------ # This class performs game end screen processing. #============================================================================== class Scene_End < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_End, :disabled_main_command?, :main_command_input) #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make command window s1 = SDK::Scene_Commands::Scene_End::To_Title s2 = SDK::Scene_Commands::Scene_End::Shutdown s3 = SDK::Scene_Commands::Scene_End::Cancel @command_window = Window_Command.new(192, [s1, s2, s3]) @command_window.x = 320 - @command_window.width / 2 @command_window.y = 240 - @command_window.height / 2 end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to menu screen $scene = Scene_Menu.new(5) return end # If C button was pressed if Input.trigger?(Input::C) # Return if Disabled Command if disabled_main_command? # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Command Input main_command_input return end end #-------------------------------------------------------------------------- # * Disabled Main Command? Test #-------------------------------------------------------------------------- def disabled_main_command? return false end #-------------------------------------------------------------------------- # * Main Command Input #-------------------------------------------------------------------------- def main_command_input # Branch by command window cursor position case @command_window.command when SDK::Scene_Commands::Scene_End::To_Title # to title command_to_title when SDK::Scene_Commands::Scene_End::Shutdown # shutdown command_shutdown when SDK::Scene_Commands::Scene_End::Cancel # cancel command_cancel end end end #============================================================================== # ** Ends Enable Part IV Check #============================================================================== end #============================================================================== # ** Enable Part IV Check #============================================================================== if SDK::Parts.include?(4) || (SDK::Indidual_Parts.include?('PART 3#SCENE_BATTLE') && SDK::Indidual_Parts.include?('PART 4#SCENE_BATTLE')) #============================================================================== # ** Scene_Battle #------------------------------------------------------------------------------ # This class performs battle screen processing. #============================================================================== class Scene_Battle < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Battle, :update_phase2, :phase2_command_disabled?, :phase2_command_input) SDK.log_branch(:Scene_Battle, :update_phase3_basic_command, :phase3_basic_command_disabled?, :phase3_basic_command_input) SDK.log_branch(:Scene_Battle, :phase2_command_input, :phase2_command_fight, :phase2_command_escape) SDK.log_branch(:Scene_Battle, :phase3_basic_command_input, :phase3_command_attack, :phase3_command_skill, :phase3_command_guard, :phase3_command_item) #-------------------------------------------------------------------------- # * Main Processing : Window Initialization #-------------------------------------------------------------------------- def main_window super # Make actor command window s1 = SDK::Scene_Commands::Scene_Battle::Attack s2 = SDK::Scene_Commands::Scene_Battle::Skill s3 = SDK::Scene_Commands::Scene_Battle::Guard s4 = SDK::Scene_Commands::Scene_Battle::Item @actor_command_window = Window_Command.new(160, [s1, s2, s3, s4]) @actor_command_window.y = 160 @actor_command_window.back_opacity = 160 @actor_command_window.active = false @actor_command_window.visible = false # Make other windows @party_command_window = Window_PartyCommand.new @help_window = Window_Help.new @help_window.back_opacity = 160 @help_window.visible = false @status_window = Window_BattleStatus.new @message_window = Window_Message.new end #-------------------------------------------------------------------------- # * Frame Update (party command phase) #-------------------------------------------------------------------------- def update_phase2 # If C button was pressed if Input.trigger?(Input::C) # Return if Disabled Command if phase2_command_disabled? # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Command Input phase2_command_input return end end #-------------------------------------------------------------------------- # * Frame Update (actor command phase : basic command) #-------------------------------------------------------------------------- def update_phase3_basic_command # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Go to command input for previous actor phase3_prior_actor return end # If C button was pressed if Input.trigger?(Input::C) # Return if Disabled Command if phase3_basic_command_disabled? # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end # Command Input phase3_basic_command_input return end end #-------------------------------------------------------------------------- # * Phase 2 : Command Disabled? Test #-------------------------------------------------------------------------- def phase2_command_disabled? # If Escape Selected if @party_command_window.command == SDK::Scene_Commands::Scene_Battle::Escape # If it's not possible to escape return true unless $game_temp.battle_can_escape end return false end #-------------------------------------------------------------------------- # * Phase 2 : Command Input #-------------------------------------------------------------------------- def phase2_command_input # Play decision SE $game_system.se_play($data_system.decision_se) # Branch by party command window cursor position case @party_command_window.command when SDK::Scene_Commands::Scene_Battle::Fight # fight phase2_command_fight when SDK::Scene_Commands::Scene_Battle::Escape # escape phase2_command_escape end end #-------------------------------------------------------------------------- # * Phase 3 - Basic : Command Disabled? Test #-------------------------------------------------------------------------- def phase3_basic_command_disabled? return false end #-------------------------------------------------------------------------- # * Phase 3 Basic : Command Input #-------------------------------------------------------------------------- def phase3_basic_command_input # Play decision SE $game_system.se_play($data_system.decision_se) # Branch by actor command window cursor position case @actor_command_window.command when SDK::Scene_Commands::Scene_Battle::Attack # attack phase3_command_attack when SDK::Scene_Commands::Scene_Battle::Skill # skill phase3_command_skill when SDK::Scene_Commands::Scene_Battle::Guard # guard phase3_command_guard when SDK::Scene_Commands::Scene_Battle::Item # item phase3_command_item end end #-------------------------------------------------------------------------- # * Phase 2 : Command - Fight #-------------------------------------------------------------------------- def phase2_command_fight # Start actor command phase start_phase3 end #-------------------------------------------------------------------------- # * Phase 2 : Command - Escape #-------------------------------------------------------------------------- def phase2_command_escape # Escape processing update_phase2_escape end #-------------------------------------------------------------------------- # * Phase 3 - Basic : Command - Attack #-------------------------------------------------------------------------- def phase3_command_attack # Set action @active_battler.current_action.kind = 0 @active_battler.current_action.basic = 0 # Start enemy selection start_enemy_select end #-------------------------------------------------------------------------- # * Phase 3 - Basic : Command - Skill #-------------------------------------------------------------------------- def phase3_command_skill # Set action @active_battler.current_action.kind = 1 # Start skill selection start_skill_select end #-------------------------------------------------------------------------- # * Phase 3 - Basic : Command - Guard #-------------------------------------------------------------------------- def phase3_command_guard # Set action @active_battler.current_action.kind = 0 @active_battler.current_action.basic = 1 # Go to command input for next actor phase3_next_actor end #-------------------------------------------------------------------------- # * Phase 3 - Basic : Command - Item #-------------------------------------------------------------------------- def phase3_command_item # Set action @active_battler.current_action.kind = 2 # Start item selection start_item_select end end #============================================================================== # ** Ends Enable Part IV Check #============================================================================== end #============================================================================== # ** Enable Part IV Check #============================================================================== if SDK::Parts.include?(4) || (SDK::Indidual_Parts.include?('PART 3#SCENE_SHOP') && SDK::Indidual_Parts.include?('PART 4#SCENE_SHOP')) #============================================================================== # ** Scene_Shop #------------------------------------------------------------------------------ # This class performs shop screen processing. #============================================================================== class Scene_Shop < SDK::Scene_Base #-------------------------------------------------------------------------- SDK.log_branch(:Scene_Shop, :update_command, :disabled_main_command?, :main_command_input) SDK.log_branch(:Scene_Shop, :update_number, :number_cancel_command_input, :number_command_input) SDK.log_branch(:Scene_Shop, :main_command_input, :command_main_buy, :command_main_sell, :command_exit) SDK.log_branch(:Scene_Shop, :number_command_input, :command_number_buy, :command_number_sell) #-------------------------------------------------------------------------- # * Frame Update (when command window is active) #-------------------------------------------------------------------------- def update_command # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Switch to map screen $scene = Scene_Map.new return end # If C button was pressed if Input.trigger?(Input::C) # Return if Disabled Command if disabled_main_command? # Play buzzer SE $game_system.se_play($data_system.buzzer_se) return end main_command_input return end end #-------------------------------------------------------------------------- # * Frame Update (when quantity input window is active) #-------------------------------------------------------------------------- def update_number # If B button was pressed if Input.trigger?(Input::B) # Play cancel SE $game_system.se_play($data_system.cancel_se) # Set quantity input window to inactive / invisible @number_window.active = false @number_window.visible = false # Number Cancel Command number_cancel_command_input return end # If C button was pressed if Input.trigger?(Input::C) # Play shop SE $game_system.se_play($data_system.shop_se) # Set quantity input window to inactive / invisible @number_window.active = false @number_window.visible = false # Number Command Input number_command_input return end end #-------------------------------------------------------------------------- # * Disabled Main Command? Test #-------------------------------------------------------------------------- def disabled_main_command? return false end #-------------------------------------------------------------------------- # * Main Command Input #-------------------------------------------------------------------------- def main_command_input # Branch by command window cursor position case @command_window.command when SDK::Scene_Commands::Scene_Shop::Buy command_main_buy when SDK::Scene_Commands::Scene_Shop::Sell command_main_sell when SDK::Scene_Commands::Scene_Shop::Exit command_exit end end #-------------------------------------------------------------------------- # * Update Number Cancel Command #-------------------------------------------------------------------------- def number_cancel_command_input # Branch by command window cursor position case @command_window.command when SDK::Scene_Commands::Scene_Shop::Buy # buy # Change windows to buy mode @buy_window.active = true @buy_window.visible = true when SDK::Scene_Commands::Scene_Shop::Sell # sell # Change windows to sell mode @sell_window.active = true @sell_window.visible = true @status_window.visible = false end end #-------------------------------------------------------------------------- # * Update Number Command #-------------------------------------------------------------------------- def number_command_input # Branch by command window cursor position case @command_window.command when SDK::Scene_Commands::Scene_Shop::Buy # buy command_number_buy when SDK::Scene_Commands::Scene_Shop::Sell # sell command_number_sell end end #-------------------------------------------------------------------------- # * Command : Main Buy #-------------------------------------------------------------------------- def command_main_buy # Change windows to buy mode @command_window.active = false @dummy_window.visible = false @buy_window.active = true @buy_window.visible = true @buy_window.refresh @status_window.visible = true end #-------------------------------------------------------------------------- # * Command : Main Sell #-------------------------------------------------------------------------- def command_main_sell # Change windows to sell mode @command_window.active = false @dummy_window.visible = false @sell_window.active = true @sell_window.visible = true @sell_window.refresh end #-------------------------------------------------------------------------- # * Command : Exit #-------------------------------------------------------------------------- def command_exit # Switch to map screen $scene = Scene_Map.new end #-------------------------------------------------------------------------- # * Command : Number Buy #-------------------------------------------------------------------------- def command_number_buy # Buy process $game_party.lose_gold(@number_window.number * @item.price) case @item when RPG::Item $game_party.gain_item(@item.id, @number_window.number) when RPG::Weapon $game_party.gain_weapon(@item.id, @number_window.number) when RPG::Armor $game_party.gain_armor(@item.id, @number_window.number) end # Refresh each window @gold_window.refresh @buy_window.refresh @status_window.refresh # Change windows to buy mode @buy_window.active = true @buy_window.visible = true end #-------------------------------------------------------------------------- # * Command : Number Sell #-------------------------------------------------------------------------- def command_number_sell # Sell process $game_party.gain_gold(@number_window.number * (@item.price / 2)) case @item when RPG::Item $game_party.lose_item(@item.id, @number_window.number) when RPG::Weapon $game_party.lose_weapon(@item.id, @number_window.number) when RPG::Armor $game_party.lose_armor(@item.id, @number_window.number) end # Refresh each window @gold_window.refresh @sell_window.refresh @status_window.refresh # Change windows to sell mode @sell_window.active = true @sell_window.visible = true @status_window.visible = false end end #============================================================================== # ** Ends Enable Part IV Check #============================================================================== end<file_sep>/game/Scripts/Main.rb #============================================================================== # ■ Main #------------------------------------------------------------------------------ #  各クラスの定義が終わった後、ここから実際の処理が始まります。 #============================================================================== begin # This variable determines the default font type $defaultfonttype = "Tahoma" # This variable determines the default font size $defaultfontsize = 22 # トランジション準備 Graphics.freeze # シーンオブジェクト (タイトル画面) を作成 #NAGYKÉPBEN #$showm = Win32API.new 'user32', 'keybd_event', %w(l l l l), ' ' # Recognizes keyboard input #$showm.call(18,0,0,0) # ALT down #$showm.call(13,0,0,0) # ENTER down #$showm.call(13,0,2,0) # ENTER up #$showm.call(18,0,2,0) # ALT up #$scene = Scene_Title.new $data_actors = load_data("Data/Actors.rxdata") $data_classes = load_data("Data/Classes.rxdata") $data_skills = load_data("Data/Skills.rxdata") $data_items = load_data("Data/Items.rxdata") $data_weapons = load_data("Data/Weapons.rxdata") $data_armors = load_data("Data/Armors.rxdata") $data_enemies = load_data("Data/Enemies.rxdata") $data_troops = load_data("Data/Troops.rxdata") $data_states = load_data("Data/States.rxdata") $data_animations = load_data("Data/Animations.rxdata") $data_tilesets = load_data("Data/Tilesets.rxdata") $data_common_events = load_data("Data/CommonEvents.rxdata") $data_system = load_data("Data/System.rxdata") # Play decision SE #$game_system.se_play($data_system.decision_se) # Stop BGM Audio.bgm_stop # Reset frame count for measuring play time Graphics.frame_count = 0 # Make each type of game object $game_temp = Game_Temp.new $game_system = Game_System.new $game_switches = Game_Switches.new $game_variables = Game_Variables.new $game_self_switches = Game_SelfSwitches.new $game_screen = Game_Screen.new $game_actors = Game_Actors.new $game_party = Game_Party.new $game_troop = Game_Troop.new $game_map = Game_Map.new $game_player = Game_Player.new # Set up initial party $game_party.setup_starting_members # Set up initial map position $game_map.setup($data_system.start_map_id) # Move player to initial position $game_player.moveto($data_system.start_x, $data_system.start_y) # Refresh player $game_player.refresh # Run automatic change for BGM and BGS set with map $game_map.autoplay # Update map (run parallel process event) $game_map.update # Switch to map screen $scene = Scene_Map.new # $scene が有効な限り main メソッドを呼び出す while $scene != nil $scene.main end # フェードアウト Graphics.transition(20) rescue Errno::ENOENT # 例外 Errno::ENOENT を補足 # ファイルがオープンできなかった場合、メッセージを表示して終了する filename = $!.message.sub("No such file or directory - ", "") print("File #{filename} not found.") end <file_sep>/bootstrap.sh #!/usr/bin/env bash apt-get update apt-get install -y ruby apt-get install -y curl #apt-get install -y language-pack-hu apt-get install -y ruby-dev gem install rvpacker sudo locale-gen hu_HU.UTF-8 sudo dpkg-reconfigure locales <file_sep>/game/Game.ini [Game] Library=RGSS104E.dll Scripts=Data\Scripts.rxdata Title=Végső Küldetés - Első Epizód RTP1=Standard RTP2= RTP3= <file_sep>/README.md Build tool: https://github.com/akesterson/rvpacker
79025a07a21f6cb07527232adab3815453c2aff2
[ "Markdown", "INI", "Ruby", "Shell" ]
13
Ruby
ZeeCoder/vk-elso-epizod
30b232e4a92fc09b2f0816b190f969d83f152755
e9a690acc4c45348404f1d39ae70d06403178c06
refs/heads/master
<repo_name>guilehm/data-analysis<file_sep>/README.md # Data-Analysis **Built with Python, Matplotlib and Pygal** ## Generate a simple graph with file mpl_squares ![mpl_squares](https://user-images.githubusercontent.com/33688752/40588723-6d6180b6-61b8-11e8-962d-c13c10441556.png) ## Generate a simple graph using scatters and colormap ![scatter_squares](https://user-images.githubusercontent.com/33688752/40588731-9824ebc6-61b8-11e8-8948-28a354ec3b4d.png) ## Create a Random Walk and generate a graph. You can see where it begins and end. ![rw_visual](https://user-images.githubusercontent.com/33688752/40588745-de4ed788-61b8-11e8-9c29-7bf9f08ff2a1.png) ## Row the dice 1000 times and generate a graph showing the results. Interactive graph using Pygal ![d6 - 1000](https://user-images.githubusercontent.com/33688752/40588805-7e0cdd38-61b9-11e8-8ed9-80fdbeabb552.JPG) ## Contributing If you want to contribute, just open an issue and tell me where I can improve. Fork the repository and change whatever you'd like. Pull requests are always welcome. -------------------------------------------------------------------------------------------- <file_sep>/Generating Data/mpl_squares.py import matplotlib.pyplot as plt squares = [1, 4, 9, 16, 25] plt.plot(squares, linewidth=5) # show title and axis names plt.title('Square Numbers', fontsize=24) plt.xlabel('Value', fontsize=14) plt.ylabel('Square of Value', fontsize=14) # define the size of labels plt.tick_params(axis='both', labelsize=14) plt.savefig('graphs/mpl_squares.png') plt.show() <file_sep>/Downloading Data/python_repos.py import requests # Make an API call and store the response url = 'https://api.github.com/search/repositories?q=language:python&sort=stars' r = requests.get(url) print("Status code:", r.status_code) # Store API response in a variable. response_dict = r.json() print("Total repositories:", response_dict['total_count']) # Explore information about the repositories repo_dicts = response_dict['items'] print("Repositories returned:", len(repo_dicts)) print("\nSelected information about each repository:") for repo_dict in repo_dicts: print("\nSelected information about first repository:") print('Name:', repo_dict['name']) print('Owner:', repo_dict['owner']['login']) print('Stars:', repo_dict['stargazers_count']) print('Repository:', repo_dict['html_url']) print('Description:', repo_dict['description']) # Examine the first repository repo_dict = repo_dicts[0] print("\nSelected information about first repository:") print('Name:', repo_dict['name']) print('Owner:', repo_dict['owner']['login']) print('Stars:', repo_dict['stargazers_count']) print('Repository:', repo_dict['html_url']) print('Created:', repo_dict['created_at']) print('Updated:', repo_dict['updated_at']) print('Description:', repo_dict['description']) # Process results print(response_dict.keys()) <file_sep>/Generating Data/scatter_squares.py import matplotlib.pyplot as plt x_values = list(range(1, 1001)) y_values = [x**2 for x in x_values] plt.scatter(x_values, y_values, s=40, edgecolors='none', c=y_values, cmap=plt.cm.Blues) # define the graph title and rename axis plt.title('Square Numbers', fontsize=24) plt.xlabel('Value', fontsize=14) plt.ylabel('Square of Value', fontsize=14) # define the size of labels plt.tick_params(axis='both', which='major', labelsize=14) # define the interval for each axis plt.axis([0, 1100, 0, 1100000]) plt.savefig('graphs/scatter_squares.png') plt.show() <file_sep>/Generating Data/die.py from random import randint class Die(): """ a class that represents a single dice """ def __init__(self, num_sides=6): self.num_sides = num_sides def roll(self): """ show a random value of sides """ return randint(1, self.num_sides)
a05e22945bbe7c2bfee4ef64aa74f75957d4a064
[ "Markdown", "Python" ]
5
Markdown
guilehm/data-analysis
36d33a8468a8136403b9d29649d51a748b9a477e
4bd5a2810e49fa67d2864c4efd64c01ed67466a5
refs/heads/master
<file_sep> //BACK TO TOP $('.scroll-top').click(function(){ $('html, body').animate({ scrollTop: $( $(this).attr('href') ).offset().top }, 1000); return false; }); //EXPLORE $('.explore').click(function(){ $('html, body').animate({ scrollTop: $( $(this).attr('href') ).offset().top }, 1000); return false; }); //SIGN IN $('.login').click(function(){ $('html, body').animate({ scrollTop: $( $(this).attr('href') ).offset().top }, 1000); return false; });
407e271216378c341322fa2629e83e2f9795b996
[ "JavaScript" ]
1
JavaScript
avikothari/OpenPathCollective
b5c4d97ccb0cbf418533d5b97e146b8c1bcc0052
35e1e6ecb0869af0e2e866fcae5ba5b523ca96b2
refs/heads/main
<repo_name>teja-kishore/Rest_api_python_user<file_sep>/Rest_api_user.py from flask import Flask from flask_restful import reqparse, abort, Api, Resource app = Flask(__name__) api = Api(app) TODOS = { 'todo1': {'name': '<NAME>','age':21,'email':"<EMAIL>"}, 'todo2': {'name': 'kishore','age':21,'email':'<EMAIL>'}, 'todo3': {'name': 'V.Y.T.Kishore','age':21,'email':'<EMAIL>'}, } def abort_if_todo_doesnt_exist(todo_id): if todo_id not in TODOS: abort(404, message="Todo {} doesn't exist".format(todo_id)) parser = reqparse.RequestParser() parser.add_argument('name') parser.add_argument('age') parser.add_argument('email') class Todo(Resource): def get(self, todo_id): abort_if_todo_doesnt_exist(todo_id) return TODOS[todo_id] def delete(self, todo_id): abort_if_todo_doesnt_exist(todo_id) del TODOS[todo_id] return '', 204 def put(self, todo_id): args = parser.parse_args() name = {'name': args['name']} age = {'age': args['age']} email = {'email':args['email']} TODOS[todo_id] = name return name, 201 class TodoList(Resource): def get(self): return TODOS def post(self): args = parser.parse_args() todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1 todo_id = 'todo%i' % todo_id TODOS[todo_id] = {'task': args['task']} return TODOS[todo_id], 201 api.add_resource(TodoList, '/todos') api.add_resource(Todo, '/todos/<todo_id>') if __name__ == '__main__': app.run(debug=True)
e7ce4ebba9f3f801bfa4471de5d01cf0be728826
[ "Python" ]
1
Python
teja-kishore/Rest_api_python_user
dd2dc90eb644f4e40fcba13810e2568563a52704
697c35634e38a3bc5975186ed37b8250da9d87af
refs/heads/master
<file_sep>function count(str, char){ var i = 0; var index = []; while(i < str.length){ if(str.indexOf(char,i) >= 0){ index.push(i); i += str.indexOf(char,i) + char.length; }else{ i += char.length; } } console.log("Numero de veces que se repite '" + char + "' en '" + str + "'"); console.log(index.length); } //Datos Prueba -> devolver 2 count("hola mundo hola mundo ", "mundo"); //Datos Prueba -> devolver 1 count("mundo hola mund ", "mundo"); function filter(array){ var index = []; if(Array.isArray(array)){ array.forEach( function(valor, indice, array) { if(valor > 10){ index.push(valor); } }); console.log("Alementos mayores a 10"); index.forEach( function(valor) { console.log(valor); }); }else{ console.log("Debe suministrar un arreglo"); } } //Datos Prueba -> devolver 13,17 filter([13,5,17]); //Datos Prueba -> devolver 12 filter([0,10,12]); function hypotenuse(a, b){ console.log("Hipotenusa entre " + a + " y " + b); console.log(Math.hypot(a,b)); } //Datos Prueba -> devolver 5 hypotenuse(3, 4); //Datos Prueba -> devolver 16.401219466856727 hypotenuse(10, 13);
2fe09ee0ece6a1a6692f1cb6220d0c0a1ce1913e
[ "JavaScript" ]
1
JavaScript
MiguelAngelGutierrezMaya/MakeItRealTest
3d1391a86cb127dd6d604d7ac4567fc62c7e06a4
81e442275a72c1a444a0cb1ca169ea207b29b81e
refs/heads/master
<repo_name>Pepinonte/ProjetJsEstiamCG<file_sep>/src/db.js const { connect } = require("mongoose"); const bcrypt = require("bcryptjs"); const mongoose = require("mongoose"); mongoose .connect("mongodb://localhost:27017/projet_rere", { useNewUrlParser: true }) .then(() => console.log("Connected to Mongo…")) .catch((error) => console.log(error.message)); const userSchema = mongoose.Schema({ name: String, mail: String, password: String, // gamesId: Array, }); const gameSchema = mongoose.Schema({ name: String, adversaire: String, createur: String, score: String, etat: String, jetonsJ1: String, jetonsJ2: String, }); const User = mongoose.model("User", userSchema); module.exports.User = User; module.exports.createUser = async function createUser( user_name, user_mail, user_password ) { const user = new User({ name: user_name, mail: user_mail, password: <PASSWORD>, }); const result = await user.save(); console.log(result); }; const Game = mongoose.model("Game", gameSchema); module.exports.createGame = async function createGame( game_name, game_adversaire, createur, etat, jetonsJ1, jetonsJ2 ) { const game = new Game({ name: game_name, adversaire: game_adversaire, createur: createur, etat: etat, jetonsJ1: jetonsJ1, jetonsJ2: jetonsJ2, }); const result = await game.save(); console.log(result); }; module.exports.getCoursesAll = async function getCoursesAll() { const users = await User.find({}); return users; }; module.exports.getCoursesParNom = async function getCoursesParNom(nom) { const users = await User.find({ name: nom }); return users; }; module.exports.getCoursesParNomOne = async function getCoursesPgetCoursesParNomOnearNom(nom) { const users = await User.findOne({ name: nom }); return users; }; module.exports.getPassOne = async function getPassOne(pass) { const passs = await User.findOne({ password: pass }); return passs.password; }; module.exports.verifCredentials = async function verifCredentials(nom, pass) { const users = await User.find({ name: nom }); const text = "az"; const salt = await bcrypt.genSalt(10); const hash = users[0].password; const compare = await bcrypt.compare(text, hash); console.log(compare); for (let i = 0; i < users.length; i++) { const element = users[i]; if (await bcrypt.compare(pass, hash)) { console.log("mdp ok"); return element; } } }; module.exports.getAllGames = async function getAllGames() { const games = await Game.find({}).sort({ date: "desc" }); return games; }; module.exports.getAllGamesName = async function getAllGamesName(name) { const games = await Game.find({ createur: name }).sort({ date: "desc" }); return games; }; module.exports.getAllGamesNameAdver = async function getAllGamesNameAdver( name ) { const games = await Game.find({ adversaire: name }).sort({ date: "desc" }); return games; }; module.exports.getAllGamesOneId = async function getAllGamesOneId(id) { const game = await Game.findOne({ _id: id }); return game; }; module.exports.deleteAsId = async function getAllGames(id) { await Game.deleteOne({ _id: id }); }; module.exports.getAsId = async function getAsId(id) { await Game.findOne({ _id: id }); }; module.exports.updateJ1 = async function updateJ1(createur, jetons) { await Game.update({ createur: createur }, { $set: { jetonsJ1: jetons } }); }; // db.getCollection('games').update({createur: "az"}, {$set:{jetonsJ1: 33}}) <file_sep>/src/routes/index.js const express = require("express"); const router = express.Router(); const methodOverride = require("method-override"); const { connect } = require("mongoose"); const path = require("path"); const exphbs = require("express-handlebars"); const session = require("express-session"); const db = require("../db"); router.use(express.urlencoded()); router.use(methodOverride("_method")); router.use(express.static("./src/public")); router.use( session({ secret: "mysecretapp", resave: true, saveUninitialized: true, }) ); router.use(express.urlencoded()); router.use(methodOverride("_method")); router.use(express.static("../public")); router.get("/", (req, res) => res.render("index")); module.exports = router; <file_sep>/src/routes/users.js const express = require("express"); const router = express.Router(); const methodOverride = require("method-override"); const { connect } = require("mongoose"); const path = require("path"); const exphbs = require("express-handlebars"); const session = require("express-session"); const cookieParser = require("cookie-parser"); const bcrypt = require("bcryptjs"); const db = require("../db"); const oneDay = 1000 * 60 * 60 * 24; router.use(express.json()); router.use(express.urlencoded()); router.use(methodOverride("_method")); router.use(express.static("./src/public")); router.use( session({ secret: "mysecretapp", resave: false, saveUninitialized: false, cookie: { maxAge: oneDay }, test: "ddd", }) ); router.use(cookieParser()); router.get("/inscription", (req, res) => res.render("users/inscription")); router.get("/newGame", (req, res) => { const ssn = req.session; if (ssn.username) { res.render("game/createGame"); } else if (!ssn.username) { res.send("tu nest pas co"); } console.log(req.session.useraz); }); router.get("/connexion", (req, res) => res.render("users/connexion")); router.get("/user/connexion", (req, res) => res.render("users/connexion")); router.post("/inscription", async (req, res) => { console.log(req.body); const reponse = req.body; // db.createUser(req.body.user_name, req.body.user_mail, req.body.user_password); const pass = req.body.password; const text = req.body.user_password; console.log("ddddd", req.body.password); const hash = await bcrypt.hash(text, await bcrypt.genSalt(10)); db.createUser(req.body.user_name, req.body.user_mail, hash); const newUser = db.getCoursesParNomOne(reponse.user_name); const userId = db.getAsId(newUser._id); res.redirect("/"); }); router.post("/connexion", async (req, res) => { try { const user = await db.verifCredentials(req.body.name, req.body.password); if (user != {}) { console.log(user.name + " vien de ce conenter"); const ssn = req.session; ssn.activsUsers = []; const activsUsers = ssn.activsUsers; activsUsers.push(await db.getCoursesParNomOne(req.body.name)); console.log(activsUsers); ssn.username = req.body.name; ssn.password = <PASSWORD>; const useri = ssn.username; ssn.useri = ssn.username; const allGames = await db.getAllGames(); const allIdGames = allGames.map((e) => e.id); const allGamesNames = allGames.map((e) => { const ret = "Nom Partie:" + e.name + " " + "Adversaire:" + e.adversaire; return ret; }); const { _id } = allIdGames; console.log(allGames); res.render("users/compteUtilisateur", { us: useri, allGames, allGamesNames, allIdGames, }); } } catch (error) { console.log("identifiant ou mdp faux"); res.render("users/connexion"); } }); router.post("/parier/:id", async (req, res) => { const ssn = req.session; let jetons = 100; const someParie = req.body.montant; const partie = await db.getAllGamesOneId(req.params.id); const partieCreateur = partie.createur; const partieAdversaire = partie.adversaire; const usr = ssn.username; if (ssn.username == partieCreateur) { ssn.someParieJ1 = ssn.someParieJ1 - req.body.montant; jetons = ssn.someParieJ1; //maj misse j1 bdd db.updateJ1(ssn.username, jetons); ssn.nomJ1 = partieCreateur; } if (ssn.username == partieAdversaire) { ssn.someParieJ2 = req.body.montant; jetons = ssn.someParieJ2; //maj misse j2 bdd ssn.nomJ2 = partieAdversaire; } console.log("sommeParieJ1", ssn.someParieJ1); console.log("sommeParieJ2", ssn.someParieJ2); console.log("partieCreateur", partieCreateur); console.log("partieAdversaire", partieAdversaire); if (jetons <= 0) { res.redirect("game/defaite"); soldeTot = 100; } else if (jetons > 0 && ssn.username == partieCreateur) { res.render("game/modelGame", { jetons, id: req.params.id, usr: partieCreateur, }); } if (ssn.username == partieAdversaire) { res.render("game/modelGame", { jetons, id: req.params.id, usr: partieAdversaire, }); console.log("ok"); } }); router.get("/logout", async (req, res) => { const ssn = req.session; delete ssn.username; res.redirect("/"); }); router.get("/games", async (req, res) => { const ssn = req.session; if (ssn.username) { const allGames = await db.getAllGames(); // const allGames = await db.getAllGamesName(ssn.username); const allIdGames = allGames.map((e) => e.id); const allGamesNames = allGames.map((e) => { const ret = "Nom Partie:" + e.name + " " + "Adversaire:" + e.adversaire; return ret; }); const { _id } = allIdGames; console.log(allGames); res.render("game/allGames", { allGames, allGamesNames, allIdGames }); } else if (!ssn.username) { res.send("tu est pas co"); } }); router.get("/game/newGame/:id", async (req, res) => { const ssn = req.session; const usr = ssn.username; const tempCreator = await db.getCoursesParNom(usr); const tempCreatorIdd = tempCreator.map((e) => e.id); const tempCreatorId = tempCreatorIdd[0]; const thisGame = await db.getAllGamesOneId(req.params.id); const nameOfTrueCreator = thisGame.createur; const trueCreator = await db.getCoursesParNom(nameOfTrueCreator); const idOfTrueCreatorr = trueCreator.map((e) => e.id); const idOfTrueCreator = idOfTrueCreatorr[0]; console.log("tempCreatorId", tempCreatorId); console.log("idOfTrueCreator", idOfTrueCreator); if (tempCreatorId === idOfTrueCreator) { console.log(req.params.id); db.deleteAsId(req.params.id); const allGames = await db.getAllGames(); const allIdGames = allGames.map((e) => e.id); const allGamesNames = allGames.map((e) => { const ret = "Nom Partie:" + e.name + " " + "Adversaire:" + e.adversaire; return ret; }); const { _id } = allIdGames; console.log(allGames); res.render("game/allGames", { allGames, allGamesNames, allIdGames }); } else if (tempCreatorId != idOfTrueCreator) { res.send("vous n'etes pas le createur de cette partie"); } }); router.post("/newGame", (req, res) => { const { game_name, game_adversaire } = req.body; const errors = []; const ssn = req.session; const activsUsers = ssn.activsUsers; const usr = ssn.username; if (!game_name) { errors.push({ text: "veuillez ecrire le nom de la partie" }); } if (!game_adversaire) { errors.push({ text: "veuillez ecrire le nom de l'advesire" }); } if (errors.length > 0) { res.render("game/createGame", { errors, game_name, game_adversaire, }); } else { db.createGame(game_name, game_adversaire, usr, "en cour", 100, 100); res.redirect("/games"); } }); router.get("/game/rejoindrePartie/:id", async (req, res) => { const ssn = req.session; const usr = ssn.username; const game = await db.getAllGamesOneId(req.params.id); const jetonsJ1 = game.jetonsJ1; const jetonsJ2 = game.jetonsJ2; ssn.someParieJ1 = jetonsJ1; ssn.someParieJ2 = jetonsJ2; const createur = game.createur; const adversaire = game.adversaire; if (ssn.username == createur) { res.render("game/modelGame", { jetons: jetonsJ1, id: req.params.id, usr: usr, }); } else if (ssn.username == adversaire) { res.render("game/modelGame", { jetons: jetonsJ2, id: req.params.id, usr: usr, }); } }); module.exports = router; <file_sep>/README.md 1) Faire npm install 2) Lancer npm run dev ou nodemon ./src/index.js ou node ./src/index.js <file_sep>/src/index.js // Initialisations const express = require("express"); const app = express(); const methodOverride = require("method-override"); const path = require("path"); const exphbs = require("express-handlebars"); const session = require("express-session"); // Settings app.set("port", 3000); app.set("views", path.join(__dirname, "views")); app.engine( ".hbs", exphbs({ defaultLayout: "main", layoutsDir: path.join(app.get("views"), "layouts"), partialsDir: path.join(app.get("views"), "partials"), extname: ".hbs", }) ); app.set("view engine", ".hbs"); // Middlewares app.use(express.urlencoded()); app.use(methodOverride("_method")); app.use( session({ secret: "mysecretapp", resave: false, saveUninitialized: false, }) ); //Static Files app.use(express.static("./public")); // Variables Globales // Routes app.use(require("./routes/index")); app.use(require("./routes/users")); app.use(require("./routes/games")); // Serveur en ecoute app.listen(3000, () => { console.log("Serveur démaré"); });
4bc58beb350cc4cda79210681da0e5d27b6f6eb4
[ "JavaScript", "Markdown" ]
5
JavaScript
Pepinonte/ProjetJsEstiamCG
f32050051ca4425e577b862e995c7e1690f6449c
3cddde5648843de007e46682a4650f05a71b584e
refs/heads/master
<file_sep>// // MapViewController.swift // PlayingTemps // // Created by <NAME> on 24/05/16. // Copyright © 2016 MLBNP. All rights reserved. // import UIKit import MapKit class MapViewController: UIViewController,MKMapViewDelegate { var mapView: MKMapView! let locationManager = CLLocationManager() let locationRadius: CLLocationDistance = 1000 let places = ["Unnamed Rd, Sector 14 Hisar, Haryana 125011","Kehri Gaon, Prem Nagar, Dehradun, Uttarakhand"] override func loadView() { mapView = MKMapView() view = mapView let standardString = NSLocalizedString("Standard", comment: "Standard Map View") let hybridString = NSLocalizedString("Hybrid", comment: "Hybrid Map View") let satelliteString = NSLocalizedString("Satellite", comment: "Satellite Map View") let segementalControl = UISegmentedControl(items: [standardString,hybridString,satelliteString]) segementalControl.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5) segementalControl.selectedSegmentIndex = 0 segementalControl.translatesAutoresizingMaskIntoConstraints = false segementalControl.addTarget(self, action: #selector(MapViewController.changingTypeOfMaps(_:)), forControlEvents: .ValueChanged) let margins = view.layoutMarginsGuide let topConstraint = segementalControl.topAnchor.constraintEqualToAnchor(topLayoutGuide.bottomAnchor, constant: 8) let leadingConstraint = segementalControl.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor) let trailingConstraint = segementalControl.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor) view.addSubview(segementalControl) topConstraint.active = true leadingConstraint.active = true trailingConstraint.active = true let zoomButtonTitle = NSLocalizedString("UserLocation", comment: "Zoom Button Title") let zoomButton = UIButton() zoomButton.setTitle( (zoomButtonTitle), forState: .Normal) zoomButton.backgroundColor = UIColor.blackColor() zoomButton.setTitleColor(UIColor.whiteColor(), forState: .Normal) zoomButton.setTitleColor(UIColor.grayColor(), forState: UIControlState.Highlighted) zoomButton.translatesAutoresizingMaskIntoConstraints = false zoomButton.addTarget(self, action: #selector(MapViewController.zoomButtonTapped), forControlEvents: .TouchUpInside) let trailingConstraint1 = zoomButton.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor) let bottomConstraint = zoomButton.bottomAnchor.constraintEqualToAnchor(margins.bottomAnchor,constant: -69.0) self.view.addSubview(zoomButton) trailingConstraint1.active = true bottomConstraint.active = true } override func viewDidLoad() { super.viewDidLoad() mapView.delegate = self for place in places { getPlaceMarkForPlaces(place) } } override func viewDidAppear(animated: Bool) { permissionForUserLocation() } func changingTypeOfMaps(segControl: UISegmentedControl) { switch segControl.selectedSegmentIndex { case 0: mapView.mapType = .Standard case 1: mapView.mapType = .Hybrid case 2: mapView.mapType = .Satellite default: break } } func permissionForUserLocation() { if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { mapView.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } func zoomInOnUserLocation(location: CLLocation) { let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, locationRadius * 2, locationRadius * 2) mapView.setRegion(coordinateRegion, animated: true) } func zoomButtonTapped() { self.zoomInOnUserLocation(CLLocation(latitude: mapView.userLocation.coordinate.latitude, longitude: mapView.userLocation.coordinate.longitude)) } func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? { if annotation.isKindOfClass(PlaceAnnotations) { let annoView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "Default") annoView.pinTintColor = UIColor.blackColor() annoView.animatesDrop = true annoView.canShowCallout = true return annoView } else if annotation.isKindOfClass(MKAnnotation) { return nil } return nil } func createAnnotationForPlaces(location: CLLocation) { let annotations = PlaceAnnotations(coordinate: location.coordinate) annotations.title = "Home/P.G." annotations.subtitle = "Hometown: Hisar,P.G.: Dehradun" mapView.addAnnotation(annotations) } func getPlaceMarkForPlaces(places: String) { CLGeocoder().geocodeAddressString(places) { (placemarks: [CLPlacemark]?, error: NSError?) -> Void in if let marks = placemarks where marks.count > 0 { if let loc = marks[0].location { self.createAnnotationForPlaces(loc) } } } } } <file_sep>// // PlaceAnnotations.swift // FunWithMaps // // Created by <NAME> on 21/01/16. // Copyright © 2016 MLBNP. All rights reserved. // import Foundation import MapKit class PlaceAnnotations: NSObject, MKAnnotation { var coordinate = CLLocationCoordinate2D() var title: String? var subtitle: String? init(coordinate: CLLocationCoordinate2D) { self.coordinate = coordinate } } <file_sep># PlayingTemps Localization (Spanish) <file_sep>// // ConversionViewController.swift // PlayingTemps // // Created by <NAME> on 23/05/16. // Copyright © 2016 MLBNP. All rights reserved. // import UIKit class ConversionViewController: UIViewController,UITextFieldDelegate { @IBOutlet weak var fahrenheitLbl: UILabel! @IBOutlet weak var textField: UITextField! var celsiusValue: Double? { didSet { updateFahrenheitLabel() } } var fahrenheitValue: Double? { if let value = celsiusValue { return (value * (9/5)) + 32 } else { return nil } } override func viewDidLoad() { super.viewDidLoad() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let allowedCharacters = NSCharacterSet.init(charactersInString: "0123456789.,") let receivedCharacters = NSCharacterSet.init(charactersInString: string) let validString = allowedCharacters.isSupersetOfSet(receivedCharacters) let currentLocale = NSLocale.currentLocale() let decimalSeparator = currentLocale.objectForKey(NSLocaleDecimalSeparator) as! String let existingTextHasDecimalSeparator = textField.text?.rangeOfString(decimalSeparator) let replacementTextHasDecimalSeparator = string.rangeOfString(decimalSeparator) if existingTextHasDecimalSeparator != nil && replacementTextHasDecimalSeparator != nil { return false } else { return validString } } @IBAction func celsiusTextField(textField: UITextField) { if let text = textField.text , let value = numberFormatter.numberFromString(text) { celsiusValue = value.doubleValue if celsiusValue >= 35.0 { self.view.backgroundColor = UIColor(red: 237.0 / 255.0, green: 185.0 / 255.0, blue: 154.0 / 255.0, alpha: 1.0) } else { self.view.backgroundColor = UIColor(red: 235.0 / 255.0, green: 235.0 / 255.0, blue: 235.0 / 255.0, alpha: 1.0) } } else { celsiusValue = nil } } @IBAction func dismissKeyboard(sender: AnyObject) { textField.resignFirstResponder() } func updateFahrenheitLabel() { if let value = fahrenheitValue { fahrenheitLbl.text = numberFormatter.stringFromNumber(value) } else { fahrenheitLbl.text = "???" } } let numberFormatter: NSNumberFormatter = { let nf = NSNumberFormatter() nf.numberStyle = .DecimalStyle nf.maximumFractionDigits = 1 nf.minimumFractionDigits = 0 return nf }() // func randomColor() { // let colors = [UIColor.grayColor(),UIColor.blueColor(),UIColor.blackColor()] // let number = arc4random_uniform(UInt32(colors.count)) // self.view.backgroundColor = colors[Int(number)] // // } }
eae1ad3cd08fab68c6da908bea32334f16be6099
[ "Swift", "Markdown" ]
4
Swift
nishant3171/PlayingTemps
f5b05f13c97f3fcf4aff5a65e99881206fda0d94
0f25b02f280fc2fde361d92a2699c6e4817adcbd
refs/heads/master
<repo_name>daitran33/RinvexCountryPHPlibraryExamples<file_sep>/index.php <?php use Rinvex\countries\data; // Load Composer's autoloader require 'vendor/autoload.php'; // Get single country $egypt = country('eg'); // Get country name // Get country native name echo $egypt->getName() . "<br />"; echo $egypt->getNativeName() . "<br />"; // Get country official name // Get country ISO 3166-1 alpha2 code echo $egypt->getOfficialName() . "<br />"; echo $egypt->getIsoAlpha2() . "<br />"; // Get country emoji // Get country flag echo $egypt->getEmoji() . "<br />"; echo $egypt->getFlag() . "<br />"; // Get all countries // Get countries with where condition (continent: Oceania) $countries = countries(); $whereCountries = \Rinvex\Country\CountryLoader::where('geo.continent', ['OC' => 'Oceania']); ?><file_sep>/README.md # RinvexCountryPHPlibraryExamples PHP library of country code
ee80532bc5859bfa1e3f5c16a9c3cf80d4526e59
[ "Markdown", "PHP" ]
2
PHP
daitran33/RinvexCountryPHPlibraryExamples
c43d856b49fbd86ede828382b1c816f3e74be95d
595baed35f748f542b648e1c087fa74cce44ec21
refs/heads/master
<file_sep>#The data has been filtered before I loaded to R electric <- read.table("/Users/pedrovela/Downloads/household_power_consumption.txt", header = TRUE,sep = ";") #Create a new variable for the date time datetime <- strptime(paste(electric$Date, electric$Time, sep=" "), "%d/%m/%Y %H:%M:%S") #Transform all the variables to numeric globalAct <- as.numeric(electric$Global_active_power) globalReact <- as.numeric(electric$Global_reactive_power) volt <- as.numeric(electric$Voltage) subMet1 <- as.numeric(electric$Sub_metering_1) subMet2 <- as.numeric(electric$Sub_metering_2) subMet3 <- as.numeric(electric$Sub_metering_3) png("plot4.png", width=480, height=480) par(mfrow = c(2, 2)) plot(datetime, globalAct, type="l", xlab="", ylab="Global Active Power", cex=0.2) plot(datetime, volt, type="l", xlab="datetime", ylab="Voltage") plot(datetime, subMet1, type="l", ylab="Energy sub metering", xlab="") lines(datetime, subMet2, type="l", col="red") lines(datetime, subMet3, type="l", col="blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=, lwd=2.5, col=c("black", "red", "blue"), bty="o") plot(datetime, globalReact, type="l", xlab="datetime", ylab="Global_reactive_power") dev.off()<file_sep>#The data has been filtered before I loaded to R electric <- read.table("/Users/pedrovela/Downloads/household_power_consumption.txt",header = TRUE,sep = ";") #Create a new variable for the date time datetime <- strptime(paste(electric$Date, electric$Time, sep=" "), "%d/%m/%Y %H:%M:%S") #Transform the variable to numeric globalAct <- as.numeric(electric$Global_active_power) #Make the figure png("plot2.png", width=480, height=480) plot(datetime, globalAct, type="l", ylab="Global Active Power (kilowatts)") dev.off()<file_sep>#The data has been filtered before I loaded to R (with all clean) electric <- read.table("/Users/pedrovela/Downloads/household_power_consumption.txt",header = TRUE,sep = ";") #We make the histogram with all the values hist(electric$Global_active_power,col="red",xlab = "Global Active Power (kilowatts)", main = "Global Active Power") #We sabve it to a png file dev.copy(png,file = "/Users/pedrovela/Downloads/Others/Curso R/ExData_Plotting1/plot1.png") dev.off() <file_sep>#The data has been filtered before I loaded to R electric <- read.table("/Users/pedrovela/Downloads/household_power_consumption.txt",header = TRUE,sep = ";") #Create a new variable for the date time datetime <- strptime(paste(electric$Date, electric$Time, sep=" "), "%d/%m/%Y %H:%M:%S") #Transform all the three variables to numeric subMet1 <- as.numeric(electric$Sub_metering_1) subMet2 <- as.numeric(electric$Sub_metering_2) subMet3 <- as.numeric(electric$Sub_metering_3) #Make the figure png("plot3.png", width=480, height=480) plot(datetime, subMet1, type="l", ylab="Every Sub Metering") lines(datetime, subMet2, type="l", col="red") lines(datetime, subMet3, type="l", col="blue") legend("topright", c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), lty=1, lwd=2.5, col=c("black", "red", "blue")) dev.off()
df15819f06a22dd9eb2306290b7a19909899f7d5
[ "R" ]
4
R
pedro-vr/ExData_Plotting1
4e0d59f644ba8158f45c184e6c0fb9248721c4c7
a41b3c9b9070409adef2be57485bbfdb0da9e6a8
refs/heads/master
<file_sep>from dataclasses import dataclass from dataclasses_json import dataclass_json @dataclass_json @dataclass class CellPos: """座標""" x: int # X座標 y: int # Y座標 <file_sep>import json from functools import lru_cache from typing import List, Tuple, Set from model.CellPos import CellPos from model.CellType import CellType from model.HintType import HintType from model.SunGlass import SunGlass from service.utility import show_board_data class AlgorithmException(Exception): def __init__(self, message: str): self.message = message def __str__(self): return self.message def create_board_from_problem(problem: SunGlass) -> List[CellType]: """問題データから初期盤面を生成する Parameters ---------- problem 問題データ Returns ------- 初期盤面 """ def get_pos(pos: CellPos) -> int: return pos.x + pos.y * problem.width # ブリッジの線から、初期のレンズ位置・空白位置を決定させる board = [CellType.UNKNOWN] * (problem.width * problem.height) for bridge in problem.bridge: board[get_pos(bridge.cell[0])] = CellType.LENS board[get_pos(bridge.cell[-1])] = CellType.LENS for i in range(1, len(bridge.cell) - 1): board[get_pos(bridge.cell[i])] = CellType.BLANK return board def find_lens(board: List[CellType], width: int, pos: int, taboo_list: List[int] = None) -> List[int]: """その座標を含む、レンズ群を取得する Parameters ---------- board 盤面 width 盤面の横幅 pos 座標 taboo_list タブーリスト。ここに含まれているものは再度カウントしない Returns ------- レンズ群における座標の一覧 """ # タブーリストを初期化 if taboo_list is None: taboo_list = [pos] # 処理開始。現在位置から、上下左右に進んだ位置のマスについて、再帰を行い、結果をmergeする output = [pos] for offset in (-width, 1, width, -1): # 盤面からはみ出さないように判定 if offset == -width and pos < width: continue if offset == 1 and (pos + 1) % width == 0: continue if offset == width and pos + width >= len(board): continue if offset == -1 and pos % width == 0: continue next_pos = pos + offset # 次の位置にレンズが無かった場合は無視する if board[next_pos] != CellType.LENS: continue # 次の位置がタブーリストに含まれている場合は無視する if next_pos in taboo_list: continue # 再帰した結果を追加 output += find_lens(board, width, next_pos, taboo_list + [next_pos]) return output @lru_cache(maxsize=None) def get_next_pos(pos: int, width: int, board_size: int) -> List[int]: """次の座標の一覧を割り出す Parameters ---------- pos 座標 width 横幅 board_size 全マス数 Returns ------- 次に進めるマスの一覧 """ output: List[int] = [] for offset in (-width, 1, width, -1): # 盤面からはみ出さないように判定 if offset == -width and pos < width: continue if offset == 1 and (pos + 1) % width == 0: continue if offset == width and pos + width >= board_size: continue if offset == -1 and pos % width == 0: continue output.append(pos + offset) return output def find_lens_max(board: List[CellType], width: int, board_size: int, lens_set: Set[int], other_lens_set: Set[int]) -> List[int]: # 前処理により、レンズにならない箇所をあらかじめ空白マスにしておいた盤面を用意する board2 = board.copy() for i in range(board_size): if board[i] == CellType.LENS and i in other_lens_set: around_pos_list = get_next_pos(i, width, board_size) for pos2 in around_pos_list: if board[pos2] == CellType.UNKNOWN: board2[pos2] = CellType.BLANK """ print([pos_int_to_tuple(t, width) for t in lens_set]) mark = '?o.' for i in range(board_size): print(f'{mark[int(board2[i])]} ', end='') if i % width == width - 1: print('') print('') """ # レンズになりうる座標一覧をsetで管理し、幅優先探索で順繰りに更新していく output = set() | lens_set frontier = lens_set.copy() # print(f'lens={lens_set}') while True: # print(f' frontier={frontier} output={output}') new_frontier = set() for pos2 in frontier: new_frontier = new_frontier | set(get_next_pos(pos2, width, board_size)) new_frontier = new_frontier - frontier new_frontier = {x for x in new_frontier if board2[x] != CellType.BLANK} # print(f' new_frontier={new_frontier}') if len(new_frontier) == 0: break output = output | new_frontier frontier = frontier | new_frontier """ print('frontier') for i in range(board_size): if i in frontier: print(f'o ', end='') else: print(f'. ', end='') if i % width == width - 1: print('') print('') """ return list(frontier) def calc_lens_map(board: List[CellType], problem: SunGlass) -> List[int]: """タイリングを実施 Parameters ---------- board 盤面 problem 問題 Returns ------- 各タイル(=ブリッジから生えた各レンズ)がある位置は、そのタイルの番号が振られるようにする。 タイルの番号は1スタートの自然数であり、ブリッジから生えてない孤立レンズも認識されない """ lens_map = [0 for _ in board] lens_index = 1 for bridge in problem.bridge: # ブリッジに対して左翼のレンズの処理 for pos in find_lens(board, problem.width, bridge.cell[0].x + bridge.cell[0].y * problem.width): lens_map[pos] = lens_index lens_index += 1 # ブリッジに対して右翼のレンズの処理 for pos in find_lens(board, problem.width, bridge.cell[-1].x + bridge.cell[-1].y * problem.width): lens_map[pos] = lens_index lens_index += 1 return lens_map def pattern_do_not_join_lenses(board: List[CellType], problem: SunGlass) -> List[CellType]: """レンズ同士が接触しないように空白を設置 Parameters ---------- board 盤面 problem 問題 Returns ------- 処理後の盤面 """ # タイリングを実施。lens_mapは、各タイル(=各レンズ)がある位置は、そのタイルの番号(lens_index)が振られるようにする lens_map = calc_lens_map(board, problem) # 空白を設置 output = [x for x in board] for y in range(problem.height): for x in range(problem.width): # 指定したマスにおける上下左右のマスの合法な座標一覧 pos_list = [(x + i) + (y + j) * problem.width for i, j in ((0, -1), (1, 0), (0, 1), (-1, 0)) if 0 <= (x + i) < problem.width and 0 <= (y + j) < problem.height] # 上下左右のマスのレンズ番号を収集し、setで重複を排除する around_lens_set = {lens_map[k] for k in pos_list if lens_map[k] > 0} # この判定式が真=上下左右の周囲に2種類以上のタイルがある if len(around_lens_set) > 1: output[x + y * problem.width] = CellType.BLANK return output def is_equal(board1: List[CellType], board2: List[CellType]) -> bool: """2つの盤面が等しければTrue Parameters ---------- board1 盤面1 board2 盤面2 Returns ------- 等しければTrue """ for a, b in zip(board1, board2): if a != b: return False return True def find_around_blank_cells(board: List[CellType], width: int, height: int, lens: List[Tuple[int, int]])\ -> List[Tuple[int, int]]: """レンズの周囲における、「レンズの周囲の空白マス」の一覧を取得する Parameters ---------- board 盤面 width 横幅 height 縦幅 lens レンズ Returns ------- 「レンズの周囲の空白マス」の一覧 """ # noinspection PyTypeChecker output: Set[Tuple[int, int]] = set() for x, y in lens: for pos in get_next_pos(x + y * width, width, width * height): if board[pos] != CellType.BLANK: continue output.add((pos % width, pos // width)) return list(output) def find_around_unknown_cells(board: List[CellType], width: int, height: int, lens: List[Tuple[int, int]])\ -> List[Tuple[int, int]]: """レンズの周囲における、「レンズの周囲の不明マス」の一覧を取得する Parameters ---------- board 盤面 width 横幅 height 縦幅 lens レンズ Returns ------- 「レンズの周囲の不明マス」の一覧 """ # noinspection PyTypeChecker output: Set[Tuple[int, int]] = set() for x, y in lens: for pos in get_next_pos(x + y * width, width, width * height): if board[pos] != CellType.UNKNOWN: continue output.add((pos % width, pos // width)) return list(output) def pos_int_to_tuple(pos: int, width: int) -> Tuple[int, int]: """座標変換 Parameters ---------- pos 座標 width 横幅 Returns ------- (x, y) """ return pos % width, pos // width def calc_reverse_lens(lens: List[Tuple[int, int]], from_point: Tuple[int, int], to_point: Tuple[int, int])\ -> List[Tuple[int, int]]: """fromPointとtoPointを基準にした、lensの線対称図形を取得する Parameters ---------- lens レンズ from_point レンズを反転する際の起点 to_point レンズを反転する際の終点 Returns ------- 反転後のレンズ """ # 計算が面倒なので、from_pointとto_pointに対しての関係性から場合分けする offset = (to_point[0] - from_point[0], to_point[1] - from_point[1]) output: List[Tuple[int, int]] = [] if offset[0] == 0: # ブリッジが縦方向な場合 for cell in lens: output.append((to_point[0] + cell[0] - from_point[0], to_point[1] - cell[1] + from_point[1])) elif offset[1] == 0: # ブリッジが横方向な場合 for cell in lens: output.append((to_point[0] - cell[0] + from_point[0], to_point[1] + cell[1] - from_point[1])) else: if offset[0] * offset[1] < 0: # ブリッジが/方向な場合 for cell in lens: cell_to_from = (from_point[0] - cell[0], from_point[1] - cell[1]) to_to_cell2 = (-cell_to_from[1], -cell_to_from[0]) output.append((to_point[0] + to_to_cell2[0], to_point[1] + to_to_cell2[1])) else: # ブリッジが\方向な場合 for cell in lens: cell_to_from = (from_point[0] - cell[0], from_point[1] - cell[1]) to_to_cell2 = (cell_to_from[1], cell_to_from[0]) output.append((to_point[0] + to_to_cell2[0], to_point[1] + to_to_cell2[1])) return output def pattern_sync_bridge_lenses(board: List[CellType], problem: SunGlass) -> List[CellType]: """各ブリッジの双翼に生えているレンズの、塗りつぶし状態・上下左右の空白状態を同期 同期不可能な場合は例外を投げる Parameters ---------- board 盤面 problem 問題 Returns ------- 処理後の盤面 """ output = [x for x in board] for bridge in problem.bridge: # 左翼・右翼のレンズを取得する left_point = (bridge.cell[0].x, bridge.cell[0].y) right_point = (bridge.cell[-1].x, bridge.cell[-1].y) left_lens = [pos_int_to_tuple(x, problem.width) for x in find_lens(board, problem.width, left_point[0] + left_point[1] * problem.width)] right_lens = [pos_int_to_tuple(x, problem.width) for x in find_lens(board, problem.width, right_point[0] + right_point[1] * problem.width)] # 左翼・右翼のレンズについて、「レンズの周囲の空白マス」の一覧を取得する left_blank_cells = find_around_blank_cells(board, problem.width, problem.height, left_lens) right_blank_cells = find_around_blank_cells(board, problem.width, problem.height, right_lens) # レンズについて、塗りつぶし状態を同期する left_lens_reverse = calc_reverse_lens(left_lens, left_point, right_point) right_lens_reverse = calc_reverse_lens(right_lens, right_point, left_point) appending_lens_cells = (set(right_lens_reverse) - set(left_lens)) | (set(left_lens_reverse) - set(right_lens)) for pos in appending_lens_cells: if 0 <= pos[0] < problem.width and 0 <= pos[1] < problem.height: if output[pos[0] + pos[1] * problem.width] == CellType.BLANK: raise AlgorithmException('塗りつぶし状態を同期できません') else: output[pos[0] + pos[1] * problem.width] = CellType.LENS # レンズの周囲の空白マスの状態を同期する left_blank_cells_reverse = calc_reverse_lens(left_blank_cells, left_point, right_point) right_blank_cells_reverse = calc_reverse_lens(right_blank_cells, right_point, left_point) appending_blank_cells = (set(right_blank_cells_reverse) - set(left_blank_cells)) |\ (set(left_blank_cells_reverse) - set(right_blank_cells)) for pos in appending_blank_cells: if 0 <= pos[0] < problem.width and 0 <= pos[1] < problem.height: output[pos[0] + pos[1] * problem.width] = CellType.BLANK return output def pattern_hint(board: List[CellType], problem: SunGlass) -> List[CellType]: """ヒント数字に従い、ちょうど塗りつぶせるなら塗り潰す Parameters ---------- board 盤面 problem 問題 Returns ------- 処理後の盤面 """ output = [x for x in board] for hint in problem.hint: # レンズマスの数、空白マスの数、不明マスの位置を調べる lens_cells_count = 0 blank_cells_count = 0 unknown_cells: List[int] = [] if hint.type == HintType.ROW: # 行ヒント pos = hint.index * problem.width for _ in range(0, problem.width): if board[pos] == CellType.LENS: lens_cells_count += 1 elif board[pos] == CellType.BLANK: blank_cells_count += 1 else: unknown_cells.append(pos) pos += 1 else: # 列ヒント pos = hint.index for _ in range(0, problem.height): if board[pos] == CellType.LENS: lens_cells_count += 1 elif board[pos] == CellType.BLANK: blank_cells_count += 1 else: unknown_cells.append(pos) pos += problem.width # 不明マスの数+レンズマスの数=ヒントの数字ならば、 # 不明マスが全てレンズマスであるはず if len(unknown_cells) + lens_cells_count == hint.value: for pos in unknown_cells: output[pos] = CellType.LENS # レンズマスの数=ヒントの数字ならば、 # 不明マスが全て空白マスであるはず if lens_cells_count == hint.value: for pos in unknown_cells: output[pos] = CellType.BLANK return output def calc_symmetry_axis(left_point: Tuple[int, int], right_point: Tuple[int, int], width: int, height: int)\ -> List[Tuple[int, int]]: """線対称の軸となるマスの座標を割り出す Parameters ---------- left_point 左側の座標 right_point 右側の座標 width 横幅 height 縦幅 Returns ------- 線対称の軸となるマスの座標の一覧 """ # 左側・右側の相対関係によって場合分け。 # ただし間隔が偶数な場合と奇数な場合とで処理が異なる output: List[Tuple[int, int]] = [] if left_point[0] == right_point[0]: # 縦方向 if (left_point[1] - right_point[1]) % 2 == 1: y1 = (abs(left_point[1] - right_point[1]) - 1) // 2 + min(left_point[1], right_point[1]) y2 = y1 + 1 for k in range(width): output.append((k, y1)) output.append((k, y2)) else: y = (abs(left_point[1] - right_point[1])) // 2 + min(left_point[1], right_point[1]) for k in range(width): output.append((k, y)) return output if left_point[1] == right_point[1]: # 横方向 if (left_point[0] - right_point[0]) % 2 == 1: x1 = (abs(left_point[0] - right_point[0]) - 1) // 2 + min(left_point[0], right_point[0]) x2 = x1 + 1 for k in range(width): output.append((x1, k)) output.append((x2, k)) else: x = (abs(left_point[0] - right_point[0])) // 2 + min(left_point[0], right_point[0]) for k in range(width): output.append((x, k)) return output # 斜め方向 if (left_point[0] - right_point[0]) * (left_point[1] - right_point[1]) > 0: slant_type = 'b' # バックスラッシュ形 else: slant_type = 's' # スラッシュ形 if (left_point[0] - right_point[0]) % 2 == 1: # 間隔が偶数なケース if slant_type == 'b': x = (abs(left_point[0] - right_point[0]) - 1) // 2 + min(left_point[0], right_point[0]) y = (abs(left_point[1] - right_point[1]) - 1) // 2 + min(left_point[1], right_point[1]) + 1 center_point = (x, y) else: x = (abs(left_point[0] - right_point[0]) - 1) // 2 + min(left_point[0], right_point[0]) y = (abs(left_point[1] - right_point[1]) - 1) // 2 + min(left_point[1], right_point[1]) center_point = (x, y) else: # 間隔が奇数なケース x = (abs(left_point[0] - right_point[0]) - 1) // 2 + min(left_point[0], right_point[0]) + 1 y = (abs(left_point[1] - right_point[1]) - 1) // 2 + min(left_point[1], right_point[1]) + 1 center_point = (x, y) if slant_type == 'b': output.append(center_point) temp = (center_point[0], center_point[1]) while True: temp = (temp[0] + 1, temp[1] - 1) if 0 <= temp[0] < width and 0 <= temp[1] < height: output.append((temp[0], temp[1])) else: break temp = (center_point[0], center_point[1]) while True: temp = (temp[0] - 1, temp[1] + 1) if 0 <= temp[0] < width and 0 <= temp[1] < height: output.append((temp[0], temp[1])) else: break else: output.append(center_point) temp = (center_point[0], center_point[1]) while True: temp = (temp[0] + 1, temp[1] + 1) if 0 <= temp[0] < width and 0 <= temp[1] < height: output.append((temp[0], temp[1])) else: break temp = (center_point[0], center_point[1]) while True: temp = (temp[0] - 1, temp[1] - 1) if 0 <= temp[0] < width and 0 <= temp[1] < height: output.append((temp[0], temp[1])) else: break return output def pattern_can_not_reach(board: List[CellType], problem: SunGlass) -> List[CellType]: """どのブリッジからも塗りつぶせない位置のマスは空白マス Parameters ---------- board 盤面 problem 問題 Returns ------- 処理後の盤面 """ def print_lens(lens: List[Tuple[int, int]], star_mark=(-1, -1)): mark = '□■' arr = [0] * (problem.width * problem.height) for pos in lens: if 0 <= pos[0] < problem.width and 0 <= pos[1] < problem.height: arr[pos[0] + pos[1] * problem.width] = 1 for i in range(problem.width * problem.height): if i == star_mark[0] + star_mark[1] * problem.width: print(f'☆ ', end='') else: print(f'{mark[arr[i]]} ', end='') if i % problem.width == problem.width - 1: print('') # それぞれのブリッジにおける、現在のレンズ情報を取得する lens_list: List[Tuple[Tuple[int, int], Tuple[int, int], Set[int], Set[int]]] = [] all_lenses = set() for bridge in problem.bridge: # 左翼・右翼のレンズを取得する left_point = (bridge.cell[0].x, bridge.cell[0].y) right_point = (bridge.cell[-1].x, bridge.cell[-1].y) left_lens = set(find_lens(board, problem.width, left_point[0] + left_point[1] * problem.width)) right_lens = set(find_lens(board, problem.width, right_point[0] + right_point[1] * problem.width)) lens_list.append((left_point, right_point, left_lens, right_lens)) all_lenses = all_lenses | left_lens | right_lens # それぞれのブリッジにおいて、伸ばせる最大のレンズの範囲を算出する all_max_lenses = set() output = [x for x in board] for left_point, right_point, left_lens, right_lens in lens_list: # 右翼・左翼について、「レンズを最大限伸ばした際の範囲」を取得する left_lens_max = [pos_int_to_tuple(x, problem.width) for x in find_lens_max(board, problem.width, len(board), left_lens, all_lenses - left_lens)] right_lens_max = [pos_int_to_tuple(x, problem.width) for x in find_lens_max(board, problem.width, len(board), right_lens, all_lenses - right_lens)] """ print(f'[[left_lens_max(left_point={left_point})]]') print_lens(list(left_lens_max), left_point) print(f'[[right_lens_max(right_point={right_point})]]') print_lens(list(right_lens_max), right_point) """ # レンズは左右対称になるので、左右対称にできない部分は「レンズを最大限伸ばした際の範囲」から削れる # また、ブリッジにおける線対称の軸にあたる部分は、当然塗ることができない left_lens_max_reverse = calc_reverse_lens(left_lens_max, left_point, right_point) right_lens_max_reverse = calc_reverse_lens(right_lens_max, right_point, left_point) symmetry_axis = calc_symmetry_axis(left_point, right_point, problem.width, problem.height) left_lens_max = (set(left_lens_max) & set(right_lens_max_reverse)) - set(symmetry_axis) right_lens_max = (set(right_lens_max) & set(left_lens_max_reverse)) - set(symmetry_axis) """ if (1, 3) not in left_lens_max: print('[board]') show_board_data(board, problem) print(f'symmetry_axis') print_lens(symmetry_axis) print(f'left_lens_max_reverse') print_lens(left_lens_max_reverse, right_point) print(f'right_lens_max_reverse') print_lens(right_lens_max_reverse, left_point) print(f'[left_lens_max(left_point={left_point})]') print_lens(list(left_lens_max), left_point) print(f'[right_lens_max(right_point={right_point})]') print_lens(list(right_lens_max), right_point) """ # 「レンズを最大限伸ばした際の範囲」をmergeする all_max_lenses = all_max_lenses | left_lens_max | right_lens_max # どのレンズからも被覆できない部分は、当然空白マスになる for y in range(problem.height): for x in range(problem.width): if board[x + y * problem.width] == CellType.UNKNOWN and (x, y) not in all_max_lenses: output[x + y * problem.width] = CellType.BLANK return output def solve_by_tactics(board: List[CellType], problem: SunGlass, show_log_flg=True) -> List[CellType]: """各種定石を使用して盤面を埋める Parameters ---------- board 盤面 problem 問題 show_log_flg 途中経過を表示するならTrue Returns ------- 埋めた後の盤面 """ output_board = board.copy() while True: # レンズ同士が接触しないように空白を設置 next_board = pattern_do_not_join_lenses(output_board, problem) if not is_equal(output_board, next_board): output_board = next_board if show_log_flg: print('・レンズ同士が接触しないように空白を設置') show_board_data(output_board, problem) continue # 各ブリッジの双翼に生えているレンズの、塗りつぶし状態・上下左右の空白状態を同期 next_board = pattern_sync_bridge_lenses(output_board, problem) if not is_equal(output_board, next_board): output_board = next_board if show_log_flg: print('・塗りつぶし状態・上下左右の空白状態を同期') show_board_data(output_board, problem) continue # ヒント数字に従い、ちょうど塗りつぶせるなら塗り潰す next_board = pattern_hint(output_board, problem) if not is_equal(output_board, next_board): output_board = next_board if show_log_flg: print('・ヒント数字に従い塗りつぶせるなら塗り潰す') show_board_data(output_board, problem) continue # どのブリッジからも塗りつぶせない位置のマスは空白マス next_board = pattern_can_not_reach(output_board, problem) if not is_equal(output_board, next_board): output_board = next_board if show_log_flg: print('・どこからも塗り潰せなければそこは空白マス') show_board_data(output_board, problem) continue break return output_board def is_invalid_board(board: List[CellType], problem: SunGlass) -> bool: """矛盾が存在する盤面の場合はTrue Parameters ---------- board 盤面 problem 問題 Returns ------- 矛盾があればTrue """ # ヒント数字の条件をどうしても満たせない場合はアウト for hint in problem.hint: if hint.type == HintType.ROW: # 行についての確認 lens_count = 0 unknown_count = 0 for k in range(problem.width): cell = board[k + hint.index * problem.width] if cell == CellType.LENS: lens_count += 1 elif cell == CellType.UNKNOWN: unknown_count += 1 if lens_count + unknown_count < hint.value: return True if lens_count > hint.value: return True else: # 列についての確認 lens_count = 0 unknown_count = 0 for k in range(problem.height): cell = board[hint.index + k * problem.width] if cell == CellType.LENS: lens_count += 1 elif cell == CellType.UNKNOWN: unknown_count += 1 if lens_count + unknown_count < hint.value: return True if lens_count > hint.value: return True # どのブリッジにも属せない、孤立したレンズが存在する場合はアウト bridge_cells: Set[int] = set() for bridge in problem.bridge: bridge_cells.add(bridge.cell[0].x + bridge.cell[0].y * problem.width) bridge_cells.add(bridge.cell[-1].x + bridge.cell[-1].y * problem.width) for i in range(len(board)): # どのブリッジにも属していない、孤立レンズを検索する if board[i] != CellType.LENS: continue lens = set(find_lens(board, problem.width, i)) if len(lens & bridge_cells) != 0: continue # 孤立レンズについて、その周囲に不明マスが存在するかを確認する lens_xy = [pos_int_to_tuple(k, problem.width) for k in lens] if len(find_around_unknown_cells(board, problem.width, problem.height, lens_xy)) == 0: # 孤立レンズの周囲に不明マスがない=ブリッジと接続できないのでアウト return True return False def is_invalid_board_wrapper(input_board: List[CellType], problem: SunGlass) -> bool: try: temp_board = solve_by_tactics(input_board, problem, False) return is_invalid_board(temp_board, problem) except AlgorithmException: return True def is_invalid_board_wrapper_2(input_board: List[CellType], problem: SunGlass) -> bool: try: temp_board = solve_by_1st_absurdum(input_board, problem, False) return is_invalid_board(temp_board, problem) except AlgorithmException: return True def solve_by_1st_absurdum(board: List[CellType], problem: SunGlass, show_log_flg=True) -> List[CellType]: """1段階背理法 Parameters ---------- board 盤面 problem 問題 show_log_flg 途中経過を表示するならTrue Returns ------- 埋めたあとの盤面 """ output_board = board.copy() while True: # 定石で盤面を埋める board2 = solve_by_tactics(output_board, problem, show_log_flg) if not is_equal(output_board, board2): output_board = board2 continue if show_log_flg: print('(背理法開始)') flg = False for i in range(len(output_board)): if output_board[i] != CellType.UNKNOWN: continue # print(f'(座標{pos_int_to_tuple(i, problem.width)}に背理法)') # レンズと仮定して、矛盾すればそれはレンズではない output_board[i] = CellType.LENS if is_invalid_board_wrapper(output_board, problem): output_board[i] = CellType.BLANK if show_log_flg: print(f'・背理法 座標{pos_int_to_tuple(i, problem.width)}を空白に') show_board_data(output_board, problem) flg = True break # 空白と仮定して、矛盾すればそれは空白ではない output_board[i] = CellType.BLANK if is_invalid_board_wrapper(output_board, problem): output_board[i] = CellType.LENS if show_log_flg: print(f'・背理法 座標{pos_int_to_tuple(i, problem.width)}をレンズに') show_board_data(output_board, problem) flg = True break output_board[i] = CellType.UNKNOWN if not flg: if show_log_flg: print('(背理法終了)') break return output_board def solve_by_2nd_absurdum(board: List[CellType], problem: SunGlass, show_log_flg=True) -> List[CellType]: """2段階背理法 Parameters ---------- board 盤面 problem 問題 show_log_flg 途中経過を表示するならTrue Returns ------- 埋めたあとの盤面 """ output_board = board.copy() while True: # 1段階背理法で盤面を埋める board2 = solve_by_1st_absurdum(output_board, problem, show_log_flg) if not is_equal(output_board, board2): output_board = board2 continue if show_log_flg: print('(2段階背理法開始)') flg = False for i in range(len(output_board)): if output_board[i] != CellType.UNKNOWN: continue # print(f'(座標{pos_int_to_tuple(i, problem.width)}に背理法)') # レンズと仮定して、矛盾すればそれはレンズではない output_board[i] = CellType.LENS if is_invalid_board_wrapper_2(output_board, problem): output_board[i] = CellType.BLANK if show_log_flg: print(f'・背理法 座標{pos_int_to_tuple(i, problem.width)}を空白に') show_board_data(output_board, problem) flg = True break # 空白と仮定して、矛盾すればそれは空白ではない output_board[i] = CellType.BLANK if is_invalid_board_wrapper_2(output_board, problem): output_board[i] = CellType.LENS if show_log_flg: print(f'・背理法 座標{pos_int_to_tuple(i, problem.width)}をレンズに') show_board_data(output_board, problem) flg = True break output_board[i] = CellType.UNKNOWN if not flg: if show_log_flg: print('(2段階背理法終了)') break return output_board def solve(problem: SunGlass) -> None: """問題データから計算を行い、解答を標準出力で返す Parameters ---------- problem 問題データ Returns ------- 標準出力で処理結果を返す """ # 初期盤面データを作成する board = create_board_from_problem(problem) print('【問題】') show_board_data(board, problem) # 解析 board2 = solve_by_2nd_absurdum(board, problem) print('【結果】') show_board_data(board2, problem) def solve_from_path(path: str) -> None: """問題ファイルをファイルパスから読み込んで処理する Parameters ---------- path ファイルパス Returns ------- 標準出力で処理結果を返す """ with open(path) as f: problem = SunGlass.from_dict(json.load(f)) solve(problem) <file_sep>from enum import Enum class HintType(Enum): """「サングラス」のヒントの種類""" ROW = 'row' COLUMN = 'col' <file_sep>from dataclasses import dataclass from typing import List from dataclasses_json import dataclass_json from model.CellPos import CellPos @dataclass_json @dataclass class Bridge: """「サングラス」のブリッジデータ""" cell: List[CellPos] <file_sep>from enum import IntEnum class CellType(IntEnum): """マスの種類""" UNKNOWN = 0 # 不明 LENS = 1 # レンズ BLANK = 2 # 空白 CELL_TYPE_LIST = { CellType.UNKNOWN: 'UNKNOWN', CellType.LENS: 'LENS', CellType.BLANK: 'BLANK' } <file_sep>from typing import List from model.CellPos import CellPos from model.CellType import CellType from model.HintType import HintType from model.SunGlass import SunGlass def int_to_str(number: int) -> str: """表示向けのリッチな数字→文字列変換 Parameters ---------- number 数字 Returns ------- 数字文字列 """ if number < 10: return '0123456789'[number] else: return str(number) def show_board_data(board: List[CellType], problem: SunGlass) -> None: """盤面を可視化する Parameters ---------- board 盤面データ problem 問題データ Returns ------- 結果を標準出力で返す """ def get_pos(pos: CellPos) -> int: return pos.x + pos.y * problem.width # 初期表示内容を決定する board_str = ['□' for x in board] # ブリッジの線を描画する for bridge in problem.bridge: for i in range(len(bridge.cell)): bridge_cell = bridge.cell[i] if i < len(bridge.cell) - 1: mx, my = bridge.cell[i + 1].x - bridge_cell.x, bridge.cell[i + 1].y - bridge_cell.y else: mx, my = bridge_cell.x - bridge.cell[i - 1].x, bridge_cell.y - bridge.cell[i - 1].y if mx == 0: board_str[get_pos(bridge_cell)] = '│' elif my == 0: board_str[get_pos(bridge_cell)] = '─' elif mx * my > 0: board_str[get_pos(bridge_cell)] = '\' else: board_str[get_pos(bridge_cell)] = '/' # レンズと空白を描画する mark = '□■・' for i in range(len(board)): if board[i] == CellType.UNKNOWN: continue if board[i] == CellType.BLANK and board_str[i] != '□': continue board_str[i] = mark[board[i]] # 最終的に出力する print('  ', end='') for x in range(problem.width): # ヒント数字 temp = [t for t in problem.hint if t.index == x and t.type == HintType.COLUMN] if len(temp) > 0: print(int_to_str(temp[0].value), end='') else: print(' ', end='') print('') print(' ┏' + '━' * problem.width + '┓') for y in range(problem.height): # ヒント数字 temp = [t for t in problem.hint if t.index == y and t.type == HintType.ROW] if len(temp) > 0: print(int_to_str(temp[0].value), end='') else: print(' ', end='') # 盤面 begin_index = y * problem.width end_index = begin_index + problem.width sliced_board = board_str[begin_index:end_index] print('┃' + ''.join(sliced_board) + '┃') print(' ┗' + '━' * problem.width + '┛') <file_sep>from dataclasses import dataclass from dataclasses_json import dataclass_json from model.HintType import HintType @dataclass_json @dataclass class Hint: """「サングラス」のヒントデータ""" type: HintType # "row"か"col"。rowだと行における個数を規定し、colだと列における個数を規定する index: int # インデックス。例えば"row"でindex=2なら、3行目であることを示す value: int # 個数値。この数字の分だけ、レンズのために塗りつぶすことができる <file_sep>from service.solver import solve_from_path if __name__ == '__main__': solve_from_path('sample_problem.json') <file_sep># パズル「サングラス」用のソルバー なんとなく作りました。実用性は保証しません。 ## 問題ファイルのフォーマット 基本的にはsample_problem.jsonを読めばOKです。 今のところ、問題エディタの作成予定はないです。 - width……問題の横幅 - height……問題の縦幅 - bridge……中に次の形式で、各ブリッジのデータを書き込みます - 各マスの座標……`{x: X座標, y: Y座標}`といった形式 - XもYも0スタート、左上を(0, 0)とした形式。Xが横、Yが縦 - ブリッジの各マスの座標……支点~終点まで全て記入する ``` { "cell": [ブリッジの各マスの座標] } ``` - hint……中に次の形式で、各ヒント数字のデータを書き込みます - ヒント数字……外枠に示された、行もしくは列で塗りつぶす個数 - type……`"row"`なら行、`"col"`なら列についての指定 - index……n行目、もしくはn列目についての指定(0スタートなことに注意) - value……塗りつぶす個数 ``` "hint": [ { "type": "row", "index": 0, "value": 3 }, ... ] ```<file_sep>from dataclasses import dataclass from typing import List from dataclasses_json import dataclass_json from model.Bridge import Bridge from model.Hint import Hint @dataclass_json @dataclass class SunGlass: """「サングラス」の問題データ""" width: int # 横幅 height: int # 縦幅 bridge: List[Bridge] # ブリッジの情報 hint: List[Hint] # ヒントの情報
d670433c9963809a880ac3bc52da57f714c94a17
[ "Markdown", "Python" ]
10
Python
YSRKEN/puzzle_sunglass_solver
05162ba48a2949a893f62ee896f1922c1c3f597d
50888bec5da6dc57cdbfdad80efdd4def8c4153b
refs/heads/master
<file_sep>input.onButtonPressed(Button.A, function () { RingbitCar.freestyle(10, 10) basic.pause(500) RingbitCar.brake() }) radio.onReceivedValue(function (name, value) { if (name == "x") { xValue = value } else { if (name == "y") { yValue = value } } }) let rightwheel = 0 let leftwheel = 0 let yValue = 0 let xValue = 0 let strip = neopixel.create(DigitalPin.P0, 24, NeoPixelMode.RGB) strip.showRainbow(1, 360) basic.pause(500) strip.clear() strip.setBrightness(0) strip.showRainbow(1, 360) RingbitCar.init_wheel(AnalogPin.P1, AnalogPin.P2) basic.showIcon(IconNames.Triangle) radio.setGroup(90) xValue = 0 yValue = 0 basic.forever(function () { leftwheel = yValue + xValue rightwheel = yValue - xValue RingbitCar.freestyle(leftwheel, rightwheel) })
0f9bdd412d3c50b59c7efc83cffff8c1ed7a314b
[ "TypeScript" ]
1
TypeScript
jegyed50/ring_bit_car_01_car
18831c12b9dc5c51e89cdeb00c5b77f9feca038d
b0c5cdaf973c4e6dedd5b7ea757edb5e5350f996
refs/heads/master
<file_sep>var fs = require('fs'); var path = require('path'); var express = require('express'); var app = express(); var http = require('http').Server(app); var io = require('socket.io')(http); var port = process.env.PORT || 80; var ping = require('net-ping-hr'); var session = ping.createSession(); app.get('/', function(req, res) { res.sendFile(__dirname + '/index.html'); }); app.get('/logs', function(req, res) { res.sendFile(__dirname + '/logs/index.html'); }); app.use('/iconic', express.static(__dirname + '/logs/iconic/svg')); io.on('connection', function(socket){ console.log('Client connected from ' + socket.handshake.address); socket.on('request-ping', function(params) { setTimeout(() => { /* ping.promise.probe(params.host, { timeout: 10 }).then(function (res) { if (res.alive) { socket.emit('receive-ping', params.host + ' > Response made - ' + res.time + 'ms'); } else { socket.emit('receive-ping', 'Host unreachable.'); } }); */ session.pingHost (params.host, function (error, target, sent, received) { var rawMs = received - sent; var formattedMs = parseFloat(Math.round(rawMs * 100) / 100).toFixed(2); if (error) { console.log (target + " > " + error.toString ()); socket.emit('receive-ping', params.host + " > " + error.toString()); } else { console.log (target + " > Response Received - " + formattedMs + "ms."); socket.emit('receive-ping', params.host + " > Response Received - " + formattedMs + "ms."); } }); }, 750); }); socket.on('ping-complete', function(logs) { fs.writeFile('../APPLICATION_DATA/logs/log_' + new Date().getTime() + '.txt', logs, function(err, data) { if (err) console.log(err); io.emit('update-broadcast'); }); }); socket.on('request-listings', function() { fs.readdir('../APPLICATION_DATA/logs', function(err, items) { if (err) socket.emit('listings-error', err); socket.emit('listings-received', items); }); }); socket.on('request-read-log', function(filename) { fs.readFile('../APPLICATION_DATA/logs/' + filename, 'utf-8', function(err, contents) { if (err) socket.emit('listings-error', err); socket.emit('request-read-log-complete', contents); }); }); socket.on('request-delete-log', function(filename) { fs.unlink('../APPLICATION_DATA/logs/' + filename, function(err) { if (err) socket.emit('listings-error', err); io.emit('update-broadcast'); }); }); }); http.listen(port, function(){ console.log('listening on *:' + port); }); <file_sep># ICMP Ping Test Utility ### Purpose This web application was created because I am unable to ping ICMPv6 endpoints for work. This is a common problem at my workplace and I needed to test for network connectivity often. Being on an IPv4-only network, it was hard to test in realtime for connectivity. Therefore, this project is to set out and solve that problem. ### Tools Used This web application utilizes Express for serving the front-end, Node.JS and Socket.IO on the backend for realtime communication. The server itself is hosted by DigitalOcean. ### Live Tool This tool is available for access at http://ping.nsreverse.net/
006f64f38cd17dbb679d03851d322e8450c958c5
[ "JavaScript", "Markdown" ]
2
JavaScript
NSReverse/node-ping
a67863e9f14084dbafefd8619aa1e488680ada9f
5f7da1064bc3b044cc99146f3568664e660eced9
refs/heads/master
<file_sep># iotop-log-parser This is a parser for the iotop monitoring logs. <file_sep>#!/usr/bin/python ############################################################################### # This is an extractor for the log file "iotop.log" output by the "iotop" command: # "sudo iotop -botqqqk -d 10 > ./iotop.log" # # Input parameters: # argv[1]: the log input file name. [input] # argv[2]: the extracted output file name. [output] # argv[3]: the pid of the process to be monitored. [input] # # Each line in the output file is in form of # "Timestamp Reads(K/S) Writes(K/S) SWAPIN IO" # They are separated with a tab. # # @author <NAME> <<EMAIL>> # @date April 12th, 2017 ############################################################################### import numpy as np import sys def parse (inputLogFilename, outputFilename, pID): # lines = np.genfromtxt(inputLogFilename, dtype=None, unpack=True, delimiter=' ') outFile = open(outputFilename, "w") linestring = open(inputLogFilename, 'r').read() lines = linestring.split('\n') for line in lines: line1 = line.split() if len(line1)>10 and line1[1]==pID: outFile.write("%s\t%s\t%s\t%s\t%s\n" \ % (line1[0], line1[4], line1[6], line1[8], line1[10])) return ### # main function ### if (len(sys.argv)<2): print 'please type the input parameters correctly.' else: intputLogFilename = sys.argv[1] outputFilename = sys.argv[2] pID = sys.argv[3] parse(intputLogFilename, outputFilename, pID) <file_sep># iotop-log-parser This is an extractor for the log file "iotop.log" output by the "iotop" command: "sudo iotop -botqqqk -d 10 > ./iotop.log" The input and output parameters are described at beginning of the python file. =========== Exc command example to run this extractor: "python ./iotop-log-file-extractor.py ./iotop.log ./extracted-iotop.log 10171" Explain: ./iotop.log is the output log file of the "iotop" command above; ./extracted-iotop.log is the output file of this extractor; 10171 is the pid a process "build-tetrartree". =========== Related links about iotop: http://www.binarytides.com/monitor-disk-io-iotop-cron/ https://linux.die.net/man/1/iotop http://man.linuxde.net/iotop
0db3b0f58acedd04de6bc9a4a96b4c40babe700e
[ "Markdown", "Python", "Text" ]
3
Markdown
lvying603/iotop-log-parser
19ed289f051ceec1a31a1f2d6cef8a68c0db7e11
84513d6a59d5da87745fcf2b08455ad17740c95e
refs/heads/master
<repo_name>wrightling/.vim<file_sep>/bin/vimbundles.sh #!/usr/bin/env bash # script stolen directly from https://github.com/hashrocket/dotmatrix/blob/master/bin/vimbundles.sh # modified to work with my .vim directory structure mkdir -p ~/.vim/bundle cd ~/.vim/bundle get_bundle() { ( if [ -d "$2" ]; then echo "Updating $1's $2" cd "$2" git pull --rebase else git clone "https://github.com/$1/$2.git" fi ) } get_bundle adamlowe vim-slurper get_bundle AndrewRadev splitjoin.vim get_bundle duff vim-bufonly get_bundle godlygeek tabular get_bundle kchmck vim-coffee-script get_bundle leshill vim-json get_bundle mileszs ack.vim get_bundle pangloss vim-javascript get_bundle therubymug vim-pyte get_bundle tpope vim-abolish get_bundle tpope vim-bundler get_bundle tpope vim-commentary get_bundle tpope vim-cucumber get_bundle tpope vim-endwise get_bundle tpope vim-eunuch get_bundle tpope vim-fugitive get_bundle tpope vim-git get_bundle tpope vim-haml get_bundle tpope vim-markdown get_bundle tpope vim-pathogen get_bundle tpope vim-rake get_bundle tpope vim-ragtag get_bundle tpope vim-rails get_bundle tpope vim-repeat get_bundle tpope vim-rsi get_bundle tpope vim-sensible get_bundle tpope vim-sleuth get_bundle tpope vim-speeddating get_bundle tpope vim-surround get_bundle tpope vim-unimpaired get_bundle tpope vim-vividchalk get_bundle vim-ruby vim-ruby get_bundle wgibbs vim-irblack get_bundle vim-scripts bufkill.vim get_bundle vim-scripts bufexplorer.zip get_bundle jgdavey vim-blockle get_bundle jgdavey vim-railscasts get_bundle jgdavey tslime.vim get_bundle jgdavey vim-turbux get_bundle jgdavey vim-weefactor get_bundle gregsexton gitv get_bundle myusuf3 numbers.vim get_bundle godlygeek csapprox # get_bundle msanders snipmate.vim # get_bundle rcyrus snipmate-snippets-rubymotion get_bundle ervandew supertab get_bundle elixir-lang vim-elixir get_bundle groenewege vim-less get_bundle rondale-sc vim-spacejam get_bundle heartsentwined vim-emblem get_bundle rking ag.vim get_bundle vim-scripts VimClojure get_bundle mattn gist-vim get_bundle mattn webapi-vim get_bundle lepture vim-velocity get_bundle rizzatti dash.vim get_bundle mustache vim-mustache-handlebars get_bundle python-mode python-mode get_bundle zxqfl tabnine-vim get_bundle ctrlpvim ctrlp.vim vim -c 'call pathogen#helptags()|q'
c6ec27ae8b95560b87775b6a9b7b8bc7d5cc4718
[ "Shell" ]
1
Shell
wrightling/.vim
0ac81fbcdea4cc863aa6063846b68be2b335ed53
872d0e206609292216a036650c58526b97117700
refs/heads/master
<file_sep>import requests import json import time import tkinter as tk from bs4 import BeautifulSoup from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") pconedetect() def pconedetect(): url = "https://www.pcone.com.tw/api/merchant/products?items_per_page=1000&merchant_id=2945567&page=1" my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) data = json.loads(gotrq.text) #轉成python dict pconeIDAry = [] for i in range(len(data["products"])): pconeIDAry.append(data["products"][i]["display_id"]) GOTData = getsheet('商品ID!O:O') #獲取試算表所有資料 GOTDataAry = [] errorID = [] for i in range(len(GOTData)): try: GOTDataAry.append(GOTData[i][0]) #提取試算表資料 except: GOTDataAry.append("") #空直例外 for i in range(len(pconeIDAry)):#找網頁上架ID在不在 試算表中 try: GOTDataAry.index(pconeIDAry[i]) except: #找不到的話 errorID.append(pconeIDAry[i]) for i in range(len(errorID)): output.insert(1.0,str(errorID[i])+"\n") output.insert(1.0,"偵測完成\n") gui=tk.Tk() gui.title("查松果新上架") output= tk.Text() output.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop()<file_sep>import requests import json import time from bs4 import BeautifulSoup from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet import xlrd url = 'https://8268.com.tw/product_preorder.php' post_data = {'account': '<EMAIL>','passwd': '<PASSWORD>','verification': '','exec': 'member_account_login'} WebSession = requests.Session() WebSession.post('https://8268.com.tw/all_ajax_login.php',data = post_data) #傳送登入資料 WebSession.get('https://8268.com.tw/') #確定登入 result = WebSession.get(url) #第一次訪問 soup = BeautifulSoup(result.text, "html.parser") gotdata = [] for i in soup.select(".product-sort")[1].select('li'): #分類迴圈 link = 'https://8268.com.tw'+i.select('a')[0]['href'][1:] #商品分類網址 if link == 'https://8268.com.tw/product_preorder.php' or link == 'https://8268.com.tw/product_uptodate.php': print('忽略預購、新上架') continue sort_result = WebSession.get(link) #訪問分頁網址 sort_soup = BeautifulSoup(sort_result.text, "html.parser") #第二次訪問 try: page_num = int(sort_soup.select('.pager li a')[-1]['href'].split("=")[-1]) #取得分類頁數 except:#如果錯誤,代表只有一頁 page_num = 1 for page in range(1,page_num+1): #頁數迴圈 if page_num == 1: #如果分類只有一頁 page 前'?','&'會錯誤 page_result = WebSession.get(link+'?page_num='+str(page)) #瀏覽內頁 else: page_result = WebSession.get(link+'&page_num='+str(page)) #瀏覽內頁 page_soup = BeautifulSoup(page_result.text, "html.parser")#第三次訪問 for ii in page_soup.select('.product_name'): #搜尋產品名迴圈 try: #有些沒ID 則'無權限' gotdata.append([ii['href'].split("=")[1].split("&")[0],ii.text,ii.find_next_siblings('div')[1].text.replace("$",""),ii.find_next_sibling('div').text.replace("庫存:","")]) except: gotdata.append(['無權限',ii.text,ii.find_next_siblings('div')[1].text.replace("$",""),ii.find_next_sibling('div').text.replace("庫存:","")]) print(ii.text) id_data = [] for i in gotdata: #提取ID 資料 id_data.append(i[0]) #讀取excel 資料 #產生google 寫入資料 xlrd.Book.encoding = "utf8" #设置编码 data = xlrd.open_workbook(r"C:\Users\Owner\Desktop\shopee prd\productsID.xlsx") table1 = data.sheet_by_index(0) #取第一张工作簿 rows_count = table1.nrows #取总行数 wriso = [] #更新標題 for i in range(rows_count): wriso.append([table1.cell_value(i,0),table1.cell_value(i,1),table1.cell_value(i,2)]) wrval = [] #寫入的資料 for row in range(rows_count): wrval.append([""]) for row in range(rows_count): try: stock_count = gotdata[id_data.index(table1.cell_value(row,18))][3] #取得庫存數量 stock_count = int(stock_count)*int(table1.cell_value(row,19)) #庫存數乘以箱入數 wrval[row] = [stock_count] except: if table1.cell_value(row,18): wrval[row] = ['none'] wrval[0][0] = "官網" + time.strftime("%m/%d", time.localtime()) delsheet("庫存表!E:E") writesheet("庫存表!A1",wriso) writesheet("庫存表!E1",wrval) print("OK")<file_sep>#第一次執行需要用CMD執行 才會跑出網頁認證 from __future__ import print_function from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools # If modifying these scopes, delete the file token.json. SCOPES = 'https://www.googleapis.com/auth/spreadsheets' def main(): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) # Call the Sheets API SPREADSHEET_ID = '19ZXwhENPrLmLURoKO4xXoCDahpyMG5wuU_8xsU74kyI' RANGE_NAME = '停售!A1' values =[['AAA']] body = {'values': values} print(body) value_input_option = 'USER_ENTERED' result = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID,range=RANGE_NAME,valueInputOption=value_input_option,body=body).execute() print(result) if __name__ == '__main__': main()<file_sep>from bs4 import BeautifulSoup import tkinter as tk import requests import json def pconeID(pdid): url = "https://www.pcone.com.tw/product/info/"+pdid my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 try: strnum = soup.select('script')[23].text.find("window._pc_p = ") #提取JSON資料 gotjson = soup.select('script')[23].text[strnum+len("window._pc_p = "):-2] load = json.loads(gotjson) #轉成python dict except: strnum = soup.select('script')[24].text.find("window._pc_p = ") #提取JSON資料 gotjson = soup.select('script')[24].text[strnum+len("window._pc_p = "):-2] load = json.loads(gotjson) #轉成python dict output.insert(1.0,load['product_name']) for i in range(len(load['volumes'])): output.insert(1.0,str(load['volumes'][i]['volume_id'])+" "+str(load['volumes'][i]['volume_remaining'])+" "+str(load['volumes'][i]['option'])+"\n") def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") inputID = IDinput.get() pconeID(inputID) gui=tk.Tk() gui.title("查松果ID") output= tk.Text() output.pack() IDinput = tk.Entry() IDinput.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop()<file_sep>#查庫存ID GUI 雅虎 from bs4 import BeautifulSoup import tkinter as tk import requests import json import re def remove_emoji(data):#去除emojis if not data: return data try: # UCS-4 patt = re.compile(u'([\U00002600-\U000027BF])|([\U0001f300-\U0001f64F])|([\U0001f680-\U0001f6FF])') except re.error: # UCS-2 patt = re.compile(u'([\u2600-\u27BF])|([\uD83C][\uDF00-\uDFFF])|([\uD83D][\uDC00-\uDE4F])|([\uD83D][\uDE80-\uDEFF])') return patt.sub('', data) def yahooID(yid): url = "https://tw.bid.yahoo.com/item/"+yid my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 #for item in soup.select(".listing-title"): #html 可以使用select 選擇想要的東西 #print(item.select("a")[0].text) gotjson = soup.select("#isoredux-data")[0].get("data-state") #get 取得屬性 load = json.loads(gotjson) #轉成python dict if len(load["item"]["specs"]) != 0: for i in range(len(load["item"]["models"])): #提取ID specnameID = str(load["item"]["models"][i]["specCombination"]).split(":") specname = str(load["item"]["specs"][0]['options'][i]['name']) if specnameID[1] == str(load["item"]["specs"][0]['options'][i]['id']): text = ' 驗證成功' else: text = ' 驗證失敗' output.insert(1.0,"\n"+load["item"]["models"][i]["id"]+" :"+ str(load["item"]["models"][i]["qty"])+" "+specname+text) else: output.insert(1.0,"\n"+str(load["item"]["models"][0]["qty"])) output.insert(1.0,"\n"+remove_emoji(load["item"]["title"])) output.insert(1.0,str(load["item"]["status"])+" ● 2:上架,3:下架") def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") inputID = IDinput.get() yahooID(inputID) gui=tk.Tk() gui.title("查雅虎ID") output= tk.Text() output.pack() IDinput = tk.Entry() IDinput.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop()<file_sep>#查露天新增 from bs4 import BeautifulSoup import tkinter as tk import requests import json import threading #多線呈 from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") added_thread = threading.Thread(target=rutendetect) #添加多線呈 # 執行 thread added_thread.start() def rutendetect(): allid = [] for page in range(1,200): output.insert(1.0,".") url = "http://class.ruten.com.tw/user/index00.php?s=ting865290&p="+str(page) my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 rutenhtml = soup.find_all('div','rt-product-tag-container tagging-class') end = soup.find_all("div",class_ = "item-img-wrap") for i in range(len(rutenhtml)): try:#若裡面沒有重複值則新增 allid.index(rutenhtml[i]['name']) except: allid.append(rutenhtml[i]['name']) if len(end) == 0: break output.insert(1.0,"\n") GOTData = getsheet('商品ID!G:G') takeid = [] for i in range(len(GOTData)): try: takeid.append(GOTData[i][0]) except: continue errorid = [] for i in range(len(allid)): try: takeid.index(allid[i]) #看試算表尚存不存在網頁ID except: output.insert(1.0,str(allid[i])+"\n") output.insert(1.0,"偵測完成\n") gui=tk.Tk() gui.title("露天新上架") output= tk.Text() output.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop() <file_sep>from __future__ import print_function from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools def delsheet(sheetrange): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) # Call the Sheets API SPREADSHEET_ID = '<KEY>' RANGE_NAME = {'ranges' : [sheetrange]} result = service.spreadsheets().values().batchClear(spreadsheetId=SPREADSHEET_ID,body=RANGE_NAME).execute() print(result) def getsheet(sheetrange): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) # Call the Sheets API SPREADSHEET_ID = '<KEY>' RANGE_NAME = sheetrange result = service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME).execute() values = result.get('values', []) if not values: print('No data found.') else: return values def writesheet(sheetrange,writeVal): """Shows basic usage of the Sheets API. Prints values from a sample spreadsheet. """ store = file.Storage('token.json') creds = store.get() if not creds or creds.invalid: flow = client.flow_from_clientsecrets('credentials.json', SCOPES) creds = tools.run_flow(flow, store) service = build('sheets', 'v4', http=creds.authorize(Http())) # Call the Sheets API SPREADSHEET_ID = '19ZXwhENPrLmLURoKO4xXoCDahpyMG5wuU_8xsU74kyI' RANGE_NAME = sheetrange values =[['=52+25']] body = {'values': writeVal} value_input_option = 'USER_ENTERED' result = service.spreadsheets().values().update(spreadsheetId=SPREADSHEET_ID,range=RANGE_NAME,valueInputOption=value_input_option,body=body).execute() print(result)<file_sep>#查庫存ID GUI PCD from bs4 import BeautifulSoup import tkinter as tk import requests import json import re def remove_emoji(data):#去除emojis if not data: return data try: # UCS-4 patt = re.compile(u'([\U00002600-\U000027BF])|([\U0001f300-\U0001f64F])|([\U0001f680-\U0001f6FF])') except re.error: # UCS-2 patt = re.compile(u'([\u2600-\u27BF])|([\uD83C][\uDF00-\uDFFF])|([\uD83D][\uDC00-\uDE4F])|([\uD83D][\uDE80-\uDEFF])') return patt.sub('', data) def getpcd(pid): url = "http://seller.pcstore.com.tw/S188431702/"+pid+".htm" my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 gotjson = soup.select('#specs')[0].text load = json.loads(gotjson) outObj = {"state":"0","prd":""} prdAry = [] if type(load) == dict: #新上的都是字典檔 for k,v in load.items(): output.insert(1.0,"\n"+v['p_spec']+" "+v['p_sseq']+" 數量:"+v['p_invt']) else:#舊的都是陣列 for i in range(len(load)): output.insert(1.0,"\n"+load[i]['p_spec']+" "+load[i]['p_sseq']+" 數量:"+load[i]['p_invt']) outObj["prd"] = prdAry output.insert(1.0,"\n") output.insert(1.0,remove_emoji(soup.select('.info .tit')[0].get_text())) def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") inputID = IDinput.get() getpcd(inputID) gui=tk.Tk() gui.title("查PC大一ID") output= tk.Text() output.pack() IDinput = tk.Entry() IDinput.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop()<file_sep>#蝦皮總上架ID import tkinter as tk import requests import json from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet def updateSPID(): webidAry = [] my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} for i in range(200): url = "https://shopee.tw/api/v2/search_items/?by=pop&limit=100&match_id=2019696&newest="+str(i*100) +"&order=desc&page_type=shop" gotrq = requests.get(url,headers = my_headers) loadjson = json.loads(gotrq.text) if len(loadjson["items"]) == 0: break for ct in range(len(loadjson["items"])): webidAry.append(loadjson["items"][ct]["itemid"]) #比對新增的WEBID GOTData = getsheet('商品ID!I:I') #獲取試算表所有資料 IDAry = [] #已上的ID errorAry = [] #找到的未上ID for i in range(len(GOTData)): #提取資料 try: IDAry.append(GOTData[i][0]) except: IDAry.append("") for i in range(len(webidAry)): #找到未上的ID try: IDAry.index(str(webidAry[i])) except: errorAry.append(webidAry[i]) output.insert(1.0,"查詢完成\n") for i in range(len(errorAry)): output.insert(1.0,str(errorAry[i])+"\n") def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") updateSPID() gui=tk.Tk() gui.title("查蝦皮新上架") output= tk.Text() output.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop()<file_sep>#PCD ALL import requests import json import time from bs4 import BeautifulSoup from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet SCOPES = 'https://www.googleapis.com/auth/spreadsheets' def getpcd(pid): url = "http://seller.pcstore.com.tw/S163498400/"+pid+".htm" my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 gotjson = soup.select('#specs')[0].text load = json.loads(gotjson) outObj = {"state":"0","prd":""} prdAry = [] if type(load) == dict: #新上的都是字典檔 for k,v in load.items(): prdAry.append([v['p_sseq'],v['p_invt'],v['p_spec']]) else:#舊的都是陣列 for i in range(len(load)): prdAry.append([load[i]['p_sseq'],load[i]['p_invt'],load[i]['p_spec']]) outObj["prd"] = prdAry return outObj def getALLpcd(): prdidData = getsheet('商品ID!K:L') #獲取試算表所有資料 wiAry=[] tiAry= [] wrval = [] for row in range(len(prdidData)): wrval.append("") for row in range(len(prdidData)): print(str(row)+"/"+str(len(prdidData))) try: if prdidData[row][0]: time.sleep(0.5) #PC會檔大量讀取 gotstock = getpcd(prdidData[row][0]) #gotstock 得到PC網頁的資料 for i in range(len(gotstock["prd"])): #依網頁資料款式的種類數量迴圈 if gotstock["prd"][i][0] == prdidData[row][1]:#獲取的款式ID 等於 試算表上的款式ID wrval[row] = [gotstock["prd"][i][1]] #指派數量資料 if wrval[row] == "": wrval[row] = ["款式ID錯誤"] else: wrval[row] = ["商品ID錯誤"] except: try: if prdidData[row][0]: wrval[row] = ["錯誤或下架"] except: wrval[row] = [""] wrval[0][0] = "PC梓原" + time.strftime("%m/%d", time.localtime()) delsheet("商品ID!V:V") writesheet("商品ID!V1",wrval) print("OK") getALLpcd()<file_sep>#查雅虎新增 from bs4 import BeautifulSoup import tkinter as tk import requests import json import threading #多線呈 from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") added_thread = threading.Thread(target=yahoodetect) #添加多線呈 # 執行 thread added_thread.start() def yahoodetect(): allid = [] for page in range(1,200): try: output.insert(1.0,".") url = 'https://tw.bid.yahoo.com/booth/Y7975457951?bfe=1&page='+str(page) my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 yahoohtml = soup.find_all('div','item-wrap') if len(yahoohtml) == 0 : #找完跳出 break for i in range(len(yahoohtml)): allid.append(yahoohtml[i]['data-mid']) except: print("end") break output.insert(1.0,"\n") GOTData = getsheet('商品ID!M:M') takeid = [] for i in range(len(GOTData)): try: takeid.append(GOTData[i][0]) except: continue errorid = [] for i in range(len(allid)): try: takeid.index(allid[i]) #看試算表尚存不存在網頁ID except: output.insert(1.0,str(allid[i])+"\n") output.insert(1.0,"偵測完成\n") gui=tk.Tk() gui.title("雅虎新上架") output= tk.Text() output.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop() <file_sep>import requests import json import time from bs4 import BeautifulSoup from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet SCOPES = 'https://www.googleapis.com/auth/spreadsheets' def getpcone(pid): url = "https://www.pcone.com.tw/product/info/"+pid my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 try: strnum = soup.select('script')[23].text.find("window._pc_p = ") #提取JSON資料 gotjson = soup.select('script')[23].text[strnum+len("window._pc_p = "):-2] load = json.loads(gotjson) #轉成python dict except: strnum = soup.select('script')[24].text.find("window._pc_p = ") #提取JSON資料 gotjson = soup.select('script')[24].text[strnum+len("window._pc_p = "):-2] load = json.loads(gotjson) #轉成python dict outObj = {"state":"0","prd":""} prdAry = [] for i in range(len(load['volumes'])): prdAry.append([str(load['volumes'][i]['volume_id']),str(load['volumes'][i]['volume_remaining']),str(load['volumes'][i]['option'])]) outObj["prd"] = prdAry return outObj def getALLpcone(): prdidData = getsheet('商品ID!O:P') #獲取試算表所有資料 wiAry=[] tiAry= [] wrval = [] for row in range(len(prdidData)): wrval.append("") for row in range(len(prdidData)): print(str(row)+"/"+str(len(prdidData))) try: if prdidData[row][0]: gotstock = getpcone(prdidData[row][0]) for i in range(len(gotstock["prd"])): if gotstock["prd"][i][0] == prdidData[row][1]: wrval[row] = [gotstock["prd"][i][1]] if wrval[row] == "": wrval[row] = ["款式ID錯誤"] except: try: if prdidData[row][0]: wrval[row] = ["錯誤或下架"] except: wrval[row] = [""] wrval[0][0] = "Pcone" + time.strftime("%m/%d", time.localtime()) delsheet("商品ID!Q:Q") writesheet("商品ID!Q1",wrval) print("OK") getALLpcone()<file_sep>#查庫存ID GUI 露天 from bs4 import BeautifulSoup import tkinter as tk import requests import json import re def remove_emoji(data):#去除emojis if not data: return data try: # UCS-4 patt = re.compile(u'([\U00002600-\U000027BF])|([\U0001f300-\U0001f64F])|([\U0001f680-\U0001f6FF])') except re.error: # UCS-2 patt = re.compile(u'([\u2600-\u27BF])|([\uD83C][\uDF00-\uDFFF])|([\uD83D][\uDC00-\uDE4F])|([\uD83D][\uDE80-\uDEFF])') return patt.sub('', data) def rutenID(rid): url = "https://goods.ruten.com.tw/item/show?"+rid my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 strnum = soup.select('script[type="text/javascript"]')[15].text.find("RT.context = ") #提取JSON資料 #find 找到RT.context的位址 gotjson = soup.select('script[type="text/javascript"]')[15].text[strnum+len("RT.context = "):-2] load = json.loads(gotjson) #轉成python dict if load['item']['specInfo']: #是否有款式 for k,v in load['item']['specInfo']['specs'].items():#for 出dict 資料 try: output.insert(1.0,'\n'+str(v['spec_ext']['goods_no'])) except: print("款式沒有國際條碼") output.insert(1.0,'\n'+k+' :'+v['spec_num']+" "+v['spec_name']) output.insert(1.0,'\n') else: output.insert(1.0,'\n'+str(load['item']['remainNum'])) output.insert(1.0,'\n'+remove_emoji(load['item']['name'])) output.insert(1.0,"下架了嗎?"+str(load['item']['isSoldEnd'])) def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") inputID = IDinput.get() rutenID(inputID) gui=tk.Tk() gui.title("查露天ID") output= tk.Text() output.pack() IDinput = tk.Entry() IDinput.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop()<file_sep>#蝦皮庫存 import xlrd import time import tkinter as tk import tkinter.filedialog as filedialog import os from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet def browser(): fname = filedialog.askopenfilename(initialdir= os.getcwd(),filetypes = (("Excel","*.xlsx"),("all files","*.*"))) global filepath filepath = fname # 返回文件全路径 pathinput.delete('0',tk.END) pathinput.insert(0,filepath) #print(filedialog.askdirectory()) # 返回目录路径 def shopeeExcel(path): xlrd.Book.encoding = "utf8" #设置编码 data = xlrd.open_workbook(path) table = data.sheet_by_index(0) #取第一张工作簿 rows_count = table.nrows #取总行数 prdid = [] for row in range(rows_count):#無款式 if table.cell(row,0).value: try: prdid.append({"ID":str(int(table.cell(row,0).value)),"stock":str(int(table.cell(row,6).value))}) except: a = "a" for i in range(20): col = 5*i for row in range(rows_count): #商品款式 try: prdid.append({"ID":str(int(table.cell(row,8+col).value)),"stock":str(int(table.cell(row,12+col).value))}) except: a = "b" return prdid def run(): print(filepath) getidlist = getsheet("商品ID!I:J") oklist = shopeeExcel(filepath) #讀取EXCEL #提取sheet 資料 sprdid = [] smodelid = [] for i in range(len(getidlist)): try: sprdid.append(getidlist[i][0]) except: sprdid.append("") try: smodelid.append(getidlist[i][1]) except: smodelid.append("") #尋找並寫入sheet wrval = [] noidlist = [] for i in range(len(getidlist)): wrval.append([""]) for i in range(len(oklist)): try: findrow = sprdid.index(oklist[i]["ID"]) wrval[findrow] = [oklist[i]["stock"]] except: try: findrow = smodelid.index(oklist[i]["ID"]) wrval[findrow] = [oklist[i]["stock"]] except: noidlist.append(oklist[i]["ID"]) wrval[0] = ["Shopee"+ time.strftime("%m/%d", time.localtime())] delsheet("商品ID!R:R") writesheet("商品ID!R1",wrval) gui=tk.Tk() gui.title("更新蝦皮庫存") gui.geometry("450x50") pathinput = tk.Entry(width=50) pathinput.pack(side="left") btn2 = tk.Button(gui, text ="瀏覽", command = browser) btn2.pack(side="left") btn = tk.Button(gui, text ="執行", command = run) btn.pack(side="left") gui.mainloop() <file_sep>#露天全部 import requests import json import time from bs4 import BeautifulSoup from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet SCOPES = 'https://www.googleapis.com/auth/spreadsheets' def getruten(pid): url = "https://goods.ruten.com.tw/item/show?"+pid my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 strnum = soup.select('script[type="text/javascript"]')[15].text.find("RT.context = ") #提取JSON資料 #find 找到RT.context的位址 gotjson = soup.select('script[type="text/javascript"]')[15].text[strnum+len("RT.context = "):-2] load = json.loads(gotjson) #轉成python dict outObj = {"state":"0","prd":""} prdAry = [] if load['item']['specInfo']: #是否有款式 for k,v in load['item']['specInfo']['specs'].items():#for 出dict 資料 prdAry.append([k,v['spec_num'],v['spec_name'],v["spec_status"]]) #print(k+':'+v['spec_num']+" "+v['spec_name']+v["spec_status"]) outObj["prd"]=prdAry else: outObj["prd"]=str(load['item']['remainNum']) #print(load['remain_count']) outObj["state"] = load['item']['isSoldEnd'] return outObj def getALLRuten(): prdidData = getsheet('商品ID!G:H') #獲取試算表所有資料 wiAry=[] tiAry= [] wrval = [] #寫入的陣列 for row in range(len(prdidData)):#新增同列數陣列 wrval.append([""]) for row in range(len(prdidData)): #for row in range(5,12): print(str(row)+"/"+str(len(prdidData))) #進度 try: if prdidData[row][0]: gotstock = getruten(prdidData[row][0]) #讀取網頁 if type(gotstock['prd']) == type(""): #如果prd為文字則為無款式 wrval[row] = [gotstock['prd']] else:#有款式 for i in range(len(gotstock["prd"])): if gotstock["prd"][i][0] == prdidData[row][1]: #有找到款式ID wrval[row] = [gotstock["prd"][i][1]] #寫入資料 if gotstock["prd"][i][3] == "N": #如果發現款式是關閉 wrval[row]=["款式關閉"] if wrval[row] == "":#都沒有找到 wrval[row] = ["款式ID錯誤"] if gotstock["state"] == True: wrval[row] = ["下架"] except: #有可能ID錯誤,有可能ID無值 try: if prdidData[row][0]:#ID錯誤 wrval[row] = ["商品ID錯誤或無款式ID"] except: wrval[row] = [""] wrval[0][0] = "Ruten" + time.strftime("%m/%d", time.localtime())#寫入第一列 delsheet("商品ID!T:T") #刪除原有資料 writesheet("商品ID!T1",wrval) #寫入資料 return wrval print("OK") getALLRuten()<file_sep>#PC 新上架 from bs4 import BeautifulSoup import tkinter as tk import requests import json import threading #多線呈 from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet def clickbtn(): try: output.delete('1.0',tk.END) except: print("start") added_thread = threading.Thread(target=pcddetect) #添加多線呈 # 執行 thread added_thread.start() def pcddetect(): allid = [] for page in range(1,200): #登錄後才能訪問的網頁 url = 'http://seller.pcstore.com.tw/S188431702/plist_dt.htm?s=S188431702&c=&skw=&pg='+str(page)+'&sr=1&pp=50' #瀏覽器登錄後得到的cookie,也就是剛才複製的字符串 cookie_str = r'cbj=IqhLsP6..LOKMq6kVcXtnWgBVcXtnqojj' #######################這邊要研究 my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} #把cookie字符串處理成字典,以便接下來使用 cookies = {} for line in cookie_str.split(';'): #cookie_str.split(';') 依分號 分割成陣列 並列出 key, value = line.split('=', 1) #將陣列依序指派給key value cookies[key] = value #新增物件 session = requests.Session() res = session.get(url,cookies=cookies,headers = my_headers) soup = BeautifulSoup(res.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 html = soup.find_all('a','hotProdList') for link in html: linkID = link['href'].replace('/S188431702/','').replace('.htm','') allid.append(linkID) if len(html) < 50: break output.insert(1.0,"\n") GOTData = getsheet('商品ID!M:M') takeid = [] for i in range(len(GOTData)): try: takeid.append(GOTData[i][0]) except: continue errorid = [] for i in range(len(allid)): try: takeid.index(allid[i]) #看試算表尚存不存在網頁ID except: output.insert(1.0,str(allid[i])+"\n") output.insert(1.0,"偵測完成\n") gui=tk.Tk() gui.title("PC大一新上架") output= tk.Text() output.pack() btn = tk.Button(gui, text ="執行", command = clickbtn) btn.pack(anchor='center', expand='yes') gui.mainloop() <file_sep>import requests import json import time from bs4 import BeautifulSoup from googlesheet import delsheet from googlesheet import getsheet from googlesheet import writesheet SCOPES = 'https://www.googleapis.com/auth/spreadsheets' def getyahoo(pid): url = "https://tw.bid.yahoo.com/item/"+pid my_headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'} gotrq = requests.get(url,headers = my_headers) soup = BeautifulSoup(gotrq.text, "html.parser") #"html.parser" html解析器 將html 轉為bs4格式操作 #for item in soup.select(".listing-title"): #html 可以使用select 選擇想要的東西 #print(item.select("a")[0].text) gotjson = soup.select("#isoredux-data")[0].get("data-state") #get 取得屬性 load = json.loads(gotjson) #轉成python dict outObj = {"state":"0","prd":""} if len(load["item"]["specs"]) == 0: #print(load["item"]["models"][0]["id"]+":"+ str(load["item"]["models"][0]["qty"])) outObj["prd"] = str(load["item"]["models"][0]["qty"]) else: outAry = [] for i in range(len(load["item"]["models"])): #提取ID specnameID = str(load["item"]["models"][i]["specCombination"]).split(":") specname = str(load["item"]["specs"][0]['options'][i]['name']) outAry.append([str(load["item"]["models"][i]["id"]),str(load["item"]["models"][i]["qty"]),specname]) #print(load["item"]["models"][i]["id"]+":"+ str(load["item"]["models"][i]["qty"])+" "+specname) outObj["prd"] = outAry outObj["state"] = str(load["item"]["status"]) return outObj def getALLYahoo(): prdidData = getsheet('商品ID!E:F') #獲取試算表所有資料 wiAry=[] tiAry= [] wrval = [] #寫入的陣列 for row in range(len(prdidData)):#新增同列數陣列 wrval.append([""]) for row in range(len(prdidData)): #for row in range(5,12): print(str(row)+"/"+str(len(prdidData))) #進度 try: if prdidData[row][0]: gotstock = getyahoo(prdidData[row][0]) if type(gotstock['prd']) == type(""): #如果prd為文字則為無款式 wrval[row] = [gotstock['prd']] else:#有款式 for i in range(len(gotstock["prd"])): if gotstock["prd"][i][0] == prdidData[row][1]: wrval[row] = [gotstock["prd"][i][1]] if wrval[row] == "":#都沒有找到 wrval[row] = ["款式ID錯誤"] if gotstock["state"] == '3': wrval[row] = ["下架"] except: #有可能ID錯誤,有可能ID無值 try: if prdidData[row][0]:#ID錯誤 wrval[row] = ["商品ID錯誤或無款式ID"] except: wrval[row] = [""] wrval[0][0] = "Yahoo" + time.strftime("%m/%d", time.localtime()) delsheet("商品ID!S:S") writesheet("商品ID!S1",wrval) return wrval print("OK") getALLYahoo()
487356a3b24c0b9a907888e284b12c8dbe35495d
[ "Python" ]
17
Python
yashichi05/shopee-prd
0973f5a07b6d37d9ea4aec0d27628d2a85fcaeef
00357435d860ecf9fea26f0420cbd7ca178f9cde
refs/heads/master
<repo_name>aserunix/python3_book_HeadFirstPython<file_sep>/hf_py_c6.py #!/usr/bin/env python3 #-*- coding:utf-8 -*- class Athlete: def __int__(self,value=0): ##the code to initialize a "Athlete" object self.thing=value def how_big(self): return(len(self.thing)) d=Athlete("Holy Grail") <file_sep>/hf_py_c3.py #!/usr/bin/env python3 #-*- coding: utf-8 -*- import os # try: # data=open('missing.txt','w') # # print(data.readline(),end='') # print("It's...",file=data) # except IOError as err: # print('File error: ' + str(err) ) # finally: # if 'data' in locals(): # data.close() # print("Current Dir: " + os.getcwd()) # try: # with open('test.txt','w') as data: # print("It's...",file=data) # except IOError as err: # print('File error:',+str(err)) def print_lol(the_list,indent=False,level=0): for each_item in the_list: if isinstance(each_item,list): print_lol(each_item,indent,level+1) else: if indent: for tab_stop in range(level): print("\t",end='') print(each_item) <file_sep>/hf_py_c7.py #!/usr/bin/env python3 #-*- coding:utf-8 -*- # import pickle # # from athletelist import AthleteList # # def get_coach_data(filename): # # def put_to_store(files_list): # all_athletes=() # for each_file in files_list: # ath=get_coach_data(each_file) # all_athletes[ath.name]=ath # try: # with open('athletes.pickle','wb') as athf: # pickle.dump(all_athletes,athf) # except IOError as ioerr: # print('File error(put_and_store):'+str(ioerr)) # return(all_athletes) # # def get_from_store(): # all_athleles={} # try: # with open('athletes.pickle','rb') as athf: # all_athleles=pickle.load(athf) # except IOError as ioerr: # print('File error(get_from_store):'+str(ioerr)) # return(all_athleles) from string import Template def start_response(resp="text/html"): return('Content-type; '+resp+'\n\n') def include_header(the_title): whith open('templates/header.html') as headf head_text=headf.read() header=Template(head_text) return(header.substitude(title=the_title)) def include_footer(the_links): with open('tmeplates/footer.html') as footf: foot_text=footf.read() link_string='' for key in the_links: link_string+='<a href="'+the_links[key]+'">'+key+'</a>&nbsp;&nbsp;&nbsp;&nbsp;' footer=Template(foot_text) return(footer.substitute(links=link_string)) def start_form(the_url,form_type="POST"): return('<form action="'+the_url+'" method="'+form_type+'">') def end_form(submit_msg="Submit"): return('<p></p><input type=submit value="'+submit_msg+'">') def radio_button(rb_name,rb_value): return('<input type="radio"' name="'+rb_name+'" value="'+rb_value+'">'">'+rb_value+'<br />') <file_sep>/monitor.py UsageCpu={'us':0,'us':0,'ni':0,'id':0,'wa':0,'hi':0,'si':0,'st':0} UsageMem={'total':0,'used':0,'free':0,'shard':0,'buffers':0,'cached':0,'real_used':0,'real_free':0} UsageSwap={'total':0,'used':0,'free':0,'shard':0,'buffers':0,'cached':0,'real_used':0,'real_free':0} UsageDiskSpace={} UsageDiskInode={} UsageDiskIO={} UsageNicIOPackets={} UsageNicIOBytes={} UsageNicSpeedRate={}<file_sep>/hf_py_c5.py #!/usr/bin/env python3 #-*- coding: utf-8 -*- def sanitize(time_string): if '-' in time_string: splitter='-' elif ':' in time_string: splitter=':' else: return(time_string) (mins,secs)=time_string.split(splitter) return(mins+'.'+secs) with open('julie.txt') as juf: data=juf.readline() julie=data.strip().split(',') clean_julie=[] for each_time in julie: clean_julie=clean_julie.append(sanitize(each_time)) # print(sorted(clean_julie)) # print(clean_julie) # a=[6,3,2,5,4] # a=sorted(a) # print(a) <file_sep>/hf_py_c4.py #!/usr/bin/env python3 #-*- coding: utf-8 -*- import pickle with open('mydata.pickle','wb') as mysavedata: pickle.dump([1,2,'three'],mysavedata) with open('mydata.pickle','rb') as myrestoredata: a_list=pickle.load(mystoredata) print(a_list)
9e92eda3dcc2a220044187fad0f84246d2daa6ea
[ "Python" ]
6
Python
aserunix/python3_book_HeadFirstPython
fb4caa5a0abd94134e7f40a77efcc78e3c8358ba
0ae0e4d0f684695688ec8bd3a2b2e0c123f362c4
refs/heads/main
<repo_name>miguelgrinberg/aioflask<file_sep>/tests/utils.py import asyncio from greenletio.core import bridge def async_test(f): def wrapper(*args, **kwargs): asyncio.get_event_loop().run_until_complete(f(*args, **kwargs)) return wrapper <file_sep>/examples/aioflaskr/tests/conftest.py from datetime import datetime import pytest from flaskr import create_app from flaskr import db from flaskr import init_db from flaskr.models import User from flaskr.models import Post @pytest.fixture async def app(): """Create and configure a new app instance for each test.""" # create the app with common test config app = create_app({"TESTING": True, "ALCHEMICAL_DATABASE_URL": "sqlite:///:memory:"}) # create the database and load test data async with app.app_context(): await init_db() user = User(username="test", password="<PASSWORD>") db.session.add_all( ( user, User(username="other", password="<PASSWORD>"), Post( title="test title", body="test\nbody", author=user, created=datetime(2018, 1, 1), ), ) ) await db.session.commit() yield app @pytest.fixture def client(app): """A test client for the app.""" return app.test_client() @pytest.fixture def runner(app): """A test runner for the app's Click commands.""" return app.test_cli_runner() class AuthActions: def __init__(self, client): self._client = client async def login(self, username="test", password="<PASSWORD>"): return await self._client.post( "/auth/login", data={"username": username, "password": <PASSWORD>} ) async def logout(self): return await self._client.get("/auth/logout") @pytest.fixture def auth(client): return AuthActions(client) <file_sep>/examples/aioflaskr/flaskr/blog.py from aioflask import Blueprint from aioflask import flash from aioflask import redirect from aioflask import render_template from aioflask import request from aioflask import url_for from werkzeug.exceptions import abort from aioflask.patched.flask_login import current_user from aioflask.patched.flask_login import login_required from flaskr import db from flaskr.models import Post bp = Blueprint("blog", __name__) @bp.route("/") async def index(): """Show all the posts, most recent first.""" posts = (await db.session.scalars(Post.select())).all() return await render_template("blog/index.html", posts=posts) async def get_post(id, check_author=True): """Get a post and its author by id. Checks that the id exists and optionally that the current user is the author. :param id: id of post to get :param check_author: require the current user to be the author :return: the post with author information :raise 404: if a post with the given id doesn't exist :raise 403: if the current user isn't the author """ post = await db.session.get(Post, id) if post is None: abort(404, f"Post id {id} doesn't exist.") if check_author and post.author != current_user: abort(403) return post @bp.route("/create", methods=("GET", "POST")) @login_required async def create(): """Create a new post for the current user.""" if request.method == "POST": title = request.form["title"] body = request.form["body"] error = None if not title: error = "Title is required." if error is not None: flash(error) else: db.session.add(Post(title=title, body=body, author=current_user)) await db.session.commit() return redirect(url_for("blog.index")) return await render_template("blog/create.html") @bp.route("/<int:id>/update", methods=("GET", "POST")) @login_required async def update(id): """Update a post if the current user is the author.""" post = await get_post(id) if request.method == "POST": title = request.form["title"] body = request.form["body"] error = None if not title: error = "Title is required." if error is not None: flash(error) else: post.title = title post.body = body await db.session.commit() return redirect(url_for("blog.index")) return await render_template("blog/update.html", post=post) @bp.route("/<int:id>/delete", methods=("POST",)) @login_required async def delete(id): """Delete a post. Ensures that the post exists and that the logged in user is the author of the post. """ post = await get_post(id) await db.session.delete(post) await db.session.commit() return redirect(url_for("blog.index")) <file_sep>/src/aioflask/testing.py from flask.testing import * from flask.testing import FlaskClient as OriginalFlaskClient, \ FlaskCliRunner as OriginalFlaskCliRunner from flask import _request_ctx_stack from werkzeug.test import run_wsgi_app from greenletio import async_ class FlaskClient(OriginalFlaskClient): def run_wsgi_app(self, environ, buffered=False): """Runs the wrapped WSGI app with the given environment. :meta private: """ if self.cookie_jar is not None: self.cookie_jar.inject_wsgi(environ) rv = run_wsgi_app(self.application.wsgi_app, environ, buffered=buffered) if self.cookie_jar is not None: self.cookie_jar.extract_wsgi(environ, rv[2]) return rv async def get(self, *args, **kwargs): return await async_(super().get)(*args, **kwargs) async def post(self, *args, **kwargs): return await async_(super().post)(*args, **kwargs) async def put(self, *args, **kwargs): return await async_(super().put)(*args, **kwargs) async def patch(self, *args, **kwargs): return await async_(super().patch)(*args, **kwargs) async def delete(self, *args, **kwargs): return await async_(super().delete)(*args, **kwargs) async def head(self, *args, **kwargs): return await async_(super().head)(*args, **kwargs) async def options(self, *args, **kwargs): return await async_(super().options)(*args, **kwargs) async def trace(self, *args, **kwargs): return await async_(super().trace)(*args, **kwargs) async def __aenter__(self): if self.preserve_context: raise RuntimeError("Cannot nest client invocations") self.preserve_context = True return self async def __aexit__(self, exc_type, exc_value, tb): self.preserve_context = False # Normally the request context is preserved until the next # request in the same thread comes. When the client exits we # want to clean up earlier. Pop request contexts until the stack # is empty or a non-preserved one is found. while True: top = _request_ctx_stack.top if top is not None and top.preserved: await top.apop() else: break class FlaskCliRunner(OriginalFlaskCliRunner): async def invoke(self, *args, **kwargs): return await async_(super().invoke)(*args, **kwargs) <file_sep>/examples/AsyncProgressBar/requirements.txt aioflask aioredis==1.3.1 async-timeout==3.0.1 click==7.1.2 Flask==1.1.2 greenlet==0.4.16 greenletio h11==0.9.0 hiredis==1.1.0 httptools==0.1.1 itsdangerous==1.1.0 Jinja2==2.11.2 MarkupSafe==1.1.1 redis==3.5.3 uvicorn==0.11.6 uvloop==0.14.0 websockets==8.1 Werkzeug==1.0.1 <file_sep>/examples/AsyncProgressBar/progress_bar.py import asyncio import random import aioredis import redis from aioflask import Flask, request, url_for, jsonify app = Flask(__name__) sr = redis.StrictRedis(host='localhost', port=6379) sr.execute_command('FLUSHDB') async def some_work(): global aredis await aredis.set('state', 'running') work_to_do = range(1, 26) await aredis.set('length_of_work', len(work_to_do)) for i in work_to_do: await aredis.set('processed', i) await asyncio.sleep(random.random()) await aredis.set('state', 'ready') await aredis.set('percent', 100) @app.route('/check_status/') async def check_status(): global aredis, sr status = dict() try: if await aredis.get('state') == b'running': if await aredis.get('processed') != await aredis.get('lastProcessed'): await aredis.set('percent', round( int(await aredis.get('processed')) / int(await aredis.get('length_of_work')) * 100, 2)) await aredis.set('lastProcessed', str(await aredis.get('processed'))) except: pass try: status['state'] = sr.get('state').decode() status['processed'] = sr.get('processed').decode() status['length_of_work'] = sr.get('length_of_work').decode() status['percent_complete'] = sr.get('percent').decode() except: status['state'] = sr.get('state') status['processed'] = sr.get('processed') status['length_of_work'] = sr.get('length_of_work') status['percent_complete'] = sr.get('percent') status['hint'] = 'refresh me.' return jsonify(status) @app.route('/progress/') async def progress(): return """ <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Asyncio Progress Bar Demo</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> var percent; function checkStatus() { $.getJSON('""" + url_for('check_status') + """', function (data) { console.log(data); percent = parseFloat(data.percent_complete); update_bar(percent); update_text(percent); }); if (percent != 100) { setTimeout(checkStatus, 1000); } } function update_bar(val) { if (val.length <= 0) { val = 0; } $( "#progressBar" ).progressbar({ value: val }); }; function update_text(val) { if (val != 100) { document.getElementById("progressData").innerHTML = "&nbsp;<center>"+percent+"%</center>"; } else { document.getElementById("progressData").innerHTML = "&nbsp;<center>Done!</center>"; } } checkStatus(); </script> </head> <body> <center><h2>Progress of work is shown below</h2></center> <div id="progressBar"></div> <div id="progressData" name="progressData"><center></center></div> </body> </html>""" @app.route('/') async def index(): return 'This is the index page. Try the following to <a href="' + url_for( 'start_work') + '">start some test work</a> with a progress indicator.' @app.route('/start_work/') async def start_work(): global aredis loop = asyncio.get_event_loop() aredis = await aioredis.create_redis('redis://localhost', loop=loop) if await aredis.get('state') == b'running': return "<center>Please wait for current work to finish.</center>" else: await aredis.set('state', 'ready') if await aredis.get('state') == b'ready': loop.create_task(some_work()) body = ''' <center> work started! </center> <script type="text/javascript"> window.location = "''' + url_for('progress') + '''"; </script>''' return body if __name__ == "__main__": app.run('localhost', port=5000, debug=True) <file_sep>/src/aioflask/cli.py from functools import wraps from inspect import iscoroutinefunction import os import sys from flask.cli import * from flask.cli import AppGroup, ScriptInfo, update_wrapper, \ SeparatedPathType, pass_script_info, get_debug_flag, NoAppException, \ prepare_import from flask.cli import _validate_key from flask.globals import _app_ctx_stack from flask.helpers import get_env from greenletio import await_ from werkzeug.utils import import_string import click import uvicorn try: import ssl except ImportError: # pragma: no cover ssl = None OriginalAppGroup = AppGroup def _ensure_sync(func, with_appcontext=False): if not iscoroutinefunction(func): return func def decorated(*args, **kwargs): if with_appcontext: appctx = _app_ctx_stack.top @await_ async def _coro(): with appctx: return await func(*args, **kwargs) else: @await_ async def _coro(): return await func(*args, **kwargs) return _coro() return decorated def with_appcontext(f): """Wraps a callback so that it's guaranteed to be executed with the script's application context. If callbacks are registered directly to the ``app.cli`` object then they are wrapped with this function by default unless it's disabled. """ @click.pass_context def decorator(__ctx, *args, **kwargs): with __ctx.ensure_object(ScriptInfo).load_app().app_context(): return __ctx.invoke(_ensure_sync(f, True), *args, **kwargs) return update_wrapper(decorator, f) class AppGroup(OriginalAppGroup): """This works similar to a regular click :class:`~click.Group` but it changes the behavior of the :meth:`command` decorator so that it automatically wraps the functions in :func:`with_appcontext`. Not to be confused with :class:`FlaskGroup`. """ def command(self, *args, **kwargs): """This works exactly like the method of the same name on a regular :class:`click.Group` but it wraps callbacks in :func:`with_appcontext` unless it's disabled by passing ``with_appcontext=False``. """ wrap_for_ctx = kwargs.pop("with_appcontext", True) def decorator(f): if wrap_for_ctx: f = with_appcontext(f) return click.Group.command(self, *args, **kwargs)(_ensure_sync(f)) return decorator def show_server_banner(env, debug, app_import_path, eager_loading): """Show extra startup messages the first time the server is run, ignoring the reloader. """ if app_import_path is not None: message = f" * Serving Flask app {app_import_path!r}" click.echo(message) click.echo(f" * Environment: {env}") if debug is not None: click.echo(f" * Debug mode: {'on' if debug else 'off'}") class CertParamType(click.ParamType): """Click option type for the ``--cert`` option. Allows either an existing file, the string ``'adhoc'``, or an import for a :class:`~ssl.SSLContext` object. """ name = "path" def __init__(self): self.path_type = click.Path(exists=True, dir_okay=False, resolve_path=True) def convert(self, value, param, ctx): if ssl is None: raise click.BadParameter('Using "--cert" requires Python to be ' 'compiled with SSL support.', ctx, param) try: return self.path_type(value, param, ctx) except click.BadParameter: value = click.STRING(value, param, ctx).lower() if value == "adhoc": raise click.BadParameter("Aad-hoc certificates are currently " "not supported by aioflask.", ctx, param) return value obj = import_string(value, silent=True) if isinstance(obj, ssl.SSLContext): return obj raise @click.command("run", short_help="Run a development server.") @click.option("--host", "-h", default="127.0.0.1", help="The interface to bind to.") @click.option("--port", "-p", default=5000, help="The port to bind to.") @click.option( "--cert", type=CertParamType(), help="Specify a certificate file to use HTTPS." ) @click.option( "--key", type=click.Path(exists=True, dir_okay=False, resolve_path=True), callback=_validate_key, expose_value=False, help="The key file to use when specifying a certificate.", ) @click.option( "--reload/--no-reload", default=None, help="Enable or disable the reloader. By default the reloader " "is active if debug is enabled.", ) @click.option( "--debugger/--no-debugger", default=None, help="Enable or disable the debugger. By default the debugger " "is active if debug is enabled.", ) @click.option( "--eager-loading/--lazy-loading", default=None, help="Enable or disable eager loading. By default eager " "loading is enabled if the reloader is disabled.", ) @click.option( "--with-threads/--without-threads", default=True, help="Enable or disable multithreading.", ) @click.option( "--extra-files", default=None, type=SeparatedPathType(), help=( "Extra files that trigger a reload on change. Multiple paths" f" are separated by {os.path.pathsep!r}." ), ) @pass_script_info def run_command(info, host, port, reload, debugger, eager_loading, with_threads, cert, extra_files): """Run a local development server. This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers. The reloader and debugger are enabled by default if FLASK_ENV=development or FLASK_DEBUG=1. """ debug = get_debug_flag() if reload is None: reload = debug if debugger is None: debugger = debug if debugger: os.environ['AIOFLASK_USE_DEBUGGER'] = 'true' certfile = None keyfile = None if cert is not None and len(cert) == 2: certfile = cert[0] keyfile = cert[1] show_server_banner(get_env(), debug, info.app_import_path, eager_loading) app_import_path = info.app_import_path if app_import_path is None: for path in ('wsgi', 'app'): if os.path.exists(path) or os.path.exists(path + '.py'): app_import_path = path break if app_import_path is None: raise NoAppException( "Could not locate a Flask application. You did not provide " 'the "FLASK_APP" environment variable, and a "wsgi.py" or ' '"app.py" module was not found in the current directory.' ) if app_import_path.endswith('.py'): app_import_path = app_import_path[:-3] factory = False if app_import_path.endswith('()'): # TODO: this needs to be expanded to accept arguments for the factory # function app_import_path = app_import_path[:-2] factory = True if ':' not in app_import_path: app_import_path += ':app' import_name, app_name = app_import_path.split(':') import_name = prepare_import(import_name) uvicorn.run( import_name + ':' + app_name, factory=factory, host=host, port=port, reload=reload, workers=1, log_level='debug' if debug else 'info', ssl_certfile=certfile, ssl_keyfile=keyfile, ) # currently not supported: # - eager_loading # - with_threads # - adhoc certs # - extra_files <file_sep>/README.md # aioflask ![Build status](https://github.com/miguelgrinberg/aioflask/workflows/build/badge.svg) [![codecov](https://codecov.io/gh/miguelgrinberg/aioflask/branch/main/graph/badge.svg?token=CDMKF3L0ID)](https://codecov.io/gh/miguelgrinberg/aioflask) Flask 2.x running on asyncio! Is there a purpose for this, now that Flask 2.0 is out with support for async views? Yes! Flask's own support for async handlers is very limited, as the application still runs inside a WSGI web server, which severely limits scalability. With aioflask you get a true ASGI application, running in a 100% async environment. WARNING: This is an experiment at this point. Not at all production ready! ## Quick start To use async view functions and other handlers, use the `aioflask` package instead of `flask`. The `aioflask.Flask` class is a subclass of `flask.Flask` that changes a few minor things to help the application run properly under the asyncio loop. In particular, it overrides the following aspects of the application instance: - The `route`, `before_request`, `before_first_request`, `after_request`, `teardown_request`, `teardown_appcontext`, `errorhandler` and `cli.command` decorators accept coroutines as well as regular functions. The handlers all run inside an asyncio loop, so when using regular functions, care must be taken to not block. - The WSGI callable entry point is replaced with an ASGI equivalent. - The `run()` method uses uvicorn as web server. There are also changes outside of the `Flask` class: - The `flask aiorun` command starts an ASGI application using the uvicorn web server. - The `render_template()` and `render_template_string()` functions are asynchronous and must be awaited. - The context managers for the Flask application and request contexts are async. - The test client and test CLI runner use coroutines. ## Example ```python import asyncio from aioflask import Flask, render_template app = Flask(__name__) @app.route('/') async def index(): await asyncio.sleep(1) return await render_template('index.html') ``` <file_sep>/src/aioflask/__init__.py from flask import * from .app import Flask from .templating import render_template, render_template_string from .testing import FlaskClient <file_sep>/tests/test_app.py import asyncio import os import unittest from unittest import mock import aioflask from .utils import async_test class TestApp(unittest.TestCase): @async_test async def test_app(self): app = aioflask.Flask(__name__) @app.route('/async') async def async_route(): await asyncio.sleep(0) assert aioflask.current_app._get_current_object() == app return 'async' @app.route('/sync') def sync_route(): assert aioflask.current_app._get_current_object() == app return 'sync' client = app.test_client() response = await client.get('/async') assert response.data == b'async' response = await client.get('/sync') assert response.data == b'sync' @async_test async def test_g(self): app = aioflask.Flask(__name__) app.secret_key = 'secret' @app.before_request async def async_before_request(): aioflask.g.asyncvar = 'async' @app.before_request def sync_before_request(): aioflask.g.syncvar = 'sync' @app.route('/async') async def async_route(): aioflask.session['a'] = 'async' return f'{aioflask.g.asyncvar}-{aioflask.g.syncvar}' @app.route('/sync') async def sync_route(): aioflask.session['s'] = 'sync' return f'{aioflask.g.asyncvar}-{aioflask.g.syncvar}' @app.route('/session') async def session(): return f'{aioflask.session.get("a")}-{aioflask.session.get("s")}' @app.after_request async def after_request(rv): rv.data += f'/{aioflask.g.asyncvar}-{aioflask.g.syncvar}'.encode() return rv client = app.test_client() response = await client.get('/session') assert response.data == b'None-None/async-sync' response = await client.get('/async') assert response.data == b'async-sync/async-sync' response = await client.get('/session') assert response.data == b'async-None/async-sync' response = await client.get('/sync') assert response.data == b'async-sync/async-sync' response = await client.get('/session') assert response.data == b'async-sync/async-sync' @mock.patch('aioflask.app.uvicorn') def test_app_run(self, uvicorn): app = aioflask.Flask(__name__) app.run() uvicorn.run.assert_called_with('tests.test_app:app', host='127.0.0.1', port=5000, reload=False, workers=1, log_level='info', ssl_certfile=None, ssl_keyfile=None) app.run(host='1.2.3.4', port=3000) uvicorn.run.assert_called_with('tests.test_app:app', host='1.2.3.4', port=3000, reload=False, workers=1, log_level='info', ssl_certfile=None, ssl_keyfile=None) app.run(debug=True) uvicorn.run.assert_called_with('tests.test_app:app', host='127.0.0.1', port=5000, reload=True, workers=1, log_level='debug', ssl_certfile=None, ssl_keyfile=None) app.run(debug=True, use_reloader=False) uvicorn.run.assert_called_with('tests.test_app:app', host='127.0.0.1', port=5000, reload=False, workers=1, log_level='debug', ssl_certfile=None, ssl_keyfile=None) if 'FLASK_DEBUG' in os.environ: del os.environ['FLASK_DEBUG'] if 'AIOFLASK_USE_DEBUGGER' in os.environ: del os.environ['AIOFLASK_USE_DEBUGGER'] <file_sep>/examples/g/app.py from aioflask import Flask, g import aiohttp app = Flask(__name__) @app.before_request async def before_request(): g.session = aiohttp.ClientSession() @app.teardown_appcontext async def teardown_appcontext(exc): await g.session.close() @app.route('/') async def index(): response = await g.session.get('https://api.quotable.io/random') return (await response.json())['content'] <file_sep>/tests/test_templating.py import asyncio import os import unittest from unittest import mock import aioflask from .utils import async_test class TestTemplating(unittest.TestCase): @async_test async def test_template_strng(self): app = aioflask.Flask(__name__) app.secret_key = 'secret' @app.before_request def before_request(): aioflask.g.x = 'foo' aioflask.session['y'] = 'bar' @app.route('/') async def async_route(): return await aioflask.render_template_string( '{{ g.x }}{{ session.y }}') client = app.test_client() response = await client.get('/') assert response.data == b'foobar' @async_test async def test_template(self): app = aioflask.Flask(__name__) app.secret_key = 'secret' @app.before_request def before_request(): aioflask.g.x = 'foo' aioflask.session['y'] = 'bar' @app.route('/') async def async_route(): return await aioflask.render_template('template.html') client = app.test_client() response = await client.get('/') assert response.data == b'foobar' <file_sep>/examples/quotes-requests/quotes_app.py import asyncio from aioflask import Flask, render_template_string from greenletio import async_ import requests app = Flask(__name__) template = '''<!doctype html> <html> <head> <title>Quotes</title> </head> <body> <h1>Quotes</h1> {% for quote in quotes %} <p><i>"{{ quote.content }}"</i> &mdash; {{ quote.author }}</p> {% endfor %} </body> </html>''' # this is a blocking function that is converted to asynchronous with # greenletio's @async_ decorator. For this to work, all the low-level I/O # functions started from this function must be asynchronous, which can be # achieved with greenletio's monkey patching feature. @async_ def get_quote(): response = requests.get('https://api.quotable.io/random') return response.json() @app.route('/') async def index(): tasks = [get_quote() for _ in range(10)] quotes = await asyncio.gather(*tasks) return await render_template_string(template, quotes=quotes) <file_sep>/examples/aioflaskr/.flaskenv FLASK_APP=flaskr:create_app() <file_sep>/src/aioflask/app.py import asyncio from functools import wraps from inspect import iscoroutinefunction import os from flask.app import * from flask.app import Flask as OriginalFlask from flask import cli from flask.globals import _app_ctx_stack, _request_ctx_stack from flask.helpers import get_debug_flag, get_env, get_load_dotenv from greenletio import await_ import uvicorn from .asgi import WsgiToAsgiInstance from .cli import show_server_banner, AppGroup from .ctx import AppContext, RequestContext from .testing import FlaskClient, FlaskCliRunner class Flask(OriginalFlask): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.cli = AppGroup() self.jinja_options['enable_async'] = True self.test_client_class = FlaskClient self.test_cli_runner_class = FlaskCliRunner self.async_fixed = False def ensure_sync(self, func): if not iscoroutinefunction(func): return func def wrapped(*args, **kwargs): appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top async def _coro(): # app context is push internally to avoid changing reference # counts and emitting duplicate signals _app_ctx_stack.push(appctx) if reqctx: _request_ctx_stack.push(reqctx) ret = await func(*args, **kwargs) if reqctx: _request_ctx_stack.pop() _app_ctx_stack.pop() return ret return await_(_coro()) return wrapped def app_context(self): return AppContext(self) def request_context(self, environ): return RequestContext(self, environ) def _fix_async(self): # pragma: no cover self.async_fixed = True if os.environ.get('AIOFLASK_USE_DEBUGGER') == 'true': os.environ['WERKZEUG_RUN_MAIN'] = 'true' from werkzeug.debug import DebuggedApplication self.wsgi_app = DebuggedApplication(self.wsgi_app, evalex=True) async def asgi_app(self, scope, receive, send): # pragma: no cover if not self.async_fixed: self._fix_async() return await WsgiToAsgiInstance(self.wsgi_app)(scope, receive, send) async def __call__(self, scope, receive, send=None): # pragma: no cover if send is None: # we were called with two arguments, so this is likely a WSGI app raise RuntimeError('The WSGI interface is not supported by ' 'aioflask, use an ASGI web server instead.') return await self.asgi_app(scope, receive, send) def run(self, host=None, port=None, debug=None, load_dotenv=True, **options): if get_load_dotenv(load_dotenv): cli.load_dotenv() # if set, let env vars override previous values if "FLASK_ENV" in os.environ: self.env = get_env() self.debug = get_debug_flag() elif "FLASK_DEBUG" in os.environ: self.debug = get_debug_flag() # debug passed to method overrides all other sources if debug is not None: self.debug = bool(debug) server_name = self.config.get("SERVER_NAME") sn_host = sn_port = None if server_name: sn_host, _, sn_port = server_name.partition(":") if not host: if sn_host: host = sn_host else: host = "127.0.0.1" if port or port == 0: port = int(port) elif sn_port: port = int(sn_port) else: port = 5000 options.setdefault("use_reloader", self.debug) options.setdefault("use_debugger", self.debug) options.setdefault("threaded", True) options.setdefault("workers", 1) certfile = None keyfile = None cert = options.get('ssl_context') if cert is not None and len(cert) == 2: certfile = cert[0] keyfile = cert[1] elif cert == 'adhoc': raise RuntimeError( 'Aad-hoc certificates are not supported by aioflask.') if debug: os.environ['FLASK_DEBUG'] = 'true' if options['use_debugger']: os.environ['AIOFLASK_USE_DEBUGGER'] = 'true' show_server_banner(self.env, self.debug, self.name, False) uvicorn.run( self.import_name + ':app', host=host, port=port, reload=options['use_reloader'], workers=options['workers'], log_level='debug' if self.debug else 'info', ssl_certfile=certfile, ssl_keyfile=keyfile, ) <file_sep>/src/aioflask/patch.py from functools import wraps from aioflask import current_app def patch_decorator(decorator): def patched_decorator(f): @wraps(f) def ensure_sync(*a, **kw): return current_app.ensure_sync(f)(*a, **kw) return decorator(ensure_sync) return patched_decorator def patch_decorator_with_args(decorator): def patched_decorator(*args, **kwargs): def inner_patched_decorator(f): @wraps(f) def ensure_sync(*a, **kw): return current_app.ensure_sync(f)(*a, **kw) return decorator(*args, **kwargs)(ensure_sync) return inner_patched_decorator return patched_decorator def patch_decorator_method(class_, method_name): original_decorator = getattr(class_, method_name) def patched_decorator_method(self, f): @wraps(f) def ensure_sync(*a, **kw): return current_app.ensure_sync(f)(*a, **kw) return original_decorator(self, ensure_sync) return patched_decorator_method def patch_decorator_method_with_args(class_, method_name): original_decorator = getattr(class_, method_name) def patched_decorator_method(self, *args, **kwargs): def inner_patched_decorator_method(f): @wraps(f) def ensure_sync(*a, **kw): return current_app.ensure_sync(f)(*a, **kw) return original_decorator(self, *args, **kwargs)(ensure_sync) return inner_patched_decorator_method return patched_decorator_method <file_sep>/tox.ini [tox] envlist=flake8,,py37,py38,py39,py310,pypy3,docs skip_missing_interpreters=True [gh-actions] python = 3.7: py37 3.8: py38 3.9: py39 3.10: py310 pypy3: pypy-3 [testenv] commands= pip install -e . pytest -p no:logging --cov=src/aioflask --cov-branch examples/aioflaskr/tests pytest -p no:logging --cov=src/aioflask --cov-branch --cov-report=term-missing --cov-report=xml --cov-append tests deps= aiosqlite greenletio alchemical flask-login pytest pytest-asyncio pytest-cov [testenv:flake8] deps= flake8 commands= flake8 --ignore=F401,F403 --exclude=".*" src/aioflask tests [testenv:docs] changedir=docs deps= sphinx whitelist_externals= make commands= make html <file_sep>/examples/aioflaskr/tests/test_blog.py import pytest from sqlalchemy import func from sqlalchemy import select from flaskr import db from flaskr.models import User from flaskr.models import Post @pytest.mark.asyncio async def test_index(client, auth): response = await client.get("/") assert b"Log In" in response.data assert b"Register" in response.data await auth.login() response = await client.get("/") assert b"test title" in response.data assert b"by test on 2018-01-01" in response.data assert b"test\nbody" in response.data assert b'href="/1/update"' in response.data @pytest.mark.asyncio @pytest.mark.parametrize("path", ("/create", "/1/update", "/1/delete")) async def test_login_required(client, path): response = await client.post(path) assert response.headers["Location"].startswith("/auth/login?next=") @pytest.mark.asyncio async def test_author_required(app, client, auth): # change the post author to another user async with app.app_context(): (await db.session.get(Post, 1)).author = await db.session.get(User, 2) await db.session.commit() await auth.login() # current user can't modify other user's post assert (await client.post("/1/update")).status_code == 403 assert (await client.post("/1/delete")).status_code == 403 # current user doesn't see edit link assert b'href="/1/update"' not in (await client.get("/")).data @pytest.mark.asyncio @pytest.mark.parametrize("path", ("/2/update", "/2/delete")) async def test_exists_required(client, auth, path): await auth.login() assert (await client.post(path)).status_code == 404 @pytest.mark.asyncio async def test_create(client, auth, app): await auth.login() assert (await client.get("/create")).status_code == 200 await client.post("/create", data={"title": "created", "body": ""}) async with app.app_context(): query = select(func.count()).select_from(Post) assert await db.session.scalar(query) == 2 @pytest.mark.asyncio async def test_update(client, auth, app): await auth.login() assert (await client.get("/1/update")).status_code == 200 await client.post("/1/update", data={"title": "updated", "body": ""}) async with app.app_context(): assert (await db.session.get(Post, 1)).title == "updated" @pytest.mark.asyncio @pytest.mark.parametrize("path", ("/create", "/1/update")) async def test_create_update_validate(client, auth, path): await auth.login() response = await client.post(path, data={"title": "", "body": ""}) assert b"Title is required." in response.data @pytest.mark.asyncio async def test_delete(client, auth, app): await auth.login() response = await client.post("/1/delete") assert response.headers["Location"] == "/" async with app.app_context(): assert (await db.session.get(Post, 1)) is None <file_sep>/examples/quotes-requests/quotes.py import greenletio # import the application with blocking functions monkey patched with greenletio.patch_blocking(): from quotes_app import app <file_sep>/tests/test_ctx.py import unittest import pytest import aioflask from .utils import async_test class TestApp(unittest.TestCase): @async_test async def test_app_context(self): app = aioflask.Flask(__name__) called_t1 = False called_t2 = False @app.teardown_appcontext async def t1(exc): nonlocal called_t1 called_t1 = True @app.teardown_appcontext def t2(exc): nonlocal called_t2 called_t2 = True async with app.app_context(): assert aioflask.current_app == app async with app.app_context(): assert aioflask.current_app == app assert aioflask.current_app == app assert called_t1 assert called_t2 with pytest.raises(RuntimeError): print(aioflask.current_app) @async_test async def test_req_context(self): app = aioflask.Flask(__name__) called_t1 = False called_t2 = False @app.teardown_appcontext async def t1(exc): nonlocal called_t1 called_t1 = True @app.teardown_appcontext def t2(exc): nonlocal called_t2 called_t2 = True async with app.test_request_context('/foo'): assert aioflask.current_app == app assert aioflask.request.path == '/foo' assert called_t1 assert called_t2 async with app.app_context(): async with app.test_request_context('/bar') as reqctx: assert aioflask.current_app == app assert aioflask.request.path == '/bar' async with reqctx: assert aioflask.current_app == app assert aioflask.request.path == '/bar' with pytest.raises(RuntimeError): print(aioflask.current_app) <file_sep>/examples/aioflaskr/requirements.txt aioflask aiosqlite==0.17.0 alchemical asgiref==3.4.1 click==8.0.1 Flask==2.0.1 Flask-Login==0.5.0 greenlet==1.1.1 greenletio h11==0.12.0 importlib-metadata==4.6.3 itsdangerous==2.0.1 Jinja2==3.0.1 MarkupSafe==2.0.1 python-dotenv==0.19.0 SQLAlchemy==1.4.25 typing-extensions==3.10.0.0 uvicorn==0.14.0 Werkzeug==2.0.1 zipp==3.5.0 <file_sep>/examples/aioflaskr/README.md aioflaskr ========= This is the "Flaskr" application from the tutorial section of the Flask documentation, adapted to work as an asyncio application with aioflask as the web framework and Alchemical for its database. The Flask-Login extension is used to maintain the logged in state of the user. Install ------- ```bash # clone the repository $ git clone https://github.com/miguelgrinberg/aioflask $ cd aioflask/examples/aioflaskr ``` Create a virtualenv and activate it: ```bash $ python3 -m venv venv $ . venv/bin/activate ``` Or on Windows cmd: ```text $ py -3 -m venv venv $ venv\Scripts\activate.bat ``` Install the requirements ```bash $ pip install -r requirements.txt ``` Run --- ```bash flask init-db flask aiorun ``` Open http://127.0.0.1:5000 in a browser. Test ---- ```bash $ pip install pytest pytest-asyncio $ python -m pytest ``` Run with coverage report: ```bash $ pip install pytest-cov $ python -m pytest --cov=flaskr --cov-branch --cov-report=term-missing ``` <file_sep>/examples/aioflaskr/flaskr/auth.py from aioflask import Blueprint from aioflask import flash from aioflask import redirect from aioflask import render_template from aioflask import request from aioflask import url_for from aioflask.patched.flask_login import login_user from aioflask.patched.flask_login import logout_user from sqlalchemy.exc import IntegrityError from flaskr import db, login from flaskr.models import User bp = Blueprint("auth", __name__, url_prefix="/auth") @login.user_loader async def load_user(id): return await db.session.get(User, int(id)) @bp.route("/register", methods=("GET", "POST")) async def register(): """Register a new user. Validates that the username is not already taken. Hashes the password for security. """ if request.method == "POST": username = request.form["username"] password = request.form["password"] error = None if not username: error = "Username is required." elif not password: error = "Password is required." if error is None: try: db.session.add(User(username=username, password=<PASSWORD>)) await db.session.commit() except IntegrityError: # The username was already taken, which caused the # commit to fail. Show a validation error. error = f"User {username} is already registered." else: # Success, go to the login page. return redirect(url_for("auth.login")) flash(error) return await render_template("auth/register.html") @bp.route("/login", methods=("GET", "POST")) async def login(): """Log in a registered user by adding the user id to the session.""" if request.method == "POST": username = request.form["username"] password = request.form["password"] error = None query = User.select().filter_by(username=username) user = await db.session.scalar(query) if user is None: error = "Incorrect username." elif not user.check_password(password): error = "Incorrect password." if error is None: # store the user id in a new session and return to the index login_user(user) return redirect(url_for("index")) flash(error) return await render_template("auth/login.html") @bp.route("/logout") async def logout(): """Clear the current session, including the stored user id.""" logout_user() return redirect(url_for("index")) <file_sep>/src/aioflask/patched/flask_login/__init__.py from functools import wraps import sys from werkzeug.local import LocalProxy from aioflask import current_app, g from flask import _request_ctx_stack from aioflask.patch import patch_decorator, patch_decorator_method import flask_login from flask_login import login_required, fresh_login_required, \ LoginManager as OriginalLoginManager for symbol in flask_login.__all__: try: globals()[symbol] = getattr(flask_login, symbol) except AttributeError: pass def _user_context_processor(): return {'current_user': _get_user()} def _load_user(): # Obtain the current user and preserve it in the g object. Flask-Login # saves the user in a custom attribute of the request context, but that # doesn't work with aioflask because when a copy of the request context is # made, custom attributes are not carried over to the copy. current_app.login_manager._load_user() g.flask_login_current_user = _request_ctx_stack.top.user def _get_user(): # Return the current user. This function is linked to the current_user # context local, but unlike the original in Flask-Login, it does not # attempt to load the user, it just returns the user that was pre-loaded. # This avoids the somewhat tricky complication of triggering database # operations that need to be awaited, which would require using something # like (await current_user) if hasattr(g, 'flask_login_current_user'): return g.flask_login_current_user return current_app.login_manager.anonymous_user() class LoginManager(OriginalLoginManager): def init_app(self, app, add_context_processor=True): super().init_app(app, add_context_processor=False) if add_context_processor: app.context_processor(_user_context_processor) # To prevent the current_user context local from triggering I/O at a # random time when it is first referenced (which is a big complication # if the I/O is async and needs to be awaited), we force the user to be # loaded before each request. This isn't a perfect solution, because # a before request handler registered before this one will not see the # current user. app.before_request(_load_user) # the decorators that register callbacks need to be patched to support # async views user_loader = patch_decorator_method(OriginalLoginManager, 'user_loader') header_loader = patch_decorator_method( OriginalLoginManager, 'header_loader') request_loader = patch_decorator_method( OriginalLoginManager, 'request_loader') unauthorized_handler = patch_decorator_method( OriginalLoginManager, 'unauthorized_handler') needs_refresh_handler = patch_decorator_method( OriginalLoginManager, 'needs_refresh_handler') # patch the two login_required decorators so that they accept async views login_required = patch_decorator(login_required) fresh_login_required = patch_decorator(fresh_login_required) # redefine the current_user context local current_user = LocalProxy(_get_user) # patch the _get_user() function in the flask_login.utils module so that any # calls to get current_user in Flask-Login functions are redirected here setattr(sys.modules['flask_login.utils'], '_get_user', _get_user) <file_sep>/examples/aioflaskr/tests/test_auth.py import pytest from flaskr import db from flaskr.models import User @pytest.mark.asyncio async def test_register(client, app): # test that viewing the page renders without template errors assert (await client.get("/auth/register")).status_code == 200 # test that successful registration redirects to the login page response = await client.post("/auth/register", data={"username": "a", "password": "a"}) assert "/auth/login" == response.headers["Location"] # test that the user was inserted into the database async with app.app_context(): query = User.select().filter_by(username="a") assert await db.session.scalar(query) is not None def test_user_password(app): user = User(username="a", password="a") assert user.password_hash != "a" assert user.check_password("a") @pytest.mark.asyncio @pytest.mark.parametrize( ("username", "password", "message"), ( ("", "", b"Username is required."), ("a", "", b"Password is required."), ("test", "test", b"already registered"), ), ) async def test_register_validate_input(client, username, password, message): response = await client.post( "/auth/register", data={"username": username, "password": password} ) assert message in response.data @pytest.mark.asyncio async def test_login(client, auth): # test that viewing the page renders without template errors assert (await client.get("/auth/login")).status_code == 200 # test that successful login redirects to the index page response = await auth.login() assert response.headers["Location"] == "/" # login request set the user_id in the session # check that the user is loaded from the session async with client: response = await client.get("/") assert b"<span>test</span>" in response.data @pytest.mark.asyncio @pytest.mark.parametrize( ("username", "password", "message"), (("a", "test", b"Incorrect username."), ("test", "a", b"Incorrect password.")), ) async def test_login_validate_input(auth, username, password, message): response = await auth.login(username, password) assert message in response.data @pytest.mark.asyncio async def test_logout(client, auth): await auth.login() async with client: await auth.logout() response = await client.get("/") assert b"Log In" in response.data <file_sep>/examples/aioflaskr/flaskr/__init__.py import os import click from aioflask import Flask from aioflask.cli import with_appcontext from alchemical.aioflask import Alchemical from aioflask.patched.flask_login import LoginManager db = Alchemical() login = LoginManager() login.login_view = 'auth.login' def create_app(test_config=None): """Create and configure an instance of the Flask application.""" app = Flask(__name__, instance_relative_config=True) # some deploy systems set the database url in the environ db_url = os.environ.get("DATABASE_URL") if db_url is None: # default to a sqlite database in the instance folder db_path = os.path.join(app.instance_path, "flaskr.sqlite") db_url = f"sqlite:///{db_path}" # ensure the instance folder exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( SECRET_KEY=os.environ.get("SECRET_KEY", "dev"), ALCHEMICAL_DATABASE_URL=db_url, ) if test_config is None: # load the instance config, if it exists, when not testing app.config.from_pyfile("config.py", silent=True) else: # load the test config if passed in app.config.update(test_config) # initialize Flask-Alchemical and the init-db command db.init_app(app) app.cli.add_command(init_db_command) # initialize Flask-Login login.init_app(app) # apply the blueprints to the app from flaskr import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make "index" point at "/", which is handled by "blog.index" app.add_url_rule("/", endpoint="index") return app async def init_db(): await db.drop_all() await db.create_all() @click.command("init-db") @with_appcontext async def init_db_command(): """Clear existing data and create new tables.""" await init_db() click.echo("Initialized the database.") <file_sep>/examples/login/app.py from aioflask import Flask, request, redirect from aioflask.patched.flask_login import LoginManager, login_required, UserMixin, login_user, logout_user, current_user import aiohttp app = Flask(__name__) app.secret_key = 'top-secret!' login = LoginManager(app) login.login_view = 'login' class User(UserMixin): def __init__(self, user_id): self.id = user_id @login.user_loader async def load_user(user_id): return User(user_id) @app.route('/') @login_required async def index(): return f''' <html> <body> <p>Logged in user: {current_user.id}</p> <form method="POST" action="/logout"> <input type="submit" value="Logout"> </form> </body> </html>''' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'GET': return ''' <html> <body> <form method="POST" action=""> <input type="text" name="username"> <input type="submit" value="Login"> </form> </body> </html>''' else: login_user(User(request.form['username'])) return redirect(request.args.get('next', '/')) @app.route('/logout', methods=['POST']) def logout(): logout_user() return redirect('/') <file_sep>/examples/aioflaskr/flaskr/models.py from werkzeug.security import check_password_hash from werkzeug.security import generate_password_hash from aioflask import url_for from aioflask.patched.flask_login import UserMixin from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, func from sqlalchemy.orm import relationship from flaskr import db class User(UserMixin, db.Model): id = Column(Integer, primary_key=True) username = Column(String, unique=True, nullable=False) password_hash = Column(String, nullable=False) @property def password(self): raise RuntimeError('Cannot get user passwords!') @password.setter def password(self, value): """Store the password as a hash for security.""" self.password_hash = generate_password_hash(value) def check_password(self, value): return check_password_hash(self.password_hash, value) class Post(db.Model): id = Column(Integer, primary_key=True) author_id = Column(ForeignKey(User.id), nullable=False) created = Column( DateTime, nullable=False, server_default=func.current_timestamp() ) title = Column(String, nullable=False) body = Column(String, nullable=False) # User object backed by author_id # lazy="joined" means the user is returned with the post in one query author = relationship(User, lazy="joined", backref="posts") @property def update_url(self): return url_for("blog.update", id=self.id) @property def delete_url(self): return url_for("blog.delete", id=self.id) <file_sep>/examples/hello_world/app.py from aioflask import Flask, render_template app = Flask(__name__) @app.route('/') async def index(): return await render_template('index.html') @app.cli.command() async def hello(): """Example async CLI handler.""" print('hello!') <file_sep>/examples/quotes-aiohttp/quotes.py import asyncio import aiohttp from aioflask import Flask, render_template_string app = Flask(__name__) template = '''<!doctype html> <html> <head> <title>Quotes</title> </head> <body> <h1>Quotes</h1> {% for quote in quotes %} <p><i>"{{ quote.content }}"</i> &mdash; {{ quote.author }}</p> {% endfor %} </body> </html>''' async def get_quote(session): response = await session.get('https://api.quotable.io/random') return await response.json() @app.route('/') async def index(): async with aiohttp.ClientSession() as session: tasks = [get_quote(session) for _ in range(10)] quotes = await asyncio.gather(*tasks) return await render_template_string(template, quotes=quotes) <file_sep>/examples/quotes-requests/README.md Quotes ====== Returns 10 famous quotes each time the page is refreshed. Quotes are obtained by sending concurrent HTTP requests to a Quotes API with the requests client. This example shows how you can incorporate blocking code into your aioflask application without blocking the asyncio loop. To run this example, set `FLASK_APP=quotes.py` in your environment and then use the standard `flask aiorun` command to start the server. <file_sep>/src/aioflask/templating.py from flask.templating import * from flask.templating import _app_ctx_stack, before_render_template, \ template_rendered async def _render(template, context, app): """Renders the template and fires the signal""" before_render_template.send(app, template=template, context=context) rv = await template.render_async(context) template_rendered.send(app, template=template, context=context) return rv async def render_template(template_name_or_list, **context): """Renders a template from the template folder with the given context. :param template_name_or_list: the name of the template to be rendered, or an iterable with template names the first one existing will be rendered :param context: the variables that should be available in the context of the template. """ ctx = _app_ctx_stack.top ctx.app.update_template_context(context) return await _render( ctx.app.jinja_env.get_or_select_template(template_name_or_list), context, ctx.app, ) async def render_template_string(source, **context): """Renders a template from the given template source string with the given context. Template variables will be autoescaped. :param source: the source code of the template to be rendered :param context: the variables that should be available in the context of the template. """ ctx = _app_ctx_stack.top ctx.app.update_template_context(context) return await _render(ctx.app.jinja_env.from_string(source), context, ctx.app) <file_sep>/examples/AsyncProgressBar/README.md AsyncProgressBar ================ This is the *AsyncProgressBar* from Quart ported to Flask. You need to have a Redis server running on localhost:6379 for this example to run. <file_sep>/tests/test_patch.py import unittest import aioflask import aioflask.patch from .utils import async_test class TestPatch(unittest.TestCase): @async_test async def test_decorator(self): def foo(f): def decorator(*args, **kwargs): return f(*args, **kwargs) + '-decorated' return decorator foo = aioflask.patch.patch_decorator(foo) app = aioflask.Flask(__name__) @app.route('/abc/<int:id>') @foo async def abc(id): return str(id) client = app.test_client() response = await client.get('/abc/123') assert response.data == b'123-decorated' @async_test async def test_decorator_with_args(self): def foo(value): def inner_foo(f): def decorator(*args, **kwargs): return f(*args, **kwargs) + str(value) return decorator return inner_foo foo = aioflask.patch.patch_decorator_with_args(foo) app = aioflask.Flask(__name__) @app.route('/abc/<int:id>') @foo(456) async def abc(id): return str(id) client = app.test_client() response = await client.get('/abc/123') assert response.data == b'123456' @async_test async def test_decorator_method(self): class Foo: def __init__(self, value): self.value = value def deco(self, f): def decorator(*args, **kwargs): return f(*args, **kwargs) + str(self.value) return decorator Foo.deco = aioflask.patch.patch_decorator_method(Foo, 'deco') app = aioflask.Flask(__name__) foo = Foo(456) @app.route('/abc/<int:id>') @foo.deco async def abc(id): return str(id) client = app.test_client() response = await client.get('/abc/123') assert response.data == b'123456' @async_test async def test_decorator_method_with_args(self): class Foo: def __init__(self, value): self.value = value def deco(self, value2): def decorator(f): def inner_decorator(*args, **kwargs): return f(*args, **kwargs) + str(self.value) + \ str(value2) return inner_decorator return decorator Foo.deco = aioflask.patch.patch_decorator_method_with_args(Foo, 'deco') app = aioflask.Flask(__name__) foo = Foo(456) @app.route('/abc/<int:id>') @foo.deco(789) async def abc(id): return str(id) client = app.test_client() response = await client.get('/abc/123') assert response.data == b'123456789' <file_sep>/examples/aioflaskr/tests/test_init.py import pytest from flaskr import create_app def test_config(): """Test create_app without passing test config.""" assert not create_app().testing assert create_app({"TESTING": True}).testing def test_db_url_environ(monkeypatch): """Test DATABASE_URL environment variable.""" monkeypatch.setenv("DATABASE_URL", "sqlite:///environ") app = create_app() assert app.config["ALCHEMICAL_DATABASE_URL"] == "sqlite:///environ" @pytest.mark.asyncio async def test_init_db_command(runner, monkeypatch): class Recorder: called = False async def fake_init_db(): Recorder.called = True monkeypatch.setattr("flaskr.init_db", fake_init_db) result = await runner.invoke(args=["init-db"]) assert "Initialized" in result.output assert Recorder.called <file_sep>/tests/test_cli.py import os import unittest from unittest import mock import click from click.testing import CliRunner import aioflask import aioflask.cli from .utils import async_test class TestCli(unittest.TestCase): @async_test async def test_command_with_appcontext(self): app = aioflask.Flask('testapp') @app.cli.command(with_appcontext=True) async def testcmd(): click.echo(aioflask.current_app.name) result = await app.test_cli_runner().invoke(testcmd) assert result.exit_code == 0 assert result.output == "testapp\n" @async_test async def test_command_without_appcontext(self): app = aioflask.Flask('testapp') @app.cli.command(with_appcontext=False) async def testcmd(): click.echo(aioflask.current_app.name) result = await app.test_cli_runner().invoke(testcmd) assert result.exit_code == 1 assert type(result.exception) == RuntimeError @async_test async def test_with_appcontext(self): @click.command() @aioflask.cli.with_appcontext async def testcmd(): click.echo(aioflask.current_app.name) app = aioflask.Flask('testapp') result = await app.test_cli_runner().invoke(testcmd) assert result.exit_code == 0 assert result.output == "testapp\n" @mock.patch('aioflask.cli.uvicorn') def test_aiorun(self, uvicorn): app = aioflask.Flask('testapp') obj = aioflask.cli.ScriptInfo(app_import_path='app.py', create_app=lambda: app) result = CliRunner().invoke(aioflask.cli.run_command, obj=obj) assert result.exit_code == 0 uvicorn.run.assert_called_with('app:app', factory=False, host='127.0.0.1', port=5000, reload=False, workers=1, log_level='info', ssl_certfile=None, ssl_keyfile=None) result = CliRunner().invoke(aioflask.cli.run_command, '--host 1.2.3.4 --port 3000', obj=obj) assert result.exit_code == 0 uvicorn.run.assert_called_with('app:app', factory=False, host='1.2.3.4', port=3000, reload=False, workers=1, log_level='info', ssl_certfile=None, ssl_keyfile=None) os.environ['FLASK_DEBUG'] = 'true' result = CliRunner().invoke(aioflask.cli.run_command, obj=obj) assert result.exit_code == 0 uvicorn.run.assert_called_with('app:app', factory=False, host='127.0.0.1', port=5000, reload=True, workers=1, log_level='debug', ssl_certfile=None, ssl_keyfile=None) os.environ['FLASK_DEBUG'] = 'true' result = CliRunner().invoke(aioflask.cli.run_command, '--no-reload', obj=obj) assert result.exit_code == 0 uvicorn.run.assert_called_with('app:app', factory=False, host='127.0.0.1', port=5000, reload=False, workers=1, log_level='debug', ssl_certfile=None, ssl_keyfile=None) if 'FLASK_DEBUG' in os.environ: del os.environ['FLASK_DEBUG'] if 'AIOFLASK_USE_DEBUGGER' in os.environ: del os.environ['AIOFLASK_USE_DEBUGGER'] @mock.patch('aioflask.cli.uvicorn') def test_aiorun_with_factory(self, uvicorn): app = aioflask.Flask('testapp') obj = aioflask.cli.ScriptInfo(app_import_path='app:create_app()', create_app=lambda: app) result = CliRunner().invoke(aioflask.cli.run_command, obj=obj) assert result.exit_code == 0 uvicorn.run.assert_called_with('app:create_app', factory=True, host='127.0.0.1', port=5000, reload=False, workers=1, log_level='info', ssl_certfile=None, ssl_keyfile=None)
38d8a72059f2c364ba4cc8844d7ed4e3ae4829b8
[ "Markdown", "INI", "Python", "Text", "Shell" ]
36
Python
miguelgrinberg/aioflask
7f447e79c81ce7ca46edc5f5852845ff9806ce6a
9d14c06747e13d4d12aabe61254e48e91860c4dd
refs/heads/master
<file_sep>{ init: function(elevators, floors) { var NUM_ELEVATORS = elevators.length; var NUM_FLOORS = floors.length - 1; var IDLE_ELEVS = []; const OK_LOAD_FACTOR = 0.7; function dedup(arr) { let s = new Set(arr); let it = s.values(); return Array.from(it); } function remove_item_from_arr(arr, item) { for(var i = arr.length - 1; i >= 0; i--) { if(arr[i] === item) { arr.splice(i, 1); } } } function cleanUpDQ(elevator) { var elev_index = elevators.indexOf(elevator); var dq = elevator.destinationQueue; dq.forEach(function(floorNum) { // Check if someone's still waiting on each floor of the DQ // if neither button is activated on the floor, then remove it from the DQ (some other elevator must have serviced it earlier) var floor = floors[floorNum]; if(!floor.buttonStates.down == "activated" && !floor.buttonStates.up == "activated") { var pressedFloors = elevator.getPressedFloors(); if(!pressedFloors.includes(floorNum)) {// only remove a floorNum if it's not a number pressed inside the elevator console.log(` [cleanUpDQ ELEV ${elev_index}] Remove floor ${floorNum}`); remove_item_from_arr(dq, floorNum); } } }); console.log(`[cleanUpDQ ELEV ${elev_index}] DQ after cleanup: ${dq}`); elevator.destinationQueue = dq; elevator.checkDestinationQueue(); // enforce new DQ } function newDirectionAfterStopping(elevator) { var elev_index = elevators.indexOf(elevator); var curFloor = elevator.currentFloor(); // decide direction based on next floor from the DQ // get next floor from the list of pressed floors in the elevator, that is NEAREST to current floor pressedFloors = elevator.getPressedFloors(); if (pressedFloors.length > 0) { var closestFloor = pressedFloors.reduce(function(prev, curr) { return (Math.abs(curr - curFloor) < Math.abs(prev - curFloor) ? curr : prev); }); if(closestFloor - curFloor > 0) { // closestFloor is above currentFloor, going UP console.log(`[nDAS:Elev${elev_index}] stopped at:${curFloor}. Going UP to pressedFloor:${closestFloor}`); elevator.goingDownIndicator(false); elevator.goingUpIndicator(true); } else { console.log(`[nDAS:Elev${elev_index}] stopped at:${curFloor}. Going DOWN to pressedFloor:${closestFloor}`); elevator.goingDownIndicator(true); elevator.goingUpIndicator(false); } } // if there are no pressed floors (no one in elevator), then try to use next elem in DQ to decide direction else if (elevator.destinationQueue.length > 0) { var nextFloorNum = elevator.destinationQueue[0]; if(nextFloorNum - curFloor > 0) { // nextFloorNum is above currentFloor, going UP console.log(`[nDAS:Elev${elev_index}] stopped at:${curFloor}. Going UP from DQ to:${nextFloorNum}`); elevator.goingDownIndicator(false); elevator.goingUpIndicator(true); } else { console.log(`[nDAS:Elev${elev_index}] stopped at:${curFloor}. Going DOWN from DQ to:${nextFloorNum}`); elevator.goingDownIndicator(true); elevator.goingUpIndicator(false); } } else { // no pressed floors, no destination queue: go IDLE! console.log(`[nDAS:Elev${elev_index}] Go IDLE and turn BOTH indicators on!`); if (!IDLE_ELEVS.includes(elevator)) { IDLE_ELEVS.push(elevator); console.log(`[IDLE_ELEVS] length: ${IDLE_ELEVS.length}`); } // can't decide direction: at least set both indicators on, so that the lift is more usable elevator.goingDownIndicator(true); elevator.goingUpIndicator(true); } } function directionAndSort(elevator) { var elev_index = elevators.indexOf(elevator); // console.log("destinationDirection: " + elevator.destinationDirection()); if(elevator.destinationDirection() == "up") { console.log(`[directionAndSort] Elev ${elev_index} going up, hence sorting DQ asc`); elevator.goingDownIndicator(false); elevator.goingUpIndicator(true); } else if(elevator.destinationDirection() == "down") { console.log(`[directionAndSort] Elev ${elev_index} going down, hence sorting DQ desc`); elevator.goingDownIndicator(true); elevator.goingUpIndicator(false); } else if(elevator.destinationDirection() == "stopped") { newDirectionAfterStopping(elevator); } else { console.error("ERROR: directionAndSort: destinationDirection invalid"); } } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } function getSuitableElevator(floor) { // get nearest eligible elevator to the target floor, that also has least load factor var eligible_elevs = []; var elev_floors = []; var floor_number = floor.floorNum(); // prioritize idle elevators if (IDLE_ELEVS.length > 0) { chosen_elevator = IDLE_ELEVS.shift(); var chosen_elevator_index = elevators.indexOf(chosen_elevator); console.log(`[gSE:floor${floor_number}] choosing IDLE elev: ${chosen_elevator_index}`); console.log(`[IDLE_ELEVS] length decremented: ${IDLE_ELEVS.length}`); return chosen_elevator; } // get 'eligible' elevators: that have < OK_LOAD_FACTOR elevators.forEach(function(elevator) { if(elevator.loadFactor() < OK_LOAD_FACTOR) { eligible_elevs.push(elevator); } }); if (eligible_elevs.length > 0) { eligible_elevs.forEach(function(elevator) { // get elevator floors elev_floors.push(elevator.currentFloor()); }); console.log(`[gSE:floor${floor_number}] eligible elevs are on floors: ${elev_floors}`); var closestElevFloor = elev_floors.reduce(function(prev, curr) { return (Math.abs(curr - floor_number) < Math.abs(prev - floor_number) ? curr : prev); }); var chosen_elevator_index = elev_floors.indexOf(closestElevFloor); var chosen_elevator = eligible_elevs[chosen_elevator_index]; var overall_elev_index = elevators.indexOf(chosen_elevator); console.log(`[gSE:floor${floor_number}] closest suitable elevator (${overall_elev_index}) is on floor: ${closestElevFloor}`); return chosen_elevator; } else { console.log(`[gSE:floor${floor_number}] [WARN] Could NOT find suitable elevator for floor ${floor_number}`); return null; } } function handleFloorCall(floor, floor_num){ // pick most suitable elevator to service this request var elev = getSuitableElevator(floor); var chosen_elev_index; if(elev) { // if a suitable elev could be found chosen_elev_index = elevators.indexOf(elev); // if(elev.currentFloor() != floor_num) { //only enqueue if not already on the target floor elev.goToFloor(floor_num); // enqueue the floor elev.destinationQueue = dedup(elev.destinationQueue); cleanUpDQ(elev); // remove floors where no one's waiting any more, from DQ elev.checkDestinationQueue(); // enforce new DQ console.log(`[FLOOR ${floor_num} BUTTON] Elev ${chosen_elev_index} DQ after handleFloorCall(): ${elev.destinationQueue}`); // } } else { // Ignore impatient floor button presses console.log(`[FLOOR ${floor_num} BUTTON] Couldn't find suitable elevator! IGNORE floor request!`); } } floors.forEach(function(floor) { // initialize all floors with handlers var floor_num = floor.floorNum(); console.log(`Setting up floor ${floor_num} ...`); floor.on("up_button_pressed", function(floor) { console.log(`[FLOOR ${floor_num} BUTTON] UP button pressed`); handleFloorCall(floor, floor_num); }); floor.on("down_button_pressed", function(floor) { console.log(`[FLOOR ${floor_num} BUTTON] DOWN button pressed`); handleFloorCall(floor, floor_num); }); }); /* SETUP ELEVATORS */ elevators.forEach(function(elevator) { // Setup all elevators var this_elev_index = elevators.indexOf(elevator); console.log(`Setting up elevator ${this_elev_index} ...`); // Whenever the elevator is idle (has no more queued destinations) ... elevator.on("idle", function() { console.log(`[ELEV ${this_elev_index}] OnIDLE! DQ: ${elevator.destinationQueue}`); elevator.goingDownIndicator(true); elevator.goingUpIndicator(true); // nearestActiveFloor = getNearestActiveFloor(elevator); if (!IDLE_ELEVS.includes(elevator)) { IDLE_ELEVS.push(elevator); console.log(`[IDLE_ELEVS] OnIDLE: Pushed elev to IDLE_ELEVS, length: ${IDLE_ELEVS.length}`); } else console.log(`[IDLE_ELEVS] OnIDLE: Didn't push elev to IDLE_ELEVS, length: ${IDLE_ELEVS.length}`); }); elevator.on("floor_button_pressed", function(floorNum) { // button was pressed INSIDE the elevator, not a "floor button"!! console.log(`[ELEV ${this_elev_index} BUTTON]: Pressed floor ${floorNum}.`); elevator.goToFloor(floorNum); directionAndSort(elevator); // this can make an elevator go idle again: darn // if this elevator is in IDLE_ELEVS, remove from IDLE_ELEVS remove_item_from_arr(IDLE_ELEVS, elevator); console.log(`[ELEV ${this_elev_index} BUTTON]: Leaving. DQ now: ${elevator.destinationQueue}`); console.log(`[ELEV ${this_elev_index} BUTTON]: removed elev from IDLE_ELEVS, length: ${IDLE_ELEVS.length}`); }); elevator.on("passing_floor", function(floorNum, direction) { var passing_floor = floors[floorNum]; var pressedFloors = elevator.getPressedFloors(); // Clean up DQ: remove unnecessary floors where no one's waiting any more cleanUpDQ(elevator); // if passing by a floor that has been 'pressed', always stop on it if(pressedFloors.includes(floorNum)) { // if the passing floor is ON the stop list of "PressedFloors" console.log(`[ELEV ${this_elev_index} PASSING ${floorNum}] STOP at pressed floor: ${floorNum}`); elevator.goToFloor(floorNum, true); // Do it before anything else console.log(`[ELEV ${this_elev_index} PASSING ${floorNum}] DQ is now: ${elevator.destinationQueue}`); } // decide if we want to pick up additional passengers on a passing floor else if(elevator.loadFactor() < OK_LOAD_FACTOR) { // if there's still space in the elevator console.log(`[ELEV ${this_elev_index} PASSING ${floorNum}] with ok load and direction '${direction}'`); // if((passing_floor.buttonStates.down == "activated" && direction == "down") || // (passing_floor.buttonStates.up == "activated" && direction == "up")) if( (elevator.goingDownIndicator() && passing_floor.buttonStates.down == "activated") || (elevator.goingUpIndicator() && passing_floor.buttonStates.up == "activated") ) { console.log(`[ELEV ${this_elev_index} PASSING ${floorNum}] STOP at DQ floor: ${floorNum}`); elevator.goToFloor(floorNum, true); // Do it before anything else console.log(`[ELEV ${this_elev_index} PASSING ${floorNum}] DQ is now: ${elevator.destinationQueue}`); } } }); // elevator was traveling and has arrived at floor elevator.on("stopped_at_floor", function(floorNum) { // remove all dupes of this floor from the dq // this is okay, because even if some people on this floor can't fit in the elevator, // they will just keep calling the elevator again and again later, so the floor will get enqueued then remove_item_from_arr(elevator.destinationQueue, floorNum); console.log(`[ELEV ${this_elev_index} STOPPED at ${floorNum}] removed all entries of floor ${floorNum}. DQ: '${elevator.destinationQueue}'`); // Clean up DQ: remove unnecessary floors where no one's waiting any more cleanUpDQ(elevator); newDirectionAfterStopping(elevator); }); }); }, update: function(dt, elevators, floors) { // We normally don't need to do anything here } }
72d88657f70d5533ccc239928770143429c3f850
[ "JavaScript" ]
1
JavaScript
nonbeing/elevator-saga-challenge
a900c49b3676b0ede218e59a195c0d094cd69f3a
c80f568fe91d164833a6843364e8de361002ca13
refs/heads/master
<repo_name>estefaniag08/RecursividadModelos<file_sep>/200218_Recursividad.py def sumarDigito(numero): if numero<10: return numero else: return sumarDigito(int(numero/10))+(numero%10) def potencia(numero, numerito): if numerito==0: return 1 else: return potencia(numero,numerito-1)*numero def producto(numero, numerito): if numerito==1: return numero else: return producto(numero,numerito-1)+numero def maxDigito(numero): if numero<100: if numero%10 <= numero/10: return numero/10 else: return numero%10 else: if maxDigito(numero/10)<=numero%10: return numero%10 else: return maxDigito(numero/10) def longitud(numero): if numero<10: return 1 else: return longitud(numero/10)+1 def palindromo(numero): if numero<10: return True elif numero<100: return int(numero/10) == numero%10 else: return palindromo(int((numero-(int(numero/(10**(longitud(numero)-1)))*(10**(longitud(numero)-1))))/10)) and int(numero/(10**(longitud(numero)-1))) == numero%10 def invertido(numero): if numero<10: return numero elif numero<100: return int(numero/10) + (numero%10)*10 else: return invertido(int((numero-(int(numero/(10**(longitud(numero)-1)))*(10**(longitud(numero)-1))))/10)) *10 + int(numero/(10**(longitud(numero)-1))) + ((numero%10)*(10**(longitud(numero)-1))) def division(numero, numerito ): if numerito>numero : return 0 elif numero==numerito : return 1 else : return division(numero-numerito, numerito)+1 def fibonnacci(numero): if numero <=1 : return 1 else : return fibonnacci(numero-1) + fibonnacci(numero-2)
df6c95325768533d02323543b55b73c8f1ec0ddc
[ "Python" ]
1
Python
estefaniag08/RecursividadModelos
84f9abdc9b48cd84dd8359354924f8ccf7ce5367
5e4e5a5aa59d2d92fbdeed99bb4d09c91135bbef
refs/heads/master
<file_sep>using System; namespace Iterative { class Program { static void Main(string[] args) { // Console.WriteLine("Enter the number: "); // int num = Convert.ToInt32(Console.ReadLine()); // int fibNum = Fib_Recursive(num); // Console.WriteLine("7th fibonacci Number: " +fibNum); GCD_iterative(45,30); } // static int Fib_Recursive(int n) // { // if (n == 1) // return 0; // if (n == 2) // return 1; // return Fib_Recursive(n - 1) + Fib_Recursive(n - 2); // } // static Fib_Iterative(n){ // int i; // int a = 0; // int b = 1; // int fiboArr; // for(i = 3; i <= n; i++) // { // fiboArr = a + b; // } // } stativ GCD_Iterative(int a, int b) { if(b == 0) return a; if (a == 0) return b; while(b != 0) { int t = b; b = a % b; a = t; } return a; } } }
d6d657bedf800581c847d5c1cec4fb7b621b3a17
[ "C#" ]
1
C#
dipanbhusal/5th-sem
110b66d10a3a603c859978be2622c719c9b2ef88
2f54586b401dd03a1a54b0fa34d14c83ed0f51c0
refs/heads/master
<repo_name>SergiooOliveira/Kermit<file_sep>/app/src/main/java/ipca/cm/kermit/Scores.kt package ipca.cm.kermit import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Button class Scores : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_scores) val menu = findViewById<Button>(R.id.button_menu) menu.setOnClickListener{ val intent = Intent(this@Scores, MainActivity::class.java) startActivity(intent) } } }<file_sep>/app/src/main/java/ipca/cm/kermit/LoginActivity.kt package ipca.cm.kermit import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.ProgressBar import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase class LoginActivity : Activity() { private val TAG = "LoginActivity" private lateinit var auth : FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) val username = findViewById<EditText>(R.id.username) val password = findViewById<EditText>(R.id.password) val login = findViewById<Button>(R.id.register) val loading = findViewById<ProgressBar>(R.id.loading) auth = Firebase.auth login.setOnClickListener { auth.signInWithEmailAndPassword(username.text.toString(), password.text.toString()) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "signInWithEmail:success") val user = auth.currentUser //updateUI(user) val intent = Intent(this@LoginActivity, MainActivity::class.java) startActivity(intent) } else { // If sign in fails, display a message to the user. Log.w(TAG, "signInWithEmail:failure", task.exception) Toast.makeText( baseContext, "Authentication failed.", Toast.LENGTH_SHORT ).show() //updateUI(null) } } } val buttonback = findViewById<Button>(R.id.menu) buttonback.setOnClickListener { val intent = Intent(this@LoginActivity, MainActivity::class.java) startActivity(intent) } } }<file_sep>/app/src/main/java/ipca/cm/kermit/Player.kt package ipca.cm.kermit import android.graphics.Rect import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory class Player { // player position var x = 0 var y = 0 //timer to change between bitmaps var bitTimer : Int = 0 var bitShow : Int = 1 var shootX = 0 var shootY = 0 var KermitHeight : Int get() = y set(value) {} var KermiteWidth : Int get() = x set(value) {} // number of lifes var lifesRemaining = 3 // score var currentScore = 0 // Bitmap image var bitmap : Bitmap var bitmap2 : Bitmap var bitDraw : Bitmap //collision rect var collisionRect : Rect constructor(width: Int, height: Int, context: Context){ x = width / 2 y = height - (height / 6) bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.player_mod1) bitmap2 = BitmapFactory.decodeResource(context.resources, R.drawable.player_mod2) bitmap = Bitmap.createScaledBitmap(bitmap, 175, 175, true) bitmap2 = Bitmap.createScaledBitmap(bitmap2, 175, 175, true) bitDraw = bitmap collisionRect = Rect(x,y,bitmap.width,bitmap.height) } fun update(){ collisionRect.left = x collisionRect.top = y collisionRect.right = x + bitmap.width collisionRect.bottom = y + bitmap.height } fun changeBitMap(){ if (bitTimer >= 20 && bitShow == 2){ bitDraw = bitmap bitTimer = 0 bitShow = 1 } if (bitTimer >= 20 && bitShow == 1) { bitDraw = bitmap2 bitTimer = 0 bitShow = 2 } } fun getPlayerX() : Int { return x } }<file_sep>/app/src/main/java/ipca/cm/kermit/Bullets.kt package ipca.cm.kermit import android.content.Context import android.widget.Toast class Bullets(var context: Context, var height: Int) { var bulletsArray = mutableListOf<Bullet>() var bulletsToRemove = mutableListOf<Bullet>() fun addBullet(x: Int, y: Int) { if (bulletsArray.size < 4) bulletsArray.add(Bullet(x, y, context)) } fun update() { for (b in bulletsArray) { b.update() if (b.y <= 0) b.active = false if (!b.active) bulletsToRemove.add(b) } bulletsArray.removeAll(bulletsToRemove) } }<file_sep>/app/src/main/java/ipca/cm/kermit/Bullet.kt package ipca.cm.kermit import android.graphics.Rect import android.graphics.Bitmap import android.graphics.BitmapFactory import android.content.Context class Bullet(x: Int, y: Int, context: Context) { //position variables var x = 0 var y = 0 // Bitmap image var bitmap : Bitmap //collision rect var collisionRect : Rect var active = true init { this.x = x + 50 this.y = y + 20 bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.player_mod1) bitmap = Bitmap.createScaledBitmap(bitmap, 50, 50, true) collisionRect = Rect(x, y, bitmap.width, bitmap.height) } fun update(){ y -= 10 collisionRect.left = x collisionRect.top = y collisionRect.right = x + bitmap.width collisionRect.bottom = y + bitmap.height } }<file_sep>/app/src/main/java/ipca/cm/kermit/Enemies.kt package ipca.cm.kermit import android.content.Context class Enemies { val enemiesArray = arrayListOf<Enemy>() var spawnTimer = 0 constructor(width: Int, height: Int, quantity: Int, context: Context) { for (i in 1..quantity) { //while loop to delay the spawn of enemies //TODO: get the delays working for the first time while ( spawnTimer < 50000) { if (spawnTimer == 30000) { enemiesArray.add(Enemy(width, height, context)) spawnTimer++ } else spawnTimer++ } spawnTimer = 0 } } fun update(height: Int) { for (e in enemiesArray) { e.update(height) } } } <file_sep>/app/src/main/java/ipca/cm/kermit/GameView.kt package ipca.cm.kermit import android.content.Context import android.content.Intent import android.graphics.* import android.util.AttributeSet import android.view.MotionEvent import android.view.SurfaceHolder import android.view.SurfaceView import android.widget.ImageView class GameView : SurfaceView, Runnable { //life removal timer + boolean so it doesn't remove the player's lives all at once var lifeRemoval : Boolean = true var lifeRemovalTimer : Int = 0 //game variables var surfaceHolder : SurfaceHolder? = null var gameThread : Thread? = null var canvas : Canvas? = null var paint : Paint = Paint() var _isMoving = false //player variables var player : Player? = null val kermit : ImageView? = null //enemy variables var enemies : Enemies? = null var playing = false //bullet variables var bullets : Bullets? = null var createBullet = false var bulletCount = 0 var mContext : Context? = null var lifeIcon : Bitmap? = null var coinScore : Bitmap? = null var background : Bitmap? = null private fun init(context: Context?, width: Int, height: Int){ surfaceHolder = holder player = Player(width, height, context!!) enemies = Enemies(width, height, 3, context) mContext = getContext() bullets = Bullets(context, height) } constructor(context: Context?, width: Int, height: Int) : super(context){ init(context, width, height) } constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs){ init(context, 0, 0) } constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super( context, attrs, defStyleAttr ){ init(context, 0, 0) } override fun run() { while (playing){ update() draw() control() } } private fun update() { player?.update() enemies?.update(player!!.KermitHeight) bullets?.update() for (e in enemies?.enemiesArray!!) { if (e.y >= e.maxY * 4 && e.playing) { e.playing = false if (player?.lifesRemaining!! > 0) player?.lifesRemaining = player?.lifesRemaining!! - 1 else { val intent = Intent(mContext, Scores::class.java) mContext?.startActivity(intent) } } if (Rect.intersects(player!!.collisionRect, e.collisionRect) && lifeRemoval && lifeRemovalTimer >= 120){ e.playing = false lifeRemoval = false lifeRemovalTimer = 0 if (player?.lifesRemaining!! > 0) player?.lifesRemaining = player?.lifesRemaining!! - 1 else { val intent = Intent(mContext, Scores::class.java) mContext?.startActivity(intent) } } for (b in bullets?.bulletsArray!!) { if (Rect.intersects(b.collisionRect, e.collisionRect) && b.active) { e.playing = false b.active = false player?.currentScore = player?.currentScore?.plus(100)!! } } if (lifeRemovalTimer > 120) lifeRemoval = true lifeRemovalTimer++ } player!!.bitTimer++ } private fun control() { Thread.sleep(17L) } private fun draw() { surfaceHolder?.let { if (it.surface.isValid) { canvas = surfaceHolder?.lockCanvas() canvas?.drawColor(Color.BLACK) /*background = BitmapFactory.decodeResource(context.resources, R.drawable.fundo) background = Bitmap.createScaledBitmap(background!!, width, height, true) canvas?.drawBitmap(background!!, 0f, 0f, null)*/ //lives left text drawing paint.color = Color.WHITE paint.textSize = 40F lifeIcon = BitmapFactory.decodeResource(context.resources, R.drawable.life1) lifeIcon = Bitmap.createScaledBitmap(lifeIcon!!, 50, 50, true) canvas?.drawBitmap(lifeIcon!!, 0f, 10f, paint) canvas?.drawText(player?.lifesRemaining.toString(), 50f, 50f, paint) coinScore = BitmapFactory.decodeResource(context.resources, R.drawable.point) coinScore = Bitmap.createScaledBitmap(coinScore!!, 50, 50, true) canvas?.drawBitmap(coinScore!!, 100f, 10f, paint) canvas?.drawText(player?.currentScore.toString(), 150f, 50f, paint) //enemies drawing cycle for (e in enemies?.enemiesArray!!) { if (e.playing) canvas?.drawBitmap(e.bitmap, e.x.toFloat(), e.y.toFloat(), paint) } player?.changeBitMap() canvas?.drawBitmap(player!!.bitDraw, player!!.x.toFloat(), player!!.y.toFloat(), paint) //drawing bullets if (bullets?.bulletsArray!!.size > 0) { for (b in bullets?.bulletsArray!!) if (b.active) canvas?.drawBitmap(b.bitmap, b.x.toFloat(), b.y.toFloat(), paint) } surfaceHolder?.unlockCanvasAndPost(canvas) } } } fun pause(){ playing = false gameThread?.join() } fun resume(){ playing = true gameThread = Thread(this) gameThread!!.start() } override fun onTouchEvent(event: MotionEvent?): Boolean { when (event?.action) { MotionEvent.ACTION_MOVE -> { player?.x = event.x.toInt() _isMoving = true } MotionEvent.ACTION_UP-> { if (!_isMoving) bullets?.addBullet(player?.KermiteWidth!!, player?.KermitHeight!!) _isMoving = false } } return true } } <file_sep>/app/src/main/java/ipca/cm/kermit/Game.kt package ipca.cm.kermit import android.app.Activity import android.graphics.Point import android.os.Bundle class Game : Activity() { var gameView : GameView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val display = windowManager.defaultDisplay val size = Point() display.getSize(size) gameView = GameView(this, size.x, size.y ) setContentView(gameView) } override fun onPause() { super.onPause() gameView?.pause() } override fun onResume() { super.onResume() gameView?.resume() } }<file_sep>/app/src/main/java/ipca/cm/kermit/Enemy.kt package ipca.cm.kermit import android.graphics.Rect import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import java.util.* class Enemy { var x = 0 var y = 0 var maxY = 0 var minY = 0 var maxX = 0 var minX = 0 private var timer = 0 var playing = true //bitmap image var bitmap : Bitmap //collision rectangle var collisionRect : Rect constructor(width: Int, height: Int, context: Context) { bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.inimigos) bitmap = Bitmap.createScaledBitmap(bitmap, 175, 175, true) maxX = width - bitmap.width minX = 0 maxY = height / 4 minY = -200 val generator = Random() x = generator.nextInt(maxX) y = generator.nextInt(maxY) collisionRect = Rect(x, y, bitmap.width, bitmap.height) } fun update(height: Int){ if (y > (height + 100f) && playing) { playing = false }else if(!playing) { respawn() } y += 10 if (playing) { collisionRect.left = x collisionRect.top = y collisionRect.right = x + bitmap.width collisionRect.bottom = y + bitmap.height }else if (!playing) collisionRect.setEmpty() //makes so that the hitbox doesn't hit the player even if the enemy is dead } //respawn delay private fun respawn(){ timer++ if (timer >= 50) { val generator = Random() x = generator.nextInt(maxX - 100) y = generator.nextInt(maxY) playing = true timer = 0 } } }<file_sep>/app/src/main/java/ipca/cm/kermit/RegisterActivity.kt package ipca.cm.kermit import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.EditText import android.widget.ProgressBar import android.widget.Toast import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.ktx.auth import com.google.firebase.ktx.Firebase private val TAG = "RegisterActivity" private lateinit var auth: FirebaseAuth class RegisterActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_register) val username = findViewById<EditText>(R.id.username) val password = findViewById<EditText>(R.id.password) val register = findViewById<Button>(R.id.register) val loading = findViewById<ProgressBar>(R.id.loading) auth = Firebase.auth register.setOnClickListener { auth.createUserWithEmailAndPassword(username.text.toString(), password.text.toString()) .addOnCompleteListener(this) { task -> if (task.isSuccessful) { // Sign in success, update UI with the signed-in user's information Log.d(TAG, "createUserWithEmail:success") val user = auth.currentUser val intent = Intent(this, MainActivity::class.java) startActivity(intent) } else { // If sign in fails, display a message to the user. Log.w(TAG, "createUserWithEmail:failure", task.exception) Toast.makeText(baseContext, "Authentication failed.", Toast.LENGTH_SHORT).show() } } } val buttonback = findViewById<Button>(R.id.menu) buttonback.setOnClickListener{ val intent = Intent(this@RegisterActivity, MainActivity::class.java) startActivity(intent) } } }<file_sep>/app/src/main/java/ipca/cm/kermit/Options.kt package ipca.cm.kermit import android.app.Activity import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button class Options : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_options) val buttonbeckoptomenu = findViewById<Button>(R.id.button_beck_op_to_menu) buttonbeckoptomenu.setOnClickListener { val intent = Intent(this@Options, MainActivity::class.java) startActivity(intent) } } }<file_sep>/app/src/main/java/ipca/cm/kermit/MainActivity.kt package ipca.cm.kermit import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Button import com.google.firebase.database.ktx.database import com.google.firebase.ktx.Firebase import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.ktx.storage class MainActivity : Activity() { lateinit var storage : FirebaseStorage override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val database = Firebase.database val myRef = database.getReference("allphotos") storage = Firebase.storage var storageRef = storage.reference val buttonStart = findViewById<Button>(R.id.button_Start) buttonStart.setOnClickListener{ val intent = Intent(this@MainActivity, Game::class.java) startActivity(intent) } val buttonMenu = findViewById<Button>(R.id.button_Menu) buttonMenu.setOnClickListener{ val intent = Intent(this@MainActivity, Options::class.java) startActivity(intent) } val buttonscores = findViewById<Button>(R.id.button_scores) buttonscores.setOnClickListener{ val intent = Intent(this@MainActivity, Scores::class.java) startActivity(intent) } val buttonlogin = findViewById<Button>(R.id.button_login) buttonlogin.setOnClickListener{ val intent = Intent(this@MainActivity, LoginActivity::class.java) startActivity(intent) } val buttonregister = findViewById<Button>(R.id.button_register) buttonregister.setOnClickListener{ val intent = Intent(this@MainActivity, RegisterActivity::class.java) startActivity(intent) } } }<file_sep>/app/src/main/java/ipca/cm/kermit/GameOver.kt package ipca.cm.kermit import android.app.Activity import android.content.Intent import android.os.Bundle import android.widget.Button class GameOver : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_game_over) val buttonagin = findViewById<Button>(R.id.button_menu) buttonagin.setOnClickListener { val intent = Intent(this@GameOver,MainActivity::class.java) startActivity(intent) } } }<file_sep>/app/src/main/java/ipca/cm/kermit/Square.kt package ipca.cm.kermit import java.util.* // // Created by lourencogomes on 1/6/21. // class Square { var x = 0 var y = 0 var maxY = 0 var minY = 0 var maxX = 0 var minX = 0 private var _isGoingDown = false var isGoingDown : Boolean get() = _isGoingDown set(value) { if (y == minY) { _isGoingDown = value } } constructor( width: Int, height: Int){ maxX = width minX = 0 maxY = height minY = 0 val generator = Random() x = generator.nextInt(maxX) y = generator.nextInt(maxY) } fun update(){ if (_isGoingDown) { y += 5 }else { y -= 5 if (y <= minY) { y = minY } } } }
6e3b8a5a379c847dc1b095880b7530c882ae0a50
[ "Kotlin" ]
14
Kotlin
SergiooOliveira/Kermit
503a0efd29e12a6cf06f488432c7aa6640074951
ae25c93c8f0ed4cd82f3efab2c514d7d80956d3f
refs/heads/master
<repo_name>foodie-trackie/backend<file_sep>/src/info/api/urls.py from django.urls import path from .views import UserItemListView, UserListCreateView, ItemDetailView, ItemCreateView, UserDetailView, signup_view, login_view urlpatterns = [ path('users/<owner>/items/', UserItemListView.as_view()), path('items/<int:pk>', ItemDetailView.as_view()), path('items/', ItemCreateView.as_view()), path('users/', UserListCreateView.as_view()), path('users/<int:pk>/', UserDetailView.as_view()), path('signup/', signup_view), path('login/', login_view) ] <file_sep>/src/info/models.py from django.db import models # Create your models here. class Item(models.Model): name = models.CharField(max_length=120) number = models.IntegerField() production_date = models.DateField() shelf_life = models.IntegerField() expiration_date = models.DateField() owner = models.ForeignKey('auth.User', related_name='items', on_delete=models.CASCADE) def __str__(self): return self.name <file_sep>/src/info/api/views.py from rest_framework.generics import ListCreateAPIView, ListAPIView, CreateAPIView, RetrieveAPIView, RetrieveUpdateDestroyAPIView from rest_framework.decorators import api_view from info.models import Item from .forms import SignUpForm from django.contrib.auth.models import User from django.contrib.auth import login, authenticate from django.http import HttpResponse from .serializers import ItemSerializer, UserSerializer import json class UserItemListView(ListAPIView): serializer_class = ItemSerializer def get_queryset(self): owner = self.kwargs['owner'] return Item.objects.filter(owner=owner) class ItemDetailView(RetrieveUpdateDestroyAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer class ItemCreateView(CreateAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer class UserListCreateView(ListCreateAPIView): queryset = User.objects.all() serializer_class = UserSerializer class UserDetailView(RetrieveAPIView): queryset = User.objects.all() serializer_class = UserSerializer def signup_view(request): data = json.loads(request.body.decode('utf-8')) print(data) if request.method == 'POST': form = SignUpForm(data) print(form.errors) if form.is_valid(): form.save() return HttpResponse(status=201) return HttpResponse(form.errors.as_json(), status=400) def login_view(request): data = json.loads(request.body.decode('utf-8')) if request.method == 'POST': username = data['username'] password = data['<PASSWORD>'] user = authenticate(username=username, password=password) userData = UserSerializer(user).data if user is not None: login(request, user) return HttpResponse(json.dumps({'id': userData['id'], 'username': userData['username'], 'email': userData['email']}), status=200) return HttpResponse(status=404) <file_sep>/src/info/api/serializers.py from rest_framework import serializers from info.models import Item from django.contrib.auth.models import User class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'name', 'number', 'production_date', 'shelf_life', 'expiration_date', 'owner') class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'password') write_only_fields = ('password') # To makesure passwords are not displayed def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'] ) print(validated_data) user.set_password(validated_data['password']) # To generate a hash for the password user.save() return user
8a669f060255ffa8a08d905708bd00d82e273a1e
[ "Python" ]
4
Python
foodie-trackie/backend
ff9c7f506dfefd363cc4533ecabec0675003112a
785c6053c2088a81c3fef9b4665e6cf254ccb45e
refs/heads/master
<file_sep>//// //// OperationDataManger.swift //// Blah Blah Chat //// //// Created by Екатерина on 09.03.2019. //// Copyright © 2019 Wineapp. All rights reserved. //// // //import Foundation // //class OperationDataManager: DataManager { // // let profileHandler: ProfileHandler = ProfileHandler() // // func saveProfile(data: ProfileData, completion: @escaping (Bool) -> Void) { // // let operationQueue = OperationQueue() // let saveOperation = SaveProfileOperation(profileHandler: self.profileHandler, profile: data) // saveOperation.qualityOfService = .userInitiated // // saveOperation.completionBlock = { // OperationQueue.main.addOperation { // completion(saveOperation.saveSucceeded) // } // } // operationQueue.addOperation(saveOperation) // } // // func loadProfile(completion: @escaping (ProfileData?) -> Void) { // // let operationQueue = OperationQueue() // let loadOperation = LoadProfileOperation(profileHandler: self.profileHandler) // loadOperation.qualityOfService = .userInitiated // // loadOperation.completionBlock = { // OperationQueue.main.addOperation { // completion(loadOperation.profile) // } // } // operationQueue.addOperation(loadOperation) // } //} <file_sep>// // CoreAssembly.swift // Blah Blah Chat // // Created by Екатерина on 16.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation protocol CoreAssemblyProtocol { var multipeerCommunicator: Communicator { get } var dataManager: DataManager { get } var themesManager: ThemesManagerProtocol { get } var coreDataStub: CoreDataStackProtocol { get } var requestSender: RequestSenderProtocol { get } } class CoreAssembly: CoreAssemblyProtocol { private let coreDataManager = CoreDataManager() lazy var multipeerCommunicator: Communicator = MultipeerCommunicator() lazy var themesManager: ThemesManagerProtocol = ThemesManager() lazy var dataManager: DataManager = coreDataManager lazy var coreDataStub: CoreDataStackProtocol = coreDataManager lazy var requestSender: RequestSenderProtocol = RequestSender() } <file_sep>//// //// DataManager.swift //// Blah Blah Chat //// //// Created by Екатерина on 10.03.2019. //// Copyright © 2019 Wineapp. All rights reserved. //// // //import Foundation // //protocol DDataManager { // func saveProfile(data: ProfileData, completion: @escaping (_ successful: Bool) -> Void) // func loadProfile(completion: @escaping (_ profile: ProfileData?) -> Void) //} <file_sep>// // NetworkingProtocols.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation protocol RequestProtocol { var urlRequest: URLRequest? { get } } protocol ParserProtocol { associatedtype Model func parse(data: Data) -> Model? } struct RequestConfig<Parser> where Parser: ParserProtocol { let request: RequestProtocol let parser: Parser } protocol RequestSenderProtocol { func send<Parser>(config: RequestConfig<Parser>, completionHandler: @escaping (Result<Parser.Model>) -> Void) } <file_sep>// // Conversation.swift // Blah Blah Chat // // Created by Екатерина on 19.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol ConversationModelProtocol: class { var communicationService: CommunicatorDelegate { get } var frService: FRServiceProtocol { get } var dataSource: ConversationDataSource? { get set } func reloadThemeSettings() func saveSettings(for theme: UIColor) } class ConversationModel: ConversationModelProtocol { var dataSource: ConversationDataSource? var communicationService: CommunicatorDelegate var frService: FRServiceProtocol private let themesService: ThemesServiceProtocol init(communicationService: CommunicatorDelegate, themesService: ThemesServiceProtocol, frService: FRServiceProtocol) { self.communicationService = communicationService self.themesService = themesService self.frService = frService } func reloadThemeSettings() { themesService.load() } func saveSettings(for theme: UIColor) { themesService.save(theme) } } <file_sep>// // MessageTableViewCell.swift // Blah Blah Chat // // Created by Екатерина on 28.02.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol MessageCellConfiguration { var messageText: String? { get set } var isIncoming: Bool { get set } } class MessageTableViewCell: UITableViewCell, MessageCellConfiguration { @IBOutlet var messageLabel: UILabel! var messageText: String? { didSet { messageLabel.text = messageText } } var isIncoming = false override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } func configureCell(message: Message) { self.messageText = message.messageText self.isIncoming = message.isIncoming } } <file_sep>// // ThemesViewController.swift // Blah Blah Chat // // Created by Екатерина on 05.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit class ThemesViewControllerSwift: UIViewController { private let model: ThemesModelProtocol init(model: ThemesModelProtocol) { self.model = model super.init(nibName: "ThemesViewController", bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupNavBar() DispatchQueue.global(qos: .userInteractive).async { if let theme = UserDefaults.standard.colorForKey(key: "Theme") { DispatchQueue.main.async { self.view.backgroundColor = theme } } } } private func setupNavBar() { navigationItem.title = "Themes" let leftItem = UIBarButtonItem(title: "Back", style: .plain, target: self, action: #selector(closeView)) navigationItem.setLeftBarButton(leftItem, animated: true) } @IBAction func selectThemeOne(_ sender: Any) { let selectedColor = model.theme1 model.closure(self, selectedColor) self.view.backgroundColor = selectedColor //self.reloadView() } @IBAction func selectThemeTwo(_ sender: Any) { let selectedColor = model.theme2 model.closure(self, selectedColor) self.view.backgroundColor = selectedColor // self.reloadView() } @IBAction func selectThemeThree(_ sender: Any) { let selectedColor = model.theme3 model.closure(self, selectedColor) self.view.backgroundColor = selectedColor //self.reloadView() } // private func reloadView() { // for window in UIApplication.shared.windows { // for view in window.subviews { // view.removeFromSuperview() // window.addSubview(view) // } // } // } @objc func closeView() { self.dismiss(animated: true, completion: nil) } } <file_sep>// // ProfileViewController.swift // Blah Blah Chat // // Created by Екатерина on 10.02.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit class ProfileViewController: UIViewController { let imagePicker = UIImagePickerController() private let presentationAssembly: PresentationAssemblyProtocol @IBOutlet weak var profilePhotoImageView: UIImageView! @IBOutlet weak var editButton: UIButton! @IBOutlet weak var pickPhotoButton: UIButton! @IBOutlet var saveButton: UIButton! @IBOutlet var nameTextField: UITextField! @IBOutlet var desciptionTextField: UITextField! @IBOutlet var activityIndicator: UIActivityIndicatorView! private var dataWasChanged: Bool { return model.name != nameTextField.text || model.description != desciptionTextField.text || model.picture != profilePhotoImageView.image } private var editingMode: Bool = false private var model: AppUserModelProtocol private var emitter: Emitter! init(model: AppUserModelProtocol, presentationAssembly: PresentationAssemblyProtocol) { self.model = model self.presentationAssembly = presentationAssembly super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() activityIndicator.startAnimating() activityIndicator.hidesWhenStopped = true setupSubviews() self.imagePicker.delegate = self self.desciptionTextField.delegate = self self.nameTextField.delegate = self self.nameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) self.desciptionTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) self.nameTextField.autocorrectionType = UITextAutocorrectionType.no self.desciptionTextField.autocorrectionType = UITextAutocorrectionType.no model.load { [unowned self] profile in guard let profile = profile else { self.activityIndicator.stopAnimating() return } self.model.set(on: profile) if let name = profile.name { self.nameTextField.text = name } if let descr = profile.description { self.desciptionTextField.text = descr } if let picture = profile.picture { self.profilePhotoImageView.image = picture } self.activityIndicator.stopAnimating() } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(sender:)), name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let cornerRadius = self.pickPhotoButton.frame.width/2 self.pickPhotoButton.layer.cornerRadius = cornerRadius self.profilePhotoImageView.layer.cornerRadius = cornerRadius } private func setupSubviews() { self.navigationItem.title = "Profile" self.editButton.layer.borderWidth = 1.0 self.editButton.layer.borderColor = UIColor.black.cgColor self.editButton.layer.cornerRadius = 10 self.saveButton.layer.borderWidth = 1.0 self.saveButton.layer.borderColor = UIColor.black.cgColor self.saveButton.layer.cornerRadius = 10 self.saveButton.isHidden = true self.pickPhotoButton.layer.masksToBounds = true self.profilePhotoImageView.layer.masksToBounds = true self.activityIndicator.center = self.view.center navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(backToChats)) setEnabledState(enabled: false) setEditingState(editing: false) } @IBAction func editButtonPressed(_ sender: UIBarButtonItem) { self.editingMode = true self.setEnabledState(enabled: false) self.animateSaveButton(enabled: false) self.setEditingState(editing: true) } @objc func backToChats() { self.dismiss(animated: true, completion: nil) } @IBAction func pickPhoto(_ sender: Any) { print("Выбери изображение профиля") if !self.editingMode { self.showAlert(title: "Нажмите кнопку Редактировать", message: "Чтобы выбрать фото, нажмите кнопку Редактировать", retry: nil) return } let alert = UIAlertController(title: nil, message: "Выбери изображение профиля", preferredStyle: UIAlertController.Style.actionSheet) alert.addAction(UIAlertAction(title: "Сделать фото", style: .default) { (_: UIAlertAction) -> Void in self.pickPhotoFromCamera() }) alert.addAction(UIAlertAction(title: "Выбрать фото", style: .default) { (_: UIAlertAction) -> Void in self.pickPhotoFromLibrary() }) alert.addAction(UIAlertAction(title: "Загрузить", style: .default) { (_: UIAlertAction) -> Void in self.downloadPhoto() }) alert.addAction(UIAlertAction(title: "Отменить", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } @IBAction func saveButtonPressed(_ sender: Any) { activityIndicator.startAnimating() view.endEditing(true) if nameTextField.text != model.name { model.name = nameTextField.text } if desciptionTextField.text != model.description { model.description = desciptionTextField.text } if profilePhotoImageView.image != model.picture { model.picture = profilePhotoImageView.image } model.save { [weak self] error in if !error { self?.showSuccessAlert() } else { self?.showErrorAlert() } self?.activityIndicator.stopAnimating() } self.editingMode = false self.setEditingState(editing: false) self.setEnabledState(enabled: false) self.animateSaveButton(enabled: false) } private func showSuccessAlert() { let alertController = UIAlertController(title: "Changes saved!", message: nil, preferredStyle: .alert) alertController.view.tintColor = UIColor.black alertController.addAction(UIAlertAction(title: "Done", style: .default, handler: nil)) self.present(alertController, animated: true, completion: nil) } private func showErrorAlert() { let alertController = UIAlertController(title: "Error", message: "could not save data", preferredStyle: .alert) alertController.view.tintColor = UIColor.black alertController.addAction(UIAlertAction(title: "Done", style: .cancel, handler: nil)) alertController.addAction(UIAlertAction(title: "Retry", style: .default) { _ in self.saveButtonPressed(self) }) self.present(alertController, animated: true, completion: nil) } } // MARK: - Change ViewController State extension ProfileViewController { private func setEditingState(editing: Bool) { if editing { self.nameTextField.placeholder = "Введите имя" } self.editButton.isHidden = editing self.saveButton.isHidden = !editing self.nameTextField.isEnabled = editing self.desciptionTextField.isEnabled = editing } private func setEnabledState(enabled: Bool) { self.saveButton.isEnabled = enabled } private func animateSaveButton(enabled: Bool) { let buttonFrame: CGRect = self.saveButton.frame UIView.animate(withDuration: 1.0, delay: 0, options: [], animations: { self.saveButton.alpha = enabled ? 1.0 : 0.2 let originX = buttonFrame.origin.x let originY = buttonFrame.origin.y let originWidth = buttonFrame.size.width let originHeight = buttonFrame.size.height self.saveButton.frame = CGRect(x: originX + originWidth*0.15/2, y: originY + originHeight*0.15/2, width: originWidth - originWidth*0.15, height: originHeight - originHeight*0.15) }, completion: { _ in }) } } // MARK: - Hide Keyboard extension ProfileViewController { @objc func keyboardWillShow(_ notification: NSNotification) { if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { if self.view.frame.origin.y >= 0 { let keyboardRectangle = keyboardFrame.cgRectValue self.view.frame.origin.y -= keyboardRectangle.height } } } @objc func keyboardWillHide(sender: NSNotification) { if let keyboardFrame: NSValue = sender.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { if self.view.frame.origin.y < 0 { let keyboardRectangle = keyboardFrame.cgRectValue self.view.frame.origin.y += keyboardRectangle.height } } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // hides keyboard when tapped outside keyboard self.view.endEditing(true) } } // MARK: - Photo picker methods extension ProfileViewController { func pickPhotoFromLibrary() { imagePicker.allowsEditing = false imagePicker.sourceType = .photoLibrary imagePicker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)! imagePicker.modalPresentationStyle = .popover present(imagePicker, animated: true, completion: nil) } func pickPhotoFromCamera() { if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePicker.allowsEditing = false imagePicker.sourceType = .camera imagePicker.cameraCaptureMode = .photo imagePicker.modalPresentationStyle = .fullScreen present(imagePicker, animated: true, completion: nil) } else { showNoCameraWarn() } } func downloadPhoto() { let controller = self.presentationAssembly.picturesViewController() controller.collectionPickerDelegate = self let navigationController = UINavigationController() navigationController.viewControllers = [controller] self.present(navigationController, animated: true) } func showNoCameraWarn() { let alertVC = UIAlertController(title: "No Camera", message: "Sorry, your device has no camera", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) alertVC.addAction(okAction) self.emitter = Emitter(view: (navigationController?.view)!) present(alertVC, animated: true, completion: nil) } } // MARK: - Image Picker Delegate Methods extension ProfileViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { self.profilePhotoImageView.image = image setEnabledState(enabled: dataWasChanged) animateSaveButton(enabled: dataWasChanged) } else { // error occured print("Error picking image") } picker.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } // MARK: - UITextFieldDelegate extension ProfileViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return true } // user edited text field @objc func textFieldDidChange(_ textField: UITextField) { setEnabledState(enabled: dataWasChanged) animateSaveButton(enabled: dataWasChanged) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.count + string.count - range.length return newLength <= 100 } } extension ProfileViewController: PicturesViewControllerDelegateProtocol { func collectionPickerController(_ picker: CollectionPickerControllerProtocol, didFinishPickingImage image: UIImage) { profilePhotoImageView.image = image setEnabledState(enabled: true) picker.close() } } <file_sep>// // PicturesViewController.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit class PicturesViewController: UIViewController { private let model: PicturesModelProtocol weak var collectionPickerDelegate: PicturesViewControllerDelegateProtocol? @IBOutlet var picCollectionView: UICollectionView! @IBOutlet var spin: UIActivityIndicatorView! private let itemsPerRow: CGFloat = 3 init(model: PicturesModelProtocol) { self.model = model super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.spin.hidesWhenStopped = true configureData() configureCollectionView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) configureNavigationPane() } private func configureData() { spin.layer.cornerRadius = spin.frame.size.width / 2 spin.startAnimating() model.fetchAllPictures { [weak self] pictures, error in if let pictures = pictures { self?.model.data = pictures DispatchQueue.main.async { self?.spin.stopAnimating() self?.picCollectionView.reloadData() } } else { self?.spin.stopAnimating() self?.showErrorMessage(error) } } } private func showErrorMessage(_ message: String?) { DispatchQueue.main.async { let alertController = UIAlertController(title: "Error occured", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Done", style: .cancel)) self.present(alertController, animated: true) } } private func configureCollectionView() { picCollectionView.register(UINib(nibName: "PictureCell", bundle: nil), forCellWithReuseIdentifier: "PictureCell") picCollectionView.dataSource = self picCollectionView.delegate = self as UICollectionViewDelegate } private func configureNavigationPane() { let leftItem = UIBarButtonItem(title: "Назад", style: .plain, target: self, action: #selector(close)) navigationItem.setLeftBarButton(leftItem, animated: true) } } // MARK: - UICollectionViewDataSource extension PicturesViewController: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return model.data.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: PictureCell let identifier = "PictureCell" if let dequeuedCell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as? PictureCell { cell = dequeuedCell } else { cell = PictureCell(frame: CGRect.zero) } let picture = model.data[indexPath.item] DispatchQueue.global(qos: .userInteractive).async { self.model.fetchPicture(urlString: picture.previewUrl) { image in guard let image = image else { return } DispatchQueue.main.async { cell.setup(image: image, picture: picture) } } } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let cell = collectionView.cellForItem(at: indexPath) as? PictureCell { DispatchQueue.global(qos: .userInteractive).async { guard let url = cell.largeImageUrl else { self.showErrorMessage("Error loading image") return } DispatchQueue.main.async { self.picCollectionView.alpha = 0.1 self.spin.startAnimating() } self.model.fetchPicture(urlString: url) { image in DispatchQueue.main.async { self.picCollectionView.alpha = 1 self.spin.stopAnimating() guard let image = image else { self.showErrorMessage("Error fetching image") return } self.collectionPickerDelegate?.collectionPickerController(self, didFinishPickingImage: image) } } } } } } // MARK: - UICollectionViewDelegateFlowLayout extension PicturesViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let screenRect = UIScreen.main.bounds let anotherOne = itemsPerRow + 1 let width = screenRect.size.width - 10.0 * anotherOne let height = width / itemsPerRow return CGSize(width: floor(height), height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 10.0, left: 10.0, bottom: 10.0, right: 10.0) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10.0 } } // MARK: - ICollectionPickerController extension PicturesViewController: CollectionPickerControllerProtocol { @objc func close() { dismiss(animated: true) } } <file_sep>// // ButtonWithShadow.swift // Blah Blah Chat // // Created by Екатерина on 22.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit class ButtonWithShadow: UIButton { required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 5, height: 5) self.layer.shadowRadius = 5 self.layer.shadowOpacity = 1.0 } } <file_sep>//// //// LoadOperation.swift //// Blah Blah Chat //// //// Created by Екатерина on 13.03.2019. //// Copyright © 2019 Wineapp. All rights reserved. //// // //import Foundation // //class LoadProfileOperation: Operation { // // private let profileHandler: ProfileHandler // var profile: ProfileData? // // init(profileHandler: ProfileHandler) { // self.profileHandler = profileHandler // super.init() // } // // override func main() { // if self.isCancelled { return } // self.profile = self.profileHandler.loadData() // } //} <file_sep>// // UserDefaults.swift // Blah Blah Chat // // Created by Екатерина on 06.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit import MultipeerConnectivity extension UserDefaults { func setColor(color: UIColor?, forKey key: String) { var colorData: NSData? if let color = color { colorData = NSKeyedArchiver.archivedData(withRootObject: color) as NSData? } set(colorData, forKey: key) } func colorForKey(key: String) -> UIColor? { var color: UIColor? if let colorData = data(forKey: key) { color = NSKeyedUnarchiver.unarchiveObject(with: colorData) as? UIColor } return color } func setPeerId(peer: MCPeerID?, forKey key: String) { var peerData: NSData? if let myPeer = peer { peerData = NSKeyedArchiver.archivedData(withRootObject: myPeer) as NSData? } set(peerData, forKey: key) } func peerIdForKey(key: String) -> MCPeerID? { var peer: MCPeerID? if let peerData = data(forKey: key) { peer = NSKeyedUnarchiver.unarchiveObject(with: peerData) as? MCPeerID } return peer } } <file_sep>// // DateExtension.swift // Blah Blah Chat // // Created by Екатерина on 24.02.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation extension Date { func toShortFormatString() -> String { let calendar = Calendar.current let dateFormatter = DateFormatter() if calendar.isDateInToday(self) { dateFormatter.dateFormat = "HH:mm" } else { dateFormatter.dateFormat = "dd MMM" } return dateFormatter.string(from: self) } } <file_sep>// // ViewControllerExtension.swift // Blah Blah Chat // // Created by Екатерина on 13.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit extension UIViewController { func showAlert(title: String, message: String?, retry: (() -> Void)?) { let alert = UIAlertController(title: title, message: message, preferredStyle: .alert) if let retry = retry { let retryAction = UIAlertAction(title: "Повторить", style: .default) { _ in retry() } alert.addAction(retryAction) } let окAction = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(окAction) present(alert, animated: true, completion: nil) } } <file_sep>// // PictureCell.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit class PictureCell: UICollectionViewCell, PictureCellConfigurationProtocol { var previewUrl, largeImageUrl: String? @IBOutlet var picImageView: UIImageView! func setup(image: UIImage, picture: Picture) { picImageView.image = image previewUrl = picture.previewUrl largeImageUrl = picture.largeImageUrl } } <file_sep>//// //// TestData.swift //// Blah Blah Chat //// //// Created by Екатерина on 24.02.2019. //// Copyright © 2019 Wineapp. All rights reserved. //// // //import Foundation // //let conversationList: [(String, String?, Date?, Bool, Bool)] = [ // ("Mike", "you have to get someone enthusiastic enough to want to do it for free :)", Date(timeIntervalSinceNow: 0), true, false), // ("Jane", "I'm not sure, I can discuss with you what little I know", Date(timeIntervalSinceNow: -3260), true, false), // ("Hanna", nil, nil, true, false), // ("Tony", "hehe", Date(timeIntervalSinceNow: -2341), true, false), // ("Sara", "yeah, no problems here", Date(timeIntervalSinceNow: -827364), true, true), // ("Mia", "i suppose you don't normally do it with dev tools, it's just trial and error", Date(timeIntervalSinceNow: -84376), true, false), // ("Nina", nil, nil, true, false), // ("John", "it's a great dataset", Date(timeIntervalSinceNow: -2134354), true, false), // ("Perry", nil, nil, true, false), // ("Elliot", "too complicated", Date(timeIntervalSinceNow: -314), true, true), // ("Dave", "cheers", Date(timeIntervalSinceNow: -63746), false, false), // ("Peter", "I have a feeling they will, truth be told", Date(timeIntervalSinceNow: -4386521), false, true), // ("Terry", "ok, so what's the deal?", Date(timeIntervalSinceNow: -2348732), false, true), // ("Helen", nil, nil, false, false), // ("Julia", "sounds good. what's the goal?", Date(timeIntervalSinceNow: -2364735), false, false), // ("Jessy", "you know what I mean, right?", Date(timeIntervalSinceNow: -443636), false, true), // ("Liza", nil, nil, false, false), // ("Alex", nil, nil, false, false), // ("Phil", "not sure why", Date(timeIntervalSinceNow: -239865), false, true), // ("Mary", nil, nil, false, false) //] // //func randomString(length: Int) -> String { // let characters = " abcdefghijklmnopqrstuvwxyz" // let randomCharacters = (0..<length).map { _ in characters.randomElement()! } // let randomString = String(randomCharacters) // // return randomString //} // //func generateRandomMessages() -> [(String, MessageType)] { // var resultArray: [(String, MessageType)] = [] // let number = Int(arc4random_uniform(10) + 10) // for _ in 1...number { // let messageLength = Int.random(in: 10...200) // let type = Int.random(in: 0...1) // let messageType = type == 0 ? MessageType.incoming : MessageType.outcoming // resultArray.append((randomString(length: messageLength), messageType)) // } // return resultArray //} <file_sep>// // ConversationTableViewCell.swift // Blah Blah Chat // // Created by Екатерина on 22.02.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol ConversationCellConfiguration: class { var name: String? { get set } var lastMessageText: String? { get set } var date: Date? { get set } var online: Bool { get set } var hasUnreadMessages: Bool { get set } } class ConversationTableViewCell: UITableViewCell, ConversationCellConfiguration { @IBOutlet var nameLabel: UILabel! @IBOutlet var messageLabel: UILabel! @IBOutlet var dateLabel: UILabel! var name: String? { didSet { nameLabel.text = name ?? "Name" } } var lastMessageText: String? { didSet { if let textValue = lastMessageText { self.messageLabel.text = textValue self.messageLabel.font = UIFont.systemFont(ofSize: self.messageLabel.font.pointSize) } else { self.messageLabel.text = "No messages yet" self.messageLabel.font = UIFont.italicSystemFont(ofSize: self.messageLabel.font.pointSize) } } } var date: Date? { didSet { if let date = date { self.dateLabel.text = date.toShortFormatString() self.dateLabel.isHidden = false } else { self.dateLabel.isHidden = true } } } var online = false { didSet { if online { self.backgroundColor = Colors.lightYellow } else { self.backgroundColor = UIColor.white } } } var hasUnreadMessages = false { didSet { if hasUnreadMessages { self.messageLabel.font = UIFont.boldSystemFont(ofSize: self.messageLabel.font.pointSize) self.messageLabel.textColor = UIColor.black } else { self.messageLabel.font = UIFont.systemFont(ofSize: self.messageLabel.font.pointSize) } } } override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override func prepareForReuse() { super.prepareForReuse() } func configureCell(conversation: Conversation) { self.online = conversation.isOnline self.date = conversation.lastMessage?.date ?? nil self.lastMessageText = conversation.lastMessage?.messageText ?? nil self.hasUnreadMessages = conversation.hasUnreadMessages } } <file_sep>// // ModelExtension.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation extension Message: MessageCellConfiguration { @nonobjc class func generateMessageId() -> String { return "\(arc4random_uniform(UINT32_MAX))+\(Date.timeIntervalSinceReferenceDate)" .data(using: .utf8)!.base64EncodedString() } } <file_sep>//// //// GCDDataManager.swift //// Blah Blah Chat //// //// Created by Екатерина on 09.03.2019. //// Copyright © 2019 Wineapp. All rights reserved. //// // //import Foundation // //class GCDDataManager: DataManager { // // let profileHandler: ProfileHandler = ProfileHandler() // // func saveProfile(data: ProfileData, completion: @escaping (_ success: Bool) -> Void) { // DispatchQueue.global(qos: .userInitiated).async { // let saveSucceeded = self.profileHandler.saveData(profile: data) // // DispatchQueue.main.async { // completion(saveSucceeded) // } // } // } // // func loadProfile(completion: @escaping (_ profile: ProfileData?) -> Void) { // DispatchQueue.global(qos: .userInitiated).async { // let profile = self.profileHandler.loadData() // // DispatchQueue.main.async { // completion(profile) // } // } // } // // func syncLoadProfile() -> ProfileData? { // return DispatchQueue.global(qos: .userInitiated).sync { // self.profileHandler.loadData() // } // } //} <file_sep>// // ChatViewController.swift // Blah Blah Chat // // Created by Екатерина on 24.02.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit extension UITableView: DataSourceDelegate { // UITableView used as a DataSourceDelegate protocol object } class ChatViewController: UIViewController, UITableViewDelegate { @IBOutlet weak var messagesTableView: UITableView! { didSet { // workaround for displaying messages bottom -> top messagesTableView.transform = CGAffineTransform(scaleX: 1, y: -1) } } @IBOutlet var messageTextField: UITextField! @IBOutlet var sendButton: UIButton! private var titleLabel: UILabel! private var model: ChatModel var sendButtonLocked = false init(model: ChatModel) { self.model = model titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 250, height: 30)) super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.setupNavigationTitle() self.messageTextField.delegate = self messageTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) self.setupTableView() self.model.dataSource = MessagesDataSource(delegate: messagesTableView, fetchRequest: model.frService.messagesInConversation(with: model.conversation.conversationId!)!, context: model.frService.saveContext) if let count = model.conversation.messages?.count, count > 0 { messagesTableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true) } else { setupNoMessagesView() } } private func setupNavigationTitle() { navigationItem.titleView = titleLabel titleLabel.textColor = UIColor.black titleLabel.textAlignment = .center titleLabel.font = UIFont.systemFont(ofSize: 13, weight: .bold) titleLabel.text = model.conversation.user?.name } private func setupTableView() { self.messagesTableView.delegate = self self.messagesTableView.dataSource = self let nib = UINib(nibName: "IncomingMessageTableViewCell", bundle: nil) self.messagesTableView.register(nib, forCellReuseIdentifier: "incomingMessage") let nib1 = UINib(nibName: "OutcomingMessageTableViewCell", bundle: nil) self.messagesTableView.register(nib1, forCellReuseIdentifier: "outcomingMessage") self.messagesTableView.rowHeight = UITableView.automaticDimension self.messagesTableView.estimatedRowHeight = 50 } private func setupKeyboard() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(hideKeyboard)) self.messagesTableView.addGestureRecognizer(tapGesture) } func setupNoMessagesView() { let noMessagesLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 50)) noMessagesLabel.text = "No messages yet" noMessagesLabel.textColor = UIColor.darkGray noMessagesLabel.font = UIFont.systemFont(ofSize: 14) noMessagesLabel.textAlignment = .center self.messagesTableView.tableHeaderView = noMessagesLabel self.messagesTableView.tableHeaderView?.transform = CGAffineTransform(scaleX: 1, y: -1) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.setupKeyboard() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) model.setUserConnectionTracker(self) if model.conversation.isOnline == false { changeControlsState(enabled: false) } else { performAnimationSetLabelState(titleLabel, enabled: true) } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // removing observers NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) model.makeRead() view.gestureRecognizers?.removeAll() } // MARK: - sendButtonLock @objc private func textFieldDidChange(_ textField: UITextField) { if textField == messageTextField { if let text = messageTextField.text, !text.trimmingCharacters(in: .whitespaces).isEmpty { if sendButtonLocked == true { sendButtonLocked = false performAnimationSetButtonState(sendButton, enabled: true) } } else { if sendButtonLocked == false { sendButtonLocked = true performAnimationSetButtonState(sendButton, enabled: false) } } } } @IBAction func sendTapped(_ sender: Any) { if !sendButtonLocked { guard let text = messageTextField.text, let receiver = model.conversation.user?.userId, !text.isEmpty else { return } model.communicationService.communicator.sendMessage(text: text, to: receiver) { [weak self] success, error in if success { self?.messageTextField.text = nil if sendButtonLocked == false { self?.sendButtonLocked = true performAnimationSetButtonState(sendButton, enabled: false) } self?.messagesTableView.tableHeaderView = nil } else { let alert = UIAlertController(title: "Error occured", message: error?.localizedDescription, preferredStyle: .alert) alert.addAction(UIAlertAction(title: "done", style: .cancel)) self?.present(alert, animated: true) } } } } } extension ChatViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { guard let sections = model.dataSource?.fetchedResultsController.sections?.count else { return 0 } return sections } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let sections = model.dataSource?.fetchedResultsController.sections else { return 0 } return sections[section].numberOfObjects } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: MessageTableViewCell? if let message = model.dataSource?.fetchedResultsController.object(at: indexPath) { var identifier: String if message.isIncoming { identifier = "incomingMessage" } else { identifier = "outcomingMessage" } if let messCell = tableView.dequeueReusableCell(withIdentifier: identifier) as? MessageTableViewCell { cell = messCell } else { cell = MessageTableViewCell(style: .default, reuseIdentifier: identifier) } cell?.configureCell(message: message) // workaround for displaying messages bottom -> top cell?.contentView.transform = CGAffineTransform(scaleX: 1, y: -1) } return cell ?? UITableViewCell() } } // MARK: - UITextFieldDelegate extension ChatViewController: UITextFieldDelegate { // hide the keyboard after pressing return key func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // limiting input length for textfield func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.count + string.count - range.length return newLength <= 300 } } // MARK: - Show/hide Keyboard extension ChatViewController { @objc func hideKeyboard(_ sender: UITapGestureRecognizer) { self.messageTextField.endEditing(true) } @objc func keyboardWillShow(_ notification: Notification) { if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { if self.view.frame.origin.y >= 0 { let keyboardRectangle = keyboardFrame.cgRectValue self.view.frame.origin.y -= keyboardRectangle.height } } } @objc func keyboardWillHide(_ notification: Notification) { if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue { if self.view.frame.origin.y < 0 { let keyboardRectangle = keyboardFrame.cgRectValue self.view.frame.origin.y += keyboardRectangle.height } } } } // MARK: - Enable/disable controls extension ChatViewController: UserConnectionTrackerProtocol { func changeControlsState(enabled: Bool) { if enabled { // set controls on DispatchQueue.main.async { self.textFieldDidChange(self.messageTextField) self.messageTextField.isEnabled = true self.performAnimationSetLabelState(self.titleLabel, enabled: true) } } else { // set controls off DispatchQueue.main.async { self.messageTextField.isEnabled = false self.performAnimationSetLabelState(self.titleLabel, enabled: false) if self.sendButtonLocked == false { self.sendButtonLocked = true self.performAnimationSetButtonState(self.sendButton, enabled: false) } } } } } // MARK: - Animations extension ChatViewController { private func performAnimationSetButtonState(_ button: UIButton, enabled: Bool) { if enabled { UIView.animate(withDuration: 1, animations: { () -> Void in button.setTitleColor(UIColor.green, for: .normal) }) UIView.animate(withDuration: 0.5, animations: { button.transform = CGAffineTransform(scaleX: 1.15, y: 1.15) }, completion: { _ in UIView.animate(withDuration: 0.5) { button.transform = CGAffineTransform.identity } }) } else { UIView.animate(withDuration: 1, animations: { () -> Void in button.setTitleColor(UIColor.red, for: .normal) }) UIView.animate(withDuration: 0.5, animations: { button.transform = CGAffineTransform(scaleX: 1.15, y: 1.15) }, completion: { _ in UIView.animate(withDuration: 0.5) { button.transform = CGAffineTransform.identity } }) } } private func performAnimationSetLabelState(_ label: UILabel, enabled: Bool) { if enabled { // user is online UIView.animate(withDuration: 1, animations: { () -> Void in label.textColor = UIColor.green label.transform = CGAffineTransform(scaleX: 1.10, y: 1.10) }) } else { // user is offline UIView.animate(withDuration: 1, animations: { () -> Void in label.textColor = UIColor.black label.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }) } } } <file_sep>// // ProfileData.swift // Blah Blah Chat // // Created by Екатерина on 09.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol AppUserData { var name: String? { get set } var description: String? { get set } var picture: UIImage? { get set } } protocol AppUserModelProtocol: AppUserData { func set(on profile: AppUserData) func save(_ completion: @escaping (Bool) -> Void) func load(_ completion: @escaping (AppUserData?) -> Void) } class Profile: AppUserData { var name: String? var description: String? var picture: UIImage? init(name: String? = nil, descr: String? = nil, picture: UIImage? = nil) { self.name = name self.description = descr self.picture = picture } } class ProfileModel: AppUserModelProtocol { private let dataService: DataManager var name: String? var description: String? var picture: UIImage? init(dataService: DataManager, name: String? = nil, descr: String? = nil, picture: UIImage? = nil) { self.dataService = dataService self.name = name self.description = descr self.picture = picture } func set(on profile: AppUserData) { self.name = profile.name self.description = profile.description self.picture = profile.picture } func save(_ completion: @escaping (Bool) -> Void) { dataService.saveAppUser(self, completion: completion) } func load(_ completion: @escaping (AppUserData?) -> Void) { dataService.loadAppUser(completion: completion) } } <file_sep>// // RequestsFactory.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation struct RequestsFactory { struct PixabayRequests { private static let apiKey = "12226226-b36092e3b9d1c2c414f89a5c5" static func searchImages() -> RequestConfig<SearchImagesParser> { let request = SearchImagesRequest(key: apiKey) let parser = SearchImagesParser() return RequestConfig<SearchImagesParser>(request: request, parser: parser) } static func downloadImage(urlString: String) -> RequestConfig<DownloadImageParser> { let request = DownloadImageRequest(urlString: urlString) let parser = DownloadImageParser() return RequestConfig<DownloadImageParser>(request: request, parser: parser) } } } <file_sep>// // ThemesModel.swift // Blah Blah Chat // // Created by Екатерина on 10.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit typealias ColorAlias = ((ThemesViewControllerSwift, UIColor?) -> Void) protocol ThemesModelProtocol: class { var theme1: UIColor { get } var theme2: UIColor { get } var theme3: UIColor { get } typealias ColorAlias = ((ThemesViewControllerSwift, UIColor?) -> Void) var closure: ColorAlias { get } } class ThemesModel: ThemesModelProtocol { var theme1, theme2, theme3: UIColor var closure: ColorAlias init(theme1: UIColor, theme2: UIColor, theme3: UIColor, closure: @escaping ColorAlias) { self.theme1 = theme1 self.theme2 = theme2 self.theme3 = theme3 self.closure = closure } } <file_sep>// // PictureServiceProtocol.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol PicturesServiceProtocol { func getPictures(completionHandler: @escaping ([Picture]?, String?) -> Void) func downloadPicture(urlString: String, completionHandler: @escaping (UIImage?, String?) -> Void) } <file_sep>//// //// ProfileHandler.swift //// Blah Blah Chat //// //// Created by Екатерина on 13.03.2019. //// Copyright © 2019 Wineapp. All rights reserved. //// // //import UIKit // //class ProfileHandler { // // private let nameFileName = "name.txt" // private let descrFileName = "description.txt" // private let photoFileName = "photo.png" // // let filePath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] // // func saveData(profile: ProfileData) -> Bool { // do { // if profile.nameChanged, let name = profile.name { // try name.write(to: filePath.appendingPathComponent(self.nameFileName), atomically: true, encoding: String.Encoding.utf8) // } // // if profile.descriptionChanged, let descr = profile.description { // try descr.write(to: filePath.appendingPathComponent(self.descrFileName), atomically: true, encoding: String.Encoding.utf8) // } // // if profile.photoChanged, let photo = profile.photo { // let imageData = photo.pngData() // try imageData?.write(to: filePath.appendingPathComponent(self.photoFileName), options: .atomic) // } // return true // } catch { // return false // } // } // // func loadData() -> ProfileData? { // let profile = ProfileData() // do { // profile.name = try String(contentsOf: filePath.appendingPathComponent(self.nameFileName)) // profile.description = try String(contentsOf: filePath.appendingPathComponent(self.descrFileName)) // profile.photo = UIImage(contentsOfFile: filePath.appendingPathComponent(self.photoFileName).path) // return profile // } catch { // return nil // } // } //} <file_sep>// // DownloadParser.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit class DownloadImageParser: ParserProtocol { typealias Model = UIImage func parse(data: Data) -> Model? { guard let image = UIImage(data: data) else { return nil } return image } } <file_sep>// // MultipeerCommunicator.swift // Blah Blah Chat // // Created by Екатерина on 15.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation import MultipeerConnectivity protocol Communicator { func sendMessage(text: String, to userId: String, completionHandler: ((_ success: Bool, _ error: Error?) -> Void)) var delegate: CommunicatorDelegate? {get set} var online: Bool {get set} } class MultipeerCommunicator: NSObject, Communicator { weak var delegate: CommunicatorDelegate? private let serviceType = "tinkoff-chat" private var myPeerId: MCPeerID = { if let peer = UserDefaults.standard.peerIdForKey(key: "MyPeerId") { return peer } else { let newPeer = MCPeerID(displayName: UIDevice.current.name) UserDefaults.standard.setPeerId(peer: newPeer, forKey: "MyPeerId") return newPeer } }() private let serviceAdvertiser: MCNearbyServiceAdvertiser private let serviceBrowser: MCNearbyServiceBrowser var online: Bool override init() { let username = UserDefaults.standard.string(forKey: "Username") serviceAdvertiser = MCNearbyServiceAdvertiser(peer: self.myPeerId, discoveryInfo: ["userName": username ?? UIDevice.current.name], serviceType: serviceType) serviceBrowser = MCNearbyServiceBrowser(peer: self.myPeerId, serviceType: serviceType) online = true super.init() serviceAdvertiser.delegate = self serviceAdvertiser.startAdvertisingPeer() serviceBrowser.delegate = self serviceBrowser.startBrowsingForPeers() } deinit { serviceAdvertiser.stopAdvertisingPeer() serviceBrowser.stopBrowsingForPeers() } private lazy var session: MCSession = { let session = MCSession(peer: myPeerId, securityIdentity: nil, encryptionPreference: .optional) session.delegate = self return session }() func sendMessage(text: String, to userId: String, completionHandler: ((_ success: Bool, _ error: Error?) -> Void)) { guard let index = session.connectedPeers.index(where: { (item) -> Bool in item.displayName == userId }) else { return } let message = ["eventType": "TextMessage", "text": text, "messageId": Message.generateMessageId()] do { let json = try! JSONSerialization.data(withJSONObject: message, options: .prettyPrinted) try session.send(json, toPeers: [session.connectedPeers[index]], with: .reliable) delegate?.didSendMessage(text: text, to: userId) completionHandler(true, nil) } catch { completionHandler(false, error) } } } // MARK: - MCNearbyServiceAdvertiserDelegate extension MultipeerCommunicator: MCNearbyServiceAdvertiserDelegate { func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) { delegate?.failedToStartAdvertising(error: error) } func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) { invitationHandler(true, session) } } // MARK: - MCSessionDelegate extension MultipeerCommunicator: MCSessionDelegate { func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { if state == .connected { print("Info: State changed to connected") } } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { do { let myJson = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: String] if let text = myJson["text"] { delegate?.didReceiveMessage(text: text, from: peerID.displayName) } } catch { print("Error: Can't parse response") } } func session(_ session: MCSession, didReceiveCertificate certificate: [Any]?, fromPeer peerID: MCPeerID, certificateHandler: @escaping (Bool) -> Void) { certificateHandler(true) } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { } } // MARK: - MCNearbyServiceBrowserDelegate extension MultipeerCommunicator: MCNearbyServiceBrowserDelegate { func browser(_ browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: Error) { delegate?.failedToStartBrowsingForUsers(error: error) } func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String]?) { guard let userName = info?["userName"] else { return } browser.invitePeer(peerID, to: session, withContext: nil, timeout: 60) delegate?.didFoundUser(id: peerID.displayName, name: userName) } func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) { delegate?.didLostUser(id: peerID.displayName) } } <file_sep>// // RequestSender.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation enum Result<T> { case success(T) case error(String) } class RequestSender: RequestSenderProtocol { let session = URLSession(configuration: URLSessionConfiguration.default) func send<Parser>(config: RequestConfig<Parser>, completionHandler: @escaping (Result<Parser.Model>) -> Void) where Parser: ParserProtocol { guard let urlRequest = config.request.urlRequest else { completionHandler(.error("url string can't be parsed to URL")) return } let task = session.dataTask(with: urlRequest) { (data: Data?, _: URLResponse?, error: Error?) in if let error = error { completionHandler(.error(error.localizedDescription)) return } guard let data = data, let parsedModel: Parser.Model = config.parser.parse(data: data) else { completionHandler(.error("data can't be parsed")) return } completionHandler(.success(parsedModel)) } task.resume() } } <file_sep>// // Constants.swift // Blah Blah Chat // // Created by Екатерина on 24.02.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit struct Colors { static let lightYellow = #colorLiteral(red: 1, green: 1, blue: 0.8823529412, alpha: 1) } <file_sep>// // ChatModel.swift // Blah Blah Chat // // Created by Екатерина on 16.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation import CoreData protocol ChatModelProtocol: class { var communicationService: CommunicatorDelegate { get set } var conversation: Conversation { get set } } class ChatModel: ChatModelProtocol { let frService: FRServiceProtocol var communicationService: CommunicatorDelegate var conversation: Conversation var dataSource: MessagesDataSource? func makeRead() { guard let id = conversation.conversationId else { return } communicationService.didReadConversation(id: id) } init(communicationService: CommunicatorDelegate, frService: FRServiceProtocol, conversation: Conversation) { self.communicationService = communicationService self.frService = frService self.conversation = conversation } // MARK: - UserConnectionTracker func setUserConnectionTracker(_ tracker: UserConnectionTrackerProtocol) { self.communicationService.connectionTracker = tracker } } <file_sep>// // UITableView.swift // Blah Blah Chat // // Created by Екатерина on 19.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit extension UITableView { func scrollToBottom(animated: Bool) { guard numberOfRows(inSection: 0) != 0 else { return } DispatchQueue.main.async { let indexPath = IndexPath( row: self.numberOfRows(inSection: self.numberOfSections - 1) - 1, section: self.numberOfSections - 1) self.scrollToRow(at: indexPath, at: .bottom, animated: animated) } } func scrollToTop(animated: Bool) { guard numberOfRows(inSection: 0) != 0 else { return } DispatchQueue.main.async { let indexPath = IndexPath(row: 0, section: 0) self.scrollToRow(at: indexPath, at: .top, animated: animated) } } } <file_sep>// // FetchRequestService.swift // Blah Blah Chat // // Created by Екатерина on 15.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation import CoreData protocol FRServiceProtocol: class { func allConversations() -> NSFetchRequest<Conversation>? func messagesInConversation(with id: String) -> NSFetchRequest<Message>? var saveContext: NSManagedObjectContext { get } } class FetchRequestService: FRServiceProtocol { private let stack: CoreDataStackProtocol init(stack: CoreDataStackProtocol) { self.stack = stack } var saveContext: NSManagedObjectContext { return stack.saveContext } func allConversations() -> NSFetchRequest<Conversation>? { let name = NSSortDescriptor(key: "user.name", ascending: true) let date = NSSortDescriptor(key: "lastMessage.date", ascending: false) let online = NSSortDescriptor(key: "isOnline", ascending: false) let fetchRequest = NSFetchRequest<Conversation>(entityName: "Conversation") fetchRequest.sortDescriptors = [online, date, name] return fetchRequest } func messagesInConversation(with id: String) -> NSFetchRequest<Message>? { return stack.fetchRequest("MessagesByConv", substitutionDictionary: ["id": id], sortDescriptors: [NSSortDescriptor(key: "date", ascending: false)]) } } <file_sep>// // RootAssembly.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation class RootAssembly { private lazy var coreAssembly: CoreAssemblyProtocol = CoreAssembly() private lazy var serviceAssembly: ServicesAssemblyProtocol = ServicesAssembly(coreAssembly: self.coreAssembly) lazy var presentationAssembly: PresentationAssemblyProtocol = PresentationAssembly(serviceAssembly: self.serviceAssembly) } <file_sep>// // CoreDataStack.swift // Blah Blah Chat // // Created by Екатерина on 20.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation import CoreData class CoreDataStack { static let shared = CoreDataStack() var storeURL: URL { let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! return documentsUrl.appendingPathComponent("BlahBlahChat.sqlite") } private let dataModelName = "ProfileModel" private let dataModelExtention = "momd" lazy var managedObjectModel: NSManagedObjectModel = { let modelURL = Bundle.main.url(forResource: self.dataModelName, withExtension: self.dataModelExtention)! return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var coreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: self.storeURL, options: nil) } catch { print("Error adding persistent store to coordinator: \(error)") } return coordinator }() lazy var masterContext: NSManagedObjectContext = { var context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) context.persistentStoreCoordinator = self.coreCoordinator context.mergePolicy = NSOverwriteMergePolicy return context }() lazy var mainContext: NSManagedObjectContext = { var context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) context.parent = self.masterContext context.mergePolicy = NSOverwriteMergePolicy return context }() lazy var saveContext: NSManagedObjectContext = { var context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) context.parent = self.mainContext context.mergePolicy = NSOverwriteMergePolicy return context }() func performSave(with context: NSManagedObjectContext, completion: @escaping (Error?) -> Void) { if context.hasChanges { context.perform { [weak self] in do { try context.save() } catch { print("Context save error: \(error)") completion(error) } if let parent = context.parent { self?.performSave(with: parent, completion: completion) } else { completion(nil) } } } else { completion(nil) } } } <file_sep>// // Logger.swift // Blah Blah Chat // // Created by Екатерина on 10.02.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit enum ApplicationState: String { case notRunning = "not running" case inactive case active case background case suspended } class Logger { static let shared = Logger() func logState(function: String = #function, moveFrom state1: ApplicationState, to state2: ApplicationState) { #if DEBUG print("Application moved from \"\(state1.rawValue)\" to \"\(state2.rawValue)\": \(function)") #endif } func logState(function: String = #function, message: String) { #if DEBUG print("View controller calls \(function): \(message)") #endif } func logThemeChanging(selectedTheme: UIColor) { #if DEBUG print("Selected color is \(String(describing: selectedTheme.cgColor.components))") #endif } } <file_sep>// // PictureProtocols.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol CollectionPickerControllerProtocol: class { func close() } protocol PicturesViewControllerDelegateProtocol: class { func collectionPickerController(_ picker: CollectionPickerControllerProtocol, didFinishPickingImage image: UIImage) } protocol PictureCellConfigurationProtocol { var previewUrl: String? { get set } var largeImageUrl: String? { get set } } protocol PicturesModelProtocol: class { var data: [Picture] { get set } func fetchAllPictures(completionHandler: @escaping ([Picture]?, String?) -> Void) func fetchPicture(urlString: String, completionHandler: @escaping (UIImage?) -> Void) } <file_sep>//// //// SaveProfileOperation.swift //// Blah Blah Chat //// //// Created by Екатерина on 13.03.2019. //// Copyright © 2019 Wineapp. All rights reserved. //// // //import Foundation // //class SaveProfileOperation: Operation { // // var saveSucceeded: Bool = true // private let profileHandler: ProfileHandler // private let profile: ProfileData // // init(profileHandler: ProfileHandler, profile: ProfileData) { // self.profileHandler = profileHandler // self.profile = profile // super.init() // } // // override func main() { // if self.isCancelled { return } // self.saveSucceeded = self.profileHandler.saveData(profile: self.profile) // } //} <file_sep>// // CommunicationManager.swift // Blah Blah Chat // // Created by Екатерина on 15.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol UserConnectionTrackerProtocol { func changeControlsState(enabled: Bool) } protocol CommunicatorDelegate: class { var communicator: Communicator { get } var connectionTracker: UserConnectionTrackerProtocol? { get set } // discovery func didFoundUser(id: String, name: String) func didLostUser(id: String) // errors func failedToStartBrowsingForUsers(error: Error) func failedToStartAdvertising(error: Error) // message func didReceiveMessage(text: String, from user: String) func didSendMessage(text: String, to user: String) // conversation func didReadConversation(id: String) } class CommunicationService: CommunicatorDelegate { var communicator: Communicator private let dataManager: DataManager var connectionTracker: UserConnectionTrackerProtocol? init(dataManager: DataManager, communicator: Communicator) { self.dataManager = dataManager self.communicator = communicator self.communicator.delegate = self } func didFoundUser(id: String, name: String) { connectionTracker?.changeControlsState(enabled: true) dataManager.appendConversation(id: id, userName: name) } func didLostUser(id: String) { connectionTracker?.changeControlsState(enabled: false) dataManager.makeConversationOffline(id: id) } func didSendMessage(text: String, to user: String) { dataManager.appendMessage(text: text, conversationId: user, isIncoming: false) } func didReceiveMessage(text: String, from user: String) { dataManager.appendMessage(text: text, conversationId: user, isIncoming: true) } func didReadConversation(id: String) { dataManager.readConversation(id: id) } func failedToStartBrowsingForUsers(error: Error) { print("Failed To Start Browsing For Users:", error.localizedDescription) let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Done", style: .cancel)) alertController.present(alertController, animated: true, completion: nil) } func failedToStartAdvertising(error: Error) { print("Failed To Start Advertising:", error.localizedDescription) let alertController = UIAlertController(title: "Error", message: error.localizedDescription, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "Done", style: .cancel)) alertController.present(alertController, animated: true, completion: nil) } } <file_sep>// // Picture.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation struct Picture: Codable { let previewUrl: String let largeImageUrl: String enum CodingKeys: String, CodingKey { case previewUrl = "previewURL" case largeImageUrl = "largeImageURL" } } <file_sep>// // MessageStorage.swift // Blah Blah Chat // // Created by Екатерина on 19.03.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation class MessagesStorage { static private var messages = [String: [Message]]() static func getMessages(from userName: String) -> [Message]? { let messagesDict = MessagesStorage.messages as NSDictionary let messages = messagesDict.value(forKey: userName) as? [Message] return messages } static func addMessage(from userName: String, message: Message) { if MessagesStorage.getMessages(from: userName) != nil { MessagesStorage.messages[userName]?.append(message) } else { MessagesStorage.messages[userName] = [message] } } } <file_sep>// // ThemesService.swift // Blah Blah Chat // // Created by Екатерина on 10.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol ThemesServiceProtocol: class { func save(_ theme: UIColor) func load() } class ThemesService: ThemesServiceProtocol { private let themesManager: ThemesManagerProtocol init(themesManager: ThemesManagerProtocol) { self.themesManager = themesManager } func save(_ theme: UIColor) { themesManager.apply(theme, save: true) } func load() { themesManager.loadAndApply() } } <file_sep>// // MessageDataSource.swift // Blah Blah Chat // // Created by Екатерина on 16.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import CoreData import UIKit class MessagesDataSource: NSObject { weak var delegate: DataSourceDelegate? var fetchedResultsController: NSFetchedResultsController<Message> init(delegate: DataSourceDelegate?, fetchRequest: NSFetchRequest<Message>, context: NSManagedObjectContext) { self.delegate = delegate fetchedResultsController = NSFetchedResultsController<Message>(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil) super.init() fetchedResultsController.delegate = self perfromFetch() } private func perfromFetch() { do { try fetchedResultsController.performFetch() } catch { print("Unable to perform fetch -- MessageDataSource") } } } extension MessagesDataSource: NSFetchedResultsControllerDelegate { func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { DispatchQueue.main.async { switch type { case .delete: if let indexPath = indexPath { self.delegate?.deleteRows(at: [indexPath], with: .automatic) } case .insert: if let newIndexPath = newIndexPath { self.delegate?.insertRows(at: [newIndexPath], with: .automatic) } case .update: if let indexPath = indexPath { self.delegate?.reloadRows(at: [indexPath], with: .automatic) } case .move: if let indexPath = indexPath { self.delegate?.deleteRows(at: [indexPath], with: .automatic) } if let newIndexPath = newIndexPath { self.delegate?.insertRows(at: [newIndexPath], with: .automatic) } } } } func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { DispatchQueue.main.async { self.delegate?.beginUpdates() } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { DispatchQueue.main.async { self.delegate?.endUpdates() } } } protocol DataSourceDelegate: class { func beginUpdates() func endUpdates() func insertRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation) func deleteRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation) func reloadRows(at indexPaths: [IndexPath], with animation: UITableView.RowAnimation) } <file_sep>// // PresentationAssembly.swift // Blah Blah Chat // // Created by Екатерина on 16.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit protocol PresentationAssemblyProtocol { func themesViewController(_ closure: @escaping ColorAlias) -> ThemesViewControllerSwift func profileViewController() -> ProfileViewController func conversationsListViewController() -> ConversationsListViewController func chatViewController(model: ChatModel) -> ChatViewController func picturesViewController() -> PicturesViewController } class PresentationAssembly: PresentationAssemblyProtocol { private let serviceAssembly: ServicesAssemblyProtocol init(serviceAssembly: ServicesAssemblyProtocol) { self.serviceAssembly = serviceAssembly } func themesViewController(_ closure: @escaping ColorAlias) -> ThemesViewControllerSwift { return ThemesViewControllerSwift(model: themesModel(closure)) } private func themesModel(_ closure: @escaping ColorAlias) -> ThemesModelProtocol { return ThemesModel(theme1: #colorLiteral(red: 0.9372549057, green: 0.9372549057, blue: 0.9568627477, alpha: 1), theme2: #colorLiteral(red: 0.2941176471, green: 0.2941176471, blue: 0.2941176471, alpha: 1), theme3: #colorLiteral(red: 0.8588235294, green: 0.9176470588, blue: 1, alpha: 1), closure: closure) } func profileViewController() -> ProfileViewController { return ProfileViewController(model: profileModel(), presentationAssembly: self) } private func profileModel() -> AppUserModelProtocol { return ProfileModel(dataService: CoreDataManager()) } func chatViewController(model: ChatModel) -> ChatViewController { return ChatViewController(model: model) } func conversationsListViewController() -> ConversationsListViewController { return ConversationsListViewController(model: conversationsListModel(), presentationAssembly: self) } private func conversationsListModel() -> ConversationModelProtocol { return ConversationModel(communicationService: serviceAssembly.communicationService, themesService: serviceAssembly.themesService, frService: serviceAssembly.frService) } func picturesViewController() -> PicturesViewController { return PicturesViewController(model: picturesModel()) } private func picturesModel() -> PicturesModelProtocol { return PicturesModel(picturesService: serviceAssembly.picturesService) } } <file_sep>// // SearchParser.swift // Blah Blah Chat // // Created by Екатерина on 17.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation struct Response: Codable { let hits: [Picture] } class SearchImagesParser: ParserProtocol { typealias Model = [Picture] func parse(data: Data) -> Model? { do { return try JSONDecoder().decode(Response.self, from: data).hits } catch { print("Error trying to convert data to JSON SearchParser") return nil } } } <file_sep>// // ServicesAssembly.swift // Blah Blah Chat // // Created by Екатерина on 15.04.2019. // Copyright © 2019 Wineapp. All rights reserved. // import Foundation protocol ServicesAssemblyProtocol { var frService: FRServiceProtocol { get } var themesService: ThemesServiceProtocol { get } var communicationService: CommunicatorDelegate { get } var picturesService: PicturesServiceProtocol { get } } class ServicesAssembly: ServicesAssemblyProtocol { private let coreAssembly: CoreAssemblyProtocol init(coreAssembly: CoreAssemblyProtocol) { self.coreAssembly = coreAssembly } lazy var frService: FRServiceProtocol = FetchRequestService(stack: coreAssembly.coreDataStub) lazy var communicationService: CommunicatorDelegate = CommunicationService(dataManager: coreAssembly.dataManager, communicator: coreAssembly.multipeerCommunicator) lazy var themesService: ThemesServiceProtocol = ThemesService(themesManager: coreAssembly.themesManager) lazy var picturesService: PicturesServiceProtocol = PicturesService(requestSender: coreAssembly.requestSender) } <file_sep>// // ConversationsListViewController.swift // Blah Blah Chat // // Created by Екатерина on 20.02.2019. // Copyright © 2019 Wineapp. All rights reserved. // import UIKit class ConversationsListViewController: UIViewController { @IBOutlet var convListTableView: UITableView! private var model: ConversationModelProtocol private let presentationAssembly: PresentationAssemblyProtocol private var emitter: Emitter! init(model: ConversationModelProtocol, presentationAssembly: PresentationAssemblyProtocol) { self.model = model self.presentationAssembly = presentationAssembly super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() model.reloadThemeSettings() setupTableView() model.dataSource = ConversationDataSource(delegate: convListTableView, fetchRequest: model.frService.allConversations()!, context: model.frService.saveContext) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) setupNavBar() } private func setupTableView() { self.convListTableView.delegate = self self.convListTableView.dataSource = self let nib = UINib(nibName: "ConversationTableViewCell", bundle: nil) self.convListTableView.register(nib, forCellReuseIdentifier: "chatCell") self.convListTableView.rowHeight = UITableView.automaticDimension self.convListTableView.estimatedRowHeight = 67 } private func setupNavBar() { navigationItem.title = "Blah Blah Chat" let profileButton = UIBarButtonItem(image: #imageLiteral(resourceName: "icons8-outline-of-a-face-50"), style: .plain, target: self, action: #selector(self.showProfile) ) profileButton.tintColor = UIColor.gray navigationItem.rightBarButtonItem = profileButton let themesButton = UIBarButtonItem(image: #imageLiteral(resourceName: "icons8-settings-filled-50"), style: .plain, target: self, action: #selector(self.showThemeSettings) ) navigationItem.leftBarButtonItem = themesButton } @objc func showProfile() { let controller = presentationAssembly.profileViewController() let navigationController = UINavigationController() navigationController.viewControllers = [controller] emitter = Emitter(view: navigationController.view) present(navigationController, animated: true) } @objc func showThemeSettings() { let controller = presentationAssembly.themesViewController { [weak self] (controller: ThemesViewControllerSwift, selectedTheme: UIColor?) in guard let theme = selectedTheme else { return } controller.view.backgroundColor = theme self?.model.saveSettings(for: theme) } let navigationController = UINavigationController() navigationController.viewControllers = [controller] emitter = Emitter(view: navigationController.view) present(navigationController, animated: true) } } // MARK: - Table View Delegate Methods extension ConversationsListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard let conversation = model.dataSource?.fetchedResultsController.object(at: indexPath) else { return } let controller = presentationAssembly.chatViewController(model: ChatModel(communicationService: model.communicationService, frService: model.frService, conversation: conversation)) controller.navigationItem.title = conversation.user?.name navigationController?.pushViewController(controller, animated: true) tableView.deselectRow(at: indexPath, animated: true) } } // MARK: - Table View Datasource extension ConversationsListViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { guard let sectionsCount = model.dataSource?.fetchedResultsController.sections?.count else { return 0 } return sectionsCount } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let sections = model.dataSource?.fetchedResultsController.sections else { return 0 } return sections[section].numberOfObjects } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier = "chatCell" var convCell: ConversationTableViewCell if let cell = tableView.dequeueReusableCell(withIdentifier: identifier) as? ConversationTableViewCell { convCell = cell } else { convCell = ConversationTableViewCell(style: .default, reuseIdentifier: identifier) } if let conversation = model.dataSource?.fetchedResultsController.object(at: indexPath) { if let user = conversation.user { convCell.name = user.name } convCell.configureCell(conversation: conversation) } return convCell } }
cabbfe03d69343e00ba30382d9544782ef723a4d
[ "Swift" ]
46
Swift
yukim17/Blah-Blah-Chat
704d5eb09d724fc3b24af74c8345885f123386d8
996607744a8dd8518c7fcb2cd298845f49025de7
refs/heads/master
<repo_name>ashishtayal89/create-node-basic-app<file_sep>/src/cli.js import getOptions from "./options"; import { createProject } from "./main"; export async function cli(args) { const options = await getOptions(args); await createProject(options); } <file_sep>/Readme.md # Create a basic node project Tutorial : twilio.com/blog/how-to-build-a-cli-with-node-js
918b79cf0f28e0166c69cb644603cd555d0b477b
[ "JavaScript", "Markdown" ]
2
JavaScript
ashishtayal89/create-node-basic-app
b118cc686b44bee146183d187e9984236e115b78
17539142e7f90f6ab5cc2080fe11d64437d1a693
refs/heads/main
<repo_name>libhide/mincast<file_sep>/app/src/main/java/com/madebyratik/mincast/NavGraph.kt package com.madebyratik.mincast import androidx.annotation.StringRes sealed class Screen(val route: String, @StringRes val resourceId: Int, val iconIdRes: Int) { object Explore : Screen("explore", R.string.explore_label, R.drawable.ic_explore) object Saved : Screen("saved", R.string.saved_label, R.drawable.ic_saved) object Search : Screen("search", R.string.search_label, R.drawable.ic_search) object Profile : Screen("profile", R.string.profile_label, R.drawable.ic_profile) }<file_sep>/app/src/main/java/com/madebyratik/mincast/ui/components/PodcastItem.kt package com.madebyratik.mincast.ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.imageResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.madebyratik.mincast.data.podcasts import com.madebyratik.mincast.model.Podcast import com.madebyratik.mincast.ui.theme.MinCastTheme @Composable fun PodcastItem(podcast: Podcast, modifier: Modifier = Modifier) { Column( modifier = modifier .width(242.dp) .padding(end = 10.dp) ) { Image( bitmap = ImageBitmap.imageResource(id = podcast.thumbnailResId), contentDescription = podcast.name, contentScale = ContentScale.FillWidth, modifier = Modifier .align(Alignment.Start) .fillMaxWidth() ) Spacer(modifier = Modifier.height(8.dp)) Text( text = podcast.name, maxLines = 2, style = MaterialTheme.typography.h3, modifier = Modifier .height(54.dp) ) } } @Preview("Podcast Item") @Composable fun PodcastItemPreview() { val podcast = podcasts.first() MinCastTheme { Surface { PodcastItem(podcast = podcast) } } } <file_sep>/app/src/main/java/com/madebyratik/mincast/ui/components/SectionWithAction.kt package com.madebyratik.mincast.ui.components import androidx.compose.foundation.layout.* import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.madebyratik.mincast.ui.theme.MinCastTheme @Composable fun SectionWithAction( title: String, actionButtonTitle: String, modifier: Modifier = Modifier, action: () -> Unit = {}, Content: @Composable () -> Unit, ) { Box(modifier = modifier.padding(bottom = 16.dp)) { Column { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .padding(bottom = 5.dp) .fillMaxWidth() ) { SectionTitle(text = title) TextButton(onClick = action) { Text(actionButtonTitle) } } Content() } } } @Preview("Section with Action") @Composable fun SectionWithActionPreview() { MinCastTheme { Surface { SectionWithAction( title = "Title", actionButtonTitle = "Action", modifier = Modifier.padding(horizontal = 16.dp) ) { Text(text = "Content") } } } }<file_sep>/app/src/main/java/com/madebyratik/mincast/data/PodcastsData.kt package com.madebyratik.mincast.data import com.madebyratik.mincast.R import com.madebyratik.mincast.model.Episode import com.madebyratik.mincast.model.Podcast val podcasts = listOf( Podcast(name = "Waveform", thumbnailResId = R.drawable.thumb_waveform), Podcast(name = "Developer Tea", thumbnailResId = R.drawable.thumb_developer_tea), Podcast( name = "<NAME> Does a Podcast With...", thumbnailResId = R.drawable.thumb_david_tennant ), Podcast( name = "The Seen and the Unseen", thumbnailResId = R.drawable.thumb_seen_unseen ), Podcast(name = "Vergecast", thumbnailResId = R.drawable.thumb_vergecast), ) val episodes = listOf( Episode( name = "The Walls Close In", publishDelta = "10h", duration = 45, artworkResId = R.drawable.artwork_tal ), Episode( name = "The Art of Gathering", publishDelta = "2d", duration = 30, artworkResId = R.drawable.artwork_hurry_slowly ), Episode( name = "Language with a Capital L", publishDelta = "2d", duration = 51, artworkResId = R.drawable.artwork_unbox ), Episode( name = "How do you make a stack overflow?", publishDelta = "5d", duration = 27, artworkResId = R.drawable.artwork_basecs ), Episode( name = "King Kunta by <NAME>", publishDelta = "1d", duration = 25, artworkResId = R.drawable.artwork_dissect ) )<file_sep>/build.gradle buildscript { ext { gradle_version = '7.0.0-alpha08' kotlin_version = '1.4.30' appcompat_version = '1.2.0' core_ktx_version = '1.3.2' material_version = '1.3.0' lifecycle_version = '2.3.0' compose_version = '1.0.0-beta01' nav_compose_version = "1.0.0-alpha08" nav_version = "2.3.3" } repositories { google() jcenter() } dependencies { classpath "com.android.tools.build:gradle:$gradle_version" classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } subprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }<file_sep>/app/src/main/java/com/madebyratik/mincast/ui/components/Section.kt package com.madebyratik.mincast.ui.components import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun Section( title: String, modifier: Modifier = Modifier, Content: @Composable () -> Unit, ) { Box(modifier = modifier.padding(bottom = 16.dp)) { Column { SectionTitle( text = title, modifier = Modifier.padding(bottom = 5.dp) ) Content() } } }<file_sep>/app/src/main/java/com/madebyratik/mincast/ui/search/SearchScreen.kt package com.madebyratik.mincast.ui.search import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import com.madebyratik.mincast.R import com.madebyratik.mincast.ui.components.ScreenTitle import com.madebyratik.mincast.ui.theme.MinCastTheme @Composable fun SearchScreen(navController: NavController) { Search() } @Composable fun Search() { val context = LocalContext.current val title = context.getString(R.string.search_label) Surface(modifier = Modifier.fillMaxSize()) { ScreenTitle( text = title, modifier = Modifier.wrapContentSize(align = Alignment.TopStart) ) } } @Preview("Search Screen") @Composable fun SearchScreenPreview() { MinCastTheme { Search() } } @Preview("Saved Screen • Dark Mode") @Composable fun SearchScreenDarkPreview() { MinCastTheme(darkTheme = true) { Search() } } <file_sep>/README.md # Mincast Toy app to help learn Jetpack Compose. ![Compose](https://img.shields.io/badge/Compose-1.0.0--alpha06-brightgreen) [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://GitHub.com/Naereen/StrapDown.js/graphs/commit-activity) [![MIT license](https://img.shields.io/badge/License-MIT-blue.svg)](https://lbesson.mit-license.org/) <img src="https://i.postimg.cc/nLwpSnn0/Art.jpg" alt="Screenshot of the app on the left, Jetpack Compose logo on the right" /> ## Design Credit YesYou Studio's Podcast app [mockup](https://dribbble.com/shots/13926718-Podcast-App) from Dribbble was used as a starting point for Mincast's design. <file_sep>/settings.gradle rootProject.name = "MinCast" include ':app' <file_sep>/app/src/main/java/com/madebyratik/mincast/ui/components/SectionTitle.kt package com.madebyratik.mincast.ui.components import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun SectionTitle( text: String, modifier: Modifier = Modifier ) { Text( text = text, style = MaterialTheme.typography.h2, modifier = modifier ) }<file_sep>/app/src/main/java/com/madebyratik/mincast/ui/explore/ExploreViewModel.kt package com.madebyratik.mincast.ui.explore import androidx.lifecycle.ViewModel import com.madebyratik.mincast.data.PodcastsRepo import com.madebyratik.mincast.model.Episode import com.madebyratik.mincast.model.Podcast class ExploreViewModel(private val podcastsRepo: PodcastsRepo): ViewModel() { fun getPopularPodcasts(): List<Podcast> { return podcastsRepo.getPopularPodcasts() } fun getRecommendedEpisodes(): List<Episode> { return podcastsRepo.getRecommendedEpisodes() } }<file_sep>/app/src/main/java/com/madebyratik/mincast/model/Podcast.kt package com.madebyratik.mincast.model data class Podcast( val name: String, val thumbnailResId: Int, )<file_sep>/app/src/main/java/com/madebyratik/mincast/ui/explore/ExploreScreen.kt package com.madebyratik.mincast.ui.explore import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.madebyratik.mincast.R import com.madebyratik.mincast.data.episodes import com.madebyratik.mincast.data.podcasts import com.madebyratik.mincast.model.Episode import com.madebyratik.mincast.model.Podcast import com.madebyratik.mincast.ui.components.* import com.madebyratik.mincast.ui.theme.MinCastTheme @Composable fun ExploreScreen( navController: NavController, podcasts: List<Podcast>, recommendedEpisodes: List<Episode> ) { Explore(podcasts = podcasts, recommendedEpisodes = recommendedEpisodes) } @Composable fun Explore(podcasts: List<Podcast>, recommendedEpisodes: List<Episode>) { val context = LocalContext.current val title = context.getString(R.string.explore_label) val popularShowsTitle = context.getString(R.string.popular_shows_label) val recommendedTitle = context.getString(R.string.recommended_label) val showAllActionTitle = context.getString(R.string.show_all_label) Surface(modifier = Modifier.fillMaxSize()) { Column( modifier = Modifier .fillMaxWidth() .verticalScroll(rememberScrollState()) ) { ScreenTitle(text = title) Section( title = popularShowsTitle, modifier = Modifier.padding(horizontal = 16.dp) ) { LazyRow { items(podcasts) { PodcastItem(podcast = it) } } } SectionWithAction( title = recommendedTitle, actionButtonTitle = showAllActionTitle, modifier = Modifier.padding(horizontal = 16.dp) ) { LazyRow { items(recommendedEpisodes) { EpisodeItem(episode = it) } } } } } } @Preview("Explore Screen") @Composable fun ExploreScreenPreview() { MinCastTheme { Explore( podcasts = podcasts, recommendedEpisodes = episodes ) } } @Preview("Explore Screen • Dark Mode") @Composable fun ExploreScreenDarkPreview() { MinCastTheme(darkTheme = true) { Explore( podcasts = podcasts, recommendedEpisodes = episodes ) } } <file_sep>/app/src/main/java/com/madebyratik/mincast/ui/profile/ProfileScreen.kt package com.madebyratik.mincast.ui.profile import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import com.madebyratik.mincast.R import com.madebyratik.mincast.ui.components.ScreenTitle import com.madebyratik.mincast.ui.theme.MinCastTheme @Composable fun ProfileScreen(navController: NavController) { Profile() } @Composable fun Profile() { val context = LocalContext.current val title = context.getString(R.string.profile_label) Surface(modifier = Modifier.fillMaxSize()) { ScreenTitle( text = title, modifier = Modifier.wrapContentSize(align = Alignment.TopStart) ) } } @Preview("Profile Screen") @Composable fun ProfileScreenPreview() { MinCastTheme { Profile() } } @Preview("Profile Screen • Dark Mode") @Composable fun ProfileScreenDarkPreview() { MinCastTheme(darkTheme = true) { Profile() } } <file_sep>/app/src/main/java/com/madebyratik/mincast/ui/theme/Typography.kt package com.madebyratik.mincast.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.madebyratik.mincast.R val PoppinsFontFamily = FontFamily( Font(R.font.poppins_regular), Font(R.font.poppins_medium, FontWeight.Medium), Font(R.font.poppins_semibold, FontWeight.SemiBold), Font(R.font.poppins_bold, FontWeight.Bold), ) val Typography = Typography( defaultFontFamily = PoppinsFontFamily, h1 = TextStyle( fontWeight = FontWeight.Bold, fontSize = 36.sp ), h2 = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 24.sp ), h3 = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 18.sp ), subtitle1 = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 12.sp ), subtitle2 = TextStyle( fontWeight = FontWeight.SemiBold, fontSize = 11.sp, color = MidGrey ), body1 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 16.sp ), body2 = TextStyle( fontWeight = FontWeight.Normal, fontSize = 14.sp ), button = TextStyle( fontWeight = FontWeight.Medium, fontSize = 14.sp, letterSpacing = 1.5.sp ), ) <file_sep>/app/src/main/java/com/madebyratik/mincast/model/Episode.kt package com.madebyratik.mincast.model data class Episode( val name: String, val publishDelta: String, val duration: Int, val artworkResId: Int ) { fun metadata() = "$publishDelta • ${duration}min" }<file_sep>/app/src/main/java/com/madebyratik/mincast/MinCastApp.kt package com.madebyratik.mincast import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.stringResource import androidx.compose.ui.res.vectorResource import androidx.navigation.compose.* import com.madebyratik.mincast.data.episodes import com.madebyratik.mincast.data.podcasts import com.madebyratik.mincast.ui.explore.ExploreScreen import com.madebyratik.mincast.ui.profile.ProfileScreen import com.madebyratik.mincast.ui.saved.SavedScreen import com.madebyratik.mincast.ui.search.SearchScreen import com.madebyratik.mincast.ui.theme.MinCastTheme @Composable fun MinCastApp() { val navController = rememberNavController() val navItems = listOf( Screen.Explore, Screen.Saved, Screen.Search, Screen.Profile ) MinCastTheme { Scaffold( bottomBar = { BottomNavigation { val navBackStackEntry by navController.currentBackStackEntryAsState() val currentRoute = navBackStackEntry?.arguments?.getString(KEY_ROUTE) navItems.forEach { screen -> BottomNavigationItem( icon = { Icon( imageVector = ImageVector.vectorResource(id = screen.iconIdRes), contentDescription = screen.route ) }, label = { Text(text = stringResource(id = screen.resourceId)) }, selected = currentRoute == screen.route, onClick = { // This is the equivalent to popUpTo the start destination navController.popBackStack( navController.graph.startDestination, false ) // This if check gives us a "singleTop" behavior where we do not create a // second instance of the composable if we are already on that destination if (currentRoute != screen.route) { navController.navigate(screen.route) } } ) } } } ) { NavHost(navController, startDestination = Screen.Explore.route) { composable(Screen.Explore.route) { ExploreScreen( navController, podcasts, episodes ) } composable(Screen.Saved.route) { SavedScreen(navController) } composable(Screen.Search.route) { SearchScreen(navController) } composable(Screen.Profile.route) { ProfileScreen(navController) } } } } }<file_sep>/app/src/main/java/com/madebyratik/mincast/ui/saved/SavedScreen.kt package com.madebyratik.mincast.ui.saved import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.Surface import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.navigation.NavController import com.madebyratik.mincast.R import com.madebyratik.mincast.ui.components.ScreenTitle import com.madebyratik.mincast.ui.theme.MinCastTheme @Composable fun SavedScreen(navController: NavController) { Saved() } @Composable fun Saved() { val context = LocalContext.current val title = context.getString(R.string.saved_label) Surface(modifier = Modifier.fillMaxSize()) { ScreenTitle( text = title, modifier = Modifier.wrapContentSize(align = Alignment.TopStart) ) } } @Preview("Saved Screen") @Composable fun SavedScreenPreview() { MinCastTheme { Saved() } } @Preview("Saved Screen • Dark Mode") @Composable fun SavedScreenDarkPreview() { MinCastTheme(darkTheme = true) { Saved() } } <file_sep>/app/src/main/java/com/madebyratik/mincast/data/FakePodcastsRepo.kt package com.madebyratik.mincast.data import com.madebyratik.mincast.model.Episode import com.madebyratik.mincast.model.Podcast class FakePodcastsRepo : PodcastsRepo { override fun getPopularPodcasts(): List<Podcast> { return podcasts } override fun getRecommendedEpisodes(): List<Episode> { return episodes } } <file_sep>/app/src/main/java/com/madebyratik/mincast/ui/components/EpisodeItem.kt package com.madebyratik.mincast.ui.components import androidx.compose.foundation.Image import androidx.compose.foundation.layout.* import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.imageResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.madebyratik.mincast.data.episodes import com.madebyratik.mincast.model.Episode import com.madebyratik.mincast.ui.theme.MinCastTheme @Composable fun EpisodeItem(episode: Episode, modifier: Modifier = Modifier) { Column( modifier = modifier .width(148.dp) .padding(end = 10.dp) ) { Image( bitmap = ImageBitmap.imageResource(id = episode.artworkResId), contentDescription = episode.name, contentScale = ContentScale.FillWidth, modifier = Modifier .align(Alignment.Start) .fillMaxWidth() ) Spacer(modifier = Modifier.height(10.dp)) Text( text = episode.name, maxLines = 1, style = MaterialTheme.typography.subtitle1, modifier = Modifier ) Text( text = episode.metadata(), maxLines = 1, style = MaterialTheme.typography.subtitle2, modifier = Modifier ) } } @Preview("Episode Item") @Composable fun EpisodeItemPreview() { val episode = episodes.first() MinCastTheme { Surface { EpisodeItem(episode = episode) } } } <file_sep>/app/build.gradle plugins { id 'com.android.application' id 'kotlin-android' } android { compileSdkVersion 30 defaultConfig { applicationId "com.madebyratik.mincast" minSdkVersion 30 targetSdkVersion 30 versionCode 1 versionName "1.0" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } kotlinOptions { jvmTarget = '1.8' useIR = true } buildFeatures { compose true // Disable unused AGP features buildConfig false aidl false renderScript false resValues false shaders false } composeOptions { kotlinCompilerExtensionVersion compose_version } } dependencies { // Kotlin implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation "androidx.core:core-ktx:$core_ktx_version" // Android implementation "androidx.appcompat:appcompat:$appcompat_version" implementation "com.google.android.material:material:$material_version" // Lifecycle implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version" // Compose implementation "androidx.compose.ui:ui:$compose_version" implementation "androidx.compose.runtime:runtime:$compose_version" // Tooling support (Previews, etc.) implementation "androidx.compose.ui:ui-tooling:$compose_version" // Foundation (Border, Background, Box, Image, Scroll, shapes, animations, etc.) implementation "androidx.compose.foundation:foundation:$compose_version" // Material Design implementation "androidx.compose.material:material:$compose_version" // Material design icons implementation "androidx.compose.material:material-icons-core:$compose_version" // implementation 'androidx.compose.material:material-icons-extended:1.0.0-beta01' // Navigation Compose implementation "androidx.navigation:navigation-compose:$nav_compose_version" implementation "androidx.navigation:navigation-fragment-ktx:$nav_version" implementation "androidx.navigation:navigation-ui-ktx:$nav_version" }<file_sep>/app/src/main/java/com/madebyratik/mincast/data/PodcastsRepo.kt package com.madebyratik.mincast.data import com.madebyratik.mincast.model.Episode import com.madebyratik.mincast.model.Podcast interface PodcastsRepo { fun getPopularPodcasts(): List<Podcast> fun getRecommendedEpisodes(): List<Episode> }<file_sep>/app/src/main/java/com/madebyratik/mincast/ui/theme/Color.kt package com.madebyratik.mincast.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBA86FC) val Purple300 = Color(0xFFCD52FC) val Purple600 = Color(0xFF9F00F4) val Purple700 = Color(0xFF8100EF) val Purple800 = Color(0xFF0000E1) val Red200 = Color(0xFFCF6679) val Red300 = Color(0xFFD00036) val Red800 = Color(0xFFEA6D7E) val Black = Color(0xFF000000) val Grey200 = Color(0xFFEFEFEF) val MidGrey = Color(0xFF929292) val Grey = Color(0xFF35373C) val DarkGrey = Color(0xFF27292D)<file_sep>/app/src/main/java/com/madebyratik/mincast/ui/components/ScreenTitle.kt package com.madebyratik.mincast.ui.components import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun ScreenTitle( text: String, modifier: Modifier = Modifier ) { Text( text = text, style = MaterialTheme.typography.h1, modifier = modifier .padding(vertical = 16.dp, horizontal = 16.dp) ) }
323485d6313a8327a9761179446fcf0cf39fef36
[ "Markdown", "Kotlin", "Gradle" ]
24
Kotlin
libhide/mincast
6f933b453833f4046b3bd950b99b5218300a787c
972525877fab55dbe550e70280ebc4651bb9d6a8
refs/heads/master
<file_sep># Import smtplib for the actual sending function import smtplib import email.Utils # Import the email modules we'll need from email.mime.text import MIMEText # Open a plain text file for reading. For this example, assume that # the text file contains only ASCII characters. textfile = 'message' # Create a text/plain message content = 'Testing 2 3 4' msg = MIMEText(content) FROM = '<EMAIL>' TO = '<EMAIL>' # me == the sender's email address # you == the recipient's email address msg['Subject'] = 'Wake-up call' msg['From'] = FROM msg['To'] = TO # Send the message via our own SMTP server, but don't include the # envelope header. HOST = 'smtp.gmail.com' s = smtplib.SMTP(HOST) s.starttls() s.login(FROM,'55zzajzzaj') s.sendmail(FROM, TO, msg.as_string()) s.quit() <file_sep>from sms_notifier import SMSNotifier import requests def sendAlert(args, voice): for sms in args: reply = "" number = sms['number'] entry = sms['content'].lower() queries = {} commands = entry.split(',') for command in commands: tokens = command.split(':') queries[tokens[0]] = token[1] r = requests.get("http://cs.swarthmore.edu/~ebogdan1/deploy_audio.php", params=queries) def main(): notifier = SMSNotifier() notifier.startNotifications(sendAlert) try: while True: pass except: print "\nForce quit" notifier.stopNotifications() if __name__ == '__main__': main() <file_sep>from sms_notifier import SMSNotifier from random import randint, uniform from time import sleep PRIMARY_LINE = '13392259212' CODE = 'wake me' def autoReply(args, voice): for sms in args: content = sms['content'] number = sms['number'] if number == PRIMARY_LINE and content == CODE: rand_words = ["hey","what's up","now","dude","man"] reply = "" num_words = randint(1,4) for i in range(num_words): reply += rand_words[randint(0,4)]+' ' sleep(uniform(0.5, 2.5)) print "Sending auto-reply:",reply voice.send_sms(number, reply) def main(): notifier = SMSNotifier() notifier.idleDelay = 2 #even when idle needs to be responsive notifier.startNotifications(autoReply) try: while True: pass except: print "\nForce quit" notifier.stopNotifications() if __name__ == '__main__': main() <file_sep>from voice import Voice from time import sleep from random import uniform, randint def safeBatch(voice, recipients, message_for_recipient, count): """ Sends a series of messages without triggering Google's spam blockers voice: reference to PyGoogleVoice object for sending recipients: list of phone numbers message_for_recipient: dictionary with message (value) for number (key); must include 'default' key for all messages without unique keys count: number of copies of each message to send; mostly for testing """ if not message_for_recipient.has_key('default'): print "Error: safeBatch requires dictionary with 'default' key" return -1 auto_responder = '13479278460' auto_respond_code = 'wake me' c = randint(2,3) for i in range(count): for recipient in recipients: if c == 0: try: voice.send_sms(auto_responder, auto_respond_code) print "contacted auto-responder" except: print "ERROR: failed to contact auto-responder" c = randint(2,3) sleep(uniform(2.0,4.0)) if message_for_recipient.has_key(recipient): message = message_for_recipient[recipient] else: message = message_for_recipient['default'] try: voice.send_sms(recipient, message) print "sent message",i,"to",recipient c -= 1 except: print "ERROR: failed to send message",i,"to",recipient c = 0 #attempt to correct problem by contacting auto-responder sleep(uniform(2.0,4.0)) def main(): v = Voice() v.login() print "Logged in" messages = {} messages['default'] = "Hey, that last one worked! Just so y'all know. "+\ "Definitely not using this bit of news as an excuse for another "+\ "test... Nope." # Ethan, Emily, Tessa, Ray, Ravenna, Brad, Smemo, Alex recipients = [3392259591,8314282464,8143317131,2677605589,\ 3237930250, 7328042482, 6104258656, 7033362529] safeBatch(v, recipients, messages, 1) v.logout() print "Logged out" if __name__ == '__main__': main() <file_sep>#! /usr/bin/python """*************************************************** Just one of those random scripts to ease my need to actually open a web browser while working on the terminal. Allows you to check what is being offered at sharples on that day. February 9, 2011 <NAME> ***************************************************""" import urllib2 def readData(html): page = [s.strip() for s in html.splitlines()] food = [] toggle = 0 lineNum = 0 for line in page: if (line == '<div class="dashmodule drag" id="dining">' or line == '<div class="dashmodule drag mobiledashmodule" id="dining">' or line == '<h2 class="dashmodule-header hide">Menu</h2>' or line == '<div class="dining-meal">'): toggle = 1 if (lineNum == 25 or line == '<div class="dining-menu"></div>' or line == '<div class="dining-menu"><div><div>'or line == 'div class="dashmodule-footer">' or line == '<p>&nbsp;</p>'): toggle = 0 if (toggle == 1): food.append(line) lineNum = lineNum + 1 return food def removeChaff(data): charloc = 0 rand = "" output = "" add = 1 for item in data: for lettr in item: if (lettr == '<'): add = 0 if (add == 1): rand = rand + lettr elif (lettr == '>'): add = 1 data[charloc] = rand output += rand+'\n' rand = "" charloc = charloc + 1 return output def getMenu(): url = "https://secure.swarthmore.edu/dash/" opener = urllib2.build_opener(urllib2.HTTPCookieProcessor()) urllib2.install_opener(opener) sock = urllib2.urlopen(url) htmlSource = sock.read() sock.close() food = readData(htmlSource) return removeChaff(food) def main(): print getMenu() if __name__ == '__main__': main()
771bfb71a2525a9e555684389e7c3a9a2f2f2520
[ "Python" ]
5
Python
ethan-bogdan/independent-study
06653770ce8b35326bc30526ec268a00ffc873c3
cc52ab2e50f9943b363085605834902ce843c814
refs/heads/main
<repo_name>helenamin/Perth-City-Properties<file_sep>/requirements.txt Flask==2.0.1 gunicorn==20.1.0 pandas==1.3.2 sklearn==0.0 SQLAlchemy==1.4.23 <file_sep>/README.md # Perth City Properties ![perth city](static/images/PerthCity.png) ## Table of Contents - [Introduction](#Introduction) - [Structure](#Structure) - [Deployed Site](#Deployed_Site) - [Analysis](#Analysis) - [Data Sources](#DataSources) - [Technology](#Technology) - [Contributors](#Contributors) ## Introduction <b>Project Outline:</b> To create a visualised data on real estate properties in the City of Perth. This includes suburbs - Crawley, East Perth, Nedlands, Northbridge, Perth, and West Perth. We also want to assist future buyers and investors to be able to predict the future property price. <b>Questions:</b> This project sets out to answer the following : * What are the price range of each suburb? * What are the property type that people are interested in buying? * Which age range does the sold properties mostly fall under? * Does the number of car park affect property price? * What are the key factors that are impacting the property price? * Are some properties better to rent or buy? * How much is the return of investment? * Have Covid-19 impacted the Real Estate market? <b>ETL Process:</b> Dataset scraped from http://house.speakingsame.com/ site and filled some missing data manually using another two realestate websites to ensure data integrity. Cleaned the data by removing N/A and converted data types, combined all the data of the suburbs into a single data frame. Load data onto SQLite and retrieve SQL data in Flask file to create the API. <b>Scope: </b> Properties meaning residential properties which includes Unit, Apartments, Townhouses, Houses. This project will only look at landed properties - House, Townhouse & Villa. Rent column implies that the property has been advertised and has been rented out in at the time of the Rent Date. Rent with 0 dollars value have not been advertised for Rental and will have Rent Date of 01/01/1900. ## Structure ``` Perth City Properties | |__Archive/ # conitains archived files since project started | |__ML_Model/ # contians saved mashine learning models | |__ Notebooks/ # contains ETL and ML notebooks | |__ Add location.ipynb # add Geospatial data to csv files | |__ ETL.ipynb # data extract, transform, load to SQL | |__ ML notebooks | |__ scrape.ipynb | |__SQL | |__static/ | |__ css # css files for webpage | |__ data # Directory for the data files | |__ images # images used in project | |__ js # js files for webpage | |__Tableau # tableau files | |__templates # conitan index.html | |__ .gitignore |__ app.py # flask file |__ LICENSE |__ Procfile # related Heroku |__ Project3_proposal.docx |__ README.md # read me file |__ requirement.txt # contains project dependencies ``` ## [Deployed_Site](https://cityofperthproperties.herokuapp.com/) ## Analysis #### Suburbs' Characteristics - Crawley and Nedlands have properties with more land size and a higher average price compared with the other 4 suburbs. ![Suburb Characteristics Dashboard](static/images/suburb_characteristics.png) #### Suburbs' Price Ranges - Perth, East Perth, West Perth and Northbridge have similar average price whereas Crawley and Nedlands are almost more than double. ![Suburb Price Range Dashboard](static/images/price_range.png) #### Suburbs' Property Types - More apartments and units around Perth and it's surrounding suburbs. Moving away, there are more properties with land in the outer suburbs. ![Suburb Property Type Dashboard](static/images/property_type.png) #### Ages of properties - There are properties dated all the way back to 1910s and despite the age of the property, their price are well above average. - Perth have newer properties, exploring further identified that most of them are apartments. ![Suburb Building Age Dashboard](static/images/building_age.png) #### Property car spaces - The average price of a property increases the same as number of car spaces with the height at 4 car spaces at over 2.2 Million dollars. ![Property Car Space Dashboard](static/images/car_space.png) #### Property buyer and seller guide - Buyer and sellers can use the guide to identify the average price that they would be paying for in a suburb according to the property criteria that they want. - Can also use the Best Agent chart to identify the best real estate agent when deciding to buy or sell a property. ![Buyer & Seller Guide Dashboard](static/images/buyer_seller_guide.png) #### Rent or Buy and ROIs - In some suburbs, it is much better to rent than buy due to the pricing of a property. - Most properties have a good Return of Investment (ROI) of 4 to 7% - Do note that the weekly loan payments is calculated with using the sold price of the property and a fixed annual rate of 3%, not including home loan deposits. ![Buy or Sell Dashboard](static/images/buy_or_sell.png) #### Property Market since Covid started - We can see a decline in purchase when the lockdown was announced in March 2020, however as soon as the Federal Government announced the grant in June 2020, numbers of properties sold increases. ![Property Market During Covid Era Dashboard](static/images/covid.png) ## DataSources http://house.speakingsame.com/ https://www.onthehouse.com.au/ https://www.propertyvalue.com.au/ ## Technology ![PythonLogo](static/images/tools.png) ## Contributors - [<NAME>](https://github.com/helenamin) - [<NAME>](https://foofx88.github.io) <file_sep>/Archived/app.py from flask import Flask, jsonify from flask import render_template, redirect ################################################# # Database Setup ################################################# ################################################# # Flask Setup ################################################# app = Flask(__name__) ################################################# # Flask Routes ################################################# @app.route("/") @app.route("/home") def home(): # Return template and data return render_template("index.html") @app.route("/about") def about(): # Return template and data return render_template("about.html") @app.route("/estimation") def estimation(): # Return template and data return render_template("estimation.html") if __name__ == '__main__': app.run(port=5500, debug=True)<file_sep>/app.py from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine from flask import Flask, jsonify from flask import render_template, request import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.model_selection import GridSearchCV from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error from sklearn.linear_model import Lasso import joblib import math import os ################################################# # Database Setup ################################################# engine = create_engine("sqlite:///SQL/CityOfPerth.sqlite") # reflect an existing database into a new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference to the table PerthCity = Base.classes.perthcity ################################################# # Flask Setup ################################################# app = Flask(__name__) ################################################# # Flask Routes ################################################# # Get API KEY app.config['API_KEY'] = os.environ.get('API_KEY') @app.route("/") @app.route("/home") def home(): return render_template('index.html') # for Price Prediction @app.route("/api/v1.0/predict", methods=['GET','POST']) def predict(): data = request.json print(data) suburb = data['Suburb'] house = pd.read_csv("static/data/house.csv") # Assign the data to X and y X = house[["bedrooms", "bathrooms", "car_space", "land_size", "building_size", "built_date", "perth", "west_perth", "east_perth", "northbridge", "crawley", "nedlands"]] y = house["price"].values.reshape(-1, 1) X_train, X_test, y_train, y_test = train_test_split(X, y) # Create a StandardScater model and fit it to the training data X_scaler = StandardScaler().fit(X_train) y_scaler = StandardScaler().fit(y_train) # Load the best Model # my_model = joblib.load("best_model.pkl") my_model = joblib.load("ML_Model/best_model.pkl") # my_model = load_model("keras_model_trained.h5") # X_test = X_scaler.transform([[data['Bedroom'],data['Bathroom'],data['Car_Spaces'],data['Land_Size'],data['Built_Size'],data['Built_Year'],1,0,0,0,0,0]]) if suburb == "perth": X_test = X_scaler.transform([[data['Bedroom'],data['Bathroom'],data['Car_Spaces'],data['Land_Size'],data['Built_Size'],data['Built_Year'],1,0,0,0,0,0]]) elif suburb == "westp": X_test = X_scaler.transform([[data['Bedroom'],data['Bathroom'],data['Car_Spaces'],data['Land_Size'],data['Built_Size'],data['Built_Year'],0,1,0,0,0,0]]) elif suburb == "eastp": X_test = X_scaler.transform([[data['Bedroom'],data['Bathroom'],data['Car_Spaces'],data['Land_Size'],data['Built_Size'],data['Built_Year'],0,0,1,0,0,0]]) elif suburb == "northbridge": X_test = X_scaler.transform([[data['Bedroom'],data['Bathroom'],data['Car_Spaces'],data['Land_Size'],data['Built_Size'],data['Built_Year'],0,0,0,1,0,0]]) elif suburb == "crawley": X_test = X_scaler.transform([[data['Bedroom'],data['Bathroom'],data['Car_Spaces'],data['Land_Size'],data['Built_Size'],data['Built_Year'],0,0,0,0,1,0]]) elif suburb == "nedlands": X_test = X_scaler.transform([[data['Bedroom'],data['Bathroom'],data['Car_Spaces'],data['Land_Size'],data['Built_Size'],data['Built_Year'],0,0,0,0,0,1]]) print(X_test) predictions = my_model.predict(X_test) exact_value = y_scaler.inverse_transform(predictions)[0].round(decimals=0) mse = 0.1300 min_value = math.trunc(exact_value * (1-mse)) max_value = math.trunc(exact_value * (1+mse)) result = f"${min_value} - ${max_value}" print(result) return {"result": result } #all data function should be here # Perth City API @app.route("/api/v1.0/perthcity") def perthcity(): # Create our session (link) from Python to the DB session = Session(engine) """Return a list of install data""" # Query all outputs results = session.query(PerthCity.sale_id, PerthCity.full_address, PerthCity.price, PerthCity.sold_date, PerthCity.property_type, PerthCity.bedrooms, PerthCity.bathrooms, PerthCity.car_space, PerthCity.land_size, PerthCity.building_size, PerthCity.built_date, PerthCity.rent, PerthCity.rent_date, PerthCity.agent, PerthCity.lat, PerthCity.lng, PerthCity.address, PerthCity.suburb, PerthCity.state, PerthCity.postcode).all() session.close() # Create a dictionary from the row data and append to a list of all_passengers all_properties = [] for sale_id, full_address, price, sold_date, property_type, bedrooms, bathrooms, car_space, land_size, building_size, built_date, rent, rent_date, agent, \ lat, lng, address, suburb, state, postcode in results: property_dict = {} property_dict["sale_id"] = sale_id property_dict["full_address"] = full_address property_dict["price"] = price property_dict["sold_date"] = sold_date property_dict["property_type"] = property_type property_dict["bedrooms"] = bedrooms property_dict["bathrooms"] = bathrooms property_dict["car_space"] = car_space property_dict["land_size"] = land_size property_dict["building_size"] = building_size property_dict["built_date"] = built_date property_dict["rent"] = rent property_dict["rent_date"] = rent_date property_dict["agent"] = agent property_dict["lat"] = lat property_dict["lng"] = lng property_dict["address"] = address property_dict["suburb"] = suburb property_dict["state"] = state property_dict["postcode"] = postcode all_properties.append(property_dict) return jsonify(all_properties) if __name__ == '__main__': app.run(port=5500, debug=True)<file_sep>/static/js/logic.js //create streetmap map layer var streetmap = L.tileLayer("https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}", { attribution: "© <a href='https://www.mapbox.com/about/maps/'>Mapbox</a> © <a href='http://www.openstreetmap.org/copyright'>OpenStreetMap</a> <strong><a href='https://www.mapbox.com/map-feedback/' target='_blank'>Improve this map</a></strong>", tileSize: 512, maxZoom: 18, zoomOffset: -1, id: "mapbox/streets-v11", accessToken: API_KEY }); // Create myMap to set the whole layout for the map var myMap = L.map("map", { center: [-31.9523 , 115.8613 ], //centralise the map zoom: 12, layers: [streetmap] }); //for inputs limit function onlyNumberKey(evt) { // Only ASCII character in that range allowed var ASCIICode = (evt.which) ? evt.which : evt.keyCode if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57)) return false; return true; } // function errorcatch() { // var bedroom = document.getElementById("bedroom_range").value; // var bathroom = document.getElementById("bathroom_range").value; // var carspace = document.getElementById("carspaces_range").value; // var landsize = document.getElementById("land").value; // var builtsize = document.getElementById("built").value; // var builtyear= document.getElementById("builtdate").value; // var suburb = document.getElementById("suburbs").value; // console.log(bedroom, bathroom, carspace,landsize,builtsize,builtyear,suburb) // } d3.select("#submit_this").on("click",()=>{ console.log("Clicked!") var bedroom = document.getElementById("bedroom_range").value; var bathroom = document.getElementById("bathroom_range").value; var carspace = document.getElementById("carspaces_range").value; var land = document.getElementById("land").value; var built = document.getElementById("built").value; var year= document.getElementById("builtdate").value; var suburb = document.getElementById("suburbs").value; var modal = document.getElementById("myModal"); var tryagain = document.getElementsByClassName("close")[0]; var p = document.getElementById("input_error"); // For the button on the Modal tryagain.onclick = function() { modal.style.display = "none"; } //For User to close the window when clicked anywhere window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } try { if(year == ""){ throw "Please Input Built Year. Range 1900-2021";} else if(year < 1900) {throw "Input value for Built Year out of range.<br> Try Range 1900 - 2021"; } else if(year > 2021) {throw "Input value for Built Year out of range.<br> Try Range 1900 - 2021"; } else {var builtyear = year;} } catch(err3) { p.innerHTML= err3; modal.style.display="block"; } try { if(built == ""){throw "Please Input Built Size. Range 1-1000";} else if(built < 1){throw "Input value for Built Size too Low.<br> Try Range 1 - 1000";} else if(built > 1000){throw "Input value for Built Size too High.<br> Try Range 1 - 1000";} else {var builtsize = built;} } catch(err2) { p.innerHTML= err2; modal.style.display="block"; } try { if(land == ""){throw "Please Input Land Size. Range 1-1500";} else if(land < 1){throw "Input value for Land Size too Low.<br>Try Range 1 - 1500";} else if(land > 1500){throw "Input value for Land Size too High.<br>Try Range 1 - 1500";} else {var landsize = land;} } catch(err1) { p.innerHTML= err1 ; modal.style.display="block"; } console.log(bedroom, bathroom, carspace,landsize,builtsize,builtyear,suburb) d3.json('/api/v1.0/predict', { method:"POST", body: JSON.stringify({ Bedroom: bedroom, Bathroom: bathroom, Car_Spaces: carspace, Land_Size: landsize, Built_Size: builtsize, Built_Year: builtyear, Suburb: suburb }),headers: { "Content-type": "application/json; charset=UTF-8" } }).then(data=>{ console.log(data.result) //to zoom and to add results on map if (suburb == "perth") { myMap.setView([-31.9523 , 115.8613], 17); L.marker([-31.9523 , 115.8613]) .bindPopup("<h2>Perth</h2><hr><h3>Estimation Range:</h3><br> <h3>" +data.result+ "</h3>") .addTo(myMap).openPopup(); } else if (suburb == "westp") { myMap.setView([-31.9463 , 115.8448], 17); L.marker([-31.9463 , 115.8448]) .bindPopup("<h2>West Perth</h2><hr><h3>Estimation Range:</h3><br> <h3>" +data.result+ "</h3>") .addTo(myMap).openPopup(); } else if (suburb == "eastp") { myMap.setView([-31.9608 , 115.8746], 17); L.marker([-31.9608 , 115.8746]) .bindPopup("<h2>East Perth</h2><hr><h3>Estimation Range:</h3><br> <h3>" +data.result+ "</h3>") .addTo(myMap).openPopup(); } else if (suburb == "northbridge") { myMap.setView([-31.9470 , 115.8574], 17); L.marker([-31.9470 , 115.8574]) .bindPopup("<h2>Northbridge</h2><hr><h3>Estimation Range:</h3><br> <h3>" +data.result+ "</h3>") .addTo(myMap).openPopup(); } else if (suburb == "crawley") { myMap.setView([-31.9814 , 115.8205], 17); L.marker([-31.9814 , 115.8205]) .bindPopup("<h2>Crawley</h2><hr><h3>Estimation Range:</h3><br> <h3>" +data.result+ "</h3>") .addTo(myMap).openPopup(); } else if (suburb == "nedlands") { myMap.setView([-31.9810 , 115.8039], 17); L.marker([-31.9810 , 115.8039]) .bindPopup("<h2>Nedlands</h2><hr><h3>Estimation Range:</h3><br> <h3>" +data.result+ "</h3>") .addTo(myMap).openPopup(); } // }) })<file_sep>/Archived/app copy.py from flask import Flask, jsonify from flask import render_template, redirect import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify from flask import render_template, redirect , request ################################################# # Database Setup ################################################# engine = create_engine("sqlite:///SQL/CityOfPerth.sqlite") # reflect an existing database into a new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference to the table PerthCity = Base.classes.perthcity ################################################# # Flask Setup ################################################# app = Flask(__name__) ################################################# # Flask Routes ################################################# @app.route("/") @app.route("/home") def home(): # Return template and data return render_template("index.html") @app.route("/about") def about(): # Return template and data return render_template("about.html") @app.route("/estimation" ) def estimation(): # Return template and data return render_template("estimation.html") @app.route("/api/v1.0/perthcity") def perthcity(): # Create our session (link) from Python to the DB session = Session(engine) """Return a list of install data""" # Query all outputs results = session.query(PerthCity.sale_id, PerthCity.full_address, PerthCity.price, PerthCity.sold_date, PerthCity.property_type, PerthCity.bedrooms, PerthCity.bathrooms, PerthCity.car_space, PerthCity.land_size, PerthCity.building_size, PerthCity.built_date, PerthCity.rent, PerthCity.rent_date, PerthCity.agent, PerthCity.lat, PerthCity.lng, PerthCity.address, PerthCity.suburb, PerthCity.state, PerthCity.postcode).all() session.close() # Create a dictionary from the row data and append to a list of all_passengers all_properties = [] for sale_id, full_address, price, sold_date, property_type, bedrooms, bathrooms, car_space, land_size, building_size, built_date, rent, rent_date, agent, \ lat, lng, address, suburb, state, postcode in results: property_dict = {} property_dict["sale_id"] = sale_id property_dict["full_address"] = full_address property_dict["price"] = price property_dict["sold_date"] = sold_date property_dict["property_type"] = property_type property_dict["bedrooms"] = bedrooms property_dict["bathrooms"] = bathrooms property_dict["car_space"] = car_space property_dict["land_size"] = land_size property_dict["building_size"] = building_size property_dict["built_date"] = built_date property_dict["rent"] = rent property_dict["rent_date"] = rent_date property_dict["agent"] = agent property_dict["lat"] = lat property_dict["lng"] = lng property_dict["address"] = address property_dict["suburb"] = suburb property_dict["state"] = state property_dict["postcode"] = postcode all_properties.append(property_dict) return jsonify(all_properties) if __name__ == '__main__': app.run(port=5500, debug=True)<file_sep>/templates/index.html <!DOCTYPE HTML> <html> <head> <title>Perth Property Prices</title> <meta charset="utf-8"> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.9.1.js"></script> <script src="static/css/5grid/init.js?use=mobile,desktop"></script> <script src="static/js/jquery.formerize-1.1.js"></script> <script src="static/js/init.js"></script> <!-- Leaflet CSS --> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" /> <noscript> <link rel="stylesheet" href="static/css/5grid/core.css"> <link rel="stylesheet" href="static/css/5grid/core-desktop.css"> <link rel="stylesheet" href="static/css/5grid/core-1200px.css"> <link rel="stylesheet" href="static/css/5grid/core-noscript.css"> <link rel="stylesheet" href="static/css/style.css"> <link rel="stylesheet" href="static/css/style-desktop.css"> <link rel="stylesheet" href="static/css/noscript.css"> </noscript> <!--[if lte IE 8]> <link rel="stylesheet" href="css/ie8.css"> <![endif]--> </head> <body class="homepage"> <div id="wrapper"> <nav id="nav"> <a href="#home" class="icon icon-home active"><span>Introduction</span></a> <a href="#story" class="icon icon-book"><span>Story</span></a> <a href="#predict" class="icon icon-album"><span>Predictions</span></a> <a href="#about" class="icon icon-info"><span>About</span></a> </nav> <div id="main"> <!-- Main Page --> <article id="home" class="panel"> <header> <h2 style="text-align:center">City of Perth Property Price</h2><hr> </header> <div class= "panel_intro_about"> <table> <tr> <td class ="intro"> <img src="../static/images/PerthCity.png" width="100%"> <ul> <h3><b>Introduction:</b></h3><br> <li>This project explores the property prices in the City of Perth. This includes the 6 suburbs that falls under the local government : Perth, East Perth, West Perth, Northbridge, Crawley and Nedlands. </li> </ul> <ul> <b>This project sets out to answer the following :</b> <br> <li>🏡 What are the price range of each suburb?</li> <li>🏠 What are the property type that people are interested in buying?</li> <li>🏡 Which age range does the sold properties mostly fall under? </li> <li>🏠 Does the number of car park affect property price?</li> <li>🏡 What are the key factors that are impacting the property price?</li> <li>🏠 Are some properties better to rent or buy? </li> <li>🏡 How much is the return of investment? </li> <li>🏠 Have Covid-19 impacted the Real Estate market? </li> </ul> </td> </tr> </table> </div> </article> <!-- Tableau Story --> <article id="story" class="panel"> <header> <h2 style="text-align:center">City of Perth Properties Story</h2><hr> </header> <section class="5grid is-gallery"> <div id="story"> <div class='tableauPlaceholder' id='viz1629537112605' style='position: relative'> <noscript> <a href='#'><img alt='Perth City Properties Story ' src='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Pe&#47;PerthCityProperties&#47;PerthCityPropertiesStory&#47;1_rss.png' style='border: none' /></a> </noscript> <object class='tableauViz' style='display:none;'> <param name='host_url' value='https%3A%2F%2Fpublic.tableau.com%2F' /> <param name='embed_code_version' value='3' /> <param name='site_root' value='' /> <param name='name' value='PerthCityProperties&#47;PerthCityPropertiesStory' /> <param name='tabs' value='no' /> <param name='toolbar' value='yes' /> <param name='static_image' value='https:&#47;&#47;public.tableau.com&#47;static&#47;images&#47;Pe&#47;PerthCityProperties&#47;PerthCityPropertiesStory&#47;1.png' /> <param name='animate_transition' value='yes' /> <param name='display_static_image' value='yes' /> <param name='display_spinner' value='yes' /> <param name='display_overlay' value='yes' /> <param name='display_count' value='yes' /> <param name='language' value='en-GB' /> <param name='filter' value='publish=yes' /> </object></div> <script type='text/javascript'> var divElement = document.getElementById('viz1629537112605'); var vizElement = divElement.getElementsByTagName('object')[0]; vizElement.style.width='100%';vizElement.style.height=(divElement.offsetWidth*0.75)+'px'; var scriptElement = document.createElement('script'); scriptElement.src = 'https://public.tableau.com/javascripts/api/viz_v1.js'; vizElement.parentNode.insertBefore(scriptElement, vizElement); </script> </section> </article> <!-- Prediction Page --> <article id="predict" class="panel"> <header> <h2 style="text-align:center">Property Price Prediction</h2> <hr> </header> <section class="5grid is-gallery"> <div class="container"> <div class= "row"> <div class="column"> <!-- div for the leaflet map here --> <div id="map"></div> </div> <div class="column"> <div id="prediction"> <div id ="inputfields"> <p><b><u>Input for Predictions</b></u></p> <div> <label for="Bedroom">Bedroom: </label><br> <input type="range" id="bed" name="Bedroom" min="0" max="10" value="5" step="1" oninput="bedroom_range.value = bed.value"> <output id="bedroom_range">5</output> </div> <div> <label for="Bathroom">Bathroom: </label><br> <input type="range" id="bath" name="Bathroom" min="0" max="6" value="3" step="1" oninput="bathroom_range.value = bath.value"> <output id="bathroom_range">3</output> </div> <div> <label for="CarSpaces">Car Spaces: </label><br> <input type="range" id="car" name="CarSpaces" min="0" max="10" value="5" step="1" oninput="carspaces_range.value = car.value"> <output id="carspaces_range">3</output> </div> <hr> <div> <label for="landsize">Land Size: </label><br> <input type="text" id="land" name="land_size" onkeypress="return onlyNumberKey(event)" maxlength="4" placeholder="eg. 1 - 1500"> </div> <div> <label for="built">Built Size: </label><br> <input type="text" id="built" name="built_size" onkeypress="return onlyNumberKey(event)" maxlength="4" placeholder="eg. 1 - 1000"> </div> <div> <label for="builtdate">Built Year: </label><br> <input type="text" id="builtdate" name="built_date" onkeypress="return onlyNumberKey(event)" maxlength="4" placeholder="eg. 1900 - 2020"> </div> <hr> <div> <label for="suburbs">Choose Suburb:</label><br> <select name="suburbs" id="suburbs"> <option value="perth">Perth</option> <option value="eastp">East Perth</option> <option value="westp">West Perth</option> <option value="crawley">Crawley</option> <option value="northbridge">Northbridge</option> <option value="nedlands">Nedlands</option> </select> </div> <br> <br> <div class="submit"> <button type="button" id="submit_this" class="button_base b05_3d_roll" > <div>Submit</div> <div>Submit</div> </button> </div> <!-- The Modal for the input error popup --> <div id="myModal" class="modal" style=display:none> <!-- Modal content --> <div id="modal-content"> <span class="close">&times;</span> <p id="input_error"></p> </div> </div> </div> </div> </div> </div> </div> </section> </article> <!-- About Page --> <article id="about" class="panel"> <h2 style="text-align:center">About</h2><hr> <div class = panel_intro_about> <h4>Aim</h4> <p>The aim of this project is to assist potential buyers and investors to get a better predicted property price. We've utilised Machine Learning Model to train existing dataset for better accuracy. Potential buyers and investors can then explore the properties in the City of Perth through the visualised story board. </p> <h4>Future Developments</h4> <ul> <li>• To expand the current scope to include more suburbs around WA or even Australia</li> <li>• Train Machine Learning model for Apartments and Units.This was not included in the current project as there are many factors involve in determining the price for an Apartment and Unit such as views, building and location</li> <li>• Include school catchments area, amenities such as shops, public transports to improve predictions</li> </ul> <h4>Limitation</h4> <ul> <li>• Suburbs that we looked at does not have a lot of landed houses</li> <li>• Many factors affecting property price</li> <ul> <li>&emsp;- For example, apartment would have views and strata fees </li> <li>&emsp;- Landed property with the council rates and street name </li> <li>&emsp;- Any renovations that was carried out on the property </li> <li>&emsp;- Pool, Solar panels and a nice lawn </li> <li>&emsp;- Human factor involved such as if owners are rushing to sell or failed to pay mortgage</li> </ul> <li></li> </ul> <h4>Datasets</h4> <ol> <li><a href="http://house.speakingsame.com/" target="_blank">http://house.speakingsame.com/</a></li> <li><a href="https://www.onthehouse.com.au/" target="_blank">https://www.onthehouse.com.au/</a></li> <li><a href="https://www.propertyvalue.com.au/" target="_blank">https://www.propertyvalue.com.au/</a></li> </ol> <h4>Contributors</h4> <p>Our group consists of two members and this project is a part of our Bootcamp in Data Analytics, organised by University of Western australia. </p> <table> <tr> <th colspan="2"><img class="profile" src="https://avatars.githubusercontent.com/u/78719440?v=4" width=240px alt="Helen's Profile Image"></th> <th colspan="2"><img class="profile" src="https://avatars.githubusercontent.com/u/78995824?v=4"width=240px alt="FX's Profile Image"></th> </tr> <tr> <th colspan="3"><h3><NAME></h3> <div class="figure"> <a href="https://github.com/helenamin" target="_blank"> <img src="static/css/images/github-inactive.png" alt="GitHub"> </a> </div> &emsp; <div class="figure"> <a href="https://www.linkedin.com/in/helen-amin-6a787a26/" target="_blank"> <img src="static/css/images/LI-inactive.png" alt="Linkedin"> </a> </div> </th> <th colspan="3"><h3>FX Foo</h3> <div class="figure"> <a href="https://foofx88.github.io" target="_blank"> <img src="static/css/images/github-inactive.png" alt="GitHub"> </a> </div> &emsp; <div class="figure"> <a href="https://www.linkedin.com/in/distinctivefx/" target="_blank"> <img src="static/css/images/LI-inactive.png" alt="Linkedin"> </a> </div> </th> </tr> </table> </section> </div> </article> </div> <div id="footer"> <ul class="links"> <p>Built modified version of Astral from <a href="http://html5up.net/">HTML5 Up!</a></p> </ul> </div> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="<KEY> crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <!-- essential js files for charts and deployment--> <script> var API_KEY = {{config['API_KEY']| tojson }} </script> <!-- Leaflet JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.7.1/leaflet.js"></script> <!-- D3 JavaScript --> <script src="https://d3js.org/d3.v5.min.js"></script> <!-- Our JavaScript --> // <script type="text/javascript" src="static/js/config.js"></script> <script type="text/javascript" src="static/js/logic.js"></script> </body> </html> <file_sep>/static/js/init.js /* Astral 1.0 by HTML5 Up! html5up.net | @n33co Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) */ _5grid.ready(function() { /*********************************************************************************/ /* Settings */ /*********************************************************************************/ var settings = { resizeSpeed: 600, // Speed to resize panel fadeSpeed: 300, // Speed to fade in/out sizeFactor: 11.5, // Size factor sizeLimit: 15 // Minimum point size }; /*********************************************************************************/ /* Vars */ /*********************************************************************************/ var _window = jQuery(window), _main = jQuery('#main'), _panels = _main.find('.panel'), _body = jQuery('body'), _hbw = jQuery('html,body,window'), _footer = jQuery('#footer'), _wrapper = jQuery('#wrapper'), _nav = jQuery('#nav'), _nav_links = _nav.find('a'), _jumplinks = jQuery('.jumplink'); var panels = [], activePanelId = null, firstPanelId = null, isLocked = false, isTouch = !!('ontouchstart' in window); if (isTouch) { settings.fadeSpeed = 0; settings.resizeSpeed = 0; _nav_links.find('span').remove(); } /*********************************************************************************/ /* Main (Desktop) */ /*********************************************************************************/ if (_5grid.isDesktop) { // Body _body.h5u_resize = function() { var factor = (_window.width() * _window.height()) / (1440 * 900); _body.css('font-size', Math.max(Math.floor(factor * settings.sizeFactor), settings.sizeLimit) + 'pt'); _main.height(panels[activePanelId].outerHeight()); _body.h5u_reposition(); }; _body.h5u_reposition = function() { if (isTouch && (window.orientation == 0 || window.orientation == 180)) _wrapper.css('padding-top', Math.max(((_window.height() - (panels[activePanelId].outerHeight() + _footer.outerHeight())) / 2.5) - _nav.height(), 30) + 'px'); else _wrapper.css('padding-top', (((_window.height() - panels[firstPanelId].height()) / 2.5) - _nav.height()) + 'px'); }; // Panels _panels.each(function(i) { var t = jQuery(this), id = t.attr('id'); panels[id] = t; if (i == 0) { firstPanelId = id; activePanelId = id; } else t.hide(); t.h5u_activate = function() { // Check lock state and determine whether we're already at the target if (isLocked || activePanelId == id) return false; // Lock isLocked = true; // Change nav link (if it exists) _nav_links.removeClass('active'); _nav_links.filter('[href="#' + id + '"]').addClass('active'); // Add bottom padding var x = parseInt(_wrapper.css('padding-top')) + panels[id].outerHeight() + _nav.outerHeight() + _footer.outerHeight(); if (x > _window.height()) _wrapper.addClass('tall'); else _wrapper.removeClass('tall'); // Fade out active panel _footer.fadeTo(settings.fadeSpeed, 0.0001); panels[activePanelId].fadeOut(settings.fadeSpeed, function() { // Set new active activePanelId = id; // Force scroll to top _hbw.animate({ scrollTop: 0 }, settings.resizeSpeed, 'swing'); // Reposition _body.h5u_reposition(); // Resize main to height of new panel _main.animate({ height: panels[activePanelId].outerHeight() }, settings.resizeSpeed, 'swing', function() { // Fade in new active panel _footer.fadeTo(settings.fadeSpeed, 1.0); panels[activePanelId].fadeIn(settings.fadeSpeed, function() { // Unlock isLocked = false; }); }); }); }; }); // Nav + Jumplinks _nav_links.add(_jumplinks).click(function(e) { var t = jQuery(this), href = t.attr('href'), id; if (href.substring(0,1) == '#') { e.preventDefault(); e.stopPropagation(); id = href.substring(1); if (id in panels) panels[id].h5u_activate(); } }); // Window _window .resize(function() { if (!isLocked) _body.h5u_resize(); }); // Forms (IE <= 9 only) if (navigator.userAgent.match(/MSIE ([0-9]+)\./) && RegExp.$1 <= 9) jQuery('form').formerize(); // Init _window .trigger('resize'); _wrapper .fadeTo(400, 1.0); } }, true);
5617908657bd473e05aa0dda8dba93936269e42c
[ "HTML", "Markdown", "JavaScript", "Python", "Text" ]
8
Text
helenamin/Perth-City-Properties
f553140b96863a1b8cd4fe96f3b4a49303e5caa7
44a73736efe3b3db65666da823c30a2bad73c93b
refs/heads/master
<repo_name>vgirbes/docker-laravel<file_sep>/docker/app/local-fpm.ini ; Post size upload_max_filesize = 100M post_max_size = 100M ; Opcache opcache.memory_consumption = 128 opcache.interned_strings_buffer = 16 opcache.max_accelerated_files = 16229 opcache.fast_shutdown = 1 ; Xdebug xdebug.default_enable = 0 xdebug.remote_enable = 1 xdebug.remote_autostart = 1 xdebug.profiler_enable = 0 xdebug.idekey = PHPSTORM <file_sep>/docker/app/Dockerfile FROM debian:stretch-slim # Environment WORKDIR "/var/www" ARG USER_ID ARG USER_NAME ENV DEBIAN_FRONTEND noninteractive ENV TEMPORARY apt-transport-https curl # Dependencies RUN apt-get update && \ apt-get -y upgrade && \ apt-get -y --no-install-recommends install apt-utils && \ apt-get -y --no-install-recommends install $TEMPORARY ca-certificates ffmpeg git gnupg2 iproute locales # Default user RUN useradd --user-group --create-home --shell /bin/bash --uid $USER_ID $USER_NAME # Locales RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && \ sed -i '/es_ES.UTF-8/s/^# //g' /etc/locale.gen && \ ln -s /etc/locale.alias /usr/share/locale/locale.alias && \ locale-gen # PHP RUN curl -sS https://packages.sury.org/php/apt.gpg | apt-key add - && \ echo "deb https://packages.sury.org/php/ stretch main" > /etc/apt/sources.list.d/php.list && \ apt-get update && \ apt-get -y --no-install-recommends install \ php7.0-fpm \ php7.0-bcmath \ php7.0-curl \ php7.0-gd \ php7.0-intl \ php7.0-json \ php7.0-mbstring \ php7.0-mysql \ php-redis \ php7.0-soap \ php-sodium \ php-xdebug \ php7.0-xml \ php7.0-zip ADD production.ini /etc/php/7.0/cli/conf.d/99-overrides.ini ADD production.ini /etc/php/7.0/fpm/conf.d/99-overrides.ini ADD pool.conf /etc/php/7.0/fpm/pool.d/z-overrides.conf # Composer RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer && \ echo 'export PATH=$PATH:/var/www/vendor/bin' >> ~/.bashrc && \ su -c "echo 'export PATH=$PATH:/var/www/vendor/bin' >> ~/.bashrc" $USER_NAME # Xdebug RUN echo "xdebug.remote_host=`ip route | awk '/default/ { print $3 }'`" >> /etc/php/7.0/cli/conf.d/20-xdebug.ini && \ echo "xdebug.remote_host=`ip route | awk '/default/ { print $3 }'`" >> /etc/php/7.0/fpm/conf.d/20-xdebug.ini && \ echo 'export PHP_IDE_CONFIG="serverName=default"' >> ~/.bashrc && \ su -c "echo 'export PHP_IDE_CONFIG=\"serverName=default\"' >> ~/.bashrc" $USER_NAME # Cleanup RUN apt-get -y remove $TEMPORARY && \ apt-get -y autoremove && \ apt-get clean && \ rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/* # Daemon CMD /usr/sbin/php-fpm7.0 -F -O 2>&1 | sed -u 's,.*: \"\(.*\)$,\1,'| sed -u 's,"$,,' 1>&1 <file_sep>/docker/app/local-cli.ini ; Xdebug xdebug.default_enable = 0 xdebug.remote_enable = 1 xdebug.remote_autostart = 1 xdebug.profiler_enable = 0 xdebug.idekey = PHPSTORM <file_sep>/docker/app/production.ini ; Post size upload_max_filesize = 100M post_max_size = 100M ; Opcache opcache.memory_consumption = 128 opcache.interned_strings_buffer = 16 opcache.max_accelerated_files = 16229 opcache.validate_timestamps = 0 opcache.fast_shutdown = 1 <file_sep>/.env.example # Docker USER_ID=1000 USER_NAME=default WEB_PORT=443 WEB_PORT_H1=80 DB_PORT=3306 CACHE_PORT=6379 # Application APP_ENV=local APP_DEBUG=true APP_LOG_LEVEL=debug APP_KEY= JWT_SECRET= APP_URL=https://localhost # Database DB_HOST=db DB_DATABASE=test DB_USERNAME=test DB_PASSWORD=<PASSWORD> # Cache REDIS_HOST=cache # Mail MAIL_HOST=smtp.mailtrap.io MAIL_PORT=465 MAIL_USERNAME= MAIL_PASSWORD= # Directories USER_FOLDER_PATH=/var/www/storage/users SHORT_CODES_WSDL=http://shortcodes.mobincube.com CAPONATE_JOBS_URL=http://wsdev.caponate.com/api/jobs CAPONATE_TMP=/tmp # Event Manager EVENT_MANAGER_URI=http://dev.eventmanager.mobincube.com # IP IP_SERVICE_URI=http://scripts.mobincube.com/ip2c # Maundonguilla MAUNDONGUILLA_URI=https://dev.mau.mobincube.com MAUNDONGUILLA_SECRET= # Stripe STRIPE_KEY= STRIPE_SECRET= STRIPE_ENDPOINT_SECRET= # Twitter TWITTER_CONSUMER_KEY= TWITTER_CONSUMER_SECRET= OAUTH_REDIRECT=https://localhost/oauth
0f6bc0db22a302c51669ddd25a7484c6cac52b64
[ "Shell", "Dockerfile", "INI" ]
5
INI
vgirbes/docker-laravel
9490a8364a3ea8eb1cac7bfb322325ad6c41ed32
f45edf717f41711a4c86ae3f7a8b737891494d6a
refs/heads/main
<repo_name>WEB-20-1-1/programming<file_sep>/ap.js let name1 = prompt('Введите ваше имя?'); alert(name1) let name2 = prompt('Введите вашу фамилию?'); alert(name2) let name3 = prompt('Введите ваш возвраст?'); alert(name3)
ba6c1b5cc86c1badf00bbefc02b4d0b2bef939fb
[ "JavaScript" ]
1
JavaScript
WEB-20-1-1/programming
ba9adc0b07392b85306eb784b1230959c71331ea
eba81e4e67389d4b172ac57b8ab658734766b916
refs/heads/master
<repo_name>Wirtos/dyad<file_sep>/example/httpserv2.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "dyad.h" /* An example of a simple HTTP server which serves up files. We make use of * `udata` and the DYAD_EVENT_READY event to send files in chunks as needed * instead of loading the entire file into the stream's write buffer in one go. * This allows us to send large files without any issues */ typedef struct { FILE *fp; } Client; static void client_onReady(dyad_Event *e) { Client *client = e->udata; int c; int count = 32000; while (count--) { if ((c = fgetc(client->fp)) != EOF) { dyad_write(e->stream, &c, 1); } else { dyad_end(e->stream); break; } } } static void client_onLine(dyad_Event *e) { Client *client = e->udata; char path[128]; if (sscanf(e->data, "GET %127s", path) == 1) { /* Print request */ printf("%s %s\n", dyad_getAddress(e->stream), path); /* Send header */ dyad_writef(e->stream, "HTTP/1.1 200 OK\r\n\r\n"); /* Check request */ if (strstr(path, "..") || path[1] == '/') { /* Handle bad request */ dyad_writef(e->stream, "bad request '%s'", path); dyad_end(e->stream); } else { /* Handle good request */ client->fp = fopen(path + 1, "rb"); if (client->fp) { /* Remove this event handler (we don't care about anything else the * client has to say) */ dyad_removeListener(e->stream, DYAD_EVENT_LINE, client_onLine, client); /* Add the event handler for sending the file */ dyad_addListener(e->stream, DYAD_EVENT_READY, client_onReady, client); } else { dyad_writef(e->stream, "not found '%s'\n", path); dyad_end(e->stream); } } } } static void client_onClose(dyad_Event *e) { Client *client = e->udata; if (client->fp) fclose(client->fp); free(client); } static void server_onAccept(dyad_Event *e) { Client *client = calloc(1, sizeof(*client)); dyad_addListener(e->remote, DYAD_EVENT_LINE, client_onLine, client); dyad_addListener(e->remote, DYAD_EVENT_CLOSE, client_onClose, client); } static void server_onListen(dyad_Event *e) { printf("server listening: http://localhost:%d\n", dyad_getPort(e->stream)); } static void server_onError(dyad_Event *e) { printf("server error: %s\n", e->msg); } int main(void) { dyad_Stream *serv; dyad_init(); serv = dyad_newStream(); dyad_addListener(serv, DYAD_EVENT_ERROR, server_onError, NULL); dyad_addListener(serv, DYAD_EVENT_ACCEPT, server_onAccept, NULL); dyad_addListener(serv, DYAD_EVENT_LISTEN, server_onListen, NULL); dyad_listen(serv, 8000); while (dyad_getStreamCount() > 0) { dyad_update(); } dyad_shutdown(); return 0; } <file_sep>/example/ircbot.c #include <stdio.h> #include <string.h> #include "dyad.h" /* A simple IRC bot. Connects to an IRC network, joins a channel then sits * idle, responding to the server's PING messges and printing everything the * server sends it. */ static char *server = "irc.afternet.org"; static char *channel = "#dyadbots"; static char nick[32]; static int isRegistered = 0; static void onConnect(dyad_Event *e) { /* Generate a random nick name */ sprintf(nick, "testbot%04x", (int)(dyad_getTime()) % 0xFFFF); /* Introduce ourselves to the server */ dyad_writef(e->stream, "NICK %s\r\n", nick); dyad_writef(e->stream, "USER %s %s bla :%s\r\n", nick, nick, nick); } static void onError(dyad_Event *e) { printf("error: %s\n", e->msg); } static void onLine(dyad_Event *e) { printf("%s\n", e->data); /* Handle PING */ if (!memcmp(e->data, "PING", 4)) { dyad_writef(e->stream, "PONG%s\r\n", e->data + 4); } /* Handle RPL_WELCOME */ if (!isRegistered && strstr(e->data, "001")) { /* Join channel */ dyad_writef(e->stream, "JOIN %s\r\n", channel); isRegistered = 1; } } int main(void) { dyad_Stream *s; dyad_init(); s = dyad_newStream(); dyad_addListener(s, DYAD_EVENT_CONNECT, onConnect, NULL); dyad_addListener(s, DYAD_EVENT_ERROR, onError, NULL); dyad_addListener(s, DYAD_EVENT_LINE, onLine, NULL); dyad_connect(s, server, 6667); while (dyad_getStreamCount() > 0) { dyad_update(); } dyad_shutdown(); return 0; } <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 3.10) project(dyad C) add_library(dyad src/dyad.c) target_include_directories(dyad PUBLIC src) <file_sep>/example/echoserv.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include "dyad.h" /* An echo server: Echos any data received by a client back to the client */ static void onData(dyad_Event *e) { dyad_write(e->stream, e->data, e->size); } static void onAccept(dyad_Event *e) { dyad_addListener(e->remote, DYAD_EVENT_DATA, onData, NULL); dyad_writef(e->remote, "echo server\r\n"); } static void onError(dyad_Event *e) { printf("server error: %s\n", e->msg); } int main(void) { dyad_Stream *s; dyad_init(); s = dyad_newStream(); dyad_addListener(s, DYAD_EVENT_ERROR, onError, NULL); dyad_addListener(s, DYAD_EVENT_ACCEPT, onAccept, NULL); dyad_listen(s, 8000); while (dyad_getStreamCount() > 0) { dyad_update(); } return 0; } <file_sep>/doc/api.md # Dyad API * [Functions](#functions) * [Events](#events) * [States](#states) * [Types](#types) ## Functions #### void dyad\_init(void) Initializes dyad. This should be called before any other dyad function is called. #### void dyad\_update(void) Handles all the active streams and events. This should be called with each iteration of the program's main loop. By default `dyad_update()` will block for a maximum of 1 second, `dyad_update()` can be made not to block by using `dyad_setUpdateTimeout()` to set the timeout to `0`. #### void dyad\_shutdown(void) Emits the `DYAD_EVENT_CLOSE` event on all current streams then shuts down and clears up everything. This should be called at the end of the program or when we no longer need dyad. #### const char *dyad\_getVersion(void) Returns the version of the library as a string. #### double dyad\_getTime(void) Returns the current time in seconds. This time should only be used for comparisons, as no specific epoch is guaranteed. #### int dyad\_getStreamCount(void) Returns the number of currently active streams. #### void dyad\_setUpdateTimeout(double seconds) Sets the maximum number of seconds the `dyad_update()` function can block for. If `seconds` is `0` then `dyad_update()` will not block. #### void dyad\_setTickInterval(double seconds) Sets the interval in seconds that the `DYAD_EVENT_TICK` event is emited to all streams; the default is 1 second. #### dyad\_PanicCallback dyad\_atPanic(dyad\_PanicCallback func) Sets the function which will be called when dyad encounters an error it cannot recover from. The old atPanic function is returned or `NULL` if none was set. --- #### dyad\_Stream* dyad\_newStream(void) Creates and returns a new stream. The returned stream is in a closed state by default, `dyad_listen()`, `dyad_listenEx()` or `dyad_connect()` should be called on the stream to take it out of the closed state. See [dyad\_Stream](#dyad_stream). #### int dyad\_listen(dyad\_Stream \*stream, int port) Makes the `stream` begin listening on the given `port` on all local interfaces. #### int dyad\_listenEx(dyad\_Stream \*stream, const char \*host, int port, int backlog) Performs the same task as `dyad_listen()` but provides additional options: `host` is the address of the local interface the stream should listen on. `backlog` is the maximum length of the queue of pending connections. #### int dyad\_connect(dyad\_Stream \*stream, const char \*host, int port) Connects the `stream` to the remote `host`. #### void dyad\_addListener(dyad\_Stream \*stream, int event, dyad\_Callback callback, void \*udata) Adds a listener for the `event` to the `stream`. When the event occurs the `callback` is called and the event's udata field is set to `udata`. If several listeners are added for the same event they are emitted in the order which they were added. See [Events](#events). #### void dyad\_removeListener(dyad\_Stream \*stream, int event, dyad\_Callback callback, void *udata) Removes an event listener which was added with the `dyad_addListener()` function. #### void dyad\_removeAllListeners(dyad\_Stream \*stream, int event) Removes all listeners for the given `event`. If `event` is `DYAD_EVENT_NULL` then all listeners for all events are removed. #### void dyad\_write(dyad\_Stream \*stream, const void \*data, int size) Writes the `data` of the given `size` to the stream. If you want to send a null terminated string use `dyad_writef()` instead. #### void dyad\_writef(dyad\_Stream \*stream, const char \*fmt, ...) Writes a formatted string to the `stream`. The function is similar to `sprintf()` with the following differences: * Dyad takes care of allocating enough memory for the result. * There are no flags, widths or precisions; only the following *standard* specifiers are supported: `%%` `%s` `%f` `%g` `%d` `%i` `%c` `%x` `%X` `%p`. * The `%r` specifier is provided, this takes a `FILE*` argument and writes the contents until the EOF is reached. * The `%b` specifier is provided, this takes a `void*` argument followed by an `int` argument representing the number of bytes to be written. #### void dyad\_vwritef(dyad\_Stream stream, const char \*fmt, va\_list args) `dyad_vwritef()` is to `dyad_writef()` what `vsprintf()` is to `sprintf()`. #### void dyad\_end(dyad\_Stream \*stream) Finishes sending any data the `stream` has left in its write buffer then closes the stream. The stream will stop receiving data once this function is called. #### void dyad\_close(dyad\_Stream \*stream) Immediately closes the `stream`, discarding any data left in its write buffer. #### void dyad\_setTimeout(dyad\_Stream \*stream, double seconds) Sets the number of seconds the `stream` can go without any activity (receiving or sending data) before it is automatically closed. If `0` seconds is set then the stream will never timeout, this is the default. #### void dyad\_setNoDelay(dyad\_Stream \*stream, int opt) If `opt` is `1` then Nagle's algorithm is disabled for the stream's socket, `0` enables it; by default it is enabled. #### int dyad\_getState(dyad\_Stream \*stream) Returns the current state of the `stream`, for example a connected stream would return the value `DYAD_STATE_CONNECTED`. See [States](#states). #### const char \*dyad\_getAddress(dyad\_Stream \*stream) Returns the current IP address for the `stream`. For listening streams this is the local address, for connected streams it is the remote address. #### int dyad\_getPort(dyad\_Stream \*stream) Returns the current `port` the `stream` is using. For listening streams this is the local port, for connected streams it is the remote port. #### int dyad\_getBytesReceived(dyad\_Stream \*stream) Returns the number of bytes which have been received by the `stream` since it was made. #### int dyad\_getBytesSent(dyad\_Stream \*stream) Returns the number of bytes which have been sent by the `stream` since it was made. This does not include the data in the stream's write buffer which is still waiting to be sent. #### dyad_Socket dyad\_getSocket(dyad\_Stream \*stream) Returns the socket used by the `stream`. ## Events #### DYAD\_EVENT\_DESTROY Emitted when a stream is destroyed. Once all the listeners for this event have returned then the associated stream's pointer should no longer be considered valid. #### DYAD\_EVENT\_ACCEPT Emitted when a listening stream accepts a connection. The `remote` field of the event represents the connected client's stream. #### DYAD\_EVENT\_LISTEN Emitted when a listening stream begins listening. #### DYAD\_EVENT\_CONNECT Emitted when a connecting stream successfully makes the connection to its host. #### DYAD\_EVENT\_CLOSE Emitted when a stream is closed. Closed streams are automatically destroyed by `dyad_update()`, see [DYAD\_EVENT\_DESTROY](#dyad_event_destroy) #### DYAD\_EVENT\_READY Emitted once each time the stream becomes ready to send more data. This event is useful when writing a large file to a stream, allowing you to send it in smaller chunks rather than copying all the data to the stream's write buffer at once. #### DYAD\_EVENT\_DATA Emitted whenever the stream receives data. The event's `data` field is the received data (null terminated), the `size` field is set to the size of the received data (excluding the null terminator). #### DYAD\_EVENT\_LINE Emitted whenever the stream receives a line of data. The event's `data` field is set to the received line stripped of the `\n` or `\r\n` and null terminated, the `size` field is the length of string. #### DYAD\_EVENT\_ERROR Emitted whenever an error occurs on a stream. For example, when creating a listening socket this event will be emitted if it cannot be bound. The stream is immediately closed after this event. #### DYAD\_EVENT\_TIMEOUT Emitted when the stream times out (see `dyad_setTimeout()`). The stream is immediately closed after this event. #### DYAD\_EVENT\_TICK Emitted every time a tick occurs. A tick is an event which is emitted on every stream at a constant interval; this interval can be set using `dyad_setTickInterval()`. ## States #### DYAD\_STATE\_CLOSED The stream is closed. Streams are created in this state, and, if left in this state, are destroyed automatically. #### DYAD\_STATE\_CLOSING The stream is connected but still has data in its write buffer thats waiting to be sent before it closes. #### DYAD\_STATE\_CONNECTING The stream is attempting to connect to a host. #### DYAD\_STATE\_CONNECTED The stream is connected and can send or receive data. #### DYAD\_STATE\_LISTENING The stream is currently listening for connections to accept. ## Types #### dyad\_Socket Represents a socket for the given platform. #### dyad\_Stream A stream created with `dyad_newStream()` or by a listening server when it accepts a connection. Dyad handles the resources allocated for all streams; closed streams are automatically destroyed by the `dyad_update()` function. #### dyad\_Event Contains an event's information, a pointer of which is passed to a `dyad_Callback` function when an event occurs. This struct contains the following fields: Field | Description ----------------------|------------------------------------------------------- int type | The type of event which was emitted void \*udata | The `udata` pointer passed to `dyad_addEventListener()` dyad\_Stream \*stream | The stream which emitted this event dyad\_Stream \*remote | The client stream when a connection is accepted const char \*msg | A description of the event or error message char \*data | The events associated data int size | The size in bytes of the event's associated data The `dyad_Event` struct and the data pointed to by its `data` field should never be modified by an event callback. #### dyad\_Callback An event listener callback function which can be passed to `dyad_addListener()`. The function should be of the following form: ```c void func(dyad_Event *event); ``` #### dyad\_PanicCallback An atPanic callback function which can be passed to `dyad_atPanic()`. The function should be of the following form: ```c void func(const char *message); ``` <file_sep>/example/httpserv.c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "dyad.h" /* A very simple HTTP server which responds to a number of paths with different * information. See httpserv2.c for an example of an HTTP server which responds * with files. */ static int count = 0; static void onLine(dyad_Event *e) { char path[128]; if (sscanf(e->data, "GET %127s", path) == 1) { /* Print request */ printf("%s %s\n", dyad_getAddress(e->stream), path); /* Send header */ dyad_writef(e->stream, "HTTP/1.1 200 OK\r\n\r\n"); /* Handle request */ if (!strcmp(path, "/")) { dyad_writef(e->stream, "<html><body><pre>" "<a href='/date'>date</a><br>" "<a href='/count'>count</a><br>" "<a href='/ip'>ip</a>" "</pre></html></body>" ); } else if (!strcmp(path, "/date")) { time_t t = time(0); dyad_writef(e->stream, "%s", ctime(&t)); } else if (!strcmp(path, "/count")) { dyad_writef(e->stream, "%d", ++count); } else if (!strcmp(path, "/ip")) { dyad_writef(e->stream, "%s", dyad_getAddress(e->stream)); } else { dyad_writef(e->stream, "bad request '%s'", path); } /* Close stream when all data has been sent */ dyad_end(e->stream); } } static void onAccept(dyad_Event *e) { dyad_addListener(e->remote, DYAD_EVENT_LINE, onLine, NULL); } static void onListen(dyad_Event *e) { printf("server listening: http://localhost:%d\n", dyad_getPort(e->stream)); } static void onError(dyad_Event *e) { printf("server error: %s\n", e->msg); } int main(void) { dyad_Stream *s; dyad_init(); s = dyad_newStream(); dyad_addListener(s, DYAD_EVENT_ERROR, onError, NULL); dyad_addListener(s, DYAD_EVENT_ACCEPT, onAccept, NULL); dyad_addListener(s, DYAD_EVENT_LISTEN, onListen, NULL); dyad_listen(s, 8000); while (dyad_getStreamCount() > 0) { dyad_update(); } return 0; } <file_sep>/example/daytime.c #include <stdio.h> #include "dyad.h" /* Connects to a daytime server and prints the response */ static void onConnect(dyad_Event *e) { printf("connected: %s\n", e->msg); } static void onError(dyad_Event *e) { printf("error: %s\n", e->msg); } static void onData(dyad_Event *e) { printf("%s", e->data); } int main(void) { dyad_Stream *s; dyad_init(); s = dyad_newStream(); dyad_addListener(s, DYAD_EVENT_CONNECT, onConnect, NULL); dyad_addListener(s, DYAD_EVENT_ERROR, onError, NULL); dyad_addListener(s, DYAD_EVENT_DATA, onData, NULL); dyad_connect(s, "time-nw.nist.gov", 13); while (dyad_getStreamCount() > 0) { dyad_update(); } dyad_shutdown(); return 0; } <file_sep>/example/build.py #!/usr/bin/python2.7 import os, sys COMPILER = "gcc" SRC_DIR = "../src" INCLUDE_DIR = "../src" BIN_DIR = "../bin" BIN_NAME = False CFLAGS = ["-O3", "-Wall", "-Wextra", "--std=c89", "-pedantic"] DLIBS = ["ws2_32"] if os.name == "nt" else [] DEFINES = [] def strformat(fmt, var): for k in var: fmt = fmt.replace("{%s}" % str(k), var[k]) return fmt def listdir(path): return [os.path.join(dp, f) for dp, dn, fn in os.walk(path) for f in fn] def main(): os.chdir(sys.path[0]) if len(sys.argv) < 2: print "usage: build.py c_file" sys.exit() global BIN_NAME if not BIN_NAME: BIN_NAME = sys.argv[1].replace(".c", ".exe" if os.name == "nt" else "") if not os.path.exists(BIN_DIR): os.makedirs(BIN_DIR) cfiles = filter(lambda x:x.endswith((".c", ".C")), listdir(SRC_DIR)) cfiles.append(sys.argv[1]) cmd = strformat( "{compiler} {flags} {include} {def} -o {outfile} {srcfiles} {libs} {argv}", { "compiler" : COMPILER, "flags" : " ".join(CFLAGS), "include" : "-I" + INCLUDE_DIR, "def" : " ".join(map(lambda x: "-D " + x, DEFINES)), "outfile" : BIN_DIR + "/" + BIN_NAME, "srcfiles" : " ".join(cfiles), "libs" : " ".join(map(lambda x: "-l" + x, DLIBS)), "argv" : " ".join(sys.argv[2:]) }) print "compiling..." res = os.system(cmd) if not res: print(BIN_DIR + "/" + BIN_NAME) print("done" + (" with errors" if res else "")) if __name__ == "__main__": main()
4ce4b969b678809724e739dc4662998f1e5e9022
[ "Markdown", "C", "Python", "CMake" ]
8
C
Wirtos/dyad
f6503d1ad2f158b5e5c9dc19227bf733036b42f5
f3759dc3b9955ec95b020dd06e4e8142f807ed63
refs/heads/master
<repo_name>jherrm/flipbot<file_sep>/arduino/pinball/pinball.ino #include <Servo.h> #define MOVEMENT_DELAY 0 #define RIGHT_SERVO_PIN 10 #define LEFT_SERVO_PIN 9 #define RIGHT_START 85 #define RIGHT_END 133 #define LEFT_START 85 #define LEFT_END 47 Servo right; Servo left; int rightPos = 0; int leftPos = 0; int INC = 2; void flipRight() { for (rightPos = RIGHT_START; rightPos <= RIGHT_END; rightPos += INC) { // in steps of 1 degree right.write(rightPos); delay(MOVEMENT_DELAY); } } void releaseRight() { for (rightPos = RIGHT_END; rightPos >= RIGHT_START; rightPos -= INC) { right.write(rightPos); delay(MOVEMENT_DELAY); } } void flipLeft() { for (leftPos = LEFT_START; leftPos >= LEFT_END; leftPos -= INC) { left.write(leftPos); delay(MOVEMENT_DELAY); } } void releaseLeft() { for (leftPos = LEFT_END; leftPos <= LEFT_START; leftPos += INC) { // in steps of 1 degree left.write(leftPos); delay(MOVEMENT_DELAY); } } void setup() { right.attach(RIGHT_SERVO_PIN); left.attach(LEFT_SERVO_PIN); Serial.begin(115200); } void loop() { if (Serial.available() > 0) { char c = Serial.read(); // read the next char received if (c == '0') { flipRight(); } else if (c == '1') { releaseRight(); } else if (c == '2') { flipLeft(); } else if (c == '3') { releaseLeft(); } } } <file_sep>/NeuralNet/convnetshared1.py import tensorflow as tf from tensorflow.contrib import rnn import numpy as np import sys,os sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import config def weight_variable(shape, fanIn, fanOut, name=None, coll=None): with tf.variable_scope(coll): return tf.get_variable(name, shape, initializer=tf.random_normal_initializer(stddev=1.0/np.sqrt(fanIn/2.0)) ) def weight_variable_c(shape, name=None, coll=None): fanIn = shape[0] * shape[1] * shape[2] fanOut = shape[0] * shape[1] * shape[3] with tf.variable_scope(coll): return tf.get_variable(name, shape, initializer=tf.random_normal_initializer(stddev=1.0 / np.sqrt(fanIn / 2.0))) def bias_variable(shape, name=None, coll=None): with tf.variable_scope(coll): return tf.get_variable(name, shape, initializer=tf.constant_initializer(0.0)) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def avg_pool_2x2(x): return tf.nn.avg_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') # https://stackoverflow.com/questions/36668542/flatten-batch-in-tensorflow def flatten_batch(tensor): shape = tensor.get_shape().as_list() # a list: [None, 9, 2] dim = np.prod(shape[1:]) # dim = prod(9,2) = 18 return tf.reshape(tensor, [-1, dim]) # -1 means "all" class NNModel: # static class vars n_steps = 1 # timesteps for RNN-like training (no RNN here. This is the Alexnet.) n_hidden = 128 # hidden layer num of features # n_vocab = 256 def __init__(self): self.l2_collection = [] self.visualizations = {} # Set up the inputs to the conv net self.in_image = tf.placeholder(tf.float32, shape=[None, config.width * config.height * config.img_channels], name='in_image') self.in_image_small = tf.placeholder(tf.float32, shape=[None, config.width_small * config.height_small * config.img_channels], name='in_image_small') self.in_speed = tf.placeholder(tf.float32, shape=[None], name='in_speed') # Labels self.steering_regress_ = tf.placeholder(tf.float32, shape=[None], name='steering_regress_') self.throttle_regress_ = tf.placeholder(tf.float32, shape=[None], name='throttle_regress_') # misc self.keep_prob = tf.placeholder(tf.float32) self.train_mode = tf.placeholder(tf.float32) # Reshape and put input image in range [-0.5..0.5] x_image = tf.reshape(self.in_image, [-1, config.width, config.height, config.img_channels]) / 255.0 - 0.5 # Neural net layers - first convolution, then fully connected, then final transform to output act = self.conv_layer(x_image, 8, 5, 'conv1', 'shared_conv') # act = max_pool_2x2(x_image) # act = max_pool_2x2(act) # act = max_pool_2x2(act) act = self.conv_layer(act, 12, 5, 'conv2', 'shared_conv') act = self.conv_layer(act, 16, 5, 'conv3', 'shared_conv') act = self.conv_layer(act, 32, 5, 'conv4', 'shared_conv') act_flat = flatten_batch(act) act = self.fc_layer(act_flat, 1024, 'fc1', 'shared_fc', True) # -------------------- Insert discriminator here for domain adaptation -------------------- # Sneak the speedometer value into the matrix in_speed_shaped = tf.reshape(self.in_speed, [-1, 1]) act_concat = tf.concat([act, in_speed_shaped], 1) fc2_num_outs = 1024 act = self.fc_layer(act_concat, fc2_num_outs, 'fc2', 'main', False) # Final transform without relu. Not doing l2 regularization on this because it just feels wrong. num_outputs = 1 + 1 W_fc_final = weight_variable([fc2_num_outs, num_outputs], fc2_num_outs, num_outputs, name='W_fc4', coll='main') # self.l2_collection.append(W_fc4) b_fc_final = bias_variable([num_outputs], name='b_fc4', coll='main') final_activations = tf.matmul(act, W_fc_final) + b_fc_final # pick apart the final output matrix into steering and throttle continuous values. slice_a = 1 self.steering_regress_result = tf.reshape(final_activations[:, 0:slice_a], [-1]) slice_b = slice_a + 1 self.throttle_regress_result = tf.reshape(final_activations[:, slice_a:slice_b], [-1]) # we will optimized to minimize mean squared error self.squared_diff = tf.reduce_mean(tf.squared_difference(self.steering_regress_result, self.steering_regress_)) self.squared_diff_throttle = tf.reduce_mean(tf.squared_difference(self.throttle_regress_result, self.throttle_regress_)) # L2 regularization self.regularizers = sum([tf.nn.l2_loss(tensor) for tensor in self.l2_collection]) # Add regression loss to regularizers. Arbitrary scalars to balance out the 3 things and give regression steering priority self.loss = 0.001 * self.regularizers + self.squared_diff*0.5 + self.squared_diff_throttle*1.0 tf.summary.scalar('loss', self.loss) # ----------------------------------------------------------------------------------- # http://stackoverflow.com/questions/35298326/freeze-some-variables-scopes-in-tensorflow-stop-gradient-vs-passing-variables optimizerA = tf.train.AdamOptimizer(3e-4) main_train_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "shared_fc") + tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "shared_conv") + tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES, "main") self.train_step = optimizerA.minimize(self.loss, var_list=main_train_vars) def conv_layer(self, tensor, channels_out, conv_size, name, scope_name): channels_in = tensor.get_shape().as_list()[3] W_conv = weight_variable_c([conv_size, conv_size, channels_in, channels_out], name='W_' + name, coll=scope_name) self.l2_collection.append(W_conv) b_conv = bias_variable([channels_out], name='b_' + name, coll=scope_name) h_conv = tf.nn.relu(conv2d(tensor, W_conv) + b_conv) return max_pool_2x2(h_conv) def fc_layer(self, tensor, channels_out, name, scope_name, dropout): channels_in = tensor.get_shape().as_list()[1] W_fc = weight_variable([channels_in, channels_out], channels_in, channels_out, name='W_' + name, coll=scope_name) self.l2_collection.append(W_fc) b_fc = bias_variable([channels_out], name='b_' + name, coll=scope_name) h_fc = tf.nn.relu(tf.matmul(tensor, W_fc) + b_fc) if dropout: h_fc = tf.nn.dropout(h_fc, self.keep_prob) return h_fc class LSTMModel: # static class vars n_steps = 32 # timesteps for RNN-like training n_hidden = 64 # hidden layer num of features def __init__(self): self.l2_collection = [] self.visualizations = {} # Set up the inputs to the conv net self.in_image = tf.placeholder(tf.float32, shape=[None, config.width * config.height * config.img_channels], name='in_image') self.in_image_small = tf.placeholder(tf.float32, shape=[None, self.n_steps, config.width_small * config.height_small * config.img_channels], name='in_image_small') # self.visualizations["in_image"] = ("rgb_batch_steps", tf.reshape() self.in_image) self.in_speed = tf.placeholder(tf.float32, shape=[None, self.n_steps, 1], name='in_speed') # Labels self.steering_regress_ = tf.placeholder(tf.float32, shape=[None, self.n_steps, 1], name='steering_regress_') self.throttle_regress_ = tf.placeholder(tf.float32, shape=[None, self.n_steps, 1], name='throttle_regress_') # misc self.keep_prob = tf.placeholder(tf.float32) self.train_mode = tf.placeholder(tf.float32) real_lstm = False if real_lstm: # Reshape and put input image in range [-0.5..0.5] x_image = tf.reshape(self.in_image_small, [-1, self.n_steps, config.width_small, config.height_small, config.img_channels]) / 255.0 - 0.5 batch_size = tf.shape(x_image)[0] act = tf.reshape(x_image, [-1, config.width_small, config.height_small, config.img_channels]) # act = avg_pool_2x2(act) self.visualizations["down_image"] = ("rgb_batch_steps", act) # act = self.conv_layer(act, 12, 5, 'conv2', 'shared_conv') # act = self.conv_layer(act, 4, 5, 'conv3', 'shared_conv') final_channels = 16 act = self.conv_layer(act, final_channels, 5, 'conv4', 'shared_conv') new_width = act.get_shape().as_list()[1] act = flatten_batch(act) # Sneak the speedometer value into the matrix in_speed_shaped = tf.reshape(self.in_speed, [-1, 1]) * 10.0 act = tf.concat([act, in_speed_shaped], 1) # Prepare data shape to match `rnn` function requirements # Current data input shape: (batch_size, n_steps, n_vocab) # Required shape: 'n_steps' tensors list of shape (batch_size, n_vocab) # Unstack to get a list of 'n_steps' tensors of shape (batch_size, width, height, channels) act = tf.reshape(act, [-1, self.n_steps, new_width * new_width * final_channels + 1]) act = tf.unstack(act, self.n_steps, 1) # Define a lstm cell with tensorflow with tf.variable_scope('lstm'): lstm_cell = rnn.BasicLSTMCell(self.n_hidden) # lstm_cell = tf.contrib.rnn.core_rnn_cell.BasicLSTMCell(self.n_hidden) # Get lstm cell output # outputs, states = rnn.static_rnn(lstm_cell, x, dtype=tf.float32) state = lstm_cell.zero_state(batch_size, tf.float32) outputs = [] for input_ in act: output, state = lstm_cell(input_, state) outputs.append(output) # return (outputs, state) lstm_out = outputs[-1] else: act = tf.reshape(self.in_image_small / 255.0 - 0.5, [-1, self.n_steps, config.width_small, config.height_small, config.img_channels]) act = tf.transpose(act, [0, 2, 3, 1, 4]) act = tf.reshape(act, [-1, config.width_small, config.height_small, self.n_steps * config.img_channels]) act = self.conv_layer(act, self.n_steps*4, 5, 'conv1c', 'shared_conv') act = flatten_batch(act) in_speed_shaped = tf.reshape(self.in_speed, [-1, self.n_steps]) * 10.0 act = tf.concat([act, in_speed_shaped], 1) act = self.fc_layer(act, 128, 'fc1c', 'shared_fc', True) lstm_out = act # Reshape and put input image in range [-0.5..0.5] x_image2 = tf.reshape(self.in_image / 255.0 - 0.5, [-1, config.width, config.height, config.img_channels]) # self.visualizations["pathB_image"] = ("rgb_batch", x_image2) # Neural net layers - first convolution, then fully connected, then final transform to output act = self.conv_layer(x_image2, 8, 5, 'conv1b', 'shared_conv') # act = max_pool_2x2(x_image2) act = self.conv_layer(act, 12, 5, 'conv2b', 'shared_conv') act = self.conv_layer(act, 16, 5, 'conv3b', 'shared_conv') act = self.conv_layer(act, 32, 5, 'conv4b', 'shared_conv') act = flatten_batch(act) self.mid_act = act self.mid_lstm = lstm_out * 0.01 act = tf.concat([act, self.mid_lstm], 1) # act = self.mid_lstm act = self.fc_layer(act, 1024, 'fc1', 'shared_fc', True) # -------------------- Insert discriminator here for domain adaptation -------------------- # Sneak the speedometer value into the matrix in_speed_last = tf.transpose(self.in_speed, [1, 0, 2])[-1] # [batch_size, 1] # in_speed_shaped = tf.reshape(in_speed_last, [-1, 1]) # act = tf.concat([act, in_speed_last, lstm_out], 1) act = tf.concat([act, in_speed_last], 1) fc2_num_outs = 1024 act = self.fc_layer(act, fc2_num_outs, 'fc2', 'main', False) num_outputs = 2 W_fc_final = weight_variable([fc2_num_outs, num_outputs], fc2_num_outs, num_outputs, name='W_fc4', coll='main') b_fc_final = bias_variable([num_outputs], name='b_fc4', coll='main') regress_outs = tf.matmul(act, W_fc_final) + b_fc_final self.steering_regress_result = tf.reshape(regress_outs[:, 0], [-1]) # [batch_size] self.throttle_regress_result = tf.reshape(regress_outs[:, 1], [-1]) # [batch_size] # we will optimized to minimize mean squared error steering_temp = tf.reshape(self.steering_regress_[:, -1], [-1]) throttle_temp = tf.reshape(self.throttle_regress_[:, -1], [-1]) # steering_regress_last = tf.transpose(self.steering_regress_result, [1, 0, 2])[-1] # throttle_regress_last = tf.transpose(self.throttle_regress_result, [1, 0, 2])[-1] self.squared_diff = tf.reduce_mean(tf.squared_difference(self.steering_regress_result, steering_temp)) self.squared_diff_throttle = tf.reduce_mean(tf.squared_difference(self.throttle_regress_result, throttle_temp)) self.regularizers = sum([tf.nn.l2_loss(tensor) for tensor in self.l2_collection]) # self.regularizers = tf.zeros((1)) # Add regression loss to regularizers. Arbitrary scalars to balance out the 3 things and give regression steering priority # self.loss = self.squared_diff * 0.1 + self.squared_diff_throttle * 5.0 self.loss = 0.001 * self.regularizers + self.squared_diff*0.5 + self.squared_diff_throttle*1.0 optimizerA = tf.train.AdamOptimizer(3e-4) self.train_step = optimizerA.minimize(self.loss) def conv_layer(self, tensor, channels_out, conv_size, name, scope_name, pool=True): channels_in = tensor.get_shape().as_list()[3] W_conv = weight_variable_c([conv_size, conv_size, channels_in, channels_out], name='W_' + name, coll=scope_name) self.l2_collection.append(W_conv) b_conv = bias_variable([channels_out], name='b_' + name, coll=scope_name) h_conv = tf.nn.relu(conv2d(tensor, W_conv) + b_conv) if pool: return max_pool_2x2(h_conv) else: return h_conv def fc_layer(self, tensor, channels_out, name, scope_name, dropout): channels_in = tensor.get_shape().as_list()[1] W_fc = weight_variable([channels_in, channels_out], channels_in, channels_out, name='W_' + name, coll=scope_name) self.l2_collection.append(W_fc) b_fc = bias_variable([channels_out], name='b_' + name, coll=scope_name) h_fc = tf.nn.relu(tf.matmul(tensor, W_fc) + b_fc) if dropout: h_fc = tf.nn.dropout(h_fc, self.keep_prob) return h_fc <file_sep>/capture_pinball.py import tkinter from PIL import Image, ImageTk import serial import config import cv2 import os import imutils import time ser = serial.Serial('/dev/cu.usbmodem1411', 115200) # class DummySerial(object): # def write(self, val): # print('dummy write %s' % val) # ser = DummySerial() tk = tkinter.Tk() has_prev_key_release = None left_code = 8124162 right_code = 8189699 space_code = 3211296 class MainLoop(object): def __init__(self): frame = tkinter.Frame(tk, width=100, height=100) self.lmain = tkinter.Label(tk) self.lmain.grid(row=0, column=0) self.lmain.pack() self.lmain.focus_set() self.commands = [] keys = ['Left', 'Right', 'space'] for k in keys: frame.bind('<KeyRelease-%s>' % k, self.on_key_release_repeat) frame.bind('<KeyPress-%s>' % k, self.on_key_press_repeat) frame.pack() frame.focus_set() self.setup_cam() self.frame_index = 0 self.first_frame = None self.first_left = None self.first_right = None self.is_left_down = False self.is_right_down = False self.is_recording = False self.episode_index = 0 if not os.path.exists('sessions'): os.mkdir('sessions') print('init\'d!') tk.after(16, self.on_frame) tk.mainloop() def setup_cam(self, src=1): self.camera_stream = cv2.VideoCapture(src) if not self.camera_stream.isOpened(): src = 1 - src self.camera_stream = cv2.VideoCapture(src) if not self.camera_stream.isOpened(): sys.exit("Error: Camera didn't open for capture.") # Setup frame dims. self.camera_stream.set(cv2.CAP_PROP_FRAME_WIDTH, 320) self.camera_stream.set(cv2.CAP_PROP_FRAME_HEIGHT, 240) self.camera_stream.read() def calculate_thresh(self, first_frame, current_frame): frame_delta = cv2.absdiff(first_frame, current_frame) thresh = cv2.threshold(frame_delta, 25, 255, cv2.THRESH_BINARY)[1] thresh = cv2.dilate(thresh, None, iterations=2) result = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # print(result) cnts = result[1] # print(cnts) return cnts def on_frame(self): self.frame_index += 1 now = time.time() new_list = [] for func, scheduled_time in self.commands: if scheduled_time < now: func() else: new_list.append((func, scheduled_time)) self.commands = new_list # hmmm, whats grabbed? grabbed, frame = self.camera_stream.read() width = 500 # frame = cv2.flip(frame, 1) frame = imutils.resize(frame, width=width) # frame = frame[100:220, 100:400] frame = frame[120:220, :] gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.Canny(gray, 200,300) frame = gray gray = cv2.GaussianBlur(gray, (21, 21), 0) # 100 300 left = gray[:, :width/2] right = gray[:, width/2:] cv2.imwrite('/tmp/frame.jpg', frame) cv2.imwrite('/tmp/left.jpg', left) cv2.imwrite('/tmp/right.jpg', right) # store the first_frame for image diff if self.first_frame is None: self.first_frame = gray self.first_left = left self.first_right = right else: THRESH = 500 cnts = self.calculate_thresh(self.first_frame, frame) for c in cnts: # if the contour is too small, ignore it if cv2.contourArea(c) < THRESH: continue # compute the bounding box for the contour, draw it on the frame, # and update the text (x, y, w, h) = cv2.boundingRect(c) cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) text = "Occupied" left_cnts = self.calculate_thresh(self.first_left, left) for c in left_cnts: # if the contour is too small, ignore it if cv2.contourArea(c) > THRESH: self.flip_left() self.commands.append((self.release_left, time.time() + 0.05)) else: # self.release_left() pass right_cnts = self.calculate_thresh(self.first_right, right) for c in right_cnts: # if the contour is too small, ignore it if cv2.contourArea(c) > THRESH: self.flip_right() self.commands.append((self.release_right, time.time() + 0.05)) else: # self.release_right() pass # display image in GUI img = Image.fromarray(frame) imgtk = ImageTk.PhotoImage(image=img) self.lmain.imgtk = imgtk self.lmain.configure(image=imgtk) if self.is_recording: fname = 'sessions/%d/test_%09d_%d_%d.jpg' % (self.episode_index, self.frame_index, self.is_left_down, self.is_right_down) cv2.imwrite(fname, frame) tk.after(10, self.on_frame) def flip_left(self): print("Flip left") ser.write(b'2') self.is_left_down = True def flip_right(self): print("Flip Right") ser.write(b'0') self.is_right_down = True def release_left(self): print('Release Left') ser.write(b'3') self.is_left_down = False def release_right(self): print("Release Right") ser.write(b'1') self.is_right_down = False def on_key_release(self, event): global has_prev_key_release has_prev_key_release = None # print("on_key_release", repr(event.char)) if event.keycode == left_code: self.release_left() elif event.keycode == right_code: self.release_right() def spacebar_toggle(self): self.is_recording = not self.is_recording if self.is_recording: self.episode_index += 1 print('recording episode %d' % self.episode_index) self.frame_index = 0 target_path = 'sessions/%d' % self.episode_index if not os.path.exists(target_path): os.mkdir(target_path) else: print("chillin'") def on_key_press(self, event): # print("on_key_press", repr(event.char)) print("press", event.keycode) if event.keycode == left_code: self.flip_left() elif event.keycode == right_code: self.flip_right() elif event.keycode == space_code: self.spacebar_toggle() def on_key_release_repeat(self, event): global has_prev_key_release has_prev_key_release = tk.after_idle(self.on_key_release, event) # print("on_key_release_repeat", repr(event.char)) def on_key_press_repeat(self, event): global has_prev_key_release if has_prev_key_release: tk.after_cancel(has_prev_key_release) has_prev_key_release = None # print("on_key_press_repeat", repr(event.char)) else: self.on_key_press(event) if __name__ == '__main__': m = MainLoop() <file_sep>/arduino/pinball/test.py import tkinter import serial ser = serial.Serial('/dev/cu.usbmodem1411', 115200) def flipLeft(): print('flip left') ser.write(b'2') def releaseLeft(): print('Release Left') ser.write(b'3') def flipRight(): print("Flip Right") ser.write(b'0') def releaseRight(): print("Flip Right") ser.write(b'1') tk = tkinter.Tk() has_prev_key_release = None left_code = 8124162 right_code = 8189699 def on_key_release(event): global has_prev_key_release has_prev_key_release = None # print("on_key_release", repr(event.char)) if event.keycode == left_code: releaseLeft() elif event.keycode == right_code: releaseRight() def on_key_press(event): # print("on_key_press", repr(event.char)) print("press", event.keycode) if event.keycode == left_code: flipLeft() elif event.keycode == right_code: flipRight() def on_key_release_repeat(event): global has_prev_key_release has_prev_key_release = tk.after_idle(on_key_release, event) # print("on_key_release_repeat", repr(event.char)) def on_key_press_repeat(event): global has_prev_key_release if has_prev_key_release: tk.after_cancel(has_prev_key_release) has_prev_key_release = None # print("on_key_press_repeat", repr(event.char)) else: on_key_press(event) frame = tkinter.Frame(tk, width=100, height=100) frame.bind("<KeyRelease-Left>", on_key_release_repeat) frame.bind("<KeyPress-Left>", on_key_press_repeat) frame.bind("<KeyRelease-Right>", on_key_release_repeat) frame.bind("<KeyPress-Right>", on_key_press_repeat) frame.pack() frame.focus_set() tk.mainloop() <file_sep>/readme.md # Carputer Carputer is a 1/10th scale self driving car. It drives based on video camera and speedometer inputs. It uses a neural network to drive. The camera image and speedometer get sent to the neural network and the network outputs steering and throttle motor controls for the car. Since the car uses a neural network for driving, it has to be trained. The training process is basically driving it around a track about 20 times or so using the car's radio control. During that driving, we record all of the radio control inputs along with the video and speedometer data. Once we have that, the neural network can learn how to mimic our driving style by outputting steering and throttle based on the video and speedometer. The process is to record, train, and then run autonomously, as seen in the steps below. This is an experimental setup, so it's not super-clean code or hardware. ## Setting up development on mac * install virtualenv and homebrew * create a virutalenv called flipbot `virtualenv flipbot` * Activate your virtualenv: `source flipbot/bin/activate` * `brew install freetype` * `pip install --upgrade pip` * `pip install -r requirements.txt` ## Recording pipline 0. Turn on ESC, RC controller. Plug in battery, USB. Start switch to off. 0. Run InsomniaX and disable lid sleep and idle sleep. 0. activate the virtualenv: `source /path/to/venv/bin/activate` 0. run a script to drive and record training data: `python main_car.py record` -- this will let you have manual control over the car and save out recordings when you flip the switch ## Run autonomously 0. Turn on ESC, RC controller. Plug in battery, USB. Start switch to off. 0. Run InsomniaX and disable lid sleep and idle sleep. 0. activate the virtualenv: `source /path/to/venv/bin/activate` 0. run a script to let tensorflow drive: `python main_car.py tf` -- when you flip the switch, you will lose manual control and the car will attempt to drive on its own 0. for autonomous kill switch: pull throttle and turn the steering wheel 0. to revive autonomous mode, hit the channel 3 button (near the trigger) ## Training pipline 0. convert TRAINING images to np arrays: `python NeuralNet/filemash.py /path/to/data` (Can be multiple paths) 0. convert TEST images to np arrays: `python NeuralNet/filemash.py /path/to/data --gen_test` (Can be multiple paths) 0. train a model: `python NeuralNet/convnet02.py`. Train for minimum 1500 iterations, ideally around 5000 iterations. 0. use this model to drive the car (see above) ## Analysis * for training info, see `debug.html` -- reminder: < 7 is right, > 7 is left * run `analysis/make_video.py` for debug videos * use `analysis/plot_vs_time.py` to view telemetry data ### Hardware TODOs - [ ] Fix the radio control dropped signal error - [ ] Get the TX1 working - [ ] Get the IMU recording data ### Software TODOs - [ ] Fix keepalive on Arduino - [ ] Look into remote SSH type software so we don't have to keep popping open the car. ### Hardware setup Updates - We no longer use the IMUs and we're no longer trying to run the NVidia TX1 computer. Macbook works better. ![Wiring diagram](https://github.com/otaviogood/carputer/blob/master/CarDiagram.jpg "Wiring diagram") ## Simulator Work in progress, of course. The simulator runs in Unity. I didn't check in the lighting files because they are big, but if you build lighting, it should look like this... ![Unity sim](https://github.com/otaviogood/carputer/blob/master/warehouse_sim.jpg "Unity sim")
bd123f120d36aff7f080523dd2d443d3e29a375b
[ "Markdown", "Python", "C++" ]
5
C++
jherrm/flipbot
cd34a512b9df2d0783e09c8aa4410bdf5f9a6a62
78f094c0fd35572f4e7c70adad23b457ded360cb
refs/heads/master
<repo_name>RomainMorlevat/rails-mister-cocktail<file_sep>/app/models/dose.rb class Dose < ApplicationRecord validates :description, presence: true validates :cocktail_id, uniqueness: { scope: :ingredient_id, message: "This cocktail already has a dose with this ingredient" } belongs_to :cocktail belongs_to :ingredient end
d6c3ce80dfd245131118de6ff4edd3d171624c52
[ "Ruby" ]
1
Ruby
RomainMorlevat/rails-mister-cocktail
95c52c5a7c4d5fb52caf4a0aeaa77c3f595bf93a
04d12ef3ecbe5905f653fa87a0520dec00459eef
refs/heads/master
<repo_name>Kakashi-19/PYTHON<file_sep>/RANK.py #!/bin/python3 import math import os import random import re import sys # Complete the divisibleSumPairs function below. def divisibleSumPairs(n, k, ar): ways = 0 ar.sort() for i in range(n): for a in range(i + 1, n): if (ar[i] + ar[a]) % k == 0: if i == n - 2: if (ar[i] + ar[n - 1]) % k == 0: ways += 1 break ways += 1 return ways nk = input().split() n = int(nk[0]) k = int(nk[1]) ar = list(map(int, input().rstrip().split())) result = divisibleSumPairs(n, k, ar) print(str(result) + '\n') <file_sep>/attend.py import requests, bs4 res = requests.get('http://portal.lnct.ac.in/Accsoft2/Parents/StuAttendanceStatus.aspx') res.raise_for_status() att = bs4.BeautifulSoup(res.text, 'html.parser') attend = att.select('#ctl00_ContentPlaceHolder1_UpdatePanel1 > table > tbody > tr:nth-child(2)') print(attend)<file_sep>/desktop.ini [.ShellClassInfo] IconResource=C:\Users\<NAME>\Downloads\Franksouza183-Fs-Places-folder-python.ico,0 [ViewState] Mode= Vid= FolderType=Generic <file_sep>/tic tac toe 4.py # PROGRAM FOR TIC TAC TOE import random import sys theBoard = {'topL' : ' ', 'topM' : ' ', 'topR' : ' ', 'midL' : ' ', 'midM' : ' ', 'midR' : ' ', 'lowL' : ' ', 'lowM' : ' ', 'lowR' : ' '} place = list(theBoard.keys()) #LIST OF POSSIBLE MOVES def display(board): #TO DISPLAY THE BOARD print((board)['topL'] + '|' + (board)['topM'] + '|' + (board)['topR'] ) print('-----') print((board)['midL'] + '|' + (board)['midM'] + '|' + (board)['midR'] ) print('-----') print((board)['lowL'] + '|' + (board)['lowM'] + '|' + (board)['lowR'], end = '\n\n') def intro(): #START SCREEN global Psign, Csign print('' + ' TIC-TAC-TOE') display(theBoard) print('Choose X or O') #ASSIGNING OF SIGN Psign = input() pos = ['X', 'O'] pos.remove(Psign) Csign = pos[0] intro() def condn(): #WIN AND LOSE CONDITIONS global win, lose, Psign, Csign win = Psign == theBoard['topL'] == theBoard['topM'] == theBoard['topR'] or\ Psign == theBoard['midL'] == theBoard['midM'] == theBoard['midR'] or\ Psign == theBoard['lowL'] == theBoard['lowM'] == theBoard['lowR'] or\ Psign == theBoard['topL'] == theBoard['midL'] == theBoard['lowL'] or\ Psign == theBoard['topM'] == theBoard['midM'] == theBoard['lowM'] or\ Psign == theBoard['topR'] == theBoard['midR'] == theBoard['lowR'] or\ Psign == theBoard['topL'] == theBoard['midM'] == theBoard['lowR'] or\ Psign == theBoard['topR'] == theBoard['midM'] == theBoard['lowL'] lose = Csign == theBoard['topL'] == theBoard['topM'] == theBoard['topR'] or\ Csign == theBoard['midL'] == theBoard['midM'] == theBoard['midR'] or\ Csign == theBoard['lowL'] == theBoard['lowM'] == theBoard['lowR'] or\ Csign == theBoard['topL'] == theBoard['midL'] == theBoard['lowL'] or\ Csign == theBoard['topM'] == theBoard['midM'] == theBoard['lowM'] or\ Csign == theBoard['topR'] == theBoard['midR'] == theBoard['lowR'] or\ Csign == theBoard['topL'] == theBoard['midM'] == theBoard['lowR'] or\ Csign == theBoard['topR'] == theBoard['midM'] == theBoard['lowL'] condn() def game(): global Psign, Csign, win, lose choice = random.choice(['Cpu', 'You']) #TO SLECT THE STARTING PLAYER print(choice + ' will go first\n') if choice == 'Cpu': while win == False and lose == False: #when CPU goes first moveC = random.choice(place) theBoard[(moveC)] = Csign #CPU MOVE display(theBoard) place.remove(moveC) #place.remove is used to remove used positions from possible moves list ie places condn() if win or lose == True: #condition check continue print('Choose a Move' + str(place)) print('your turn') moveP = input() theBoard[moveP] = Psign display(theBoard) #PLAYER MOVE place.remove(moveP) condn() if win == True: print('Congratulations! You Won') elif lose == True: print('You Lose') elif choice == 'You': #when player goes First while win == False and lose == False: print('Choose a Move' + str(place)) moveP = input() theBoard[moveP] = Psign display(theBoard) #PLAYER MOVE place.remove(moveP) condn() #UPADTING CONDITONS if win or lose == True: continue #condition check moveC = random.choice(place) theBoard[(moveC)] = Csign display(theBoard) # CPU MOVE place.remove(moveC) condn() #UPADTING CONDITONS if win or lose == True: #condition check continue print('your turn') if win == True: print('Congratulations! You Won') print('\nWanna Play again ? (y/n)') choice = input() if choice == 'y': intro() elif choice == 'n': print('Thank you for playing TIC TAC TOE') sys.exit() else: sys.exit() elif lose == True: print('You Lose') game() <file_sep>/calculator.py #COde vita practice n, k = map(int, input().split()) print(n) print(k) <file_sep>/palind.py import sys a = sys.argv wordL = len(a[1]) revLetter = [] for i in range(-1, -wordL + -1, -1): revLetter.append(list(a[1].lower())[i]) if list((a[1]).lower()) == revLetter: print(a[1] + ' is a Palindrome') else: print(a[1] + ' is not a Palindrome')<file_sep>/vowelcounter.py import re # program for counting vowels in a string print('Enter a Word Or Sentence') word = input() vowelRegex = re.compile(r'[aeiou]') vowels = vowelRegex.findall(word) print(len(vowels)) <file_sep>/listrank.py n = int(input()) COM = {} out = [] def rev(l): l.reverse() return l for i in range(n): com = input() COM.setdefault(i, com.split()) if 'print' in COM[i]: print(out) elif 'insert' in COM[i]: out.insert(int(COM[i][1]), int(COM[i][2])) elif 'remove' in COM[i]: out.remove(int(COM[i][1])) elif 'append' in COM[i]: out.append(int(COM[i][1])) elif 'sort' in COM[i]: out.sort() elif 'pop' in COM[i]: out.pop() elif 'reverse' in COM[i]: out = rev(out) <file_sep>/charatcter counter.py import pprint print('Enter text to count the number of each letter in the text') text = input() num = {} for letter in text.upper(): num.setdefault(letter, 0) num[letter] += 1 pprint.pprint(num) #to print it better newtext = pprint.pformat(num) # saves the pprint output as a string value for futher use <file_sep>/day8.py import sys n = int(input()) logs = {} for i in range(n): data = input().split() logs.setdefault(data[0], data[1]) while True: name = sys.stdin.readline().strip() #tolearn if name in logs.keys(): print(name + '=' + logs[name]) elif name == '': break else: print('Not found') <file_sep>/market list.py import sys, os, shelve, shutil, send2trash #TO START THE LIST def startlist(): global item, note print('' + '\n $$ LIST v1.0 $$') print('\nEnter item to Start Your List') item = input() note = [item] print('Add another item, y/n ?') choice = input() if choice == 'y': mklist() else: menu() #TO ADD EXTRA ITEMS def mklist(): global note print('\nEnter item') item = input() note += [item] xen = shelve.open('todolist') xen['list'] = note print('\nAdd another item, y/n ?') choice = input() if choice == 'y': mklist() else: menu() #TO VIE THE LIST def viewlist(): global note print('' + ' My List \n') for i in range(len(note)): print('\n' + str(i + 1) + '. ' + note[i]) menu() #TO DELETE ITEMS def delitem(): global note for i in range(len(note)): print('\n' + str(i + 1) + '. ' + note[i]) print('Which item do you want to delete ?') ch = input() del note[int(ch) - 1] print('Your new list is\n') viewlist() #MAIN MENU def menu(): print('' + ' $$ LIST v1.0 $$\n') print('\n1. Add item') print('2. Delete item') print('3. View List') print('4. Exit\n') opt = input() if opt == '1': mklist() elif opt == '3': viewlist() elif opt == '2': delitem() else: print('Thank You For Using LIST') sys.exit() startlist() <file_sep>/hack.py def count_substring(string, sub_string,): a = 0 c = 0 for i in range(len(string)): while i + a != len(string): for a in range(len(sub_string)): if string[i + a] == sub_string[a]: c = len(sub_string) - a return c if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)<file_sep>/title HAck.py # Complete the solve function below. a = [] s = input() new = s.split() for i in range(len(new)): if new[i].isalnum() == True: if list(new[i])[0].isdigit() == True: a.append(new[i]) else: new[i].title() a.append(new[i].title()) else: d = new[i].title() a.append(d) c = ' '.join(a) print(c) <file_sep>/FIndallRANK.py # Enter your code here. Read input from STDIN. Print output to STDOUT import re string = input() vowelRegex = re.compile(r'[qwrtypsdfghjklzxcvbnm]?([aeiouAEIOU]{2,})[qwrtypsdfghjklzxcvbnm]', re.I) a = vowelRegex.findall(string) if a == []: print(-1) else: print('\n'.join(a)) <file_sep>/to be named.py string = input() sub_string = input() import re def count_substring(string, sub_string, ): global t sampleRegex = re.compile((sub_string)) s = sampleRegex.findall(string) d = [] a = sub_string[0] b = sub_string[1:] i = 1 while i != 25: d.append(a + b*i) sampleRegex2 = re.compile(d[i]) t = sampleRegex2.findall(string) i = i + 1 u = len(t) + len(s) return u print(count_substring(string, sub_string))<file_sep>/HaCKer.py import random class Person: increm = 1.05 def __init__(self, name, age, position): self.name = name.title() self.age = age self.position = position.title() def printID(self): print('Name: ' + self.name) print('Position: ' + self.position) print('Age: ' + str(self.age)) print('Email: ' + <EMAIL>'.format(self.<EMAIL>, self.age), end='\n') if self.position == 'Teacher': print('Salary: ' + str(self.salary), end='\n\n') @classmethod def from_string(cls, string): data = string.split() name, age, position = data return cls(name, age, position) @staticmethod def fortune(): print('Fortune: ' + random.choice(['Good day', 'Great day', 'Awesome day'])) class Employee(Person): def __init__(self, name, age, position, salary): super().__init__(name, age, position) self.salary = salary # def printID(self): #no need to form new function as it inherits methods from the parent class # print('Name: ' + self.name) # print('Position: ' + self.position) # print('Age: ' + str(self.age)) # print('Email: ' + <EMAIL>'.<EMAIL>(self.<EMAIL>, self.age)) # print('Salary: ' + str(self.salary), end='\n\n') def raised_salary(self): self.salary = int(self.salary * self.increm) prs1 = Person.from_string('Arnav 22 student') # prs1.printID() prs2 = Employee('Vaibhav', 20, 'Teacher', 100000) prs2.printID() prs2.increm = 1.10 prs2.raised_salary() prs2.printID() ''' learn how to present a class as a dictionary objects are hashable to represent or convert into dictionary us object or instance.__dict__ like prs1.__dict__ now u can use the obejt as a dictionary and object attributes and their values as key value pairs of the dictionary ''' <file_sep>/exp.py import os totalsize = 0 <file_sep>/studentHR.py import copy, sys n = int(input()) marks = [] names = [] new = [] a = 0 for i in range(n): name = input() names.append(name) mark = float(input()) marks.append(mark) newmarks = copy.deepcopy(marks) newmarks.sort() if newmarks[0] == newmarks[1]: while newmarks[0] == newmarks[1]: newmarks.remove(newmarks[0]) if newmarks[1] == '': print(names[marks.index(newmarks[0])]) else: if newmarks[a + 1] == newmarks[a + 2]: while newmarks[a + 1] == newmarks[a + 2]: m1 = marks.index(newmarks[a + 1]) new.append(names[m1]) marks.remove(marks[m1]) names.remove(names[m1]) m2 = marks.index(newmarks[a + 1]) new.append(names[m2]) newmarks.remove(newmarks[a + 1]) new.sort() print(new[a]) print(new[a + 1]) a += 1 else: m3 = marks.index(newmarks[1]) print(names[m3])<file_sep>/listCount.py # Python3 program to Grouping list # elements based on frequency from collections import OrderedDict def group_list(lst): res = [(el, lst.count(el)) for el in lst] return list(OrderedDict(res).items()) # Driver code lst = [1, 3, 4, 4, 1, 5, 3, 1] print(group_list(lst)) #listcount and orderedDict <file_sep>/sheve.py import shelve import os import send2trash import shutil import sys # TO ADD EXTRA ITEMS xen = shelve.open('try2') note = xen['things'] def mklist(): global note, item, xen print('\nEnter Word') item = input() note.append(item) note.sort(key=str.lower) xen['things'] = note print('\nAdd another Word, y/n ?') choice = input() if choice == 'y': mklist() else: menu() # TO VIEW THE DICTIONARY def viewlist(): global note print('' + ' My Words \n') note.sort(key=str.lower) for i in range(len(note)): print('\n' + str(i + 1) + '.) ' + note[i]) menu() # TO DELETE WORDS def delitem(): try: global note for i in range(len(note)): print('\n' + str(i + 1) + '.) ' + note[i]) print('Which Word do you want to delete ?') ch = input() note.remove(ch) print(ch + ' was Deleted\n') xen['things'] = note menu() except ValueError: del note[int(ch) - 1] xen['things'] = note print(note[(ch) - 1] + ' Was Deleted\n') menu() # MAIN MENU def menu(): print('' + '\n PERSONAL DICTIONARY') print('\n1. Add Word') print('2. Delete Word') print('3. View Dictionary') print('4. Exit\n') opt = input() if opt == '1': mklist() elif opt == '3': viewlist() elif opt == '2': delitem() else: print('Thank You For Using LIST') sys.exit() menu() <file_sep>/subset hack.py s = {} nCases = int(input()) for a in range(nCases): for i in range(2): nElem = input() nSet = input() s.setdefault(nElem, nSet) s[nElem] = nSet.split() print(s) <file_sep>/g.py import webbrowser, sys, pyperclip #https://www.google.co.in/search?safe=off&sxsrf=ALeKk03Lwy6-yTMaAHcG3qdGkkU5i8CAXQ:1588065767779&q=SEARCH a = sys.argv if len(a) > 1: search = ' '.join(a[1:]) webbrowser.open('https://www.google.co.in/search?safe=off&sxsrf=ALeKk03Lwy6-yTMaAHcG3qdGkkU5i8CAXQ:1588065767779&q=' + search) else: b = pyperclip.paste() webbrowser.open('https://www.google.co.in/search?safe=off&sxsrf=ALeKk03Lwy6-yTMaAHcG3qdGkkU5i8CAXQ:1588065767779&q=' + b) <file_sep>/if else _2.py print('enter name please') name = input() if name: print('hello ' + name + ' please enter password') password = input() if (password == name) : print('access granted') else: print('access denied') else: print('you have not entered a name') <file_sep>/local scope and global scope.py eggs = 10 def good(): global eggs # to define eggs as a global variable eggs = 20 # assignment makes it a local variable unless its is assigned as a global print(eggs) good() print(eggs) # since eggs is defined as a global variable its value will be changed after good() is called <file_sep>/try and except error handling.py print('how many cats do you have ?') numcats = input() try: # how the program will run normally if int(numcats) >= 4: print('that is a lot of cats') elif int(numcats) < 0: #to prevent entering of negative numbers print('cats cant be negative') else: print('that is not a lot of cats') except ValueError: # how the program will behave in case of a value error #value error example int(string without a numeric value i.e have an alphabetical value) # a value error occurs when a wrong type of value is tried to be converted print('you did not enter a number') <file_sep>/palCV.py import copy, re s = list(input().lower()) ans = [] l = [] def rev(b): b.reverse() return b for i in range(0, len(s)): l.append(s[i]) c = copy.deepcopy(l) if l == rev(c): ans.append(''.join(l)) l=[] print(ans) <file_sep>/palindrome.py '''A Palindrome is a word that spells the same from both sides, example is Hannah ''' print('Enter a Word to check if its a Palindrome') word = list(input().lower()) def rev(l): l.reverse() return l if word == rev(word): print('Given Word is a Palindrome') else: print('Given word is not a Palindrome') <file_sep>/for loop.py print('calculator') print('enter 1st number') num1 = input() print('enter 2nd number') num2 = input() print('enter operator') opt = input() if opt == '+': print(int(num1) + int(num2)) elif opt == '*': print(int(num1) * int(num2)) elif opt == '-': print(int(num1) - int(num2)) elif opt == '/': print(int(num1) / int(num2)) else: print('invalid operator') <file_sep>/queens.py board = [ [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0] ] def solve(bo, row): if row >= 4: return True for i in range(len(bo)): if valid(bo, (row, i)): bo[row][i] = 1 if solve(bo, row + 1): return True bo[row][i] = 0 return False def print_board(bo): for i in range(len(bo)): if i != 0: print('- - - - - - - - - -') for j in range(len(bo)): if j == 3: print(bo[i][j]) else: print(bo[i][j], end=' | ') def valid(bo, pos): # for i in range(len(bo)): # if bo[pos[0]][i] == 1 and i != pos[1]: # return False for j in range(len(bo)): if bo[j][pos[1]] == 1 and j != pos[0]: return False for i in range(len(bo)): for j in range(len(bo)): if i + j == pos[0] + pos[1] and (i, j) != pos: if bo[i][j] == 1: return False for i in range(len(bo)): for j in range(len(bo)): if i - j == pos[0] - pos[1] and (i, j) != pos: if bo[i][j] == 1: return False return True print_board(board) solve(board, 0) print("Solving ...") print("Solution Found!") print_board(board) <file_sep>/regex1.py import re bdateRegex = re.compile(r'\d\d-\d\d-\d\d\d\d') print(bdateRegex.findall('my birthdate is 19-04-1999 ')) <file_sep>/regexsubRANK.py # Enter your code here. Read input from STDIN. Print output to STDOUT import re lines = int(input()) for i in range(lines): string = input() sample1 = re.compile(r'\s[&]{2}\s') a = sample1.sub(' and ', string) sample2 = re.compile(r'\s[|]{2}\s') b = sample2.sub(' or ', string) if ' && ' and ' || ' in string: c = a.replace(' || ', ' or ', 2) print(c) elif ' && ' in string: print(a) elif ' || ' in string: print(b) else: print(string) <file_sep>/TCScodevita2020_D.py #GOOD_JOB n = int(input()) h, b = map(int, input().split()) p = h*b l = list(map(int, input().split())) tv = 0 vol = [] #initial total volume for a in l: tv += a*p for i in range(len(l)): mv = 0 #left adjacents for j in range(i, -1, -1): if l[j] >= l[i]: mv += l[i]*p if l[j] < l[i]: break #right adjacents for k in range(i, len(l)): if l[k] >= l[i]: mv += l[i]*p if l[k] < l[i]: break vol.append(mv - (l[i]*p)) #coz i is counted 2 times print(tv - max(vol)) <file_sep>/hackPolynomial.py # Enter your code here. Read input from STDIN. Print output to STDOUT num = input().split() x = int(num[0]) k = int(num[1]) p = input().split(' ') for i in range(int(len(p))): print(p[i])<file_sep>/number square pattern.py #print a pattern of squares in decreasing numerical order #numerical input from user import sys try: n = int(input()) print(str(n)*(n*2-1)) for i in range(n*2-3): print(n, end='') b =[str(n-j-1) for j in range(i+1) if n-j-1 != 1] print(''.join(b), end='') print(str(n-i-1)*(n*2-3-2*len(b)), end='') b.reverse() print(''.join(b), end='') print(n) if n-i-1 == 1: for i in range((n*2-3)//2, -2, -1): if n - i - 1 != 1: print(n, end='') b =[str(n-j-1) for j in range(i+1) if n-j-1 != 1] print(''.join(b), end='') print(str(n-i-1)*(n*2-3-2*len(b)), end='') b.reverse() print(''.join(b), end='') print(n) if int(''.join(b)) % n == 0: break except ValueError: sys.exit() <file_sep>/strvalid HACk.py string = input() i =0 for i in range(len(list(string))): if list(string)[i].isalpha() or list(string)[i].isdigit() == True: print(True) break else: if i == len(list(string)) - 1: print(False) else: continue i = 0 for i in range(len(list(string))): if list(string)[i].isalpha(): print(True) break else: if i == len(list(string)) -1: print(False) else: continue i = 0 for i in range(len(list(string))): if list(string)[i].isdigit(): print(True) break else: if i == len(list(string)) - 1: print(False) else: continue i = 0 for i in range(len(list(string))): if list(string)[i].islower(): print(True) break else: if i == len(list(string)) - 1: print(False) else: continue i = 0 for i in range(len(list(string))): if list(string)[i].isupper(): print(True) break else: if i == len(list(string)) - 1: print(False) else: continue <file_sep>/tbn.py k = int(input()) roomL = input() counter = {} for i in roomL.split(): counter.setdefault(i, 0) counter[i] += 1 cl = list(counter.values()) new = list(counter.keys()) print(new[cl.index(1)]) <file_sep>/PythonOOP4.py # study of class # Python_OOP class SchoolEmployeeDb: def __init__(self, name, age, sid): self.name = name self.age = age self.sid = sid self.email = self.name + str(self.age) + '@school.in' def printID(self): print('Name: ' + self.name) print('Age: ' + str(self.age)) print('SID: ' + str(self.sid)) class student(SchoolEmployeeDb): def __init__(self, name, age, sid, branch): super().__init__(name, age, sid) self.branch = branch def printSID(self): self.printID() print('Branch: ' + self.branch) class Teacher(SchoolEmployeeDb): def __init__(self, name, age, sid, subject): super().__init__(name, age, sid) self.subject = subject def printTID(self): self.printID() print('Subject: ' + self.subject) std_1 = student('Vaibhav', 20, 110021, 'CSE') std_1.printSID() tch_1 = Teacher('arnav', '42', '273813', 'DBMS') tch_1.printTID() <file_sep>/Practice.py # input n = int(input()) query = [] for i in range(n): s = input() x = int(input()) query.append((s, x)) w = [] b = [] print(query) for a in query: for i in range(len(a[0])): w.append(0) b.append(w) # check //a[0] = s, a[1] = x c = 0 for a in query: w = b[c] for i in range(len(a[0])): if i + 1 > a[1]: if int(a[0][i]) == 1: w[i - a[1]] = 1 # i - x if int(a[0][i]) == 0: w[i - a[1]] = 0 if i + 1 + (a[1]) <= len(a[0]): if int(a[0][i]) == 1: w[i + a[1]] = 1 if int(a[0][i]) == 0: w[i + a[1]] = 0 c += 1 # apply # output <file_sep>/hackerdesign.py # Enter your code here. Read input from STDIN. Print output to STDOUT size = input().split() N = int(size[0]) M = int(size[1]) #top part for i in range((N - 1) // 2): print(('').rjust(((M - 3) // 2) - (3*i), '-') + '.|.'*((2*i) + 1) + ('').ljust(((M - 3) // 2) - (3*i), '-')) #middle line print('WELCOME'.center(M, '-')) #lower part for i in range((N - 1) // 2): print(('').rjust(3*(i +1), '-') + '.|.'*(((M // 3) - 2) - 2*i) + ('').ljust(3*(i + 1), '-')) <file_sep>/TCScodevita2020_E.py import copy cost = list(map(int, input().split())) #h, c, a cost of enclosure Area = list(map(int, input().split())) #max allotable area hn, ha = (map(int, input().split())) #min number and area cn, ca = (map(int, input().split())) an, aa = (map(int, input().split())) ta = int(input()) #zoo area ac = hn*ha + cn*ca + an*aa #area occupied tc = hn*ha*cost[0] + cn*ca*cost[1] + an*aa*cost[2] #total cost if cost.index(min(cost)) == 0: if ta - ac > Area[cost.index(min(cost))] - hn*ha: tc += min(cost)*(Area[cost.index(min(cost))] - hn*ha) ac += Area[cost.index(min(cost))] - hn*ha sc = copy.deepcopy(cost) sc.sort() tc += (ta - ac) * sc[1] print(tc) else: tc += min(cost)*(ta-ac) print(tc) elif cost.index(min(cost)) == 1: if ta - ac > Area[cost.index(min(cost))] - cn*ca: tc += min(cost) * (Area[cost.index(min(cost))] - cn * ca) ac += Area[cost.index(min(cost))] - cn * ca sc = copy.deepcopy(cost) sc.sort() tc += (ta - ac) * sc[1] print(tc) else: tc += min(cost)*(ta-ac) print(tc) elif cost.index(min(cost)) == 2: if ta - ac > Area[cost.index(min(cost))] - an*aa: tc += min(cost) * (Area[cost.index(min(cost))] - an * aa) ac += Area[cost.index(min(cost))] - an * aa sc = copy.deepcopy(cost) sc.sort() tc += (ta - ac) * sc[1] print(tc) else: tc += min(cost) * (ta - ac) print(tc) <file_sep>/emailRANK.py import re lines = int(input()) for i in range(lines): string = input() emRegex = re.compile(''' [A-Za-z]+ \s < [a-zA-Z] [a-zA-Z0-9_.-]+ @ [a-zA-Z]+ \. [a-zA-Z]{1,3} #domainname > ''', re.VERBOSE) a = emRegex.findall(string) if a != []: print(a[0])<file_sep>/EMail and phone number extractor.py #! python3 import re, pyperclip #TODO: PHONE NUMBER EXTRACTOR phRegex = re.compile(r''' ( ((\d\d\d) | (\(\d\d\d\)))? #area code (\s|-) #seperator \d\d\d #first 3 digits - #seperator (\d\d\d\d) #last 4 digits ((ext(\.)?\s|x) (\d{2,5}))? ) #extensions ''', re.VERBOSE) #EMAIL EXTRACTOR emRegex = re.compile(''' [a-zA-Z0-9_+.]+ #username @ [a-zA-Z0-9_+.]+ #domainname ''', re.VERBOSE) text = pyperclip.paste() email = emRegex.findall(text) phone = phRegex.findall(text) numbers = [] for i in phone: numbers.append(i[0]) n = '\n'.join(numbers) e = '\n'.join(email) extract = 'Phone List\n' + n + '\n' + 'Email List\n' + e #TODO: ARRANGE AND ADD EXTRACTED FILES TO CLIPBOARD pyperclip.copy(extract) <file_sep>/hackrrr.py # Enter your code here. Read input from STDIN. Print output to STDOUT import re i = int(input()) for a in range(i): string = input() floatRegex = re.compile(r'^(\+?|-?)\d*\.\d+$') b = floatRegex.findall(string) if b != []: print(True) else: print(False) <file_sep>/a.py from selenium import webdriver import time browser = webdriver.Edge() browser.get('http://portal1.lnct.ac.in/Accsoft2/Login.aspx') browser.find_element_by_css_selector('#ctl00_cph1_rdp').click() time.sleep(1) browser.find_element_by_css_selector('#ctl00_cph1_txtStuUser').send_keys('11156824879') browser.find_element_by_css_selector('#ctl00_cph1_txtStuPsw').send_keys('kanhaiya_13') browser.find_element_by_css_selector('#ctl00_cph1_btnStuLogin').click() time.sleep(1) browser.find_element_by_css_selector('#ctl00_liAcademics > a > span').click() browser.find_element_by_css_selector('#ctl00_lnkAttendanceStatus').click() <file_sep>/Guess game.py # guess number game import random #for generating a random number import sys #for exiting the program in case of error def changeName(): global name print('Please enter your name ') name = input() while name == '': print("You haven't entered a name \n") print('Please enter your name') name = input() print('\nHello ' + name + ' ! ') def game(): secretNumber = random.randint(1, 10) #for genertaing a random number and assigning it to the variable secretNumber # print('DEBUG: The secret number is ' + str(secretNumber)) #to use in case of checking try: #try and except to tackle value errors for guessesTaken in range(1,4): print('I thought of a number between 1 to 10. Take a guess! ') guess = int(input()) while guess not in range(1,11): #to deal with guesses that are out of range print('Invalid Guess!, Please guess a number between 1 to 10') guess = int(input()) guessLeft = 3 - guessesTaken if guess < secretNumber: print('Think of a bigger number \n') print('you have ' + str(guessLeft) +' guesses left ') elif guess > secretNumber: print('Think of a smaller number ') print('you have ' + str(guessLeft) +' guesses left ') else: break if guess == secretNumber: print('Bingo! ' + name) print('You guessed the secret number in only ' + str(guessesTaken) + ' guesses') print('\nwanna try again, y/n ? ') choice = input() if choice == 'y': print('wanna change name, yo/no ? ') #option to change name in a game namechoice = input() if namechoice == 'yo': changeName() game() elif namechoice == 'no': game() else: print('Inavalid choice, Continuing to game') game() elif choice == 'n': sys.exit() else: print('Invalid Choice' ) sys.exit else: print('Better luck next time! \n') print('The secret number was ' + str(secretNumber) ) print('\nwanna try again, y/n ? ') choice = input() if choice == 'y': print('wanna change name, y/n ? ') #option to change name in a game namechoice = input() if namechoice == 'y': changeName() game() elif namechoice == 'n': game() else: print('Inavalid choice, Continuing to game') game() elif choice == 'n': sys.exit() else: print('Invalid Choice' ) sys.exit except ValueError : print('Invalid Guess. ') print('\nRestart, y/n ? ') choice = input() if choice == 'y': print(' wanna change name, y/n ? ') #option to change name in a game namechoice = input() if namechoice == 'y': changeName() game() elif namechoice == 'n': game() else: print('Invalid choice, Continuing to game') game() elif choice == 'n': sys.exit() else: print('Invalid Choice' ) sys.exit() changeName() game() <file_sep>/defining arithmetic functions.py def sum(): print('enter first number') num1 = input() num11 = int(num1) print('enter second number \n') num2 = input() num22 = int(num2) res = num11 + num22 print(res) print('want to add another number to the result y / n ') choice = input() while choice == 'y': print('enter number') num3 = input() res = res + int(num3) print(res) print('want to add another number to the result y / n ') choice = input() def subtract(): print('enter first number') num1 = input() num11 = int(num1) print('enter second number') num2 = input() num22 = int(num2) res = num11 - num22 print(res) print('want to subtract another number to the result y / n ') choice = input() while choice == 'y': print('enter number') num3 = input() res = res - int(num3) print(res) print('want to subtract another number to the result y / n ') choice = input() def multiply(): print('enter first number') num1 = input() num11 = int(num1) print('enter second number') num2 = input() num22 = int(num2) res = num11 * num22 print(res) print('want to multiply another number to the result y / n ') choice = input() while choice == 'y': print('enter number') num3 = input() res = res * int(num3) print(res) print('want to multiply another number to the result y / n ') choice = input() def divide(): print('enter first number') num1 = input() num11 = int(num1) print('enter second number') num2 = input() num22 = int(num2) res = num11 / num22 print(res) print('want to divide another number to the result y / n ') choice = input() while choice == 'y': print('enter number') num3 = input() res = res / int(num3) print(res) print('want to divide another number to the result y / n ') choice = input() <file_sep>/pattern practice.py import pprint word = input() a = {} for i in word: a.setdefault(i, 0) a[i] += 1 pprint.pprint(a) <file_sep>/ErrorCodePrint.py # Enter your code here. Read input from STDIN. Print output to STDOUT n = int(input()) for i in range(n): try: string = input().split() print(int(string[0]) // int(string[1])) except ZeroDivisionError as e: print("Error Code:", e) except ValueError as e: print("Error Code:", e) <file_sep>/stringcounter.py #program to count number of vowels and consonants in a string #! python3 print('Enter a Word or Sentence') word = input() newWord = word.lower() letter = {} for i in newWord: letter.setdefault(i, 0) letter[i] += 1 letter.setdefault('a', 0) letter.setdefault('e', 0) letter.setdefault('i', 0) letter.setdefault('o', 0) letter.setdefault('u', 0) noVowels = letter['a'] + letter['e'] + letter['i'] + letter['o'] + letter['u'] letter.setdefault('.', 0) noConsonants = len(list(''.join(newWord.split()))) - noVowels - letter['.'] print("\nThere are " + str(noVowels) + " Vowels and " + str(noConsonants) + ' Consonants in : ' + word ) <file_sep>/PythonOOP2.py # study of classes # python object oriented programming #class variables class student: Exam_status = 'PASS' def __init__(self, name, email, userid): self.name = name self.email = email self.userid = userid def printidCard(self): print("Student Name: " + self.name) print("Student Email ID: " + self.email) print("Student ID: " + str(self.userid)) print("Student Status: " + self.Exam_status, end='\n\n') # calling the exam_status variable by self(instance) so that it can be changed individually. Student0 = student('vaibhav', '<EMAIL>', 217312) Student1 = student('arnav', '<EMAIL>', 100000) Student0.printidCard() Student1.printidCard() Student1.Exam_status = 'SUPER' # changing Exam status for Student1 instance Student0.printidCard() Student1.printidCard() <file_sep>/import sys rand.py import random, sys print(random.randint(1, 6)) print('ludo lovers') sys.exit() print('it will not print') <file_sep>/regexRank.py import re lines = int(input()) code = [] for i in range(lines): string = input() code.append(string) total = ' '.join(code) hexRegex1 = re.compile('(#[0-9A-Fa-f]{3,6});') a = hexRegex1.findall(total) d = '\n'.join(a) print(d) <file_sep>/TCScodevita2020_MaxSum.py #input n, w, d = map(int, input().split()) ar = list(map(int, input().split())) #group #sum #find max sum #output<file_sep>/if else.py name = 'vaibha' if name == 'vaibhav' : print('hello ' + name) else : print('you are not vaibhav') <file_sep>/strvalid HACk.pyi string = input() for i in range(list(string)): if list(string)[i].isalpha() or list(string)[i].isdigit() == True: if list(string)[i].isalpha(): print(True) if list(string)[i].islower(): print(True) else: print(False) if list(string)[i].isupper(): print(True) else: print(False) else: print(False) if list(string)[i].isdigit(): print(True) else: print(False) else: print(False) <file_sep>/swap.py i = 0 lol = [] lmao =[] a = 0 def swap_case(s): string = s.split() for a in range(len(string)): lol = [] for i in range(len(list(string[a]))): if list(string[a])[i].islower(): lol.append(list(string[a])[i].upper()) elif list(string[a])[i].isupper(): lol.append(list(string[a])[i].lower()) else: lol.append(list(string[a])[i]) lmao.append(''.join(lol)) solv = ' '.join(lmao) return solv <file_sep>/subsetHackerRank.py nCases = int(input()) for a in range(nCases): for i in range(2): nElem = input() B = nElem.split() nSet = input() A = set(nSet.split()) print(s[a].issubset(B)) <file_sep>/PythonOOP1.py # study of classes # python object oriented programming # instance variables class student: def __init__(self, name, email, id): self.name = name self.email = email self.id = id def printidCard(self): print("Student Name: " + self.name) print("Student Email ID: " + self.email) print("Student ID: " + str(self.id)) num = int(input()) for i in range(1, num + 1): name = input() email = input() id = int(input()) Student = student(name, email, id) student.printidCard(Student) <file_sep>/vvv.py import requests, bs4 lol = input() def price(url): res = requests.get(url) res.raise_for_status() att = bs4.BeautifulSoup(res.text, 'html.parser') attend = att.select('') return attend[0].text.strip() data = price(lol) print(data)<file_sep>/GETsize.py import os totalsize = 0 for file in os.listdir(r"C:\Users\vaibhav pratap singh\Desktop\python"): if os.path.isfile(os.path.join('C:\\Users\\vaibhav pratap singh\\Desktop\\python', file)) == True: b = os.path.getsize(os.path.join('C:\\Users\\vaibhav pratap singh\\Desktop\\python', file)) totalsize += b print(totalsize) <file_sep>/pycharm test.py print('vaibhav') while True: print('hello pycahrm') <file_sep>/while_loop_break_continue.py spam = 9 while spam > 0: print('still working') spam = spam - 1 if ((spam % 5) == 0): continue print('jai bholenath') print('spam is a multiple of 5') <file_sep>/PythonOOP3.py # study of classes # python object oriented programming # class methods and static methods class student: Exam_status = 'PASS' def __init__(self, name, email, userid): self.name = name self.email = email self.userid = userid def printidCard(self): print("Student Name: " + self.name) print("Student Email ID: " + self.email) print("Student ID: " + str(self.userid)) print("Student Status: " + student.Exam_status, end='\n\n') @classmethod def from_string(cls, data): name, email, userid = data.split() return cls(name, email, userid) @classmethod def set_status(cls, status): student.Exam_status = status # @staticmethod # def even(num): # if num % 2 == 0: # print('EVEN') # else: # print('ODD') # # student.even(8) S0 = student('saurabh', '<EMAIL>', 463246) data = 'vaibhav <EMAIL> 110233' S1 = student.from_string(data) S1.printidCard() S0.printidCard() S1.set_status('GOOD BOY') S0.set_status('VERY GOOD') S1.printidCard() S0.printidCard() <file_sep>/codevitaE.py import copy cost = list(map(float, input().split())) # h, c, a cost of enclosure Area = list(map(float, input().split())) # max allotable area hn, ha = (map(float, input().split())) # min number and area cn, ca = (map(float, input().split())) an, aa = (map(float, input().split())) ta = round(float(input())) # zoo area ma = [] ma.append(round(hn * ha)) ma.append(round(cn * ca)) ma.append(round(an * aa)) ac = ma[0] + ma[1] + ma[2] # area occupied tc = ma[0] * cost[0] + ma[1] * cost[1] + ma[2] * cost[2] # total cost if ta - ac > Area[cost.index(min(cost))] - ma[cost.index(min(cost))]: tc += min(cost) * (Area[cost.index(min(cost))] - ma[cost.index(min(cost))]) ac += Area[cost.index(min(cost))] - ma[cost.index(min(cost))] sc = copy.deepcopy(cost) sc.sort() if ta - ac > Area[cost.index(sc[1])] - ma[cost.index(sc[1])]: tc += sc[1]*(Area[cost.index(sc[1])] - ma[cost.index(sc[1])]) ac += Area[cost.index(sc[1])] - ma[cost.index(sc[1])] tc += max(cost)*(ta - ac) print(round(tc)) else: tc += sc[1]*(ta-ac) print(round(tc)) else: tc += min(cost) * (ta - ac) print(round(tc)) <file_sep>/TCScodevita2020_A.py import re length = int(input()) txt = input() va = 0 vb = 0 vc = 0 txtRegexA = re.compile(r'[-]*A') a = txtRegexA.findall(txt) txtRegexB = re.compile(r'B[-]*') b = txtRegexB.findall(txt) txtRegexN = re.compile(r'B[-]+A') c = txtRegexN.findall(txt) for i in a: va += len(i) for j in b: vb += len(j) for k in c: vc += len(k) n = (vc - 1*len(c))//2 if va - n > vb - n: print('A', end='') elif va - n < vb - n: print('B', end='') else: print('Coalition government', end='') <file_sep>/TCScodevita2020_Mr.String.py import inflect import re # Input N = int(input()) num = list(map(int, input().split())) # to convert to textual form n2w = inflect.engine() text = list(map(n2w.number_to_words, num)) # program for counting vowels in a string vowelRegex = re.compile(r'[aeiou]', re.I) vowels = vowelRegex.findall(' '.join(text)) a = len(vowels) for i in num: if i == 100: a -= 2 #find no of pairs in given input whose sum equals number of vowels pairs = [] for j in range(len(num)): for k in range(len(num)): if num[j]+num[k] == a and j != k: pairs.append((num[j], num[k])) #Output print(n2w.number_to_words(len(set(pairs))//2))
6e24dab6442976b5d5255c63273a3900d1389ddd
[ "Python", "INI" ]
66
Python
Kakashi-19/PYTHON
2488b106d1442624c1a9cddc205e2e9d2a0ff66b
870a856cc7c3c481af3f21a479cf1c66324e35b1
refs/heads/master
<repo_name>xnphu/GameRocket<file_sep>/src/game/enemy/CreateEnemy.java package game.enemy; import action.*; import base.GameObject; import base.GameObjectManager; import java.util.ArrayList; import java.util.List; import java.util.Random; public class CreateEnemy extends GameObject { private Random random; public CreateEnemy() { this.random = new Random(); this.configAction(); } public void configAction() { List<Enemy> enemies = new ArrayList<>(); Action createAction = new ActionAdapter() { @Override public boolean run(GameObject owner) { Enemy enemy = GameObjectManager.instance.recycle(Enemy.class); enemy.position.set(random.nextInt(1024), random.nextInt(600)); enemy.velocity.set(random.nextInt(2) + 1, random.nextInt(2) + 1); enemies.add(enemy); return true; } }; Action waitAction = new ActionAdapter() { @Override public boolean run(GameObject owner) { enemies.removeIf(enemy -> !enemy.isAlive); return true; } }; Action stopAction = new ActionAdapter() { @Override public boolean run(GameObject owner) { for (int i = 0; i < enemies.size(); i++) { enemies.get(i).velocity.set(0, 0); } return true; } }; Action shootAction = new ActionAdapter() { @Override public boolean run(GameObject owner) { EnemyShoot enemyShoot = new EnemyShoot(); for (int i = 0; i < enemies.size(); i++) { enemyShoot.run(enemies.get(i)); } return true; } }; Action continueAction = new ActionAdapter() { @Override public boolean run(GameObject owner) { for (int i = 0; i < enemies.size(); i++) { enemies.get(i).velocity.set(random.nextInt(2) + 1, random.nextInt(2) + 1); } return true; } }; this.addAction( new SequenceAction( new WaitAction(20), new LimitAction(4, new SequenceAction( createAction, new WaitAction(40), stopAction, new WaitAction(40), shootAction, new WaitAction(40), continueAction, new WaitAction(40), waitAction ) ) ) ); } } <file_sep>/src/game/enemy/EnemyShoot.java package game.enemy; import base.Attribute; import base.FrameCounter; import base.GameObjectManager; import base.Vector2D; public class EnemyShoot implements Attribute<Enemy> { private FrameCounter frameCounter; public EnemyShoot() { this.frameCounter = new FrameCounter(100); } @Override public void run(Enemy gameObject) { if (this.frameCounter.run()) { for (double angle = 0.0; angle < 360.0; angle += 360.0 / 5) { BulletEnemy bulletEnemy = GameObjectManager.instance.recycle(BulletEnemy.class); bulletEnemy.position.set(gameObject.position); bulletEnemy.velocity.set( (new Vector2D(2, 0)).rotate(angle) ); } this.frameCounter.reset(); } } }
f620a74353c9ee51383f4f5fab9b1755c3c12295
[ "Java" ]
2
Java
xnphu/GameRocket
0347e8ba2ead2e340cdaf5e6365814d46de99b9f
8cc7ce2368614721d94fa84e2e165a0e5deb0025
refs/heads/master
<file_sep>using ProductBL; using ProductDTO; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace ProductAPI.Controllers { public class ProductController : ApiController { ProdBL blObj; public List<ProdDTO> GetProduct() { blObj = new ProdBL(); var result = blObj.GetProduct(); return (List<ProdDTO>)result; } } } <file_sep>using ProductDAL; using ProductDTO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProductBL { public class ProdBL { ProdDAL DALObj = new ProdDAL(); public List<ProdDTO> GetProduct() { return DALObj.FetchDetails(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProductDTO { public class ProdDTO { public int ProductID { get; set; } public string Name { get; set; } public string ProductNumber { get; set; } public bool MakeFlag { get; set; } public bool FinishedGoodsFlag { get; set; } public string Color { get; set; } public short SafetyStockLevel { get; set; } public short ReorderPoint { get; set; } public decimal StandardCost { get; set; } public decimal ListPrice { get; set; } public string Size { get; set; } } }
f025515e5199a641135612d1f0e8aba6f95568da
[ "C#" ]
3
C#
Bhuvana-295556/vg
6543c4b1ed09fc7b277209ac9ec2bbbd98565f70
b134eb0a9f52e570c08773c9b987b4a6020bfb31
refs/heads/master
<repo_name>Viktor-V/MagentoMailCatcher<file_sep>/app/code/local/ViktorV/MailCatcher/Model/Core/Email/Template.php <?php /** * Created by PhpStorm. * User: viktor * Date: 15.5.10 * Time: 22:54 */ class ViktorV_MailCatcher_Model_Core_Email_Template extends Mage_Core_Model_Email_Template { /** * Retrieve mail object instance * * @return Zend_Mail */ public function getMail() { if (is_null($this->_mail)) { $host = Mage::getStoreConfig('mailcatcher/options/host'); $port = Mage::getStoreConfig('mailcatcher/options/port'); $transport = new Zend_Mail_Transport_Smtp($host, array('port' => $port)); Zend_Mail::setDefaultTransport($transport); $this->_mail = new Zend_Mail('utf-8'); } return $this->_mail; } }<file_sep>/app/code/local/ViktorV/MailCatcher/sql/mailcatcher_setup/mysql4-install-0.1.0.php <?php /* @var $installer Mage_Core_Model_Resource_Setup */ $config = new Mage_Core_Model_Config(); $config->saveConfig('mailcatcher/options/host', '127.0.0.1'); $config->saveConfig('mailcatcher/options/port', '1025');<file_sep>/app/code/local/ViktorV/MailCatcher/Helper/Data.php <?php /** * Created by PhpStorm. * User: viktor * Date: 15.18.10 * Time: 23:56 */ class ViktorV_MailCatcher_Helper_Data extends Mage_Core_Helper_Abstract { }
9dad80667e64feb9267debba7659ed43c3b5f4e0
[ "PHP" ]
3
PHP
Viktor-V/MagentoMailCatcher
85f93a184240d8bf97a91de468b83d71b243545d
1ffeaba79453822bac11bacf17d97a7afdc5487b
refs/heads/master
<file_sep>package com.peninsula.nuunn; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); ImageView floater; ImageView floater2; ImageButton alphas; Animation animFloat; Animation animFloat2; Animation animAlpha; Animation animAlphaOut; floater = (ImageView) findViewById(R.id.ghost); floater2 = (ImageView) findViewById(R.id.talsman); alphas = (ImageButton)findViewById(R.id.startGame); animFloat = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.floata); animFloat2 = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.floata2); animAlpha = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.alpha); animAlphaOut = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.alphaout); floater.startAnimation(animFloat); floater2.startAnimation(animFloat2); alphas.startAnimation(animAlpha); ImageButton btn = (ImageButton) findViewById(R.id.startGame); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent myIntent = new Intent(v.getContext(), StoryScreen.class); startActivity(myIntent); overridePendingTransition(R.anim.alpha, R.anim.alphaout); } }); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); if (hasFocus) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } } }
2070a0657055ecad72d7ce9e95cd0675d6574b1e
[ "Java" ]
1
Java
Mylo1993/Nuunn3
f0574a2fc8ea3cc63e80e78ad26d41ee4417b94e
b18259cd1c94422bc67c87df5b67d64fcdcce20d
refs/heads/master
<file_sep>/* Suppose an array in ascending order is rotated at some pivot unknown to you beforehand. You are given a target value to search. If found in array, return its index, otherwise return -1. Assume no duplicate exists in the array. */ /* input: [4,5,6,7,0,1,2]. element to search 0. If search for 8, return -1 */ public class SearchInRotatedArray { public int getPivot(int[] nums, int start, int end) { int pivot = (start + end) / 2; if (nums[pivot] < nums[(pivot - 1) % nums.length]) { return pivot; } else if (nums[pivot] > nums[(pivot - 1) % nums.length]) { return getPivot(nums, pivot + 1, nums.length - 1); } return 0; } public static void main(String[] args) { int[] a = new int[] {4,5,6,7,0,1,2}; SearchInRotatedArray sira = new SearchInRotatedArray(); int pivot = sira.getPivot(a, 0, a.length); System.out.println("pivot: " + pivot); } } <file_sep>import java.io.*; import java.util.List; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; class MyCode { public static void main (String[] args) { List<String> list1 = new ArrayList<>(); list1.add("Perl"); list1.add("Python"); list1.add("Python"); list1.add("Python"); list1.add("Java"); list1.add("Ruby"); list1.add("Go"); list1.add("Go"); list1.add("C"); list1.add("C++"); list1.add("Java"); list1.add("Java"); list1.add("C"); list1.add("C"); list1.add("Java"); list1.add("Java"); list1.add("C"); List<String> list2 = new ArrayList<>(); list2.add("Java"); list2.add("Python"); list2.add("Go"); System.out.println(list1); System.out.println(list2); HashMap<String, Integer> list2map = new HashMap<>(); for (String s :list2) { list2map.put(s, 0); } for (String l : list1) { if (list2map.containsKey(l)) { int v = list2map.get(l); list2map.put(l, ++v); } } list1.removeAll(list2); System.out.println(list1); Collections.sort(list1); System.out.println(list1); //ashMap<String, int> count = new HashMap<>(); List<String> count = new ArrayList<>(); for (String s : list2) { for (int i = 0; i < list2map.get(s); i++) { count.add(s); } } count.addAll(list1); list2.addAll(list1); System.out.println(list2); System.out.println(count); } } <file_sep>#!/home/asmita/anaconda2/bin/python import random def genIp(): return '.'.join(map(lambda x: str(random.randint(0, 255)), range(4))) for i in range(10): print(genIp()) # def genIpInt(): # my $ipInt = 1 + int(rand(2 ** 32 - 1)) # my $ip = join '.', unpack('C4', pack('N', $ipInt)) # warn $ip # return $ip # def genMac(): # my $ri = sub { 1 + int(rand(2 ** 8 - 1)) } # my $mac = join ':', map { sprintf("%0X", $ri->()) } (0..5) # warn $mac # return $mac # print("\n\n"); # for i in range(10): # print(genIpInt()) # } # print("\n\n"); # for i in range(10): # print(genMac()) # } <file_sep>#!/usr/bin/python # missing number from sorted array items = [1, 2, 3, 5] def bin_search(start, items): count = len(items) if (count == 1): if (start + 1 == items[0]): # if number is already in items print 'found missing number: ' + str(start) return else: print 'found missing number: ' + str(start + 1) return half = int(count / 2) expected_num = start + half got_num = items[half] if got_num == expected_num: bin_search(items[half], items[half::]) elif got_num != expected_num: bin_search(start, items[0:half]) items = [1, 2, 3, 5] bin_search(1, items) items = [1, 2, 3, 5, 6, 7, 8] bin_search(1, items) items = [1, 2, 3, 4, 5, 6, 8, 9, 10] bin_search(1, items) items = [1, 3, 4, 5, 6, 7, 8, 9, 10] bin_search(1, items) items = [2, 3, 4, 5, 6, 7, 8, 9, 10] bin_search(1, items) items = [1, 2, 3, 4, 6, 7, 8, 9, 10] bin_search(1, items) <file_sep>package trees; public class BinarySearch { public static void main(String[] args) { int[] arr = new int[] {4,5,6,7,1,2}; int[] arr1 = new int[] {0,0,0,1,2,3,4,5,5,6,7,8,9,9,9}; // int[] arr1 = new int[] {0,1,2,3,4,5,6,7,8,9}; // int[] arr1 = new int[] {4,5,6,7,8,9}; int search = 9; // int pivot = binarySearch(arr, search, 0, arr.length); int index = binarySearch1(arr1, search, 0, arr1.length - 1); //System.out.println("pivot " + pivot); System.out.println("index " + index); } private static int binarySearch1(int[] arr, int search, int start, int end) { if (end == start) { return end; } int len = end - start; int mid = start + (len / 2); System.out.println("mid " + mid + " and len " + len); if (search == arr[mid]) { System.out.println("FOund arr mid " + arr[mid]); return mid; } else if (search > arr[mid]) { System.out.println("on right arr mid " + arr[mid + 1] + " and end " + arr[end]); return binarySearch1(arr, search, mid + 1, end); } else { System.out.println("on left arr start " + arr[start] + " and mid - 1 " + arr[(mid - 1)]); return binarySearch1(arr, search, start, (mid - 1)); } } private static int binarySearch(int[] arr, int search, int start, int end) { int len = end - start + 1; int mid = (end - start) / 2; System.out.println("mid " + mid + " and len " + len); if (arr[mid] < arr[mid - 1]) { System.out.println("arr mid " + arr[mid]); return arr[mid]; } System.out.println("mid - 1 mod len " + (mid - 1) % len); if (arr[mid] > arr[(mid - 1) % len]) { System.out.println("arr mid " + arr[mid] + " and end " + arr[end - 1]); binarySearch(arr, search, mid, end - 1); } else if (arr[mid] < arr[(mid - 1) % len]) { System.out.println("arr start " + arr[start] + " and mid - 1 mod len " + arr[(mid - 1) % len]); binarySearch(arr, search, start, (mid - 1) % len); } return 0; } }
0f05b41583cb73dd062c0e83731615dbe237539b
[ "Java", "Python" ]
5
Java
asmitajoshi/quiz
fc8a56d855997ad82025f90065e15b033bd15588
19a0b09ce3ff9b4905443d2edc0a4c5c7ebdb539
refs/heads/master
<repo_name>ravyt3ja/ravi<file_sep>/neural.py # ravi from numpy import exp, array, random, dot class NeuralNetwork(): def __init__(self): random.seed(1) self.synaptic_weights = 2*random.random((3,1))-1 def _sigmoid(self,x): return 1/(1+exp(-x)) def predict(self, inputs): return self._sigmoid(dot(inputs, self.synaptic_weights)) def train(self, training_set_inputs, training_set_outputs, number_of_training_iterations): for iteration in range(number_of_training_iterations): output= self.predict(training_set_inputs) error=training_set_outputs - output adjustment = dot(training_set_inputs.T, error*self._sigmoid_derivative(output)) self.synaptic_weights +=adjustment def _sigmoid_derivative(self, x): return x*(1-x) if __name__ == '__main__': #initialize a single neuron neural network neural_network = NeuralNetwork() print('Random starting synaptic weights:') print(neural_network.synaptic_weights) training_set_inputs = array([[0,0,1],[1,1,1],[1,0,1],[0,1,1]]) training_set_outputs = array([[0,1,1,0]]).T neural_network.train(training_set_inputs, training_set_outputs, 1000) print('New synaptic weights after training:') print(neural_network.synaptic_weights) print('predicting..') print(neural_network.predict(array([1,1,0]))) <file_sep>/linear regression.py import pandas as pd import matplotlib.pyplot as plt import numpy as np import seaborn as sns %matplotlib inline from sklearn import linear_model df = pd.read_csv('F:/Spring 18/samsung/python algorithms/linear_regression_df.csv') df.columns = ['X', 'Y'] df.head() sns.set_context("notebook", font_scale=1.1) sns.set_style("ticks") sns.lmplot('X','Y', data=df) plt.ylabel('Response') plt.xlabel('Explanatory') linear = linear_model.LinearRegression() trainX = np.asarray(df.X[20:len(df.X)]).reshape(-1, 1) trainY = np.asarray(df.Y[20:len(df.Y)]).reshape(-1, 1) testX = np.asarray(df.X[:20]).reshape(-1, 1) testY = np.asarray(df.Y[:20]).reshape(-1, 1) linear.fit(trainX, trainY) linear.score(trainX, trainY) print('Coefficient: \n', linear.coef_) print('Intercept: \n', linear.intercept_) print('R^2 Value: \n', linear.score(trainX, trainY)) predicted = linear.predict(testX)
df9689b9403167cbc94078d564f3aef986cccc41
[ "Python" ]
2
Python
ravyt3ja/ravi
343d8ac528157c84795f9ea85e65f21239bcba98
32791310f6df9def34d03e29627772f46e657e61
refs/heads/master
<repo_name>sarkiroka/progbot<file_sep>/source/common/event/on/escape.js /** * handle escape key * @author sarkiroka on 2017.06.02. */ var debug = require('debug')('progbot:event:end-of-game'); var drawTheEnd = require('../../draw/the-end'); var onEndOfProgramming = require('./end-of-programming/end-of-programming'); var state = require('../../../game/state/index'); module.exports = function () { var initKeyboard = require('../../../init/init-keyboard');// because circular dependency if (state() == state.RESULT_ANIMATION) { debug('canceling the result screen'); onEndOfProgramming.cancelResult(); } else if (state() == state.IDLE) { debug('end of the game'); state(state.END); initKeyboard.done(); drawTheEnd(); } else { console.warn('oh no, escape'); } }; <file_sep>/source/init/init-resize.js /** * fel és leiratkozik az átméretezés eseményre * @author sarkiroka on 2017.06.01. */ var onResize = require('../common/event/on/resize'); module.exports = function () { window.addEventListener('resize', onResize); onResize(); }; module.exports.done = function () { window.removeEventListener('resize', onResize); }; <file_sep>/source/common/draw/result.js /** * kirajzolja az eredményt * @author sarkiroka on 2017.12.29. */ var canvas = require('./canvas'); var smiley = document.getElementById('smiley'); var sad = document.getElementById('sad'); module.exports = function (result) { var ctx = canvas.ctx; var size = Math.min(canvas.centerX, canvas.centerY); var size05 = size * 0.05; var size90 = size * 0.9; var size2 = size * 0.5; ctx.save(); ctx.translate(canvas.centerX, canvas.centerY); ctx.rotate((Math.random() * 45 - 22.5) * Math.PI / 180); ctx.drawImage(result ? smiley : sad, -size2 + size05, -size2 + size05, size90, size90); ctx.restore(); }; <file_sep>/developer-tools/scripts/dev #!/bin/bash CURRENT_DIRECTORY=$(pwd | grep -o '[^/]*$') if [ "$CURRENT_DIRECTORY" == "developer-tools" ] ; then cd .. fi latest_hash_of_package_json="$(git log --pretty=format:%H developer-tools/package.json | head -1)" latest_saved_hash="" cd developer-tools need_npm_i=false if [[ -f latest_hash_of_package_json && -d node_modules ]]; then latest_saved_hash="$(cat latest_hash_of_package_json | head -1)" if [ "$latest_saved_hash" == "$latest_hash_of_package_json" ]; then echo "doesn't need npm i" need_npm_i=false else echo "package.json is changed, need npm i" need_npm_i=true fi else echo "initial run" need_npm_i=true fi if $need_npm_i ; then echo "running the npm install..." npm set progress=false npm i OUT=$? if [ $OUT -eq 0 ]; then echo "${latest_hash_of_package_json}" > latest_hash_of_package_json fi fi ./node_modules/.bin/gulp watch --silent --gulpfile gulpfile-pug.js & ./node_modules/.bin/gulp watch --silent --gulpfile gulpfile-images.js & ./node_modules/.bin/gulp watch --silent --gulpfile gulpfile-boards.js & ./node_modules/.bin/webpack -w <file_sep>/source/init/init-game.js /** * első pálya lekérése * @author sarkiroka on 2017.12.28. */ var state = require('../game/state/index'); module.exports = function (callback) { state.loadBoard(callback); }; <file_sep>/developer-tools/scripts/build #!/bin/bash CURRENT_DIRECTORY=$(pwd | grep -o '[^/]*$') if [ "$CURRENT_DIRECTORY" == "developer-tools" ] ; then cd .. fi latest_hash_of_package_json="$(git log --pretty=format:%H developer-tools/package.json | head -1)" latest_saved_hash="" cd developer-tools need_npm_i=false if [[ -f latest_hash_of_package_json && -d node_modules ]]; then latest_saved_hash="$(cat latest_hash_of_package_json | head -1)" if [ "$latest_saved_hash" == "$latest_hash_of_package_json" ]; then echo "doesn't need npm i" need_npm_i=false else echo "package.json is changed, need npm i" need_npm_i=true fi else echo "initial run" need_npm_i=true fi error=false if $need_npm_i ; then echo "running the npm install..." npm set progress=false npm i OUT=$? if [ $OUT -eq 0 ]; then echo "${latest_hash_of_package_json}" > latest_hash_of_package_json else error=true fi fi ./node_modules/.bin/gulp --silent --gulpfile gulpfile-pug.js if [ $? -ne 0 ] ; then error=true fi ./node_modules/.bin/gulp --silent --gulpfile gulpfile-images.js if [ $? -ne 0 ] ; then error=true fi ./node_modules/.bin/gulp --silent --gulpfile gulpfile-boards.js if [ $? -ne 0 ] ; then error=true fi ./node_modules/.bin/webpack if [ $? -ne 0 ] ; then error=true fi if $error ; then exit -1 else echo "application available in 'dist/progbot.html'" fi <file_sep>/source/game/on/key.js /** * handle the key event * @author sarkiroka on 2017.08.18. */ var state=require('../state/index'); module.exports = function (key) { state.addProgramStep(key); }; <file_sep>/source/common/event/on/key.js /** * handle of the arrow buttons * TODO ennek a fájlnak a neve nem túl következetes * @author sarkiroka on 2017.12.27. */ var onKey = require('../../../game/on/key'); var redraw = require('../../draw/redraw'); var state = require('../../../game/state/index'); module.exports = function (key) { if (state() == state.IDLE) { onKey(key); redraw(); } else { console.warn('don\'t touch keyboard while animating!', state()); } }; <file_sep>/source/common/draw/constants.js /** * a rajzoláshoz használt konstansok helye * @author sarkiroka on 2017.07.03. */ module.exports = { //colors backgroundColor: '#777', programStepBackground: '#999', programStepHighlightBackground: '#ddd', arrowGradientStartColor:'#000', arrowGradientEndColor:'#888', arrowHighlightGradiendStartColor:'#800', arrowHighlightGradiendEndColor:'#d00', waitGradientStartColor:'#080000', waitGradientEndColor:'#928888', waitHighlightGradiendStartColor:'#800', waitHighlightGradiendEndColor:'#d22', waitTextColor: '#aaa', waitTextHighlightColor: '#eee', //sizes programStepSize: 50, // egy kirajzolt program négyzet mérete programStepMargin: 3, // egy kirajzolt program négyzet méretéből visszavett érték boardItemSize: 50, boardItemMargin:3, dummy: null // last one }; <file_sep>/source/init/index.js /** * inicializálás * @author sarkiroka on 2017.06.01. */ require('./debug'); var initCanvas = require('./init-canvas'); var initGame = require('./init-game'); var initResize = require('./init-resize'); var initKeyboard = require('./init-keyboard'); module.exports = function () { initGame(function () { initCanvas(); initResize(); initKeyboard(); }); }; <file_sep>/source/common/event/on/space.js /** * kezeli a szóköz nyomást * @author sarkiroka on 2017.12.30. */ var onKey = require('../../../game/on/key'); var redraw = require('../../draw/redraw'); var state = require('../../../game/state/index'); module.exports = function () { if (state() == state.IDLE) { onKey('space'); redraw(); } else { console.warn('don\'t touch keyboard while animating!', state()); } }; <file_sep>/source/common/event/on/end-of-programming/animate-step.js /** * animál egyetlen program utasítást * @author sarkiroka on 2017.12.29. */ var calculateNextPosition = require('./calculate-next-position'); var calculateNextTile = require('./calculate-next-tile'); var debug = require('debug')('progbot:event:on:end-of-programming:animate-step'); var drawRobot = require('../../../draw/robot'); var fallDown = require('./fall-down'); var gameConstants = require('../../../../game/constants'); var isFree = require('../../../../game/board/is-free'); var saveBoard = require('../../../draw/board/save'); var fps = 25; var delay = 1000 / fps; // animation speed module.exports = function (position, instruction, callback) { var nextTile = calculateNextTile(position, instruction); var canVisit = isFree(nextTile); var startTime = Date.now(); var needMoving = canVisit == null || canVisit == true; debug('need to move?', needMoving); move(); function move() { var animationTime = gameConstants.robotStepTimeSeconds * 1000; // azért itt, hogy később lehessen állítani a sebességen var currentTime = Date.now(); var elapsedTime = currentTime - startTime; var elapsedPercent = Math.min(1, elapsedTime / animationTime); var nextPosition = calculateNextPosition(position, instruction, needMoving ? elapsedPercent : Math.random() * 0.1); saveBoard.restore(); drawRobot(nextPosition); if (elapsedPercent < 1) { setTimeout(move, delay); } else { if (needMoving) { if (canVisit == null) { fallDown(nextPosition, function () { callback(nextPosition, true) }); } else { callback(nextPosition); } } else { saveBoard.restore(); drawRobot(position); callback(position); } } } }; <file_sep>/developer-tools/scripts/help #!/bin/sh echo echo "**********************" echo "* sarkiroka miniprog *" echo "**********************" echo if [ $# -ne 0 ] ; then echo "Error: \"$1\" not available in this project" echo "" fi echo "Available commands:" echo " ./run - build the application" echo " ./run build - build the application" echo " ./run dev - build & watch" echo " ./run help - shows this help" echo "" <file_sep>/source/boards/readme.md # dat format minden karakter egy résznek felel meg a pályán. attól függően, hogy milyen betű van ott, attól függően más és más alakzatok jelenhetnek meg a játék közben - S: Start - E: End - X: barrier - #: empty - C: Checkpoint Például egy függőleges 3 elemű pálya így nézhet ki: ``` S # E ``` Vagy ugyanez vizszintesen: ``` S#E ``` <file_sep>/source/common/event/on/resize.js /** * az átméretezés kezelője * @author sarkiroka on 2017.06.02. */ var canvas = require('../../draw/canvas'); var debug = require('debug')('progbot:event:resize'); var redraw = require('../../draw/redraw'); module.exports = function (e) { debug(e ? 'resize event handling' : 'initial resize event'); canvas.setSize(window.innerWidth, window.innerHeight); redraw(); }; <file_sep>/source/game/on/backspace.js /** * handle the backspace event * @author sarkiroka on 2017.08.18. */ var state=require('../state/index'); module.exports = function () { state.removeLastProgramStep(); }; <file_sep>/readme.md # MiniProg / ProgBot There are many similar games on the market, but their learning curve is too steep for kids. One or two examples are not enough for them, they need more to prepare for the upcoming levels. My experience is that my 5 year old son enjoys playing on the first two levels, but doesn't understand the third level, thus never playing the successive levels, because the newer parts come too fast. He cannot learn the foundations that quick, so he can't use or combine them with future elements. This game contains plenty of levels for kids to really get into abstraction, logic, control, selection, etc. This provides enough time for kids to get familiar with each topic, while giving them enough time to learn how to combine exisiting knowledge with the newer elements. It was developed on computer running linux and it was designed mainly for android. It should work on desktop and mobiles, but it was not tested - don't expect me to make it work on Internet Explorer. ## Start You should build all source file to run the game. It is easy, but you need to installed [nodejs](https://nodejs.org/en/download/) on your computer. To build, run this simple command in the root of this project: ``` ./run ``` After that you have some new file in the `dist` folder. Open the html file in the browser, and enjoy :) <file_sep>/source/common/draw/clear.js /** * törli a transzformációs mátrixot és lesatírozza a képernyőt * @author sarkiroka on 2017.06.02. */ var canvas = require('./canvas'); var constants = require('./constants'); var debug = require('debug')('progbot:draw:clear'); var state = require('../../game/state/index'); module.exports = function () { debug('clear all pixels'); var ctx = canvas.ctx; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.save(); ctx.fillStyle = constants.backgroundColor; ctx.fillRect(0, 0, canvas.canvas.width, canvas.canvas.height); ctx.textAlign = 'right'; ctx.textBaseline = 'top'; ctx.fillStyle = '#fff'; ctx.fillText('#' + state.getLevel(), canvas.width - 5, 5); ctx.restore(); }; <file_sep>/source/common/draw/the-end.js /** * the end * @author sarkiroka on 2017.07.13. */ var canvas = require('./canvas'); var clear = require('./clear'); module.exports = function () { clear(); var ctx = canvas.ctx; ctx.textAlign = 'center'; ctx.fillStyle = '#e00'; ctx.font = '64px Arial'; ctx.fillText('The End', canvas.centerX, canvas.centerY); }; <file_sep>/source/common/draw/board/board.js /** * kirájzolja az aktuális pályát * @author sarkiroka on 2017.12.28. */ var canvas = require('../canvas'); var constants = require('../constants'); var debug = require('debug')('progbot:draw:board'); var tile = require('./tile'); var getSize = require('./get-size'); module.exports = function (board, withoutRobot) { var sizes = getSize(board); var leftTopX = canvas.centerX - Math.floor(sizes.x / 2) * constants.boardItemSize - constants.boardItemSize / 2; var leftTopY = canvas.centerY - Math.floor(sizes.y / 2) * constants.boardItemSize - constants.boardItemSize / 2; debug('draw the board'); canvas.ctx.fillStyle = '#eee'; canvas.ctx.strokeStyle = '#000'; if (board) { for (var i = 0; i < board.length; i++) { tile(board[i], withoutRobot); } } var boardPositionAndSize = { x: leftTopX, y: leftTopY, w: 2 * (canvas.centerX - leftTopX), h: 2 * (canvas.centerY - leftTopY) }; //TODO el kéne menteneni itt is robottal a pályát aztán következő kirajzolásnál csak a mentettet venni. ha nincs mentett akkor rajzolni. játék végén meg törölni a mentést return boardPositionAndSize; }; <file_sep>/source/game/constants.js /** * a játék állandói * @author sarkiroka on 2017.12.29. */ module.exports = { beforeResultTimeSeconds: 0.75, resultTimeSeconds: 5, robotStepTimeSeconds: 2, waitForNextStepSeconds: 0.5 }; <file_sep>/source/common/event/on/end-of-programming/animate-program.js /** * végiganimálja a programkódot, majd a végén meghívja a callback-et * @author sarkiroka on 2017.12.29. */ var animateStep = require('./animate-step'); var board2CanvasCoordinates = require('../../../util/board-to-canvas-coordinate'); var boardConstants = require('../../../../game/board/constants'); var debug = require('debug')('progbot:event:on:end-of-programming:animate-program'); var drawProgramSteps = require('../../../draw/program-steps'); var gameConstants = require('../../../../game/constants'); var state = require('../../../../game/state/index'); var instructionPointer = -1; var robotPosition = null; module.exports = function animateProgram(callback) { var error = null; var program = state.getProgram(); if (program.length == 0) { error = new Error('there is no program'); return callback(error, {x: 0, y: 0, direction: 0}); } if (!robotPosition) { debug('there is no robot position, calculate it'); var board = state.getBoard(); var startTile = board.find(tile=>tile.type == boardConstants.S); if (!startTile) { error = new Error('invalid board, no start position defined'); console.error(error); return callback(error, null); } var canvasCoordinates = board2CanvasCoordinates(startTile.x, startTile.y); robotPosition = { x: canvasCoordinates.x, y: canvasCoordinates.y, direction: 0 // up } } instructionPointer++; var programStep = program[instructionPointer]; drawProgramSteps(program, instructionPointer); animateStep(robotPosition, programStep, function (newPosition, accident) { if (!accident) {//volt hova menni setTimeout(function () { // rest in this cell a little robotPosition = newPosition; if (instructionPointer < program.length - 1) { animateProgram(callback); } else { callback(null, newPosition); } }, gameConstants.waitForNextStepSeconds * 1000); } else {//leesett, így azonnal abbahagyjuk a dolgokat callback(null, newPosition) } }); }; module.exports.reset = function () {//TODO meghivni a játék végén instructionPointer = -1; robotPosition = null; }; <file_sep>/run #!/bin/sh scripts="./developer-tools/scripts"; if [ $# -eq 0 ] ; then $scripts/build else command="$scripts/$1"; if [ -f $command ] ; then $command else $scripts/help $1 fi fi <file_sep>/source/common/draw/canvas.js /** * ez tárolja a canvas-os objektumokat * @author sarkiroka on 2017.06.01. */ var exportObject = function (canvas, ctx) { exportObject.canvas = canvas; exportObject.ctx = ctx; }; exportObject.canvas = null; exportObject.ctx = null; exportObject.center = {}; exportObject.centerX = 0; exportObject.centerY = 0; exportObject.setSize = function (width, height) { exportObject.width = width; exportObject.height = height; exportObject.canvas.width = width; exportObject.canvas.height = height; exportObject.centerX = width / 2; exportObject.centerY = height / 2; exportObject.center = {x: exportObject.centerX, y: exportObject.centerY}; }; module.exports = exportObject; <file_sep>/source/init/init-canvas.js /** * * @author sarkiroka on 2017.06.01. */ var canvas = require('../common/draw/canvas'); module.exports = function () { var canvasElement = document.getElementById('c'); var ctx = canvasElement.getContext('2d'); canvas(canvasElement, ctx); }; <file_sep>/source/common/draw/redraw.js /** * * @author sarkiroka on 2017.06.02. */ var clear = require('./clear'); var debug = require('debug')('progbot:draw:redraw'); var drawBoard = require('./board/board'); var drawProgramSteps = require('./program-steps'); var state = require('../../game/state/index'); module.exports = function () { debug('now redraw'); clear(); drawProgramSteps(state.getProgram()); drawBoard(state.getBoard()); }; <file_sep>/developer-tools/gulpfile-images.js /** * builds images * @author sarkiroka on 2017.04.30. */ var decompress = require('gulp-decompress'); var endOfBuild = require('./end-of-build')('IMAGES'); var gulp = require('gulp'); var path = require('path'); var plumber= require('gulp-plumber'); const TARGET_FOLDER = path.normalize(path.join(__dirname, '..', 'dist')); gulp.task('images', function extractFavicon(){ return gulp.src('../source/images.zip') .pipe(plumber(function (err) { console.error('images error', err); this.emit('end'); })) .pipe(decompress({strip: 1})) .pipe(gulp.dest(TARGET_FOLDER)); }); gulp.task('watchimages', ['images'], function () { gulp.watch('../source/images.zip', function () { gulp.start('images', endOfBuild); }); }); gulp.task('watch', ['watchimages'], endOfBuild); gulp.task('default', ['images'], endOfBuild); <file_sep>/source/common/draw/draw-step.js /** * kirajzol egy programlépést. * ehhez kap sor és oszlop koordinátákat amiket a bal alsó saroktól - mint origótól - kezdve jelenit meg * @author sarkiroka on 2017.12.28. */ var canvas = require('./canvas'); var constants = require('./constants'); var debug = require('debug')('progbot:draw:draw-step'); var drawArrow = require('./arrow'); var drawWait = require('./wait'); var rectangleSize = constants.programStepSize - constants.programStepMargin; module.exports = function (row, col, step, highlight) { debug('now draw a step', row, col, step); var x0 = col * constants.programStepSize; var y0 = canvas.height - (row + 1) * constants.programStepSize; canvas.ctx.fillStyle = highlight ? constants.programStepHighlightBackground : constants.programStepBackground; canvas.ctx.fillRect(x0, y0, rectangleSize, rectangleSize); canvas.ctx.strokeRect(x0, y0, rectangleSize, rectangleSize); var isArrow = step == 'left' || step == 'right' || step == 'up' || step == 'down'; if (isArrow) { drawArrow(x0 + rectangleSize / 2, y0 + rectangleSize / 2, step, rectangleSize, highlight); } else if (step == 'space') { drawWait(x0 + rectangleSize / 2, y0 + rectangleSize / 2, rectangleSize, highlight); } else { console.warn('unknown program step', step); } }; //TODO ez a fájl nem is draw-step, hanem csak step <file_sep>/source/common/event/on/backspace.js /** * handle of the backspace button * @author sarkiroka on 2017.08.10. */ var onBackspace = require('../../../game/on/backspace'); var redraw = require('../../draw/redraw'); var state = require('../../../game/state/index'); module.exports = function () { if (state() == state.IDLE) { onBackspace(); redraw(); } else { console.warn('don\'t touch keyboard while animating...', state()); } }; <file_sep>/source/common/draw/arrow.js /** * kirajzolja a nyilat * @author sarkiroka on 2017.12.28. */ var canvas = require('./canvas'); var constants = require('./constants'); var debug = require('debug')('progbot:draw:arrow'); var angles = { left: Math.PI * 270 / 180, up: Math.PI * 0 / 180, right: Math.PI * 90 / 180, down: Math.PI * 180 / 180 }; var gradient = null; module.exports = function (x, y, direction, size, highlight) { var size90 = size * 0.45; var size70 = size * 0.35; var size50 = size * 0.25; var size40 = size * 0.2; var size20 = size * 0.1; var size10 = size * 0.05; var ctx = canvas.ctx; debug('draw %s arrow', direction); ctx.save(); ctx.translate(x, y); ctx.beginPath(); if (highlight) { var highlightGradient = ctx.createLinearGradient(0, size90, 0, -size90); highlightGradient.addColorStop(0, constants.arrowHighlightGradiendStartColor); highlightGradient.addColorStop(1, constants.arrowHighlightGradiendEndColor); ctx.fillStyle = highlightGradient; } else { if (!gradient) { gradient = ctx.createLinearGradient(0, size90, 0, -size90); gradient.addColorStop(0, constants.arrowGradientStartColor); gradient.addColorStop(1, constants.arrowGradientEndColor); } ctx.fillStyle = gradient; } if (direction == 'up' || direction == 'down') { ctx.rotate(angles[direction]); ctx.moveTo(0, -size90); // csúcs ctx.lineTo(size90, 0); // jobb oldal - TODO quadraticCurveTo ctx.lineTo(size40, -size10); ctx.lineTo(size50, size90); // TODO quadraticCurveTo ctx.lineTo(-size50, size90); // TODO quadraticCurveTo ctx.lineTo(-size40, -size10); ctx.lineTo(-size90, 0); } else if (direction == 'right') { ctx.moveTo(size90,0); ctx.lineTo(size10,-size90); ctx.lineTo(size20,-size40); ctx.arcTo(-size70,-size40,-size70,size40,size90); ctx.lineTo(-size70,size90); ctx.lineTo(0,size90); ctx.arcTo(0,size50,size20,size40,size40); ctx.lineTo(size10,size90); } else if (direction == 'left') { ctx.moveTo(-size90,0); ctx.lineTo(-size10,-size90); ctx.lineTo(-size20,-size40); ctx.arcTo(size70,-size40,size70,size40,size90); ctx.lineTo(size70,size90); ctx.lineTo(0,size90); ctx.arcTo(0,size50,-size20,size40,size40); ctx.lineTo(-size10,size90); } else { console.warn('invalid direction in arrow', direction); } ctx.closePath(); ctx.fill(); ctx.stroke(); ctx.restore(); }; <file_sep>/source/common/event/on-key-event.js /** * minden billentyűzetesemények elosztója * @author sarkiroka on 2017.06.01. */ var onBackspace = require('./on/backspace'); var onEscape = require('./on/escape'); var onEndOfProgramming = require('./on/end-of-programming/end-of-programming'); var onF = require('../../game/on/f'); var onKey = require('./on/key'); var onSpace = require('./on/space'); module.exports = function (event) { event.preventDefault(); switch (event.key) { case 'ArrowLeft': case 'ArrowRight': case 'ArrowUp': case 'ArrowDown': onKey(event.key.replace('Arrow', '').toLowerCase()); break; case ' ': onSpace(); break; case 'Backspace': onBackspace(); break; case 'Enter': onEndOfProgramming(); break; case 'F': case 'f': onF(); break; case 'Escape': onEscape(); break; case 'F5': location.reload(); break; default: console.log('unhandled keyboard event', event); } }; <file_sep>/source/common/util/pad.js /** * pad with... * @author sarkiroka on 2017.12.28. */ module.exports = function pad(str, length, pad) { var retValue = str + ''; var padString = pad + ''; var willGrowing = !!padString.length; var notEnoughLong = retValue.length < length; if (!willGrowing) { console.warn('pad inpossible because no pad character defined', arguments); } while (notEnoughLong && willGrowing) { retValue = padString + retValue; notEnoughLong = retValue.length < length; } return retValue; }; <file_sep>/source/init/init-keyboard.js /** * fel és leiratkozik a billentyűzet eseményekre * @author sarkiroka on 2017.06.01. */ var onKeyEvent=require('../common/event/on-key-event'); module.exports = function () { document.addEventListener('keydown', onKeyEvent); }; module.exports.done = function () { document.removeEventListener('keydown', onKeyEvent); }; <file_sep>/source/common/draw/board/tile.js /** * kirajzol a pályáról egyetlen pályaelemet * @author sarkiroka on 2017.12.28. */ var canvas = require('../canvas'); var constants = require('../constants'); var board2CanvasCoordinate = require('../../util/board-to-canvas-coordinate'); var boardConstants = require('../../../game/board/constants'); var drawRobot = require('../robot'); var box = document.getElementById('box'); module.exports = function (tile, withoutRobot) { var ctx = canvas.ctx; var canvasCoordinates = board2CanvasCoordinate(tile.x, tile.y); var x = canvasCoordinates.x; var y = canvasCoordinates.y; var size = constants.boardItemSize - constants.boardItemMargin; var size05 = size * 0.05; var size90 = size * 0.9; var size80 = size * 0.8; var size40 = size * 0.4; var size20 = size * 0.2; var size2 = size * 0.5; ctx.fillRect(x - size2, y - size2, size, size); ctx.strokeRect(x - size2, y - size2, size, size); switch (tile.type) { case boardConstants.X: ctx.save(); ctx.translate(x, y); ctx.rotate(Math.random() * 3 * Math.PI / 180); ctx.drawImage(box, -size2 + size05, -size2 + size05, size90, size90); ctx.restore(); break; case boardConstants.S: if (!withoutRobot) { drawRobot({x: x, y: y, direction: 0}); } break; case boardConstants.E: ctx.save(); ctx.translate(x, y); ctx.beginPath(); ctx.strokeStyle = '#000'; ctx.lineWidth = size05; ctx.arc(0, 0, size40, 0, Math.PI * 2); ctx.stroke(); ctx.beginPath(); ctx.strokeStyle = '#D00'; ctx.fillStyle = '#D00'; ctx.arc(0, 0, 2 * size05, 0, Math.PI * 2); ctx.stroke(); ctx.fill(); ctx.beginPath(); ctx.lineWidth = 1; ctx.strokeStyle = '#000'; ctx.moveTo(0, -size40); ctx.lineTo(0, size40); ctx.moveTo(-size40, 0); ctx.lineTo(size40, 0); ctx.moveTo(-size20, -size05); ctx.lineTo(-size20, size05); ctx.moveTo(size20, -size05); ctx.lineTo(size20, size05); ctx.lineWidth = 0.5; ctx.moveTo(-size05, size20); ctx.lineTo(size05, size20); ctx.moveTo(-size05, -size20); ctx.lineTo(size05, -size20); ctx.stroke(); ctx.restore(); break; } }; <file_sep>/source/game/board/get-board.js /** * a tábla lekérése * @author sarkiroka on 2017.12.28. */ var debug = require('debug')('progbot:game:board:get-board'); var pad = require('../../common/util/pad'); module.exports = function getTheBoard(level, callback) { var name = pad(level, 4, '0') + '.json'; debug('try to get the "%s" board', name); var xhr = new XMLHttpRequest(); xhr.open('GET', name); xhr.onload = function () { var retValue = []; var err = null; if (xhr.status == 200) { try { var response = JSON.parse(xhr.responseText); retValue = response; } catch (e) { err = 'json parse error in ajax request'; } } else { err = 'ajax request failed. status code: ' + xhr.status; } callback(err, retValue); }; xhr.send(); }; <file_sep>/source/common/event/on/end-of-programming/calculate-next-position.js /** * kiszámolja hogy hol van az adott százalékkal arrébb tett robot * @author sarkiroka on 2017.12.29. */ var constants = require('../../../draw/constants'); module.exports = function (startPosition, direction, percent) { if (percent > 1) { console.warn('percent is greater than one :(', percent); percent = 1; } if (percent < 0) { console.warn('percent is lower than zero :(', percent); percent = 0; } var retValue = Object.assign({}, startPosition); switch (direction) { case 'up': // forward switch (startPosition.direction) { case 0: retValue.y -= constants.boardItemSize * percent; break; case 90: retValue.x += constants.boardItemSize * percent; break; case 180: retValue.y += constants.boardItemSize * percent; break; case 270: retValue.x -= constants.boardItemSize * percent; break; default: console.error('wrong direction detected', startPosition); } break; case 'down': // backward switch (startPosition.direction) { case 0: retValue.y += constants.boardItemSize * percent; break; case 90: retValue.x -= constants.boardItemSize * percent; break; case 180: retValue.y -= constants.boardItemSize * percent; break; case 270: retValue.x += constants.boardItemSize * percent; break; default: console.error('wrong direction detected', startPosition); } break; case 'left': //turn left retValue.direction -= 90 * percent; break; case 'right': //turn right retValue.direction += 90 * percent; break; case 'space': break; default: console.warn('unknown program instruction detected', direction); } // normalize direction while (retValue.direction >= 360) { retValue.direction -= 360; } while (retValue.direction < 0) { retValue.direction += 360; } return retValue; }; <file_sep>/source/game/toggle-animation-speed.js /** * ki-be kapcsolja az animáció közbeni gyorsítást * @author sarkiroka on 2017.12.30. */ var gameConstants = require('./constants'); var speedupAnimation = false; var speedupMultiplier = 12; var originalRobotStepTimeSeconds = gameConstants.robotStepTimeSeconds; var originalWaitForNextStepSeconds = gameConstants.waitForNextStepSeconds; //var originalBeforeResultTimeSeconds = gameConstants.beforeResultTimeSeconds; var originalResultTimeSeconds = gameConstants.resultTimeSeconds; var originalRobotStepTimeSecondsFast = gameConstants.robotStepTimeSeconds / speedupMultiplier; var originalWaitForNextStepSecondsFast = gameConstants.waitForNextStepSeconds / speedupMultiplier; //var originalBeforeResultTimeSecondsFast = gameConstants.beforeResultTimeSeconds / speedupMultiplier; var originalResultTimeSecondsFast = gameConstants.resultTimeSeconds / speedupMultiplier; module.exports = function toggleAnimationSpeed() { speedupAnimation = !speedupAnimation; if (speedupAnimation) { gameConstants.resultTimeSeconds = originalResultTimeSecondsFast; gameConstants.robotStepTimeSeconds = originalRobotStepTimeSecondsFast; gameConstants.waitForNextStepSeconds = originalWaitForNextStepSecondsFast; // gameConstants.beforeResultTimeSeconds = originalBeforeResultTimeSecondsFast; } else { gameConstants.resultTimeSeconds = originalResultTimeSeconds; gameConstants.robotStepTimeSeconds = originalRobotStepTimeSeconds; gameConstants.waitForNextStepSeconds = originalWaitForNextStepSeconds; // gameConstants.beforeResultTimeSeconds = originalBeforeResultTimeSeconds; } }; <file_sep>/developer-tools/end-of-build.js /** * kiirja a build végét * @author sarkiroka on 2017.04.29. */ module.exports = function (what) { return function () { setTimeout(function () { console.log(what, 'builded:', new Date()) }, 1); } }; <file_sep>/source/game/index.js /** * * @author sarkiroka on 2017.06.01. */ module.exports = function () { }; <file_sep>/source/index.js /** * a játék * * az a Tippem hogy valahogy úgy kéne felépülnie, hogy vannak a bill események, meg vannak a játékállapotok és * akkor a bill az állapottól függően az állapoton tesz változást * * @author sarkiroka on 2017.06.01. */ var init = require('./init'); var game = require('./game'); init(); game(); <file_sep>/source/common/util/extend-board.js /** * kiterjeszti a board méretét egy-egy cellával körbe * @author sarkiroka on 2017.12.29. */ var canvas = require('../draw/canvas'); var constants = require('../draw/constants'); var debug = require('debug')('progbot:draw:util:extend-board'); module.exports = function (positionAndSize) { var retValue = Object.assign({}, positionAndSize); retValue.x = Math.max(0, retValue.x - constants.boardItemSize); retValue.y = Math.max(0, retValue.y - constants.boardItemSize); retValue.w = Math.min(canvas.width, retValue.w + 2 * constants.boardItemSize); retValue.h = Math.min(canvas.height, retValue.h + 2 * constants.boardItemSize); debug('extend board from %o to %o', positionAndSize, retValue); return retValue; }; <file_sep>/source/game/board/is-free.js /** * viszaadja hogy az adott cella üres-e vagy sem. ha nincs cella akkor null-al tér vissza * @author sarkiroka on 2017.12.29. */ module.exports = function (tile) { var retValue=null; if(tile){ retValue=!(tile.type & 1); } return retValue; }; <file_sep>/source/common/event/on/end-of-programming/calculate-next-tile.js /** * kiszámitja és visszaadja a tábla azon elemét, ahova lépne az utasítás után * @author sarkiroka on 2017.12.29. */ var board2canvasCoordinate = require('../../../util/board-to-canvas-coordinate'); var state = require('../../../../game/state/index'); module.exports = function (position, instruction) { var board = state.getBoard(); var currentTileCoordinate = board2canvasCoordinate.reverse(position.x, position.y); var targetCoordinate = Object.assign({}, currentTileCoordinate); var d = 0; if (instruction == 'up') {//TODO az up/down stb szavakat kiszervezni egy konstansba d = 1; } else if (instruction == 'down') { d = -1; } if (d) { switch (position.direction) { case 0: targetCoordinate.y -= d; break; case 90: targetCoordinate.x += d; break; case 180: targetCoordinate.y += d; break; case 270: targetCoordinate.x -= d; break; } } var retValue = board.find(tile=>tile.x == targetCoordinate.x && tile.y == targetCoordinate.y); return retValue; };
e76d4f4c083f6fc601a25c929fbcc808c2dd976f
[ "JavaScript", "Markdown", "Shell" ]
43
JavaScript
sarkiroka/progbot
298ad87ffbe2742a462af62b294f40f1ac728668
eb638660fbef7df2ff6278228c20adc5c5a4bab1
refs/heads/master
<file_sep>import { ContextType } from 'server/types/apiTypes'; import { requestLimiter } from 'server/helpers/rateLimiter'; import { toWithError } from 'server/helpers/async'; import { appUrls } from 'server/utils/appUrls'; import { request, gql } from 'graphql-request'; const getBaseCanConnectQuery = gql` { hello } `; const getBaseNodesQuery = gql` { getNodes { _id name public_key socket } } `; const getBasePointsQuery = gql` { getPoints { alias amount } } `; const createBaseInvoiceQuery = gql` mutation CreateInvoice($amount: Int!) { createInvoice(amount: $amount) { request id } } `; const createThunderPointsQuery = gql` mutation CreatePoints( $id: String! $alias: String! $uris: [String!]! $public_key: String! ) { createPoints(id: $id, alias: $alias, uris: $uris, public_key: $public_key) } `; export const tbaseResolvers = { Query: { getBaseCanConnect: async ( _: undefined, __: undefined, context: ContextType ): Promise<boolean> => { await requestLimiter(context.ip, 'getBaseCanConnect'); const [data, error] = await toWithError( request(appUrls.tbase, getBaseCanConnectQuery) ); if (error || !data?.hello) return false; return true; }, getBaseNodes: async (_: undefined, __: any, context: ContextType) => { await requestLimiter(context.ip, 'getBaseNodes'); const [data, error] = await toWithError( request(appUrls.tbase, getBaseNodesQuery) ); if (error || !data?.getNodes) return []; return data.getNodes.filter( (n: { public_key: string; socket: string }) => n.public_key && n.socket ); }, getBasePoints: async (_: undefined, __: any, context: ContextType) => { await requestLimiter(context.ip, 'getBasePoints'); const [data, error] = await toWithError( request(appUrls.tbase, getBasePointsQuery) ); if (error || !data?.getPoints) return []; return data.getPoints; }, }, Mutation: { createBaseInvoice: async ( _: undefined, params: { amount: number }, context: ContextType ) => { await requestLimiter(context.ip, 'getBaseInvoice'); if (!params?.amount) return ''; const [data, error] = await toWithError( request(appUrls.tbase, createBaseInvoiceQuery, params) ); if (error) return null; if (data?.createInvoice) return data.createInvoice; return null; }, createThunderPoints: async ( _: undefined, params: { id: string; alias: string; uris: string[]; public_key: string }, context: ContextType ): Promise<boolean> => { await requestLimiter(context.ip, 'getThunderPoints'); const [info, error] = await toWithError( request(appUrls.tbase, createThunderPointsQuery, params) ); if (error || !info?.createPoints) return false; return true; }, }, }; <file_sep>import { ServerResponse } from 'http'; import { LndObject } from './ln-service.types'; export type SSOType = { macaroon: string; cert: string | null; socket: string; }; export type AccountType = { name: string; id: string; socket: string; macaroon: string; cert: string | null; password: string; }; export type ContextType = { ip: string; lnd: LndObject | null; secret: string; id: string | null; sso: SSOType | null; accounts: AccountType[]; res: ServerResponse; lnMarketsAuth: string | null; }; <file_sep># --------------- # Install Dependencies # --------------- FROM node:14.15-alpine as build # Install dependencies neccesary for node-gyp on node alpine RUN apk add --update --no-cache \ python \ make \ g++ # Install app dependencies COPY package.json . COPY package-lock.json . RUN npm install --silent # Build the NextJS application COPY . . RUN npm run build # Remove non production necessary modules RUN npm prune --production # --------------- # Build App # --------------- FROM node:14.15-alpine WORKDIR /app # Copy dependencies and build from build stage COPY --from=build node_modules node_modules COPY --from=build .next .next # Bundle app source COPY . . EXPOSE 3000 CMD [ "npm", "start" ]<file_sep>import { createHash, randomBytes } from 'crypto'; import * as bip39 from 'bip39'; import * as bip32 from 'bip32'; export const getPreimageAndHash = () => { const preimage = randomBytes(32); const preimageHash = createHash('sha256') .update(preimage) .digest() .toString('hex'); return { preimage, hash: preimageHash }; }; export const getPrivateAndPublicKey = () => { const secretKey = bip39.generateMnemonic(); const base58 = bip39.mnemonicToSeedSync(secretKey); // Derive private seed const node: bip32.BIP32Interface = bip32.fromSeed(base58); const derived = node.derivePath(`m/0/0`); // Get private and public key from derived private seed const privateKey = derived.privateKey?.toString('hex'); const publicKey = derived.publicKey.toString('hex'); return { privateKey, publicKey }; };
427cc0c6a486c566a4970c4d24cae5a0c0cac0d9
[ "TypeScript", "Dockerfile" ]
4
TypeScript
fiatjaf/thunderhub
f070d2d7de4afcbe0e41b4c6d390b8c2174a96db
afd1c012e92c288b3089e45539262f3a73618e74
refs/heads/master
<repo_name>samarv/Sprint-Challenge--SQL<file_sep>/queries.sql CREATE TABLE Organizations( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(128) NOT NULL, channels_id INT REFERENCES channels(id)); CREATE TABLE Channels( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(128) NOT NULL, users_id INT REFERENCES users(id)); CREATE TABLE Users( id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(128) NOT NULL); CREATE TABLE Messages( id INTEGER PRIMARY KEY AUTOINCREMENT, content VARCHAR(128) NOT NULL, post_time DATETIME DEFAULT CURRENT_TIMESTAMP,channels_id INT REFERENCES channels(id),users_id INT REFERENCES users(id)); INSERT INTO Organizations (name, channels_id) VALUES ("Lambda School", 1); INSERT INTO Channels(name, users_id) VALUES ("general", "1,2"); INSERT INTO Channels(name, users_id) VALUES ("random", "1,3"); INSERT INTO Users(name) VALUES ("Alice"); INSERT INTO Users(name) VALUES ("bob"); INSERT INTO Users(name) VALUES ("chris"); INSERT INTO Messages(content, channels_id, users_id) VALUES ("hey i am in general",1, 1); INSERT INTO Messages(content, channels_id, users_id) VALUES ("hey i am in general AS WELL",1, 2); INSERT INTO Messages(content, channels_id, users_id) VALUES ("am i bob",1, 2); INSERT INTO Messages(content, channels_id, users_id) VALUES ("another message",1, 2); INSERT INTO Messages(content, channels_id, users_id) VALUES ("boooL",1, 1); INSERT INTO Messages(content, channels_id, users_id) VALUES ("hey from random",2, 1); INSERT INTO Messages(content, channels_id, users_id) VALUES (" i am alice",2, 1); INSERT INTO Messages(content, channels_id, users_id) VALUES (" i am chris",2, 3); INSERT INTO Messages(content, channels_id, users_id) VALUES (" i am",2, 3); INSERT INTO Messages(content, channels_id, users_id) VALUES (" i am duper",2, 3); INSERT INTO Messages(content, channels_id, users_id) VALUES (" i am cool",2, 3); SELECT NAME FROM Organizations; SELECT NAME FROM Channels; SELECT * FROM Organizations,Channels WHERE Organizations.name = "Lambda School"; SELECT * FROM Messages, Channels WHERE Channels.name is "general" AND messages.channels_id = channels.id Order BY post_time; SELECT * FROM users,Channels WHERE Users.name is "Alice"; SELECT * FROM users,Channels,Messages WHERE Users.name is "bob" AND channels.Name = "random" AND messages.channels_id = channels.id; SELECT COUNT(messages.channels_id),users.name FROM users,Channels,Messages WHERE messages.channels_id = channels.id AND messages.users_id = users.id GROUP BY users.Name; -- CASCADE - A foreign key with cascade delete means that if a record in the parent table is deleted, -- then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.
e6e35148a1ce3da54e5d60510c208577f810fdd4
[ "SQL" ]
1
SQL
samarv/Sprint-Challenge--SQL
55a154060d5d123086ec017e9e33fea612ab0564
27b7368aa6506a077ddea6d4c264e516e817dd15
refs/heads/main
<file_sep>const startBtn = document.querySelector('button[data-start]'); const stopBtn = document.querySelector('button[data-stop]'); startBtn.addEventListener('click', onStartBtnClick); stopBtn.addEventListener('click', onStopBtnClick); let isChangeThemeActiv = false; let intervalId = ''; function onStartBtnClick(evt) { if (isChangeThemeActiv) { return } startBtn.setAttribute('disabled', true); intervalId = setInterval(() => { isChangeThemeActiv = true const hexColor = getRandomHexColor(); document.body.style.backgroundColor = hexColor; }, 1000); }; function onStopBtnClick() { clearInterval(intervalId); isChangeThemeActiv = false; startBtn.removeAttribute('disabled'); } function getRandomHexColor() { return `#${Math.floor(Math.random() * 16777215).toString(16)}`; };
c41000263fd0f5fed713e228a9b0fc7ffb587979
[ "JavaScript" ]
1
JavaScript
DennyZ24/goit-js-hw-11
5836d623e104d57e7de415d49b9d47351e51f0cf
586dea9761126aa7fbc07b41d4e8693ba6fb985b
refs/heads/master
<repo_name>mesutgolcuk/AccelerometerTestApp<file_sep>/app/src/main/java/com/mesutgolcuk/accelerometer_hw/MainActivity.java package com.mesutgolcuk.accelerometer_hw; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.TextView; /** * @author <NAME> */ public class MainActivity extends AppCompatActivity implements SensorEventListener { // sensor tanimlamalari private Sensor accelerometer; private SensorManager sm; // widget tanimlamalari private EditText epsilon; private EditText threshold; private TextView activeText; private TextView passiveText; // sensor okunan deger tanimlamalari private long lastTime = 0; private double lastX, lastY, lastZ; // kacar saniye o durumda bulunduklari private int activeSecond; private int passiveSecond; // kullanicinin girebildigi threshold ve epsilon degerleri private double epsilonValue; private double thresholdValue; private final static double SECOND = 1000; /** * Activity ilk olusturuldugunda calisir * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // arayuzdeki widget lari id lerine gore bulup eslestirir findWidgets(); // active ve passive degerlerini 0 a esitler updateActive(0); updatePassive(0); // SensorManager objesi Servis olarak alınır sm = (SensorManager) getSystemService(SENSOR_SERVICE); // Sensor Manager dan accelerometer sensoru alinir accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // accelerometer listener icin register edilir registerListener(); getValues(); } /** * Widget lari id leri ile eslestirip objeleri olusturur */ public void findWidgets(){ epsilon = (EditText) findViewById(R.id.epsilonText); threshold = (EditText) findViewById(R.id.thresholdText); activeText = (TextView) findViewById(R.id.activeText); passiveText = (TextView) findViewById(R.id.passiveText); } /** * Edit textlerin degerlerini okur */ public void getValues(){ epsilonValue = Double.parseDouble(epsilon.getText().toString()); thresholdValue = Double.parseDouble(threshold.getText().toString()); } /** * * @param event */ @Override public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; double x,y,z; long currentTime; // degeri okunan sensorun dogrulugu kontrol edilir if (sensor.getType() == Sensor.TYPE_ACCELEROMETER) { // Sistem saati alinir currentTime = System.currentTimeMillis(); // son sensor okumasinin uzerinden 1 sn gectiyse if ( (currentTime - lastTime) > SECOND ) { // Accelerometre nin x y z degerleri okunur x = event.values[0]; y = event.values[1]; z = event.values[2]; lastTime = currentTime; // okunan degerler ile ondan onceki degerler arasi fark thresholddan yuksekse if ( isHigherXYZ(lastX-x,lastY-y,lastZ-z,thresholdValue) ) { Log.i("active", String.valueOf(activeSecond)); // aktif olunan sureyi 1 arttirip guncelle updateActive(activeSecond + 1); } // okunan degerler ile ondan onceki degerler arasi fark epsilondan kucukse else if( isLowerXYZ(lastX-x,lastY-y,lastZ-z,epsilonValue) ){ Log.i("passive", String.valueOf(passiveSecond)); // pasif olunan sureyi 1 artirip guncelle updatePassive(passiveSecond + 1); } // bir once okunmus olan degerleri guncelle lastX = x; lastY = y; lastZ = z; } } } /** * * @param sensor * @param accuracy */ @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } /** * Start button tiklandi * @param v */ public void startClicked(View v){ getValues(); registerListener(); } /** * Stop button tiklandi * @param v */ public void stopClicked(View v){ unregisterListener(); } /** * Sensoru dinlemek uzere kaydet */ public void registerListener(){ sm.registerListener(this,accelerometer,SensorManager.SENSOR_DELAY_NORMAL); } /** * Sensorun kaydini sil */ public void unregisterListener(){ sm.unregisterListener(this,accelerometer); } /** * Verilen 1,2,3. parametrelerin mutlak degerinin 4. parametreden buyuklugu kontrol edilir * @param x 1. sayi * @param y 2. sayi * @param z 3. sayi * @param value buyuklugu kontrol edilen sayi * @return Hem 1 hem 2 hem 3 4 den buyukse true else false */ public boolean isHigherXYZ(double x,double y, double z,double value){ if( Math.abs(x) > value && Math.abs(y) > value && Math.abs(z) > value ){ return true; } else{ return false; } } /** * Verilen 1,2,3. parametrelerin mutlak degerinin 4. parametreden kucuklugu kontrol edilir * @param x 1. sayi * @param y 2. sayi * @param z 3. sayi * @param value buyuklugu kontrol edilen sayi * @return Hem 1 hem 2 hem 3 4 den kucukse true else false */ public boolean isLowerXYZ( double x,double y, double z,double value ){ if(Math.abs(x) < value && Math.abs(y) < value && Math.abs(z) < value){ return true; } else{ return false; } } /** * aktif suresini temizleme butonu tiklandi * @param v */ public void clearActiveClicked(View v){ updateActive(0); lastTime = System.currentTimeMillis(); } /** * pasif suresini temizleme butonu tiklandi * @param v */ public void clearPassiveClicked(View v){ updatePassive(0); lastTime = System.currentTimeMillis(); } /** * pasif suresini guncelle * @param sec guncellenecek deger */ public void updatePassive(int sec){ passiveSecond = sec; activeText.setText("Passive: "+ sec); } /** * aktif suresini guncelle * @param sec guncellenecek deger */ public void updateActive(int sec){ activeSecond = sec; passiveText.setText("Active: "+ sec); } }
6b87c502f24c075f8d781420f36e84fb26b5801d
[ "Java" ]
1
Java
mesutgolcuk/AccelerometerTestApp
297f746dfbcfe196734486034721fae6a9bfda99
23f9d9c9d0df5a1c34186c3568668d20c6d46f16
refs/heads/master
<file_sep>import ReactDOM from 'react-dom'; import React, { Component } from 'react'; import { createStore } from 'redux'; import reducer from './reducer'; import PropTypes from 'prop-types'; import { Provider, connect } from 'react-redux'; import TodoList from './TodoList'; import AddTodo from './AddTodo'; import FilterLink from './FilterLink'; const store = createStore(reducer); window.store = store; store.subscribe(() => { console.log('state tree changed', store.getState()); }) // const Link = ({ children, onClick, active }) => ( // active ? // <span style={{ color: 'red' }}>{children}</span> // : // <a onClick={onClick} // href="#"> // {children} // </a> // ) // class FilterLink extends Component { // componentDidMount() { // const store = this.context.store; // this.unsubscribe = store.subscribe(() => { // this.forceUpdate(); // console.log('++ force update FilterLink') // }) // } // componentWillUnmount() { // this.unsubscribe(); // console.log('-- unmount FilterLink') // } // render() { // let store = this.context.store; // let state = store.getState(); // let props = this.props; // return ( // <Link // active={state.filter === props.filter } // onClick={ () => store.dispatch({ type: 'SET_FILTER', filter: props.filter }) } // > // {props.children} // </Link> // ) // } // } // FilterLink.contextTypes = { // store: PropTypes.object // } const Footer = () => { return ( <div> <FilterLink filter="all">Show All</FilterLink> <FilterLink filter="done">DONE</FilterLink> <FilterLink filter="active">Active</FilterLink> </div> ) } // const todoFilter = (filter, todos) => { // if (filter === 'all') { // return todos; // } else if (filter === 'done') { // return todos.filter(todo => todo.isDone) // } else if (filter === 'active') { // return todos.filter(todo => !todo.isDone) // } // } // const Todo = ({ todo, isDone, onClick }) => ( // <li style={{ textDecoration: isDone ? 'line-through' : 'none' }} onClick={onClick}> // {todo} // </li> // ) // const TodoList = ({ todos, onTodoClick }) => ( // <ul> // { // todos.map(todo => <Todo key={todo.id} onClick={() => onTodoClick(todo.id)} {...todo}/>) // } // </ul> // ) // class TodoListContainer extends Component { // componentDidMount() { // const store = this.context.store; // this.unsubscribe = store.subscribe(() => { // this.forceUpdate(); // console.log('++ force update TodoList') // }) // } // componentWillUnmount() { // this.unsubscribe(); // console.log('-- unmount TodoList'); // } // render() { // let store = this.context.store; // let state = store.getState(); // let { filter, todos } = state; // let props = this.props; // return ( // <TodoList // todos={todoFilter(filter, todos)} // onTodoClick={(id) => store.dispatch({ type: 'TOGGLE_TODO', id: id })} // /> // ) // } // } // TodoListContainer.contextTypes = { // store: PropTypes.object // } // const AddTodo = (props, context) => { // let input = ''; // return ( // <form // onSubmit={(e) => { // e.preventDefault(); // context.store.dispatch({ id: id++, type: 'ADD_TODO', todo: input.value}); // input.value = ''; // } // } // > // <input ref={node => { input = node }} /> // <button>Add Todo</button> // </form> // ) // } // AddTodo.contextTypes = { // store: PropTypes.object // } const TodoApp = () => ( <div> <div>TODO APP</div> <AddTodo /> <Footer /> <TodoList /> </div> ) TodoApp.contextTypes = { store: PropTypes.object } // class Provider extends Component { // getChildContext() { // return { // store: this.props.store // } // } // render() { // return this.props.children; // } // } // Provider.childContextTypes = { // store: PropTypes.object // } ReactDOM.render( <Provider store={store}><TodoApp /></Provider>, document.getElementById('app') ); // import App from './App'; // ReactDOM.render(<App />, document.getElementById('app')); <file_sep>import { combineReducers } from 'redux'; const todo = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return { id: action.id, todo: action.todo, isDone: false } break; case 'TOGGLE_TODO': return state.id === action.id ? Object.assign({}, state, {isDone: !state.isDone}) : state break; default: return state; } } const todosReducer = (state = [], action) => { switch (action.type) { case 'ADD_TODO': return [...state, todo(undefined, action)]; break; case 'TOGGLE_TODO': return state.map(item => todo(item, action)) break; case 'REMOVE_TODO': return state.filter(item => item.id !== action.id) break; default: return state; } } const filterReducer = (state = 'all', action) => { switch (action.type) { case 'SET_FILTER': return action.filter break; default: return state; } } const combineReducersCustom = (reducerObject) => { return (state = {}, action) => { return Object.keys(reducerObject).reduce((acc, key) => { acc[key] = reducerObject[key](state[key], action) return acc; }, {}) } } const todoApp = combineReducers({ todos: todosReducer, filter: filterReducer }) // const todoApp = (state = {}, action) => { // return { // todos: todosReducer(state.todos, action), // filter: filterReducer(state.filter, action) // } // } export default todoApp; export { todosReducer }<file_sep>import React from 'react'; import { connect } from 'react-redux'; import { setFilter } from './actionCreators'; const Link = ({ children, onClick, active }) => ( active ? <span style={{ color: 'red' }}>{children}</span> : <a onClick={onClick} href="#"> {children} </a> ) const FilterLink = ({ active, onClick, children }) => ( <Link active={active} onClick={ onClick } > {children} </Link> ) const mapStateToProps = (state, props) => { return { active: state.filter === props.filter } } const mapDispatchToProps = (dispatch, props) => { return { onClick: () => dispatch( setFilter(props.filter) ) } } export default connect(mapStateToProps, mapDispatchToProps)(FilterLink)<file_sep>import { todosReducer } from './reducer'; const deepFreeze = require('deep-freeze'); test('test ADD_TODO', () => { let prevState = []; let action = {type: 'ADD_TODO', id: 0, todo: 'sth important'}; deepFreeze(prevState); deepFreeze(action); let afterState = [{id: 0, todo: 'sth important', isDone: false}]; let result = todosReducer(prevState, action); expect(result).toMatchObject(afterState); }); test('test TOGGLE_TODO', () => { let prevState = [{id: 0, todo: 'sth important', isDone: false}]; let action = {type: 'TOGGLE_TODO', id: 0}; deepFreeze(prevState); deepFreeze(action); let afterState = [{id: 0, todo: 'sth important', isDone: true}]; expect(todosReducer(prevState, action)).toMatchObject(afterState); }) test('test REMOVE_TODO', () => { let prevState = [{id: 0, todo: 'sth important', isDone: false}]; let action = {type: 'REMOVE_TODO', id: 0}; deepFreeze(prevState); deepFreeze(action); let afterState = []; expect(todosReducer(prevState, action)).toMatchObject(afterState); }) <file_sep>let id = 0; export const addTodo = (text) => ({ id: id++, type: 'ADD_TODO', todo: text }) export const toggleTodo = (id) => ({ type: 'TOGGLE_TODO', id }) export const setFilter = (filter) => ({ type: 'SET_FILTER', filter })
b42fce74df0b54f3ba76fb3a6471d55db4679989
[ "JavaScript" ]
5
JavaScript
vnscriptkid/todo-react-redux
7e40612b44780d4f575e1f686cf2a0807b37ee5d
ffeff77b44a6e4423e6cb92e5cb175e35d1c8ff2