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>hypernova-studios/ShantyJam4<file_sep>/UnityProject/Assets/Scripts/BreadControll.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class BreadControll : MonoBehaviour { public GameObject p; // Start is called before the first frame update void Start() { for(int j = 0; j < 7; j++) { int i = HSRandom.Next(20-j); var c = transform.GetChild(i); Instantiate(p, c.position, c.rotation); Destroy(c.gameObject); } } } <file_sep>/UnityProject/Assets/Scripts/PlayerBread.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class PlayerBread : MonoBehaviour { public int HowManyBreadsHaveYouEatenInYourLife; public Text t; void OnCollisionEnter(Collision collision) { if(collision.gameObject.tag == "Bread") { Destroy(collision.gameObject); HowManyBreadsHaveYouEatenInYourLife++; t.text = HowManyBreadsHaveYouEatenInYourLife.ToString(); } } public bool HasEnough() { return HowManyBreadsHaveYouEatenInYourLife >= 5; } } <file_sep>/UnityProject/Assets/Scripts/PlayerMouse.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMouse : MonoBehaviour { // Control Variables [SerializeField] public float sensitivity = 5.0f; [SerializeField] public float smoothing = 2.0f; public GameObject character; private Vector2 mouseLook; private Vector2 smoothV; // Start is called before the first frame update void Start() { character = this.transform.parent.gameObject; } // Update is called once per frame void Update() { // The maths var mouseDelta = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y")); mouseDelta = Vector2.Scale(mouseDelta, new Vector2(sensitivity * smoothing, sensitivity * smoothing)); smoothV.x = Mathf.Lerp(smoothV.x, mouseDelta.x, 1f / smoothing); smoothV.y = Mathf.Lerp(smoothV.y, mouseDelta.y, 1f / smoothing); mouseLook += smoothV; mouseLook.y = Mathf.Clamp(mouseLook.y, -90, 90); // Move the camera and character if(-mouseLook.y > 90) { transform.localRotation = Quaternion.AngleAxis(90, Vector3.right); } else if(-mouseLook.y < -90) { transform.localRotation = Quaternion.AngleAxis(-90, Vector3.right); } else { transform.localRotation = Quaternion.AngleAxis(-mouseLook.y, Vector3.right); } character.transform.localRotation = Quaternion.AngleAxis(mouseLook.x, character.transform.up); } } <file_sep>/UnityProject/Assets/Scripts/EnemyChase.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class EnemyChase : MonoBehaviour { private bool isDone = false; private bool isActive = false; public GameObject player; public float speed = 2.0f; public RuntimeAnimatorController animWalk; public RuntimeAnimatorController animEat; [Header("UI Stuff")] public Text t; // Sound stuff [Header("Sound Stuff")] public AudioSource teleportSound; public AudioSource endGameSound; public AudioSource winGameSound; // Update is called once per frame void Update() { speed = player.GetComponent<PlayerBread>().HowManyBreadsHaveYouEatenInYourLife; if(!isActive) { if(player.GetComponent<PlayerBread>().HowManyBreadsHaveYouEatenInYourLife > 0) { isActive = true; } } if(isActive) { if(!isDone) { // Move our position a step closer to the target. float step = speed * Time.deltaTime; // calculate distance to move transform.position = Vector3.MoveTowards(transform.position, player.transform.position, step); // Make birb look at the player transform.LookAt(player.transform); } // Layer for the line cast int layermask = 1 << 8; layermask = ~layermask; // Check dist between birb and player var dist = Vector3.Distance(transform.position, player.transform.position); // Draw the sightline debug Debug.DrawLine(transform.position, player.transform.position, Color.red, 0.0f); // Teleport the birb if conditions are met if (dist > 15f && Physics.Linecast(transform.position, player.transform.position, layermask)) { int q = HSRandom.Next(10); if(q==0) { transform.position = player.transform.position + (player.transform.forward * 7f); } else { transform.position = player.transform.position - (player.transform.forward * 7); } teleportSound.Play(0); } if (dist < 7) { this.GetComponentInChildren<Animator>().runtimeAnimatorController = animEat as RuntimeAnimatorController; } else { this.GetComponentInChildren<Animator>().runtimeAnimatorController = animWalk as RuntimeAnimatorController; } } } void OnCollisionEnter(Collision collision) { if(collision.gameObject.tag == "Player") { if(player.GetComponent<PlayerBread>().HasEnough()) { // Good end t.text = "You Win"; winGameSound.Play(0); StartCoroutine(EndGame(8)); } else { // Bad end t.text = "You Lose"; isDone = true; player.transform.LookAt(transform); endGameSound.Play(0); StartCoroutine(EndGame(13)); } } IEnumerator EndGame(int x) { yield return new WaitForSeconds(x); Cursor.lockState = CursorLockMode.None; SceneManager.LoadScene("menuScene"); } } } <file_sep>/UnityProject/Assets/Scripts/PlayerMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { // Variables to be used public float speed = 10.0f; public float forward; public float strafe; private float vvel = 0f; private bool iscol = true; private bool ismov = false; private bool isActive = true; [Header("Sound Stuff")] public AudioSource walksound; void OnCollisionEnter(Collision collision) { //if hitting the floor if (collision.gameObject.tag == "ground") { //do not lmao iscol = true; vvel = 0f; } else if(collision.gameObject.tag == "BadBoy") { isActive = false; } } // Start is called before the first frame update void Start() { // Turn off cursor Cursor.lockState = CursorLockMode.Locked; } // Update is called once per frame void Update() { if(isActive) { bool prevmov = ismov; // Movement forward = Input.GetAxis("Vertical") * speed * Time.deltaTime; strafe = Input.GetAxis("Horizontal") * speed * Time.deltaTime; ismov = forward != 0 || strafe != 0; transform.Translate(strafe, 0, forward); if (Input.GetKeyDown("escape")) { // turn on the cursor Cursor.lockState = CursorLockMode.None; } else if (Input.GetKeyDown("space") && vvel == 0) { vvel = 0.2f; iscol = false; } if (!iscol) { //decrease vertical velocity vvel -= 0.0075f; transform.Translate(0, vvel, 0); } if (prevmov != ismov && ismov) walksound.Play(0); else if (prevmov != ismov) walksound.Stop(); } } } <file_sep>/UnityProject/Assets/Scripts/MenuLight.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class MenuLight : MonoBehaviour { private bool on = false; public AudioSource a; // Update is called once per frame void Update() { var q = HSRandom.Next(10); if(q==0) { on = !on; if(on) { a.Play(0); } else { a.Stop(); } } if(on) { GetComponent<Light>().intensity = 7; } else { GetComponent<Light>().intensity = 0; } } }
8be8c5acee98cb53e5a8f7f54042a8d6d07d9615
[ "C#" ]
6
C#
hypernova-studios/ShantyJam4
1981f349dd5cf04304ee52446aa40b8cb0de6968
6ad519670310e027684abee47623643e6bb9000d
refs/heads/master
<file_sep>{% extends "base.html" %} {% block title %}{{title}} - Online invest dictionary{% endblock %} {% block dict %} <script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/json/json-min.js"></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.7.0/build/connection/connection-min.js"></script> <script type="text/javascript"> </script> <div style="text-align:center;height:400px"> <input type="text" name="search_term" id="search_term" style="width:300px"> <input type="button" value="Search"> <div id="result"> </div> </div> {% endblock %} <file_sep># !/usr/bin/env python # # Copyright 2008 CPedia.com. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = '<NAME>' import cgi import wsgiref.handlers import os import re import datetime import calendar import logging import string import urllib import traceback from xml.etree import ElementTree from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.api import memcache from google.appengine.ext import search from google.appengine.api import images from google.appengine.api import mail from cpedia.dict.handlers import restful import cpedia.dict.models.dict as models from cpedia.utils import utils import simplejson import authorized import view import config import sys import urllib from google.appengine.api import urlfetch from BeautifulSoup import BeautifulSoup class BaseRequestHandler(webapp.RequestHandler): """Supplies a common template generation function. When you call generate(), we augment the template variables supplied with the current user in the 'user' variable and the current webapp request in the 'request' variable. """ def generate(self, template_name, template_values={}): values = { #'archiveList': util.getArchiveList(), } values.update(template_values) view.ViewPage(cache_time=0).render(self, template_name, values) def generate_dictionary(self,alphabetical): try: terms_page = urlfetch.fetch( url="http://www.investopedia.com/terms/%s/?viewed=1" % alphabetical, method=urlfetch.GET, headers={'Content-Type': 'text/html; charset=UTF-8'} ) terms = [] if terms_page.status_code == 200: term_soap = BeautifulSoup(terms_page.content) term_span = term_soap.find("span",id="Span1") links = term_span.findAll("a") for link in links: term = models.Terms(alphabetical="#") term.term = utils.utf82uni(str(link.contents[0])) url_quote = link.get("href").replace(".asp","").replace("/terms/","").split("/") url_quote_len = len(url_quote) if url_quote_len > 2: term.category = url_quote[0] term.alphabetical = url_quote[url_quote_len-2] term.term_url_quote = url_quote[url_quote_len-1] term_ = models.Terms.gql('where term_url_quote =:1',term.term_url_quote).fetch(10) if term_ and len(term_) > 0: pass else: terms+=[term] for term in reversed(terms): term.put() template_values = { "msg":"Generate dictionary terms from investopedia.com successfully.", } except Exception, exception: mail.send_mail(sender="invest.cpedia.com <<EMAIL>>", to="<NAME> <<EMAIL>>", subject="Something wrong with the dictionary terms Generation Job.", body=""" Hi Ping, Something wroing with the dictionary terms Generation Job. Below is the detailed exception information: %s Please access app engine console to resolve the problem. http://appengine.google.com/a/cpedia.com Sent from invest.cpedia.com """ % traceback.format_exc()) template_values = { "msg":"Generate dictionary terms from investopedia.com unsuccessfully. An alert email sent out.<br>" + traceback.format_exc(), } self.generate('dict.html',template_values) def generate_category(self): try: terms_page = urlfetch.fetch( url="http://www.investopedia.com/dictionary/default.asp?viewed=1", method=urlfetch.GET, headers={'Content-Type': 'text/html; charset=UTF-8'} ) categories = [] if terms_page.status_code == 200: term_soap = BeautifulSoup(terms_page.content) term_span = term_soap.find("div",attrs={"class":"dictionarycategories"}) links = term_span.findAll("a") for link in links: category = models.Category() category.category = utils.utf82uni(str(link.contents[0])) url_quote = link.get("href").replace(".asp","").replace("/categories/","") category.category_url_quote = url_quote category_ = models.Category.gql('where category_url_quote =:1',url_quote).fetch(10) if category_ and len(category_) > 0: pass else: categories+=[category] for category in reversed(categories): category.put() template_values = { "msg":"Generate dictionary categories from investopedia.com successfully.", } except Exception, exception: mail.send_mail(sender="invest.cpedia.com <<EMAIL>>", to="<NAME> <<EMAIL>>", subject="Something wrong with the dictionary categories Generation Job.", body=""" Hi Ping, Something wroing with the dictionary categories Generation Job. Below is the detailed exception information: %s Please access app engine console to resolve the problem. http://appengine.google.com/a/cpedia.com Sent from invest.cpedia.com """ % traceback.format_exc()) template_values = { "msg":"Generate dictionary categories from investopedia.com unsuccessfully. An alert email sent out.<br>" + traceback.format_exc(), } self.generate('dict.html',template_values) class NotFoundHandler(webapp.RequestHandler): def get(self): self.error(404) view.ViewPage(cache_time=36000).render(self,"notfound.html") class UnauthorizedHandler(webapp.RequestHandler): def get(self): self.error(403) view.ViewPage(cache_time=36000).render(self,"unauthorized.html") class MainPage(BaseRequestHandler): def get(self): user = users.get_current_user() template_values = { } self.generate('dict.html',template_values) class GetTermsJob(BaseRequestHandler): def get(self): #if self.get("X-AppEngine-Cron")=="true": self.generate_dictionary("1") def post(self): self.get() class GetTermsJobAtoZ(BaseRequestHandler): def get(self,alphabetical): #if self.get("X-AppEngine-Cron")=="true": self.generate_dictionary(alphabetical) class GetCategories(BaseRequestHandler): def get(self): #if self.get("X-AppEngine-Cron")=="true": self.generate_category() <file_sep># !/usr/bin/env python # # Copyright 2008 CPedia.com. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = '<NAME>' import wsgiref.handlers from google.appengine.ext import webapp import logging import os import config from cpedia.dict.handlers import dict from cpedia.dict.handlers import rpc from google.appengine.ext.webapp import template template.register_template_library('cpedia.filter.replace') template.register_template_library('cpedia.filter.gravatar') # Force Django to reload its settings. #from django.conf import settings #settings._target = None # Must set this env var before importing any part of Django #os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' def main(): application = webapp.WSGIApplication( [ ('/json/([-\w\.]+)/*$', rpc.RPCHandler), ('/403.html', dict.UnauthorizedHandler), ('/404.html', dict.NotFoundHandler), ('/tasks/getterms/*$', dict.GetTermsJob), ('/tasks/getterms/([-\w\.]+)/*$', dict.GetTermsJobAtoZ), ('/tasks/getcategories/*$', dict.GetCategories), ('/*$', dict.MainPage), ], debug=config.DEBUG) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main() <file_sep># !/usr/bin/env python # # Copyright 2008 CPedia.com. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = '<NAME>' import os import logging import datetime import simplejson import wsgiref.handlers from google.appengine.api import datastore from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.api import memcache from google.appengine.api import images from google.appengine.ext import db import cpedia.dict.models.dict as models import authorized import config # This handler allows the functions defined in the RPCHandler class to # be called automatically by remote code. class RPCHandler(webapp.RequestHandler): def get(self,action): arg_counter = 0; args = [] while True: arg = self.request.get('arg' + str(arg_counter)) arg_counter += 1 if arg: args += (simplejson.loads(arg),); else: break; result = getattr(self, action)(*args) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(simplejson.dumps((result))) def post(self,action): request_ = self.request result = getattr(self, action)(request_) self.response.headers['Content-Type'] = 'application/json' self.response.out.write(simplejson.dumps((result))) # The RPCs exported to JavaScript follow here: @authorized.role('admin') def getDeals(self,startIndex,results): query = db.Query(models.Deals) query.order('-created_date') deals = [] for deal in query.fetch(results,startIndex): deals+=[deal.to_json()] totalRecords = query.count() returnValue = {"records":deals,"totalRecords":totalRecords,"startIndex":startIndex} return returnValue <file_sep># !/usr/bin/env python # # Copyright 2009 CPedia.com. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = '<NAME>' import pickle from google.appengine.ext import db from google.appengine.ext.db import polymodel from google.appengine.ext import search from google.appengine.api import memcache import logging import datetime import urllib import cgi import simplejson import config from cpedia.dict import models class User(models.SerializableModel): user = db.UserProperty(required=True) user_id = db.StringProperty(multiline=False) date_joined = db.DateTimeProperty(auto_now_add=True) last_syn_time = db.DateTimeProperty() def put(self): memcache.delete("user_"+self.user.user_id()) self.user_id = self.user.user_id() super(User, self).put() class Tag(models.SerializableModel): user = db.UserProperty(required=True) user_id = db.StringProperty(multiline=False) tag = db.StringProperty(multiline=False) entrycount = db.IntegerProperty(default=0) valid = db.BooleanProperty(default = True) def put(self): memcache.delete("tag_"+str(self.user.email())) self.user_id = self.user.user_id() super(Tag, self).put() class Tagable(models.MemcachedModel): tags = db.ListProperty(db.Category) def get_tags(self): '''comma delimted list of tags''' return ','.join([urllib.unquote(tag.encode('utf8')) for tag in self.tags]) def set_tags(self, tags): if tags: self.tags = [db.Category(urllib.quote(tag.strip().encode('utf8'))) for tag in tags.split(',') if tag.strip()!=''] tags_commas = property(get_tags,set_tags) class Category(models.MemcachedModel): category = db.StringProperty(multiline=False) category_lowercase = db.StringProperty(multiline=False) category_url_quote = db.StringProperty(multiline=False) created_date = db.DateTimeProperty(auto_now_add=True) last_updated_date = db.DateTimeProperty(auto_now=True) last_updated_user = db.UserProperty(auto_current_user=True) def put(self): self.category_lowercase = self.category.lower() super(Category, self).put() class Terms(models.MemcachedModel): alphabetical = db.StringProperty() #a-z category = db.StringProperty() term = db.StringProperty(multiline=False) term_lowercase = db.StringProperty(multiline=False) term_url_quote = db.StringProperty(multiline=False) explains = db.StringProperty() investopedia_explains = db.StringProperty() created_date = db.DateTimeProperty(auto_now_add=True) last_updated_date = db.DateTimeProperty(auto_now=True) last_updated_user = db.UserProperty(auto_current_user=True) def put(self): self.term_lowercase = self.term.lower() super(Terms, self).put() class SearchHistory(models.MemcachedModel): user = db.UserProperty(required=True,auto_current_user_add=True) user_id = db.StringProperty(multiline=False) term = db.StringProperty(multiline=False) term_url_quote = db.StringProperty(multiline=False) created_date = db.DateTimeProperty(auto_now_add=True) class UserNewWords(models.MemcachedModel): user_id = db.StringProperty(multiline=False) term = db.StringProperty(multiline=False) term_lowercase = db.StringProperty(multiline=False) term_url_quote = db.StringProperty(multiline=False) created_date = db.DateTimeProperty(auto_now_add=True) def put(self): self.term_lowercase = self.term.lower() super(UserNewWords, self).put() class Comment(models.MemcachedModel): user = db.UserProperty(required=True,auto_current_user_add=True) user_id = db.StringProperty(multiline=False) content = db.StringProperty() created_date = db.DateTimeProperty(auto_now_add=True) last_updated_date = db.DateTimeProperty(auto_now=True) last_updated_user = db.UserProperty() term = db.ReferenceProperty(Terms) def put(self): self.user_id = self.user.user_id() super(Comment, self).put() class AuthSubStoredToken(db.Model): user_email = db.StringProperty(required=True) target_service = db.StringProperty(multiline=False,default='base',choices=[ 'apps','base','blogger','calendar','codesearch','contacts','docs', 'albums','spreadsheet','youtube']) session_token = db.StringProperty(required=True)
9ad33f1d55b8c0663d6cf63b9c0505ddb376fb64
[ "Python", "HTML" ]
5
HTML
walleleung/hedge-fund
eeeffb30a20635a8f1442c1d953537bf918a64da
ad5b470839b310a25050ff7bb3c07b46effbaecc
refs/heads/master
<file_sep># -*- coding: utf-8 -*- """ Created on Fri Mar 22 18:16:57 2019 https://blog.naver.com/rickman2/221337023577 https://radimrehurek.com/gensim/wiki.html#latent-dirichlet-allocation http://www.engear.net/wp/topic-modeling-gensimpython/ https://lovit.github.io/nlp/2018/09/27/pyldavis_lda/ @author: admin """ import os DATA_PATH = os.getcwd().replace('\\','/') RESULT_PATH = DATA_PATH + "/result/" import warnings warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim') #gensim경고문삭제 from konlpy.tag import Komoran from gensim import corpora, models, similarities from pprint import pprint from gensim.models.coherencemodel import CoherenceModel engin = Komoran() doc_list = [] #문서를 저장하는 공간 doc_dic = [] # 문서별 단어 파싱을 저장 noun + #doc_list = ('2018.000123.123', ''안녕', [('1',''SY),('안녕',NNG)]) #doc_dic = [(''','SY'),('안녕','NNG')] def doc_pos_tokenizer(doc_pos): doc_pos_ryu = [] for item in doc_pos: if item[1] in {'NNG', 'NNP', 'SL'} : #doc_pos_ryu.append(item[0]+"_"+item[1]) doc_pos_ryu.append(item[0]) return doc_pos_ryu import csv import pandas as pd import matplotlib.pyplot as plt if __name__ == "__main__": f = open(RESULT_PATH + "minwon.txt", 'r', encoding="UTF-8") row_data = f.read().replace(",", " ").replace("부산",'').replace("부산시",'') row_data = row_data.replace("\n", ',').replace(",,",",").replace(",,,",",").replace('\ufeff','').split(',') data = csv.reader(row_data) num_row = 0 for row in data: doc_pos = engin.pos(row[0]) doc_pos = doc_pos_tokenizer(doc_pos) doc_info = (row[0], doc_pos) doc_list.append(doc_info) doc_dic.append(doc_pos) num_row += 1 print("{}번째 문장 명사 개수 : ".format(num_row) + str(len(doc_pos))) print("총 문장 개수 : " + str(len(doc_dic))) print("head : " + "< " + row_data[0] + " >") print('\n'+"="*75) #n그램모델 https://wikidocs.net/21692 bigram = models.Phrases(doc_dic, min_count=5, threshold=100) trigram = models.Phrases(bigram[doc_dic], threshold=100) bigram_mod = models.phrases.Phraser(bigram) trigram_mod = models.phrases.Phraser(trigram) doc_dic_bi_tri = [] for i in range(0, len(doc_dic)): doc_dic_bi_tri.append(trigram_mod[bigram_mod[doc_dic[i]]]) dictionary = corpora.Dictionary(doc_dic_bi_tri) dictionary.save('dictionary.dict') corpus = [dictionary.doc2bow(a_doc_dic_bi_tri) for a_doc_dic_bi_tri in doc_dic_bi_tri] corpora.MmCorpus.serialize('corpora.mm', corpus) # tfidf = models.TfidfModel(corpus) # corpus_tfidf = tfidf[corpus] print("\n※※※ 한국어텍스트전처리와 n그램모델화가 완료되었습니다. ※※※") ########################################################################################################### ml = [] numl = [] q0 = str(input("Q. LDA 정확도 계산을 진행하시겠습니까? 시간이 오래걸립니다. (y/n) : ")) if q0 == 'y' : print("\nA. LDA 정확도 계산을 시작합니다. 시간이 오래걸립니다.(10부터 200까지 20단위)") print("수치가 낮을수록 정확합니다.\n") for num in range(10,150, 20): lda_model = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics = num, random_state=100, update_every=1, chunksize=2000, passes=10, eval_every = 10, alpha="auto", eta=None, per_word_topics=True, iterations = 1000) m = lda_model.log_perplexity(corpus) print("토픽 " + str(num) + '개 Perplexity : ', m) # https://swenotes.wordpress.com/tag/nlp/ ml.append(m) numl.append(num) plt.plot(numl, ml) plt.xlabel('K') plt.ylabel('Perplexity') plt.grid(True) plt.show() ########################################################################################################### print("\n※※※ LDA/HDP분석을 시작합니다. ※※※\n") topic_num_LDA = int(input("LDA토픽개수 : ")) # LDA 토픽 개수 topic_num_HDP = int(input("HDP토픽개수 : ")) # HDP 토픽 개수 / -1을 입력 => T_max_num_of_HDP의 값 word_num = int(input("LDA/HDP단어개수 : ")) #단어 개수 T_max_num_of_HDP = 200 # HDP 최대 토픽 개수 ########################################################################################################### print("\n"+"="*25 + "LDA 모델링" + "="*25) lda_model = models.ldamodel.LdaModel(corpus=corpus, id2word=dictionary, num_topics = topic_num_LDA, random_state=100, update_every=1, chunksize=2000, passes=10, alpha="auto", per_word_topics=True, iterations = 1000) print() m = lda_model.log_perplexity(corpus) print(str(topic_num_LDA)+'개 토픽 Perplexity: ', m) # def get_topic_term_prob(lda_model): # topic_term_freqs = lda_model.state.get_lambda() # topic_term_prob = topic_term_freqs / topic_term_freqs.sum(axis=1)[:, None] # return topic_term_prob # # topic_term_prob = get_topic_term_prob(lda_model) # print(topic_term_prob[0].sum()) # print(topic_term_prob.shape) # (n_topics, n_terms) topic_num_LDA = int(input("총 {}개 토픽 중 나타낼 토픽 개수 : ".format(topic_num_LDA))) word_num = int(input("총 {}개 단어 중 나타낼 단어 개수 : ".format(word_num))) lda_topic = lda_model.print_topics(num_topics = topic_num_LDA, num_words = word_num) df0 = pd.DataFrame(lda_topic) df0.columns = ['x', 'result'] del df0['x'] print(df0 + "\n") xlsx_name = RESULT_PATH + 'LDA_result' + '.xlsx' df0.to_excel(xlsx_name, encoding='utf-8') print("\n") ########################################################################################################### print("="*25 + "HDP 모델링" + "="*25) hdp_model = models.hdpmodel.HdpModel(corpus=corpus, id2word=dictionary, max_chunks=None, max_time=None, chunksize=256, kappa=1.0, tau=64.0, K=15, T = T_max_num_of_HDP, alpha=1, gamma=1, eta=0.01, scale=1.0, var_converge=0.0001, outputdir=None, random_state=100) topic_num_HDP = int(input("총 {}개 토픽 중 나타낼 토픽 개수 : ".format(topic_num_HDP))) word_num = int(input("총 {}개 단어 중 나타낼 단어 개수 : ".format(word_num))) hdp_topic = hdp_model.print_topics(num_topics = topic_num_HDP, num_words = word_num) df1 = pd.DataFrame(hdp_topic) df1.columns = ['x', 'result'] del df1['x'] print(df1) xlsx_name = RESULT_PATH + 'HDP_result' + '.xlsx' df1.to_excel(xlsx_name, encoding='utf-8') ########################################################################################################### ''' # 시각화 코드 입니다. 위의 코드부터 이 코드까지 복사 한 후 쥬피터에서 실행시켜야합니다. # pip install pyldavis import pyLDAvis.gensim pyLDAvis.enable_notebook() pyLDAvis.gensim.prepare(lda_model, corpus, dictionary) ''' # 글자만 추출하는 코드입니다. 수정 절대 하면 안됩니다. ======================== # for topic in lda_model.show_topics(num_topics = num0, num_words = num1): # words = '' # for word, prob in lda_model.show_topic(topic[0], topn = num1): # words += word + ' ' # lda_topic = 'Topic{}: '.format(topic[0]) + words # print(lda_topic) # print() # i += 1 #===================================================================================
db8e3f168566c0fd859a9ee2a4e276c5b4d7c4b2
[ "Python" ]
1
Python
sschoi2427/Korean_LDA_HDP
87e31f65ad6d2cb8fb57918d61ce28c731feff6b
0ff209b1913cad7ba6f13688f46243a51163b415
refs/heads/master
<repo_name>aqurilla/faceswap-tps-dl<file_sep>/README.md # FaceSwap using Thin Plate Splines and Neural Nets This project implements face-swapping using two approaches - a traditional geometric approach using thin plate splines for face warping, and secondly using [PRNet](https://github.com/YadiraF/PRNet). ![rambo](https://github.com/aqurilla/faceswap-tps-dl/blob/master/Data/images/ramboTPS1.jpg) ## With TPS approach `WrapperTPS.py` contains code to run face-swapping using the thin plate spline technique for warping ### Running the program The program takes the following command line arguments- ``` --predictorpath = Path to the dlib landmarks predictor --videofilepath = Path to video file to be edited --image2filepath = Path to image in case of single face swap --swapmode = Single (single face with image) or double (two faces in the same video) --outputfilepath = Filepath to store output video --simulateframe = To toggle frame simulation for flickering ``` e.g. Swapping two faces in single video `$ python WrapperTPS.py --swapmode=2 --videofilepath='../Data/video1.mp4'` e.g. Swapping single face in video with face from image file `$ python WrapperTPS.py --swapmode=1 --videofilepath='../Data/video1.mp4' --image2filepath='../Data/TestSet_P2/Rambo.jpg'` ## With PRNet approach `WrapperPRNet.py` contains code to run face-swapping using PRNet. The net model first has to be downloaded and placed into `Code/Data/net-data/`, as mentioned on the [PRNet page](https://github.com/YadiraF/PRNet). ### Running the program The program takes the following command line arguments, ``` --videofilepath = Path to video that is to be modified --ref_path = Path to image, for single face swapping face from image to a video --outputfilepath = Path to write output video --mode = 1: for single face swap, 2: for double face swap using faces in a single video --gpu = to set GPU id ``` e.g. `$ python WrapperPRNet.py` <file_sep>/utils.py #!/usr/bin/evn python """ Utility functions for TPS faceswap Author: <NAME> ECE - UMD """ # Imports import numpy as np import cv2 import dlib import argparse import pdb def shape_to_np(shape, dtype="int"): # Return landmarks as np-array # Using the 68-point landmark predictor coords = np.zeros((68, 2), dtype=dtype) for i in range(0, 68): coords[i] = (shape.part(i).x, shape.part(i).y) return coords def rect_to_bb(rect): # take a bounding predicted by dlib and convert it # to the format (x, y, w, h) x = rect.left() y = rect.top() w = rect.right() - x h = rect.bottom() - y return (x, y, w, h) def Ufunc(r): # U function from TPS equation return r*r*np.where(r==0,0.001,np.log(r)) def TPSfunc(x,y,P,soln): # Returns the f value calculated in TPS point_sum = np.zeros(x.shape) for (i,pi) in enumerate(P): point_sum += soln[i]*Ufunc(np.sqrt( (x-pi[0])**2 + (y-pi[1])**2 )) return (soln[-1] + soln[-2]*y + soln[-3]*x + point_sum) def swapTPS(orig_img, final_img, from_pts, to_pts): """ Swaps one face at a time orig_img - image containing both faces without modifications final_img - image to perform modifications to """ # Ignore log div by 0 error np.seterr(divide='ignore') n_features = to_pts.shape[0] lmbda = 10 # The original image is masked to only show the face region contained inside the convex hull img2 = maskConvex(orig_img, to_pts) # Soln contains the TPS equation coefficients for x and y coordinates soln = solveTPS(from_pts, to_pts, n_features, lmbda) # Determine region from which face should be extracted (nrows, ncols) = orig_img.shape[:2] xmin = np.min(from_pts[:,0]) xmax = np.max(from_pts[:,0]) ymin = np.min(from_pts[:,1]) ymax = np.max(from_pts[:,1]) xlin = np.arange(xmin, xmax, 1) ylin = np.arange(ymin, ymax, 1) warped_img = np.full((orig_img.shape[0], orig_img.shape[1], 3), 0, dtype=np.uint8) warped_mask = np.full((orig_img.shape[0], orig_img.shape[1], 3), 0, dtype=np.uint8) for x in xlin: for y in ylin: warp_x = TPSfunc(x, y, from_pts, soln[:,0]) warp_y = TPSfunc(x, y, from_pts, soln[:,1]) if warp_x>0 and warp_x<ncols and warp_y>0 and warp_y<nrows: if img2[int(warp_y), int(warp_x), 0] != 0: warped_img[int(y), int(x), :] = img2[int(warp_y), int(warp_x), :] warped_mask[int(y), int(x), :] = (255,255,255) # Blend the images using seamlessClone cv2 function center_p = (int((xmin+xmax)/2), int((ymin+ymax)/2)) blended_img = cv2.seamlessClone(warped_img, final_img, warped_mask, center_p, cv2.NORMAL_CLONE) return blended_img def maskConvex(orig_img, to_pts): # Find convex hull of these points to extract face region mask_img = np.full((orig_img.shape[0], orig_img.shape[1]), 0, dtype=np.uint8) hullPoints = cv2.convexHull(to_pts) cv2.fillConvexPoly(mask_img, hullPoints, (255,255,255)) mask_img = np.dstack((mask_img, mask_img, mask_img)) return cv2.bitwise_and(orig_img, mask_img) def solveTPS(from_pts, to_pts, n_features, lmbda): # Formulate TPS equation, follows notation from project statement K = np.zeros((n_features, n_features), dtype=np.float32) P = np.ones((n_features, 3), dtype=np.float32) V = np.zeros((n_features+3, 2), dtype=np.float32) xarr = np.subtract.outer(from_pts[:,0], from_pts[:,0]) yarr = np.subtract.outer(from_pts[:,1], from_pts[:,1]) K = Ufunc(np.sqrt(xarr**2 + yarr**2)) # Pi = [xi, yi, 1] P[:,:2] = from_pts # V is the required output, i.e. to_pts V[:n_features] = to_pts K_mat_p1 = np.concatenate((K, P), axis=1) K_mat_p2 = np.concatenate((np.transpose(P), np.zeros((3,3), dtype=np.float32)), axis=1) K_mat = np.concatenate((K_mat_p1, K_mat_p2), axis=0) iden_mat = lmbda*np.identity(n_features+3) inv_mat = np.linalg.pinv(K_mat+iden_mat) # Solve TPS for x-coordinates and y-coordinates return np.dot(inv_mat, V) def dispLandmarks(img, rects, predictor): # Display facial landmarks in the image landmarks_img = img for (i, rect) in enumerate(rects): shape = predictor(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), rect) shape = shape_to_np(shape) (x,y,w,h) = rect_to_bb(rect) if i==0: cv2.rectangle(landmarks_img, (x,y), (x+w, y+h), (0,255,0), 2) else: cv2.rectangle(landmarks_img, (x,y), (x+w, y+h), (255,0,0), 2) for (x,y) in shape: cv2.circle(landmarks_img, (x,y), 1, (0,0,255), -1) cv2.imshow("Detected landmarks", landmarks_img) def imgResize(img, fcols=512): # Resize image to have specified width fcols (rows, cols) = img.shape[:2] frows = int((fcols/cols)*rows) return cv2.resize(img, (fcols, frows), interpolation=cv2.INTER_CUBIC) def processPoints(to_pts, from_pts, to_ptsArray, from_ptsArray, n_features, dwnsamp_factor, idx): # Convert to np-arrays and downsample to_pts = shape_to_np(to_pts) from_pts = shape_to_np(from_pts) to_ptsArray = np.append(to_ptsArray, to_pts.reshape((1,n_features*2)), axis=0) from_ptsArray = np.append(from_ptsArray, from_pts.reshape((1,n_features*2)), axis=0) if idx>2: to_ptsArray = to_ptsArray[-2:,:] inter_to_pts = np.mean(to_ptsArray, axis=0, dtype=int).reshape((n_features, 2)) from_ptsArray = from_ptsArray[-2:,:] inter_from_pts = np.mean(from_ptsArray, axis=0, dtype=int).reshape((n_features, 2)) inter_to_pts = inter_to_pts[::dwnsamp_factor] inter_from_pts = inter_from_pts[::dwnsamp_factor] else: inter_to_pts = to_pts[::dwnsamp_factor] inter_from_pts = from_pts[::dwnsamp_factor] to_pts = to_pts[::dwnsamp_factor] from_pts = from_pts[::dwnsamp_factor] return (to_pts, from_pts, to_ptsArray, from_ptsArray, inter_to_pts, inter_from_pts) <file_sep>/WrapperTPS.py #!/usr/bin/evn python """ CMSC733 Spring 2019: Classical and Deep Learning Approaches for Geometric Computer Vision Project 2: FaceSwap Phase 1 Wrapper code References: https://www.pyimagesearch.com/2017/04/03/facial-landmarks-dlib-opencv-python/ Author: <NAME> ECE - UMD """ # Code starts here: # Imports import numpy as np import cv2 import dlib import argparse import pdb from utils import * def main(): # Add any Command Line arguments here Parser = argparse.ArgumentParser() Parser.add_argument('--predictorpath', default='../Model/shape_predictor_68_face_landmarks.dat', help='dlib face landmarks predictor') Parser.add_argument('--videofilepath', default='../Data/video1.mp4', help='Path to video file') Parser.add_argument('--image2filepath', default='../Data/TestSet_P2/Rambo.jpg', help='Path to image file for single faceswap') Parser.add_argument('--swapmode', default=2, help='Mode for performing swap: 1 for single faceswap, 2 for double faceswap') Parser.add_argument('--outputfilepath', default='../Output/doublefaceswap.avi', help='Path to write output video') Parser.add_argument('--simulateframe', default=0, help='1: Frame simulation to improve flickering, 0: No frame simulation') Args = Parser.parse_args() predictorpath = Args.predictorpath videofilepath = Args.videofilepath image2filepath = Args.image2filepath swapmode = int(Args.swapmode) outputfilepath = Args.outputfilepath simulateframe = int(Args.simulateframe) # Setup dlib detector and predictor detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(predictorpath) # Specify factor by which to downsample landmarks points (originally 68 points) dwnsamp_factor = 2 n_features = 68 if simulateframe: fps_rate = 60 else: fps_rate = 30 # Initialize video reader and writer objects cap = cv2.VideoCapture(videofilepath) ret, img = cap.read() resized_img = imgResize(img, 512) # Rotate image if required # resized_img = cv2.rotate(resized_img, cv2.ROTATE_90_CLOCKWISE) (frame_height,frame_width) = resized_img.shape[:2] out = cv2.VideoWriter(outputfilepath, cv2.VideoWriter_fourcc('M','J','P','G'), fps_rate, (frame_width,frame_height)) # For frame simulation idx=0 to_ptsArray = np.zeros((1,n_features*2)) from_ptsArray = np.zeros((1,n_features*2)) while(cap.isOpened()): ret, img = cap.read() if ret==True: idx += 1 # Resize image to specified width img = imgResize(img, 512) # Rotate image if required # img = cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE) if swapmode==1: """ Swap a single face from the video, with a face from a second image """ cimg = cv2.imread(image2filepath) # Resize image to specified width cimg = imgResize(cimg, 512) # Detect faces in both the images rects1 = detector(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 1) rects2 = detector(cv2.cvtColor(cimg, cv2.COLOR_BGR2GRAY), 1) # Swap if atleast 1 face detected in both images if rects1 and rects2: to_pts = predictor(cv2.cvtColor(cimg, cv2.COLOR_BGR2GRAY), rects2[0]) from_pts = predictor(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), rects1[0]) to_pts, from_pts, to_ptsArray, from_ptsArray, inter_to_pts, inter_from_pts = \ processPoints(to_pts, from_pts, to_ptsArray, from_ptsArray, n_features, dwnsamp_factor, idx) # Swap face from second image into the first image output_img = swapTPS(cimg, img, from_pts, to_pts) if idx>2 and simulateframe: # Simulating frames for reducing flickering intermediate_img = swapTPS(cimg, img, inter_from_pts, inter_to_pts) else: # If both faces are not detected, return original image output_img = img if idx>2 and simulateframe: intermediate_img = img else: """ Swap both faces in a single image """ # Detect faces in the image rects = detector(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), 1) # dispLandmarks(img, rects, predictor) # Perform faceswap only if more than 1 face is detected in the image if len(rects)>1: to_pts = predictor(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), rects[0]) from_pts = predictor(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), rects[1]) to_pts, from_pts, to_ptsArray, from_ptsArray, inter_to_pts, inter_from_pts = \ processPoints(to_pts, from_pts, to_ptsArray, from_ptsArray, n_features, dwnsamp_factor, idx) # Perform one swap at a time, interchanging the points for the second swap output1 = swapTPS(img, img, from_pts, to_pts) output_img = swapTPS(img, output1, to_pts, from_pts) if idx>2 and simulateframe: # Simulating frames for reducing flickering intermediate_img1 = swapTPS(img, img, inter_from_pts, inter_to_pts) intermediate_img = swapTPS(img, intermediate_img1, inter_to_pts, inter_from_pts) else: # If only 1 face detected, return original image output_img = img if idx>2 and simulateframe: intermediate_img = img """ Filtering to improve motion flickering """ # Blur image to reduce flickering output_img = cv2.bilateralFilter(output_img, 9, 75, 75) if idx>2 and simulateframe: intermediate_img = cv2.bilateralFilter(intermediate_img, 9, 75, 75) """ Display output image and write to file """ # Display input image and final output image cv2.imshow("Original image", img) if idx>2 and simulateframe: cv2.imshow("Intermediate image", intermediate_img) cv2.imshow("Output image", output_img) cv2.waitKey(25) # Write both frames to video if idx>2 and simulateframe: out.write(intermediate_img) out.write(output_img) else: # When the video finishes break cap.release() out.release() cv2.destroyAllWindows() if __name__ == '__main__': main() <file_sep>/WrapperPRNet.py ''' Adapted from https://github.com/YadiraF/PRNet ''' import numpy as np import os from glob import glob import scipy.io as sio from skimage.io import imread, imsave from skimage.transform import rescale, resize from time import time import argparse import ast import matplotlib.pyplot as plt import argparse from misc.api import PRN from misc.render import render_texture import cv2 import pdb def texture_editing(prn, image, ref_image, mode, d, d_ref): [h, w, _] = image.shape """ Original texture """ #-- 1. 3d reconstruction -> get texture. pos = prn.process(image, d) vertices = prn.get_vertices(pos) image = image/255. texture = cv2.remap(image, pos[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT,borderValue=(0)) """ Reference texture """ #-- 2. Texture Editing # For double faceswap edit here to return ref_pos from the same image ref_pos = prn.process(ref_image, d_ref) ref_image = ref_image/255. ref_texture = cv2.remap(ref_image, ref_pos[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT,borderValue=(0)) ref_vertices = prn.get_vertices(ref_pos) new_texture = ref_texture#(texture + ref_texture)/2. """ Swap and blend image """ #-- 3. remap to input image.(render) vis_colors = np.ones((vertices.shape[0], 1)) face_mask = render_texture(vertices.T, vis_colors.T, prn.triangles.T, h, w, c = 1) face_mask = np.squeeze(face_mask > 0).astype(np.float32) new_colors = prn.get_colors_from_texture(new_texture) new_image = render_texture(vertices.T, new_colors.T, prn.triangles.T, h, w, c = 3) new_image = image*(1 - face_mask[:,:,np.newaxis]) + new_image*face_mask[:,:,np.newaxis] # Possion Editing for blending image vis_ind = np.argwhere(face_mask>0) vis_min = np.min(vis_ind, 0) vis_max = np.max(vis_ind, 0) center = (int((vis_min[1] + vis_max[1])/2+0.5), int((vis_min[0] + vis_max[0])/2+0.5)) output = cv2.seamlessClone((new_image*255).astype(np.uint8), (image*255).astype(np.uint8), (face_mask*255).astype(np.uint8), center, cv2.NORMAL_CLONE) # For double swap use this output as the image for second run, # and use copy of reference image return output # save output # imsave(output_path, output) # print('Done.') if __name__ == '__main__': parser = argparse.ArgumentParser(description='Texture Editing by PRN') #parser.add_argument('-i', '--image_path', default='TestImages/testvid2.jpg', type=str, # help='path to input image') # image containing face to swap out parser.add_argument('-r', '--ref_path', default='../Input/Rambo.jpg', type=str, help='path to reference image(texture ref)') # image containing face to swap in #parser.add_argument('-o', '--output_path', default='TestImages/output.jpg', type=str, # help='path to save output') parser.add_argument('--mode', default=1, type=int, help='1: single face swap, 2: double face swap') parser.add_argument('--gpu', default='0', type=str, help='set gpu id, -1 for CPU') parser.add_argument('--videofilepath', default='../Input/Test1.mp4', help='Path to video file') parser.add_argument('--outputfilepath', default='../Output/test1_output.avi', help='Path to write output video') # ---- init PRN os.environ['CUDA_VISIBLE_DEVICES'] = parser.parse_args().gpu # GPU number, -1 for CPU prn = PRN(is_dlib = True) # CHANGED - taking input from video # image = imread(parser.parse_args().image_path) # texture from another image or a processed texture ref_image = imread(parser.parse_args().ref_path) mode = int(parser.parse_args().mode) #output_path = parser.parse_args().output_path videofilepath = parser.parse_args().videofilepath outputfilepath = parser.parse_args().outputfilepath # Try with conversion ref_image = cv2.cvtColor(ref_image, cv2.COLOR_BGR2RGB) # Initialize video reader and writer objects cap = cv2.VideoCapture(videofilepath) ret, image = cap.read() (frame_height,frame_width) = image.shape[:2] out = cv2.VideoWriter(outputfilepath, cv2.VideoWriter_fourcc('M','J','P','G'), 30, (frame_width,frame_height)) idx = 0 if mode==1: # Get reference pos for single faceswap ref_detected_faces = prn.dlib_detect(ref_image) d_ref = ref_detected_faces[0].rect while(cap.isOpened()): ret, image = cap.read() if ret==True: if mode==1: detected_faces = prn.dlib_detect(image) if len(detected_faces)==0: # If no face is detected return the original image output = image else: d1 = detected_faces[0].rect # d2 = detected_faces[1].rect # output1 = texture_editing(prn, image, image, mode, output_path, d1, d2) output = texture_editing(prn, image, ref_image, mode, d1, d_ref) else: detected_faces = prn.dlib_detect(image) if len(detected_faces) < 2: # If only 1 face is detected return the original image output = image else: d1 = detected_faces[0].rect d2 = detected_faces[1].rect output1 = texture_editing(prn, image, image, mode, d1, d2) output = texture_editing(prn, output1, image, mode, d2, d1) out.write(output) print('Frame number: '+str(idx)) idx+=1 # cv2.imshow("Inputimage", image) # cv2.imshow("Output image", output) # cv2.waitKey(25) # imsave(output_path, output) # print('Done.') else: break print('Done') cap.release() out.release() cv2.destroyAllWindows()
9b30b3c88437ec5fabb23a260ce7da493a640524
[ "Markdown", "Python" ]
4
Markdown
aqurilla/faceswap-tps-dl
2b6f49965380b8d8ec566e36734541665b57774b
5b891ea743cea146c560f32cd1e23374e1e45316
refs/heads/master
<file_sep>from conans import ConanFile, CMake, tools, AutoToolsBuildEnvironment import os class WavpackConan(ConanFile): name = "wavpack" version = "5.1.0" description = "WavPack is a completely open audio compression format providing lossless, high-quality lossy, and a unique hybrid compression mode" url = "https://github.com/conanos/wavpack" license = "BSD_like" settings = "os", "compiler", "build_type", "arch" options = {"shared": [True, False]} default_options = "shared=True" generators = "cmake" source_subfolder = "source_subfolder" def source(self): url_ = 'https://github.com/dbry/WavPack/archive/%s.tar.gz'%(self.version) tools.get(url_) extracted_dir = "WavPack-" + self.version os.rename(extracted_dir, self.source_subfolder) def build(self): with tools.chdir(self.source_subfolder): self.run("autoreconf -f -i") autotools = AutoToolsBuildEnvironment(self) _args = ["--prefix=%s/builddir"%(os.getcwd()), "--disable-apps"] if self.options.shared: _args.extend(['--enable-shared=yes','--enable-static=no']) else: _args.extend(['--enable-shared=no','--enable-static=yes']) autotools.configure(args=_args) autotools.make(args=["-j4"]) autotools.install() def package(self): if tools.os_info.is_linux: with tools.chdir(self.source_subfolder): self.copy("*", src="%s/builddir"%(os.getcwd())) def package_info(self): self.cpp_info.libs = tools.collect_libs(self) <file_sep># wavpack WavPack is a completely open audio compression format providing lossless, high-quality lossy, and a unique hybrid compression mode http://www.wavpack.com/
445adcaa6e2f64fd25801e3ef227a813053a7156
[ "Markdown", "Python" ]
2
Python
conanos-mirror/wavpack
0e39f1fc50e1ac021804d31157de7d81c5341c97
7f90d0e8d20af10609de1388dff912eb2e968aee
refs/heads/master
<repo_name>ebrahims1902/NOC_Model<file_sep>/app.py from flask import Flask, render_template, request import pickle import numpy as np from numpy.core.numeric import outer app = Flask(__name__) model = pickle.load(open("NOC_MODEL.pkll", 'rb')) @app.route('/') def helloworld(): return render_template('home.html') @app.route('/predict', methods=['GET','POST']) def predict(): float_features = [np.float64(x) for x in request.form.values()] final = [np.array(float_features)] prediction = model.predict(final) return render_template('predict.html', pred=prediction) if __name__ == '__main__': app.run(debug=True)
70ce7a71f5a67c0aae43f521684bbaff4b158116
[ "Python" ]
1
Python
ebrahims1902/NOC_Model
d6133d290a37a87df53bf88b48f5b74beaca516b
3ece16165e692a1fb0105f2b57d817aad154b36d
refs/heads/master
<repo_name>3Rs-And-Scott/tutorial_sheepolution<file_sep>/README.md # tutorial_sheepolution This is the result of following a [love2d tutorial](http://sheepolution.com/learn/book/contents). You can spawn circles and rectangles that will move to the right. The rectangles will appear filled when they are colliding with the sheep. This was used as a learning example for myself. Controls -------- - `r` - spawn rectangle - `c` - spawn circle Installation ------- 1. Download and install [Love2D](https://love2d.org/) if you don't already have it. 2. Clone this repo with `git clone <EMAIL>:3Rs-And-Scott/tutorial_sheepolution.git`. 3. Run the game `open -n -a love tutorial_sheepolution - Running the game this way will not print text to your console. <file_sep>/rectangle.lua Rectangle = Shape:extend() function Rectangle:new(x, y, width, height) Rectangle.super.new(self, x, y) self.width = width self.height = height end function Rectangle:draw(collision) love.graphics.rectangle(self:mode(collision), self.x, self.y, self.width, self.height) end function Rectangle:mode(collision) if collision then return "fill" else return "line" end end <file_sep>/main.lua function love.load() Object = require "classic" require "shape" require "circle" require "rectangle" sheepImage = love.graphics.newImage("sheep.png") sheepLocation = { x = 100, y = 100, width = sheepImage:getWidth(), height = sheepImage:getHeight() } shapes = {} createRectangle() createCircle() end function love.update(dt) for key, shape in ipairs(shapes) do shape:update(dt) end end function love.draw() love.graphics.print("FPS: " .. love.timer.getFPS(), 10, 10) love.graphics.draw(sheepImage, sheepLocation.x, sheepLocation.y) for key, shape in ipairs(shapes) do local collision = checkCollision(shape) shape:draw(collision) end end function love.keypressed(key) if key == "c" then createCircle() elseif key == "r" then createRectangle() end end function checkCollision(shape) if not shape:is(Rectangle) then return false end local sheep_left = sheepLocation.x local sheep_top = sheepLocation.y local sheep_right = sheepLocation.x + sheepLocation.width local sheep_bottom = sheepLocation.y + sheepLocation.height local shape_left = shape.x local shape_top = shape.y local shape_right = shape.x + shape.width local shape_bottom = shape.y + shape.height if sheep_right > shape_left and sheep_left < shape_right and sheep_bottom > shape_top and sheep_top < shape_bottom then return true else return false end end function createCircle() circle = Circle(100, 300, 125) table.insert(shapes, circle) end function createRectangle() rectangle = Rectangle(100, 100, 200, 130) table.insert(shapes, rectangle) end
25f730155961de799289b70e88115e555c09f52c
[ "Markdown", "Lua" ]
3
Markdown
3Rs-And-Scott/tutorial_sheepolution
46a11dd1af0be9cae19f850148ff077ef63ca232
3e1f47b42299fd38d8a18e41e600bcb81806ab8b
refs/heads/master
<repo_name>kiranpuram/ERP_MavenJenkins<file_sep>/src/test/java/ERP/Helper.java package ERP; //import org.testng.annotations.Test; import jxl.Sheet; import jxl.Workbook; import org.testng.annotations.BeforeTest; import java.io.FileInputStream; //import java.io.FileNotFoundException; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; //import org.apache.xerces.util.SynchronizedSymbolTable; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterTest; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import java.io.File; public class Helper { WebDriver driver; String firstWindow ; String secondWindow; public void takeScreenShot(String str) throws Exception{ /*DateFormat df=new SimpleDateFormat("yyyy_MMM_dd hh_mm_ss"); Date d=new Date(); String time=df.format(d); System.out.println(time);*/ File f=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(f, new File("C:\\worksppaceNew\\str.png")); //FileUtils.copyFile(f, new File("D:\\Workspace\\"+str+time+".png")); } public void chk_loginBtn() throws Exception { //System.out.println("hello"); driver.findElement(By.xpath(".//*[@id='topbar']/div/div[2]/div[1]/div/button")).isDisplayed(); // System.out.println(x); driver.findElement(By.xpath(".//*[@id='topbar']/div/div[2]/div[1]/div/button")).click(); // Thread.sleep(1000); } public void chk_Links() { try { List<WebElement> links = driver.findElements(By.tagName("a")); System.out.println("checking links----->"); for(int i=0; i<links.size();i++) { if(!links.get(i).getText().equalsIgnoreCase("")) { if(links.get(i).getAttribute("class").equalsIgnoreCase("ui-tabs-anchor")) { System.out.println(links.get(i).getText()); // Thread.sleep(2000); links.get(i).click(); } } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void chk_TxtBox_Btns(String linkName) { System.out.println("checking textbox & buttons------>"); List<WebElement> elements = driver.findElements(By.tagName("input")); for(int i=0;i<elements.size();i++) { System.out.println(elements.get(i).getAttribute("name")); String str = elements.get(i).getAttribute("value"); if(linkName.equalsIgnoreCase("userLogin")) { if(str.equalsIgnoreCase("demouser") || str.equalsIgnoreCase("Log in")) System.out.println(elements.get(i).getAttribute("name")); }else if(linkName.equalsIgnoreCase("newAccount")) { if(str.equalsIgnoreCase("") || str.equalsIgnoreCase("Create Account")) System.out.println(elements.get(i).getAttribute("name")); } } } public void chk_Dropdown() { System.out.println("checking Dropdowns----->"); List<WebElement> sel = driver.findElements(By.tagName("select")); for(int i=0;i<sel.size();i++) System.out.println(sel.get(i).getAttribute("name")); } public void create_NewAct() throws Exception { FileInputStream fis = new FileInputStream(".\\data.xls"); Workbook w = Workbook.getWorkbook(fis); Sheet s = w.getSheet("NewAct"); System.out.println("no of rows : "+s.getRows()); //driver.findElement(By.xpath(".//*[@id='topbar']/div/div/div[3]/div[1]/div/button")).click(); //driver.findElement(By.xpath(".//*[@id='ui-id-2']")).click(); //Thread.sleep(3000); driver.findElement(By.xpath(".//*[@id='topbar']/div/div[2]/div[1]/div/button")).click(); System.out.println("clicked on Login"); // Thread.sleep(2000); driver.findElement(By.id("ui-id-2")).click(); //Thread.sleep(2000); //driver.findElement(By.xpath(".//*[@id='ui-id-2']")).sendKeys("<PASSWORD>"); for(int i=0;i<s.getRows();i++) { driver.findElement(By.xpath(s.getCell(0,i).getContents())).sendKeys(s.getCell(1,i).getContents()); } driver.findElement(By.xpath(".//*[@id='user_header']/ul/li[8]/input")).click(); } public void login() throws Exception { driver.findElement(By.xpath(".//*[@id='topbar']/div/div[2]/div[1]/div/button")).click(); driver.findElement(By.xpath(".//*[@id='user_login']/ul/li[4]/input")).click(); //System.out.println(driver.findElement(By.xpath(".//*[@id='tabsHeader']/div")).getText()); driver.findElement(By.xpath(".//*[@id='dashborad_menu']/li[1]/k/a/i")).click(); System.out.println("clicked on inventory"); Thread.sleep(3000); //System.out.println(driver.findElement(By.xpath(".//*[@id='path_by_module']/div/div[2]/ul")).getText()); driver.findElement(By.xpath(".//*[@id='path_by_module']/div/div[2]/ul/li[1]/a")).click(); Thread.sleep(3000); System.out.println("clicked on item master"); } public void chk_LinksDB() throws Exception { List<WebElement> list = driver.findElements(By.tagName("a")); System.out.println(list.size()); String arr[] = new String[list.size()]; int k=0; for(int j=50;j<list.size();j++) { if(!list.get(j).getText().equalsIgnoreCase("")) { arr[k] = list.get(j).getText(); System.out.println(arr[k]); k++; } } System.out.println("printing the array---------->>"); for(int i=0;i<k;i++) { System.out.println("array Element " +i+ ":"+ arr[i]); driver.findElement(By.linkText(arr[i])).click(); Thread.sleep(2000); driver.findElement(By.xpath(".//*[@id='header_top_quick_nav']/ul/li[4]/a/i")).click(); Thread.sleep(2000); } } public void chk_LinksInv() throws Exception { driver.findElement(By.xpath(".//*[@id='dashborad_menu']/li[1]/k/a/i")).click(); Thread.sleep(2000); List<WebElement> list = driver.findElements(By.tagName("a")); String arr[] = new String[list.size()]; int k=0; for(int i=0;i<list.size();i++) { if(!list.get(i).getText().equalsIgnoreCase("")) { arr[k] = list.get(i).getText(); k++; } } for(int j=25;j<k;j++) { if(!arr[j].equalsIgnoreCase(" On Hand")) { //System.out.println(arr[j]); driver.findElement(By.linkText(arr[j])).click(); //Thread.sleep(1000); driver.findElement(By.xpath(".//*[@id='structure']/ul/li[3]/a")).click(); //Thread.sleep(1000); } } } public void chk_LinksIM() { List<WebElement> str = driver.findElement(By.xpath(".//*[@id='item']")).findElements(By.tagName("a")); String arr[] = new String[str.size()]; int k=0; for(int j=0;j<str.size();j++) { if(!str.get(j).getText().equalsIgnoreCase("")) { arr[k]= str.get(j).getText(); System.out.println(arr[k]); k++; } } for(int i =0;i<k;i++) { if(driver.findElement(By.linkText(arr[i])).getAttribute("class").equalsIgnoreCase("ui-tabs-anchor")) driver.findElement(By.linkText(arr[i])).click(); //System.out.println(driver.findElement(by.)arr[i]); } } public void chk_Ajax() throws Exception { try { driver.findElement(By.xpath(".//*[@id='item_number']")).click(); System.out.println(driver.findElement(By.xpath(".//*[@id='tabsHeader-1']/ul/li[3]/i")).isDisplayed()); Thread.sleep(1000); // To check special characters other than -,_. driver.findElement(By.xpath(".//*[@id='item_number']")).sendKeys("[["); driver.switchTo().alert().accept(); driver.findElement(By.xpath(".//*[@id='item_number']")).clear(); driver.findElement(By.xpath(".//*[@id='item_number']")).sendKeys("ma"); Thread.sleep(1000); String str = driver.findElement(By.xpath("html/body/ul")).getText(); System.out.println(str); String arr[] = str.split("\n"); System.out.println(arr.length); for(int i=0;i<arr.length;i++) { if(arr[i].equalsIgnoreCase("MAKE_001")) { driver.findElement(By.xpath(".//*[@id='item_number']")).clear(); driver.findElement(By.xpath(".//*[@id='item_number']")).sendKeys(arr[i]); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // Thread.sleep(1000); } public void save_Item() throws Exception { WebElement dropdown = driver.findElement(By.xpath(".//*[@id='org_id']")); Select sel1 = new Select(dropdown); sel1.selectByVisibleText("MAS"); driver.findElement(By.xpath(".//*[@id='item_id']")).click(); driver.findElement(By.xpath(".//*[@id='tabsHeader-1']/ul/li[2]/i")).click(); window_Handler(); driver.findElement(By.xpath(".//*[@id='search_submit_btn']")).click(); driver.findElement(By.xpath(".//*[@id='tabsLine-0']/table/tbody/tr[2]/td[2]/a")).click(); driver.switchTo().window(firstWindow); driver.findElement(By.xpath(".//*[@id='item_description']")).clear(); driver.findElement(By.xpath(".//*[@id='item_description']")).sendKeys("Gulo TV ---->>Appended"); WebElement d = driver.findElement(By.id("item_type")); Select sel2 = new Select(d); sel2.selectByVisibleText("Equipment"); Select sel3 = new Select(driver.findElement(By.id("uom_id"))); sel3.selectByVisibleText("HR"); Select sel4 = new Select(driver.findElement(By.id("item_status"))); sel4.selectByVisibleText("Active"); driver.findElement(By.name("product_line_percentage[]")).sendKeys("80%"); driver.findElement(By.xpath("html/body/div[3]/div[3]/div[2]/div/form/div[2]/div/ul/li[5]/a")).click(); new Select(driver.findElement(By.id("make_buy"))).selectByVisibleText("BUY"); driver.findElement(By.xpath(".//*[@id='save']")).click(); } public void window_Handler() throws Exception { Set<String> windows = driver.getWindowHandles(); System.out.println(windows.size()); Iterator<String> it = windows.iterator(); System.out.println(firstWindow = it.next()); if(windows.size()>1) { secondWindow =it.next(); driver.switchTo().window(secondWindow); } else { driver.switchTo().window(firstWindow); } } @BeforeTest public void beforeTest() { driver = new FirefoxDriver(); driver.get("http://inoerp.org/extensions/user/user_login.php"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @AfterTest public void afterTest() { // driver.quit(); } }
0b21d7198b6b4efd0bae0702666b322f9faac0f9
[ "Java" ]
1
Java
kiranpuram/ERP_MavenJenkins
aaba8c118eb00bc1e9ce10d6533bf0e1514210db
617b79e07676929ddbc6679022ebdbaa9462fb37
refs/heads/master
<file_sep>package zabi.minecraft.maxpotidext; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Log { public static final Logger logger = LogManager.getLogger(MaxPotionIDExtender.MOD_ID); public static void i(CharSequence msg) { logger.info(msg); } public static void w(CharSequence msg) { logger.warn(msg); } public static void e(CharSequence msg) { logger.error(msg); } public static void d(CharSequence msg) { logger.debug(msg); } } <file_sep>package zabi.minecraft.maxpotidext; import java.util.Iterator; import java.util.function.Predicate; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.ClassNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.LdcInsnNode; import org.objectweb.asm.tree.LineNumberNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.MethodNode; import org.objectweb.asm.tree.VarInsnNode; import net.minecraft.launchwrapper.IClassTransformer; public class MPIDTransformer implements IClassTransformer { @Override public byte[] transform(String name, String transformedName, byte[] basicClass) { if (transformedName.equals("net.minecraft.client.network.NetHandlerPlayClient")) { return transformNetHandlerPlayClient(basicClass); } if (transformedName.equals("net.minecraft.potion.PotionEffect")) { return transformPotionEffect(basicClass); } if (transformedName.equals("net.minecraftforge.registries.GameData")) { return transformGameData(basicClass); } if (transformedName.equals("net.minecraft.network.play.server.SPacketEntityEffect")) { return transformSPacketEntityEffect(basicClass); } if (transformedName.equals("net.minecraft.network.play.server.SPacketRemoveEntityEffect")) { return transformSPacketRemoveEntityEffect(basicClass); } if (transformedName.equals("net.minecraft.nbt.NBTTagCompound")) { ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); if (!cn.name.equals(Obf.NBTTagCompound)) { throw new ASMException("The class NBTTagCompound has broken mappings, should be "+cn.name); } } if (transformedName.equals("net.minecraft.network.PacketBuffer")) { ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); if (!cn.name.equals(Obf.PacketBuffer)) { throw new ASMException("The class PacketBuffer has broken mappings, should be "+cn.name); } } return basicClass; } private static MethodNode locateMethod(ClassNode cn, String desc, String nameIn, String deobfNameIn) { return cn.methods.stream() .filter(n -> n.desc.equals(desc) && (n.name.equals(nameIn) || n.name.equals(deobfNameIn))) .findAny().orElseThrow(() -> new ASMException(nameIn +" ("+deobfNameIn+"): "+desc+" cannot be found in "+cn.name, cn)); } private static AbstractInsnNode locateTargetInsn(MethodNode mn, Predicate<AbstractInsnNode> filter) { AbstractInsnNode target = null; Iterator<AbstractInsnNode> i = mn.instructions.iterator(); while (i.hasNext() && target == null) { AbstractInsnNode n = i.next(); if (filter.test(n)) { target = n; } } if (target==null) { throw new ASMException("Can't locate target instruction in "+mn.name, mn); } return target; } private byte[] transformSPacketRemoveEntityEffect(byte[] basicClass) { Log.i("Patching SPacketRemoveEntityEffect"); ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); String descriptors = "(L"+Obf.PacketBuffer+";)V"; MethodNode rpd = locateMethod(cn, descriptors, "readPacketData", "a"); AbstractInsnNode target = locateTargetInsn(rpd, n -> n.getOpcode() == Opcodes.INVOKEVIRTUAL && ((MethodInsnNode)n).name.equals("readUnsignedByte")); rpd.instructions.insert(target, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Obf.PacketBuffer, "readInt", "()I", false)); rpd.instructions.remove(target); MethodNode wpd = locateMethod(cn, descriptors, "writePacketData", "b"); target = locateTargetInsn(wpd, n -> n.getOpcode() == Opcodes.INVOKEVIRTUAL && ((MethodInsnNode)n).name.equals("writeByte")); wpd.instructions.insert(target, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Obf.PacketBuffer, "writeInt", "(I)Lio/netty/buffer/ByteBuf;", false)); wpd.instructions.remove(target); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); Log.i("Patch Successful"); return cw.toByteArray(); } private byte[] transformSPacketEntityEffect(byte[] basicClass) { Log.i("Patching SPacketEntityEffect"); ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); if (!Obf.SPacketEntityEffect.equals(cn.name)) { throw new ASMException("Mapping mismatch! SPacketEntityEffect is "+cn.name+", not "+Obf.SPacketEntityEffect); } //Adding a new field, int effectInt cn.fields.add(new FieldNode(Opcodes.ACC_PUBLIC, "effectInt", "I", null, 0)); //Initialize this field in the constructor MethodNode mn_init = locateMethod(cn, "(IL"+Obf.PotionEffect+";)V", "<init>", "<init>"); Iterator<AbstractInsnNode> i = mn_init.instructions.iterator(); AbstractInsnNode targetNode = null; int line = 0; while (i.hasNext() && targetNode == null) { AbstractInsnNode node = i.next(); if (node instanceof LineNumberNode) { if (line == 1) { targetNode = node; } line++; } } if (targetNode == null) { throw new ASMException("Can't find target node for SPacketEntityEffect constructor"); } //These are reversed, they get pushed down the stack mn_init.instructions.insert(targetNode, new FieldInsnNode(Opcodes.PUTFIELD, Obf.SPacketEntityEffect, "effectInt", "I")); mn_init.instructions.insert(targetNode, new MethodInsnNode(Opcodes.INVOKESTATIC, Type.getInternalName(CodeSnippets.class), "getIdFromPotEffect", "(L"+Obf.PotionEffect+";)I", false)); mn_init.instructions.insert(targetNode, new VarInsnNode(Opcodes.ALOAD, 2)); mn_init.instructions.insert(targetNode, new VarInsnNode(Opcodes.ALOAD, 0)); MethodNode mn_empty_init = locateMethod(cn, "()V", "<init>", "<init>"); AbstractInsnNode tgt = locateTargetInsn(mn_empty_init, n -> n.getOpcode()==Opcodes.RETURN); mn_empty_init.instructions.insertBefore(tgt, new VarInsnNode(Opcodes.ALOAD, 0)); mn_empty_init.instructions.insertBefore(tgt, new LdcInsnNode(0)); mn_empty_init.instructions.insertBefore(tgt, new FieldInsnNode(Opcodes.PUTFIELD, Obf.SPacketEntityEffect, "effectInt", "I")); //Patch readPacketData MethodNode mn_readPacket = locateMethod(cn, "(L"+Obf.PacketBuffer+";)V", "readPacketData", "a"); String readVarInt_name = (Obf.isDeobf()?"readVarInt":"g"); AbstractInsnNode target = locateTargetInsn(mn_readPacket, n -> n.getOpcode()==Opcodes.RETURN).getPrevious().getPrevious(); mn_readPacket.instructions.insertBefore(target, new VarInsnNode(Opcodes.ALOAD, 0)); mn_readPacket.instructions.insertBefore(target, new VarInsnNode(Opcodes.ALOAD, 1)); mn_readPacket.instructions.insertBefore(target, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Obf.PacketBuffer, readVarInt_name, "()I", false)); mn_readPacket.instructions.insertBefore(target, new FieldInsnNode(Opcodes.PUTFIELD, Obf.SPacketEntityEffect, "effectInt", "I")); //Patch writePacketData MethodNode mn_writePacket = locateMethod(cn, "(L"+Obf.PacketBuffer+";)V", "writePacketData", "b"); String writeVarInt_name = (Obf.isDeobf()?"writeVarInt":"d"); AbstractInsnNode wp_target = locateTargetInsn(mn_writePacket, n -> n.getOpcode()==Opcodes.RETURN).getPrevious().getPrevious(); mn_writePacket.instructions.insertBefore(wp_target, new VarInsnNode(Opcodes.ALOAD, 1)); mn_writePacket.instructions.insertBefore(wp_target, new VarInsnNode(Opcodes.ALOAD, 0)); mn_writePacket.instructions.insertBefore(wp_target, new FieldInsnNode(Opcodes.GETFIELD, Obf.SPacketEntityEffect, "effectInt", "I")); mn_writePacket.instructions.insertBefore(wp_target, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Obf.PacketBuffer, writeVarInt_name, "(I)L"+Obf.PacketBuffer+";", false)); mn_writePacket.instructions.insertBefore(wp_target, new InsnNode(Opcodes.POP)); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); Log.i("Patch Successful"); return cw.toByteArray(); } private byte[] transformGameData(byte[] basicClass) { Log.i("Patching GameData"); ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); FieldNode mpid = cn.fields.stream() .filter(fn -> fn.name.equals("MAX_POTION_ID")) .findAny().orElseThrow(() -> new ASMException("Error finding MAX_POTION_ID constant in GameData.class")); cn.fields.remove(mpid); cn.fields.add(new FieldNode(mpid.access, mpid.name, mpid.desc, mpid.signature, Integer.MAX_VALUE>>2)); MethodNode mn = locateMethod(cn, "()V", "init", "init"); AbstractInsnNode target = locateTargetInsn(mn, n -> n.getOpcode()==Opcodes.SIPUSH && n.getPrevious().getOpcode()==Opcodes.LDC && Obf.isPotionClass(((LdcInsnNode) n.getPrevious()).cst.toString())); mn.instructions.insert(target, new LdcInsnNode(Integer.MAX_VALUE>>2)); mn.instructions.remove(target); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); Log.i("Patch Successful"); return cw.toByteArray(); } private byte[] transformPotionEffect(byte[] basicClass) { Log.i("Patching PotionEffect"); ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); if (!cn.name.equals(Obf.PotionEffect)) { throw new ASMException("Mapping mismatch! PotionEffect is "+cn.name+", not "+Obf.PotionEffect); } MethodNode mn = locateMethod(cn, "(L"+Obf.NBTTagCompound+";)L"+Obf.NBTTagCompound+";", "writeCustomPotionEffectToNBT", "a"); AbstractInsnNode ant = locateTargetInsn(mn, n -> n.getOpcode() == Opcodes.I2B); String mname = (Obf.isDeobf()?"setInteger":"a"); MethodInsnNode call = new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Obf.NBTTagCompound, mname, "(Ljava/lang/String;I)V", false); mn.instructions.remove(ant.getNext()); mn.instructions.insert(ant, call); mn.instructions.remove(ant); MethodNode mn2 = locateMethod(cn, "(L"+Obf.NBTTagCompound+";)L"+Obf.PotionEffect+";", "readCustomPotionEffectFromNBT", "b"); AbstractInsnNode ant2 = locateTargetInsn(mn2, n -> n.getOpcode() == Opcodes.INVOKEVIRTUAL); String name2 = (Obf.isDeobf()?"getInteger":"h"); mn2.instructions.remove(ant2.getNext()); mn2.instructions.remove(ant2.getNext()); mn2.instructions.insert(ant2, new MethodInsnNode(Opcodes.INVOKEVIRTUAL, Obf.NBTTagCompound, name2, "(Ljava/lang/String;)I", false)); mn2.instructions.remove(ant2); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); Log.i("Patch Successful"); return cw.toByteArray(); } private byte[] transformNetHandlerPlayClient(byte[] basicClass) { Log.i("Patching NetHandlerPlayClient"); ClassReader cr = new ClassReader(basicClass); ClassNode cn = new ClassNode(); cr.accept(cn, 0); MethodNode mn = locateMethod(cn, "(L"+Obf.SPacketEntityEffect+";)V", "handleEntityEffect", "a"); AbstractInsnNode target = locateTargetInsn(mn, n -> n.getOpcode()==Opcodes.SIPUSH); mn.instructions.remove(target.getPrevious()); mn.instructions.remove(target.getNext()); mn.instructions.insertBefore(target, new FieldInsnNode(Opcodes.GETFIELD, Obf.SPacketEntityEffect, "effectInt", "I")); mn.instructions.remove(target); ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); cn.accept(cw); Log.i("Patch Successful"); return cw.toByteArray(); } } <file_sep>package zabi.minecraft.maxpotidext; import java.lang.reflect.Field; import java.util.Random; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.potion.PotionType; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.common.config.Config.Type; import net.minecraftforge.common.config.ConfigManager; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.fml.client.event.ConfigChangedEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.event.FMLFingerprintViolationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.fml.common.registry.ForgeRegistries; import net.minecraftforge.fml.relauncher.ReflectionHelper; import net.minecraftforge.registries.ForgeRegistry; @Mod(modid=MaxPotionIDExtender.MOD_ID, name=MaxPotionIDExtender.NAME, version=MaxPotionIDExtender.VERSION, certificateFingerprint = MaxPotionIDExtender.FINGERPRINT) public class MaxPotionIDExtender { public static final String MOD_ID = "maxpotidext"; public static final String NAME = "MaxPotionIDExtender"; public static final String VERSION = "@VERSION@"; public static final String MC_VERSION = "[1.12.2,1.12.2]"; public static final String FINGERPRINT = "@FINGERPRINT@"; @Instance public static MaxPotionIDExtender INSTANCE; private static Field fieldMax = ReflectionHelper.findField(ForgeRegistry.class, "max"); @EventHandler public void init(FMLPreInitializationEvent evt) { try { int maxPotions = fieldMax.getInt(ForgeRegistries.POTIONS); if (maxPotions<256) { throw new ASMException("Limit is unchanged, id extension failed. Limit is: "+maxPotions); } } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } MinecraftForge.EVENT_BUS.register(this); } @EventHandler public void certInvalid(FMLFingerprintViolationEvent evt) { Log.w("\n\n!!! WARNING:\nThe signature for the mod MaxPotionIDExtender is invalid.\nPlease make sure to download only from the official source to avoid malware, go to https://minecraft.curseforge.com/projects/max-potion-id-extender\n\n"); } @SubscribeEvent public void onConfigChanged(ConfigChangedEvent evt) { if (evt.getModID().equals(MOD_ID)) { ConfigManager.sync(MOD_ID, Type.INSTANCE); } } @SubscribeEvent public void registryPotion(RegistryEvent.Register<Potion> evt) { if (ModConfig.generateTestPotions>0) { Log.i("Generating test potions"); } for (int i=0;i<ModConfig.generateTestPotions;i++) { Potion p = new PotionTest(i); p.setRegistryName(new ResourceLocation(MOD_ID, "TestPotion"+i)); evt.getRegistry().register(p); } } @SubscribeEvent public void registryPotionType(RegistryEvent.Register<PotionType> evt) { if (ModConfig.generateTestPotions>0) { Log.i("Generating test potion types"); } for (int i=0;i<ModConfig.generateTestPotions;i++) { PotionType pt = new PotionType(new PotionEffect(Potion.REGISTRY.getObject(new ResourceLocation(MOD_ID, "TestPotion"+i)), 2000, 0, false, true)); pt.setRegistryName(new ResourceLocation(MOD_ID, "TestPotionType"+i)); evt.getRegistry().register(pt); } } public static class PotionTest extends Potion { private static final Random r = new Random(); private String nm = ""; protected PotionTest(int id) { super(false, 0xFFFFFF & r.nextInt(Integer.MAX_VALUE)); nm = "Test Potion #"+id; } @Override public String getName() { return nm; } } } <file_sep>#MaxPotionIDExtender A mod that extends the max amount of potions objects from 256 to over 2 billions<file_sep>package zabi.minecraft.maxpotidext; import org.objectweb.asm.Type; import net.minecraft.launchwrapper.Launch; import net.minecraft.potion.Potion; public class Obf { public static boolean isPotionClass(String s) { if (s.endsWith(";")) { s = s.substring(1, s.length()-1); } return s.equals(Type.getInternalName(Potion.class)) || s.equals("uz"); } public static boolean isDeobf() { return (boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment"); } public static void loadData() { if ((boolean) Launch.blackboard.get("fml.deobfuscatedEnvironment")) { NBTTagCompound = "net/minecraft/nbt/NBTTagCompound"; PotionEffect ="net/minecraft/potion/PotionEffect"; SPacketEntityEffect = "net/minecraft/network/play/server/SPacketEntityEffect"; PacketBuffer = "net/minecraft/network/PacketBuffer"; } else { NBTTagCompound = "fy"; PotionEffect = "va"; SPacketEntityEffect = "kw"; PacketBuffer = "gy"; } } public static String NBTTagCompound; public static String PotionEffect; public static String SPacketEntityEffect; public static String PacketBuffer; }
e1dc074929d39a51b8c550cea1285171fe17c165
[ "Markdown", "Java" ]
5
Java
zabi94/MaxPotionIDExtender
82b5c485b8f9d819a5e08325fc3e3124c3b12e63
daa402820a42d9e5962bf4c84a767c1685ab2110
refs/heads/master
<repo_name>cmeekuk/dotfiles<file_sep>/.zshrc # __ __ # ____ / /_ ____ ___ __ __ ____ _____/ /_ # / __ \/ __ \ / __ `__ \/ / / / /_ / / ___/ __ \ # / /_/ / / / / / / / / / / /_/ / / /_(__ ) / / / # \____/_/ /_/ /_/ /_/ /_/\__, / /___/____/_/ /_/ # /____/ # # Author: <NAME> # Repo: https://github.com/cmeekuk/dotfiles/ # ##### oh-my-zsh configurations ##### export ZSH=/Users/chrismeek/.oh-my-zsh ZSH_THEME="robbyrussell" plugins=(git brew zsh-syntax-highlighting docker node npm pip redis-cli sudo tmux) source $ZSH/oh-my-zsh.sh ##### plugin configurations ##### [ -f ~/.fzf.zsh ] && source ~/.fzf.zsh source ~/Tools/z/z.sh <file_sep>/.zprofile PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:/Library/PostgreSQL/10/bin:${PATH}" export PATH
83c88b79d9107de4caac61943242d9316992ee29
[ "Shell" ]
2
Shell
cmeekuk/dotfiles
e8616082a3c9b595cf2827bc38a579f8eb625e93
ca3c82ed6ff4528d3c60dd4f75f150fe80fca871
refs/heads/master
<file_sep># MOBIWEB A Responsive Website for Workshop of Web and Application Development <file_sep><?php require('conn1.php'); require_once('header.php'); extract($_POST); if(isset($save)) { //check user alereay exists or not $sql=mysqli_query($conn,"select * from reg_details where email='$e'"); $r=mysqli_num_rows($sql); if($r==true) { $err= "<font color='red'>This user already exists</font>"; } else { $dob=$yy."-".$mm."-".$dd; $query="insert into reg_details values ('$n','$mob','$e','$tad','$pad','$pcm','$tot','$tota','$fn','$mn','$fmob','$skill','$sc','$w','$gen','$dob','$pay')"; mysqli_query($conn,$query); //upload image $err="<font color='blue'>Registration successfull !!</font>"; }} ?> <center><h1>Registration Form</h2></center><br /> <form method="post" enctype="multipart/form-data"> <fieldset> <legend>Personal information:</legend> <br /> <table class="table table-bordered"> <Tr> <Td colspan="2"><?php echo @$err;?></Td> </Tr> <tr> <td>Enter Your Name*:</td> <Td><input type="text" class="form-control" name="n" required/> </td> </tr> <tr> <td>Enter Your Mobile:</td> <Td><input class="form-control" type="number" name="mob" required/></td> </tr> <tr> <tr> <td>Enter Your Father's name*:</td> <Td><input type="text" class="form-control" name="fn" required/> </td> </tr> <tr> <td>Enter Your Fathers Contact Number*: </td> <Td><input class="form-control" type="number" name="fmob" required/></td> </tr> <tr> <td>Enter Your Mother's name*:</td> <Td><input type="text" class="form-control" name="mn" required/></td> </tr> <tr> <tr> <td>Select Your Gender*:</td> <Td> Male<input type="radio" name="gen" value="M" required/> Female<input type="radio" name="gen" value="F"/> </td> </tr> <tr> <td>Enter Your DOB*:</td> <Td> <select name="yy" required> <option value="">Year</option> <?php for($i=1950;$i<=2016;$i++) { echo "<option>".$i."</option>"; } ?> </select> <select name="mm" required> <option value="">Month</option> <?php for($i=1;$i<=12;$i++) { echo "<option>".$i."</option>"; } ?> </select> <select name="dd" required> <option value="">Date</option> <?php for($i=1;$i<=31;$i++) { echo "<option>".$i."</option>"; } ?> </select> </td> </tr> <tr> <td>Enter Your email id: </td> <Td><input type="email" class="form-control" name="e" required/></td> </tr> <tr> <td>Enter your School name*:</td> <td><textarea name="sc" rows="3" cols="20" required> </textarea> </td> </tr> <tr> <td>Enter Your Marks (in Class 11th)*: </td> <Td><input class="form-control" type="number" placeholder="PCM" name="pcm" required/></td><Td><input class="form-control" type="number" placeholder="Total" name="tot" required/></td> </tr> <tr> <td>Enter Your Marks (in Class 10th)*: </td> <Td><input class="form-control" type="number" placeholder="Total" name="tota" required/></td> </tr> <td>Enter your Permanent Address*:</td> <td><textarea name="pad" rows="4" cols="20" required> </textarea> </td> </tr> <tr> <td>Enter Address of Correspondence:</td> <td><textarea name="tad" rows="4" cols="20" > </textarea> </td><td> <input type="checkbox" name="tem" value="Same as Permanent Address"> Same as Permanent Address <br></td> </tr> <tr> <td>Enter your Skills:</td> <td><textarea name="skill" rows="2" cols="20" required> For Example, C++(Beginner),Java(Intermediate) etc. </textarea> </td> </tr> <tr> <td> Workshop Topic*: </td> <td> Web Development<input type="radio" name="w" value="Web development" required/> Application development<input type="radio" name="w" value="App development"/> </td> </tr> <tr> <td> <input type="checkbox" name="term" value="accept" required>I agree to all <a href="https://brajkishorupadhyay.000webhostapp.com/assets/images/conditions.docx" target="_blank">terms and Conditions </a> <br></td> </tr> <Td colspan="2" align="center"> <input type="submit" class="btn btn-success" value="Submit" name="save"/> <input type="reset" class="btn btn-success" value="Reset"/> </td> </tr> </table> </fieldset> </form> </body> </html><file_sep><?php $conn=mysqli_connect("localhost","id1142448_workshop","workshop","id1142448_registration"); ?><file_sep><?php if(!isset($text)) $text=""; if(!isset($username)) $username=""; require_once('functions.php'); if(isset($_POST['Submit'])) { $username=htmlentities($_POST['username'],ENT_QUOTES); $password=htmlentities($_POST['password'],ENT_QUOTES); if($username=="" or $password=="") { $text="<font color=red>Please Enter Username/Password</font>"; $_SESSION['type']=0; } else { //$username = escapeshellcmd($username); // $password = escapeshellarg($password); if (0) { $_SESSION['login']=true; $_SESSION['user']=$username; $_SESSION['type']=1; die("<script>top.location='index.php'</script>"); } else { require_once('conn.php'); $sql="Select username,role,semester from users where username='$username' and password='".(($password))."'"; $result=mysqli_query($conn,$sql); //echo mysqli_num_rows($result); if($result and mysqli_num_rows($result)>0) { $row=mysqli_fetch_array($result); $_SESSION['login']=true; $_SESSION['user']=$row['username']; $_SESSION['type']=$row['role']; $_SESSION['sem']=$row['semester']; //echo 'here'; die("<script>top.location='index.php'</script>"); } } $text="<font color=red>Invalid Username/Password</font>"; } } ?> <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>VIT Campus Student Login</title> <link rel="stylesheet" href="css/bootstrap.min.css"> <link rel="stylesheet" href="css/styles.css"> <link href='https://fonts.googleapis.com/css?family=Oxygen:400,300,700' rel='stylesheet' type='text/css'> <link rel='stylesheet prefetch' href='https://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'> <link href='https://fonts.googleapis.com/css?family=Lora' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css"> <link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'> <link rel="stylesheet" href="css/style.css"> <style media="screen"> form { border: 3px solid #f1f1f1; } input[type=text], input[type=password] { width: 94%; padding: 12px 20px; margin: 8px 0; display: inline-block; border: 1px solid #ccc; box-sizing: border-box; } button { background-color: #4CAF50; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer; width: 94%; } button:hover { opacity: 0.8; } .cancelbtn { width: auto; padding: 10px 18px; background-color: #f44336; } .imgcontainer { text-align: center; margin: 24px 0 12px 0; } img.avatar { width: 40%; border-radius: 50%; } .container { padding: 16px; } span.psw { float: right; padding-top: 16px; } /* Change styles for span and cancel button on extra small screens */ @media screen and (max-width: 300px) { span.psw { display: block; float: none; } .cancelbtn { width: 100%; } } </style> </head> <body style="background-image:url(images/IMG_4209.JPG);"> <script> function validate() { var f=document.form1 if(f.username.value=="") { error(document.getElementById("usernametext")) f.username.focus() return false; } if(f.password.value=="") { error(document.getElementById("passwordtext")) f.password.focus() return false; } return true } function error(id) { id.style.color='red' } </script> <header> <nav id="header-nav" class="navbar navbar-default" style="background-color:#DCDCDC;border:3px solid;"> <div class="container"style="margin:0px;padding:0px;padding-left:24px;background-color:#DCDCDC;"> <div class="navbar-header"> <a href="index.php" class="pull-left visible-md visible-lg"> <div id="logo-img"></div> </a> <div class="navbar-brand"> <a href="index.php"><h1 style="font-size:42px;font-weight:bold;color:#a4201d">VIVEKANANDA INSTITUTE OF TECHNOLOGY</h1> </a> </div> </div><!-- .container --> </nav><!-- #header-nav --> </header> <div id="main-content" class="container" style="max-width:500px;background-color:white;padding:1px;margin-top:100px;"> <form name="form1" method="post" onsubmit="return validate()"> <div class="imgcontainer"> <img src="img_avatar2.png" alt="Avatar" class="avatar"> </div> <label style="font-family:oxygen;color:red;font-size:16px;font-weight:bold;margin-left:15px;"> <?php echo $text ?></label> <br > <label style="font-family:oxygen;color:black;font-size:16px;font-weight:bold;margin-left:15px;"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="username" style="margin-left:15px;color:black;font-family:oxygen;" value="<?php echo $username; ?>" required> <label style="font-family:oxygen;color:black;font-size:16px;font-weight:bold;margin-left:15px;"><b>Password</b></label> <input type="<PASSWORD>" placeholder="Enter Password" name="password" style="margin-left:15px;color:black;font-family:oxygen;" required> <button type="submit" name="Submit" style="margin-left:15px;">Login</button> </form> </div><!-- End of #main-content --> <footer class="panel-footer" style="background-color: #1E90FF;border:3px solid"> <div class="text-center" style="width:100%">&copy; Copyright Vivekananda Group of Institutions</div> </div> </footer> <!-- jQuery (Bootstrap JS plugins depend on it) --> <script src="js/jquery-2.1.4.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/script.js"></script> <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script> <script src="js/index.js"></script> </body> </html>
3050570a54f389ad915e1bb6a89ce59a173fd543
[ "Markdown", "PHP" ]
4
Markdown
sanilup1234/MOBIWEB
fb902e3e7f3029f7d78d1965c853aa2a49b22026
fa6b00008e0abbb2e1b9481006c2f8404e6c6062
refs/heads/main
<file_sep><?php require ('connection.php'); if(isset($_GET["id"])){ $person_id = $_GET["id"]; } else{ $person_id = 0; } $query = "SELECT * FROM characters WHERE id = :id"; $result = $conn->prepare($query); $result->bindParam(":id", $person_id); $result->execute(); $person = $result->fetch(); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Character despriction</title> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="<KEY>" crossorigin="anonymous"> <link href="resources/css/style.css" rel="stylesheet"/> </head> <body> <header><h1><<?php echo $person["name"]; ?></h1> <a class="backbutton" href="index.php"><i class="fas fa-long-arrow-alt-left"></i> Terug</a></header> <div id="container"> <div class="detail"> <div class="left"> <img class="avatar" src="resources/images/<?php echo $person["avatar"]; ?>"> <div class="stats" style="background-color:<?php echo $person["color"];?>"> <ul class="fa-ul"> <li><span class="fa-li"><i class="fas fa-heart"></i></span> <?php echo $person["health"]; ?> </li> <li><span class="fa-li"><i class="fas fa-fist-raised"></i></span> <?php echo $person["attack"]; ?></li> <li><span class="fa-li"><i class="fas fa-shield-alt"></i></span> <?php echo $person["defense"] ?></li> </ul> <ul class="gear"> <li><b>Weapon</b>: <?php echo $person["weapon"]; ?></li> <li><b>Armor</b>: <?php echo $person["armor"]; ?> </li> </ul> </div> </div> <div class="right"> <p> <?php echo $person["bio"];?> </p> </div> <div style="clear: both"></div> </div> </div> <footer>&copy; <NAME> 2021</footer> </body> </html>
a8fd54ecc521dc5bf67ea782abc1288a4f9396f5
[ "PHP" ]
1
PHP
JoranS1/dynamic
5ecf16707bd2f23e66017f8dd149b775018b0be9
7f3b1b492de2b8456116cd56bca8e81bd779f52a
refs/heads/main
<file_sep>import json # to parse the files import pandas # read the csv import glob # looping through all the files in a folder import os # do folder in operating system if not os.path.exists("parsed_files"): os.mkdir("parsed_files") df = pandas.DataFrame() for json_file_name in glob.glob('json_files/*.json'): # json_file_name = "json_files/tmdb550.json" f = open(json_file_name, "r") json_data = json.load(f) f.close() production_countries = [item['iso_3166_1'] for item in json_data['production_countries']] production_countries = ";".join(production_countries) genres = [item['name'] for item in json_data['genres']] genres = ";".join(genres) df = df.append({ 'title': json_data['title'], 'id': json_data['id'], 'imdb_id': json_data['imdb_id'], 'budget': json_data['budget'], 'revenue': json_data['revenue'], 'genres': genres, 'release_date': json_data['release_date'], 'vote_average': json_data['vote_average'], 'production_countries': production_countries, }, ignore_index = True) df.to_csv("parsed_files/tmdb_dataset.csv") <file_sep># print("Hello") import urllib.request import os import json import time f = open("api_key", "r") api_key = f.read() f.close() # print(api_key) # This is if not os.path.exists("json_files"): os.mkdir("json_files") response = urllib.request.urlopen("https://api.themoviedb.org/3/movie/?api_key="+api_key) json_response = json.load(response) movie_end = int(json_response['id']) movie_start = movie_end - 10 for movie_id in range(movie_start, movie_end): print(movie_id) # movie_id = 550 # used only for one (while seeing if the code is working, before putting for loop for all) response = urllib.request.urlopen("https://api.themoviedb.org/3/movie/" + str(movie_id) + "?api_key=" + api_key) # print(response.read()) # taking a look : it is json, so instead of using this, use json library json_response = json.load(response) f = open("json_files/tmdb" + str(movie_id) + ".json", "w") f.write(json.dumps(json_response)) f.close() time.sleep(20) # in practice, put larger number # https://jsonformatter.org/json-pretty-print #
4d6f2f4a7861f240c340ea9fb28882428b35e8e0
[ "Python" ]
2
Python
dorissuzukiesmerio/tmbd_webscrapping
21595d995ca12f9fa15dd8b2e66afffff23b205b
eee5df052111ffbd6ae95a955cefa5c376efbd98
refs/heads/master
<repo_name>MichalPokorny/admt-challenge<file_sep>/main-project/src/Main.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.json.*; public class Main { private static boolean testPython() throws InterruptedException, IOException { Process p = Runtime.getRuntime().exec("python", new String[] { "pythonfile.py" }); p.waitFor(); return true; } public static void main(String[] args) throws IOException, InterruptedException { String mypyIssuesUrl = "https://api.github.com/repos/python/mypy/issues?per_page=100"; URL mypyUrl = new URL(mypyIssuesUrl); String thaJson = getHttp(mypyUrl); JSONArray issues = new JSONArray(thaJson); for (int i = 0; i < issues.length(); i++) { JSONObject object = issues.getJSONObject(i); String body = object.getString("body").toLowerCase(); boolean talksAboutErrors = body.contains("error") || body.contains("bug")|| body.contains("fix"); boolean containsCodeBlock = body.matches("(?s).*```(.{10,})```.*"); if (containsCodeBlock && talksAboutErrors) { System.out.println("[ISSUE] " + object.getString("title")); Pattern pattern = Pattern.compile("(?s)```([^`]{10,})```"); Matcher matcher = pattern.matcher(body); int mi = 0; while (matcher.find()) { mi++; String thaCode = matcher.group(1); if (thaCode.startsWith("python")) { thaCode = thaCode.substring(6); System.out.println(">> CODE >> " + thaCode.replace('\n', ' ').replace('\r', ' ') ); } } } } System.out.println(); } public static String getHttp(URL url) throws IOException { URLConnection conn = url.openConnection(); String pageText; try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) { pageText = reader.lines().collect(Collectors.joining("\n")); } return pageText; } } <file_sep>/test-java-module/src/testjavaclass.java /** * Created by hudecekp on 14.4.16. */ public class testjavaclass { public static void main() { System.out.println("Test"); } } <file_sep>/install_mypy.sh git clone <EMAIL>:python/mypy cd mypy git submodule update --init typeshed PYTHONPATH=`pwd` scripts/mypy <file_sep>/get_issues.py #!/usr/bin/python3 import requests import subprocess import sys import json issues = [] count = 100 url = 'https://api.github.com/repos/python/mypy/issues?state=all&filter=all&per_page=%d' % count issues = [] maxcount = None while url is not None: print(url) r = requests.get(url) if 'Link' not in r.headers: print(r) print(r.headers) break link = r.headers['Link'] nexturl = None for l in link.split(', '): if l.endswith('; rel="next"'): nexturl = l.split('>')[0][1:] break issues.extend(r.json()) url = nexturl if maxcount is not None and len(issues) > maxcount: break if len(issues) == 0: print(":(") sys.exit(1) with open('all_issues.json', 'w') as f: json.dump(issues, f) def is_runnable_python(x): try: with open('x.py', 'w') as f: f.write(x) subprocess.check_output(['python', '-m', 'py_compile', 'x.py'], stderr=subprocess.STDOUT) return True except subprocess.CalledProcessError as e: return False with_python = [] for issue in issues: print() print() # print(issue) print(issue['number']) print(issue['html_url']) if 'label' in issue: print(issue['label']) print(issue['title']) print(issue['body']) any_python = False for part in issue['body'].split("```"): if is_runnable_python(part): any_python = True break if any_python: print('contains Python') with_python.append(issue) print(len(with_python)) with open('with_python.json', 'w') as f: json.dump(with_python, f) <file_sep>/analyze.py #!/usr/bin/python3 import os import requests import subprocess import sys import json # 1363 with open('all_issues.json') as f: issues = json.load(f) def is_runnable_python3(x): try: with open('x.py', 'w') as f: f.write(x) subprocess.check_output(['python3', '-m', 'py_compile', 'x.py'], stderr=subprocess.STDOUT) return True except subprocess.CalledProcessError as e: return False def is_mypy_ok(x): try: with open('x.py', 'w') as f: f.write(x) # TODO: does this run it? e = os.environ.copy() e['PYTHONPATH'] = '/home/prvak/admt-challenge/mypy' e['MYPYPATH'] = '/home/prvak/admt-challenge/mypy/typeshed/stdlib/3' subprocess.check_output(['mypy/scripts/mypy', 'x.py'], stderr=subprocess.STDOUT, env=e) return True except subprocess.CalledProcessError as e: print(e.output) return False def get_mypy_error(x): try: with open('x.py', 'w') as f: f.write(x) # TODO: does this run it? e = os.environ.copy() e['PYTHONPATH'] = '/home/prvak/admt-challenge/mypy' e['MYPYPATH'] = '/home/prvak/admt-challenge/mypy/typeshed/stdlib/3' subprocess.check_output(['mypy/scripts/mypy', 'x.py'], stderr=subprocess.STDOUT, env=e) return None except subprocess.CalledProcessError as e: return e.output with_python = [] # 1363: false alert for issue in issues: python_chunks = [] for i, part in enumerate(issue['body'].split("```")): if i == 0: continue head = 'python' if part.startswith(head): part = part[len(head):] if is_runnable_python3(part): python_chunks.append(part) break if len(python_chunks) == 0: continue print() # print(issue) print(issue['number'], issue['html_url'], ':::', issue['title']) if 'label' in issue: print(issue['label']) #print(issue['body']) with_python.append(issue) for python_chunk in python_chunks: python_ok = is_runnable_python3(python_chunk) mp_ok = is_mypy_ok(python_chunk) # if python_ok and not mp_ok: # mp_error = get_mypy_error(python_chunk) # if mp_error in issue['body']: # Issue describes print("\t" + python_chunk) print("Python: %s MyPy: %s" % (python_ok, mp_ok)) print('-------------------------') print(len(with_python)) with open('with_python.json', 'w') as f: json.dump(with_python, f)
481aeaa7742236fbd20b80a08ffe4931052b497f
[ "Java", "Python", "Shell" ]
5
Java
MichalPokorny/admt-challenge
7f21ff4df1ce74c4096c7faf6f6df6ba2bd0dee5
e5146541399700e5795216fdeeee16a1805b5b3c
refs/heads/master
<repo_name>LazVegas/Github-API-Profile<file_sep>/src/redux/ducks/github.js // imports import axios from 'axios' import { useEffect } from 'react' import { useSelector, useDispatch } from 'react-redux' // 1. action definitions // Need to get the users const GET_USER = 'gh/GET_USER' // Need to get the repos const GET_REPOS = 'gh/GET_REPOS' // 2. initial state // We know user is an object and repos is an array const initialState = { user: {}, repos: [] } // 3. reducer // Getting from index.js export default function (state = initialState, action) { switch(action.type) { case GET_USER: return {...state, user: action.payload} case GET_REPOS: return {...state, repos: action.payload} default: return initialState } } // 4. action creators function getUser(username) { return dispatch => { axios.get(`http://api.github.com/users/${username}`).then(resp => { dispatch({ type: GET_USER, payload: resp.data }) }) } } function getRepos(username) { return dispatch => { axios.get(`http://api.github.com/users/${username}/repos`).then(resp => { dispatch({ type: GET_REPOS, payload: resp.data }) }) } } // 5. custom hooks export function useGithub(username) { const dispatch = useDispatch() const user = useSelector(appState => appState.githubReducer.user) const repos = useSelector(appState => appState.githubReducer.repos) useEffect(() => { dispatch(getUser(username)) dispatch(getRepos(username)) }, []) return { user, repos } } <file_sep>/src/components/Repos.js import React from 'react' export default function (props) { return ( <div className="mainsection"> <div className="navbar"> <div>Overview</div> <div>Repositories</div> <div> {props.repos.map((repo, i) => ( <div key={'repo' + i}> <p>{repo.public_repos}</p> </div> ))} </div> <div>Projects</div> <div>Packages</div> <div>Stars</div> <div>Followers</div> <div>Following</div> </div> <div id="navbar2"> <input type="text" placeholder="Find a repository" id="findrepo" /> <button id="type">Type: All &#9660;</button> <button id="language">Language: All &#9660;</button> <button id="new">&#127970;&nbsp;&nbsp;New</button> </div> <div> {props.repos.map((repo, i) => ( <div id="repolist" key={'repo' + i}> <a id="reponame" href={repo.html_url}>{repo.name}</a> <p>{repo.description}</p> <p>&#128514;&nbsp;&nbsp;{repo.language}</p> </div> ))} </div> </div> ) }
91a7e92a346d4fdffa922facae9795ec1f72b8c5
[ "JavaScript" ]
2
JavaScript
LazVegas/Github-API-Profile
70018dc6116fb867267cbba52c2ed2bc82948f07
56a629b67bb211e1803d7c10a8c2360268162011
refs/heads/master
<file_sep>myApp.controller('ViewParkController', ['ParksService','UserService', function( ParksService, UserService) { console.log('view park controller created'); var self = this; self.UserService = UserService; self.UserService.getuser(); // this updates the user info self.ParksService = ParksService; self.updatePark = ParksService.updatePark; self.Parks = ParksService.Parks; self.newPark = ParksService.newPark; self.addParks = ParksService.addParks; self.getParks = ParksService.getParks; self.deletePark = ParksService.deletePark; self.getParks(); }]); <file_sep># Full Stack with Auth Group Project Setup Directions ----------- * Run `npm install`, * Start mongo if not running already by using `mongod` * Run `npm start` in an open tab of terminal ![our shelf](tauShelf.png) Technologies ------------ * Mongo * Express * Angular * Node * Passport * git * github Project Description ------------------- Our client, **Prime Digital Academy: Room 3**, has asked for an app to simulate the behavior of their shelf. That is, a list of items placed on the classroom shelf. **Any visitor** to the page can view the shelf, but only logged in users should be able to place objects on the shelf. Authentication should happen on the client and the server. This will require some research, design, an implementation. Update this README.md to include the names of the group members and your team name/number. As well as any planning/docs. These can be in digital format or even pics of whiteboard/notebook sketches. Shelf Object ------------ Items placed on the shelf should have the following data: * description * placer (user) * image url (optional) You're going to have to think about how/where to store this data. Recall that each item will have to be associated with a user! > NOTE: Image url should be a full path to an existing image on the web. You should not attempt to implement image upload for this. Hard Mode ---------- * only logged in users can remove objects from the shelf * styling Pro Mode -------- * logged in users can only remove their objects from the shelf * show list of users only to logged in users * implement [file stack](https://www.npmjs.com/package/filestack-js) for image upload Super Mode ---------- * filter output by user (click on a user to only show items by that user) * users can re-order shelf
88cd2b1404de3852efac3765ddf4561d2bca14f3
[ "JavaScript", "Markdown" ]
2
JavaScript
loganolzenak/DogParkSolo
3bcef7ebf9f29dd680f811a92c69b887af86a18d
8b38af9f84c19452cc4f21dd7feedfcfce73bc9a
refs/heads/master
<file_sep>import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: AnhNBT (<EMAIL>) * Date: 10/22/2020 * Time: 2:43 PM */ public class App { public static void main(String[] args) { Scanner input = new Scanner(System.in); List<Bill> billList = new ArrayList<>(); BillManager billManager = new BillManager(); do { System.out.println("=========================="); System.out.println("QUẢN LÝ BIÊN LAI TIỀN ĐIỆN"); System.out.println("\tBy AnhNBT (1.0)"); System.out.println("=========================="); System.out.println("1. Nhập hộ gia đình"); System.out.println("2. Hiển thị hộ gia đình theo số nhà"); System.out.println("3. Tính tiền điện phải trả"); System.out.println("0. Thoát"); System.out.println("=========================="); System.out.print("Nhập lựa chọn của bạn [0-Thoát]: "); int choice = Integer.parseInt(input.nextLine()); switch (choice) { case 0: System.out.println("Thoát!"); System.exit(0); case 1: System.out.println("=========================="); System.out.println("Nhập thông tin hộ gia đình"); System.out.println("=========================="); System.out.print("Số lượng hộ muốn nhập: "); int size = Integer.parseInt(input.nextLine()); for (int i = 0; i < size; i++) { System.out.println("--------------------------"); System.out.println("Hộ gia đình thứ '" + (i + 1) + "'"); Bill bill = billManager.add(input); billList.add(bill); } System.out.println("Done."); break; case 2: for (int i = 0; i < billList.size(); i++) { System.out.println(billList.get(i).toString()); } break; case 3: System.out.println("=========================="); System.out.println("Nhập thông tin hộ gia đình"); System.out.println("=========================="); for (int i = 0; i < billList.size(); i++) { System.out.println(billList.get(i).toString()); } break; } } while (true); } } <file_sep>import java.util.Scanner; /** * Created by IntelliJ IDEA. * User: AnhNBT (<EMAIL>) * Date: 10/22/2020 * Time: 3:34 PM */ public class BillManager { public BillManager() {} public boolean checkID(User user, String id) { if (user.getId().equals(id)) { return true; } return false; } public Bill add(Scanner input) { Bill bill = new Bill(); User user = new User(); user.setId(inputID(input)); user.setName(inputName(input)); user.setElectricMeterCode(inputElectricMeterCode(input)); bill.setUser(user); bill.setSoMoi(inputSoMoi(input)); bill.setSoCu(inputSoCu(input)); bill.pay(); // Gọi phương thức thanh toán tiền return bill; } private double inputSoCu(Scanner input) { System.out.print("Nhập chỉ số công tơ điện cũ: "); while (true) { try { return Double.parseDouble(input.nextLine()); } catch (NumberFormatException ex) { System.out.print("Sai định dạng! Nhập lại số công tơ điện cũ: "); } } } private double inputSoMoi(Scanner input) { System.out.print("Nhập chỉ số công tơ điện mới: "); while (true) { try { return Double.parseDouble(input.nextLine()); } catch (NumberFormatException ex) { System.out.print("Sai định dạng! Nhập lại số công tơ điện mới: "); } } } public int inputElectricMeterCode(Scanner input) { System.out.print("Nhập mã công tơ điện: "); while (true) { try { return Integer.parseInt(input.nextLine()); } catch (NumberFormatException ex) { System.out.print("Sai định dạng! Nhập lại mã công tơ điện: "); } } } public static String inputName(Scanner input) { System.out.print("Nhập tên chủ hộ: "); return input.nextLine(); } public static String inputID(Scanner input) { System.out.print("Nhập số nhà: "); return input.nextLine(); } } <file_sep>import java.util.ArrayList; import java.util.List; /** * Created by IntelliJ IDEA. * User: AnhNBT (<EMAIL>) * Date: 10/22/2020 * Time: 2:38 PM */ public class Bill { private double soCu; private double soMoi; private double billsToPay; private User user; public Bill() { } public Bill(double soCu, double soMoi, User user) { this.soCu = soCu; this.soMoi = soMoi; this.user = user; } public double getSoCu() { return soCu; } public void setSoCu(double soCu) { this.soCu = soCu; } public double getSoMoi() { return soMoi; } public void setSoMoi(double soMoi) { this.soMoi = soMoi; } public double getBillsToPay() { return billsToPay; } public void setBillsToPay(double billsToPay) { this.billsToPay = billsToPay; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Bill{" + "soCu=" + soCu + ", soMoi=" + soMoi + ", billsToPay=" + billsToPay + ", user=" + user.toString() + '}'; } public double pay() { double total = (soMoi - soCu) * 750; setBillsToPay(total); return billsToPay; } // public void show() { // System.out.printf("%5s %15s %10s\n", "Số nhà", "Tên chủ hộ", "Mã số công tơ"); // for (User user: userlist) { // user.printFormat(); // } // } } <file_sep>#CODEGYM: Đề Thi Thực Hành 3 Để quản lý các biên lai thu tiền điện, người ta cần các thông tin như sau: - Với mỗi biên lai, có các thông tin sau: **thông tin về hộ sử dụng điện**, **chỉ số cũ**, **chỉ số mới**, **số tiền phải trả** của mỗi hộ sử dụng điện - Các thông tin riêng của mỗi hộ sử dụng điện gồm: Họ tên chủ hộ, số nhà, mã số công tơ của hộ dân sử dụng điện. 1. Hãy xây dựng lớp `KhachHang` để lưu trữ các thông tin riêng của mỗi hộ sử dụng điện. 2. Xây dựng lớp `BienLai` để quản lý việc sử dụng và thanh toán tiền điện của các hộ dân. 3. Xây dựng các phương thức nhập, và hiển thị một thông tin riêng của mỗI hộ sử dụng điện. 4. Cài đặt chương trình thực hiện các công việc sau: - Nhập vào các thông tin cho n hộ sử dụng điện - Hiển thị thông tin về các biên lai đã nhập - Tính tiền điện phải trả cho mỗi hộ dân, nếu giả sử rằng tiền phải trả được tính theo công thức sau: *Số tiền phải trả = (Số mới - số cũ) * 750.
162928dfab288695eee840d058f9f78b796b8caf
[ "Markdown", "Java" ]
4
Java
anhnbt/day-14-java-slack-exercise-3-bill-manager
0e5908ea45872fb9cb2ac8cc7ad84b73cef62d35
7484d9329266f76b4f06db992b8ad60f729e270f
refs/heads/master
<file_sep>package hr.fer.ga.crossover; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import hr.fer.ga.Strategy; public class KPointCrossover implements Crossover { private Random rand; private int k; private double mutationRate; public KPointCrossover(int k, double mutationRate) { rand = new Random(); this.k = k; this.mutationRate = mutationRate; } @Override public Strategy cross(Strategy strategy1, Strategy strategy2) { int N = 280; int[] strategyTable = new int[N]; List<Integer> intersectionPoints = new ArrayList<Integer>(); for (int i = 0; i < k; i++) { intersectionPoints.add(rand.nextInt(N)); } Collections.sort(intersectionPoints); intersectionPoints.add(N+1); int current = 0; for (int i = 0; i < N; i++) { if (i > intersectionPoints.get(current)) { current++; } if (current % 2 == 0) { strategyTable[i] = strategy1.getStrategyTable()[i]; } else { strategyTable[i] = strategy2.getStrategyTable()[i]; } if (rand.nextDouble() < mutationRate) { strategyTable[i] = 1 - strategyTable[i]; } } return new Strategy(strategyTable, strategy1.getNumberOfHands()); } } <file_sep>package hr.fer.ga.selection; import java.util.List; import java.util.Random; import hr.fer.ga.Strategy; public class TournamentSelection implements Selection { private Random rand; private int k; public TournamentSelection(int k) { this.rand = new Random(); this.k = k; } @Override public int select(List<Strategy> population) { int selected = population.size() - 1; for (int i = 0; i < k; i++) { int x = rand.nextInt(population.size()); if (selected > x) selected = x; } return selected; } }
9ee1f621ee40cad6e5eca30dcda246e84d6e11bb
[ "Java" ]
2
Java
fsosa98/bachelor-thesis
c65961db1f37ecc724a000cd6ba8378b9cfce864
71161251388b201e8eca48758ce13ec5620d692d
refs/heads/master
<file_sep>const name = "nombre"; var hola = 1; let perro = { años:"21", altura: "21cm" }; console.log(perro); let saludos = "<NAME>"; const saludo = () => { alert(`saludo ${saludos}`) }
bc1bd92225ca5fe8810f7cce5694936e1a3c199a
[ "JavaScript" ]
1
JavaScript
SebastianGasca/PrimerProyecto
8f951e2af629e5f74dd176244b6c96f8204163e1
c6b401209b7f0d6796c147f33ae58e7932d90d51
refs/heads/master
<file_sep>package Lecture07.Project1B; /** Project 1B code is below * @author xerfat (at 2021.04.01) */ public class OffByOne implements CharacterComparator { @Override public boolean equalChars(char a, char b) { return a - b == 1 || b - a == 1; } } <file_sep>//package Lecture02.Project0; /** * @author xerfat (at 2021.03.09) */ import java.lang.Math; public class NBody { public static String backgroundToDraw = "images/starfield.jpg"; public static double readRadius(String fileName) { double r; In in = new In(fileName); int firstItemInFile = in.readInt(); r = in.readDouble(); return r; } public static Body[] readBodies(String fileName) { In in = new In(fileName); int n = in.readInt(); // Number of planets double r = in.readDouble(); Body[] b = new Body[n]; double xxPos,yyPos,xxVel,yyVel,mass; String imgFileName; for (int i = 0; i < n; i = i + 1) { xxPos = in.readDouble(); yyPos = in.readDouble(); xxVel = in.readDouble(); yyVel = in.readDouble(); mass = in.readDouble(); imgFileName = in.readString(); b[i] = new Body(xxPos, yyPos, xxVel, yyVel, mass, imgFileName); } return b; } public static int readNum(String fileName) { In in = new In(fileName); int n = in.readInt(); return n; } public static void drawBackground(double r) { //StdDraw.enableDoubleBuffering(); StdDraw.setScale(-r, r); StdDraw.clear(); StdDraw.picture(0, 0, backgroundToDraw, 2*r, 2*r); //StdDraw.show(); //StdDraw.pause(1000); } public static void main(String[] args) { double T = Double.parseDouble(args[0]); double dt = Double.parseDouble(args[1]); String fileName = args[2]; int n; // Num of Bodies n = readNum(fileName); double r; // Radius r = readRadius(fileName); Body[] b = new Body[n]; // Bodies b = readBodies(fileName); double[] xForces = new double[n]; double[] yForces = new double[n]; /** a graphics technique to prevent flickering in the animation. */ StdDraw.enableDoubleBuffering(); StdAudio.play("./audio/2001.mid"); for (double s = 0; s < T; s = s + dt) { for (int i = 0; i < b.length; i += 1) { xForces[i] = b[i].calcNetForceExertedByX(b); yForces[i] = b[i].calcNetForceExertedByY(b); } for (int i = 0; i < b.length; i += 1) { b[i].update(dt, xForces[i], yForces[i]); } /** Draw the background */ drawBackground(r); /** Use loop to draw all the planets and sun */ for (int i = 0; i < b.length; i += 1) { Body.draw(b[i]); } StdDraw.show(); StdDraw.pause(1); } StdOut.printf("%d\n", b.length); StdOut.printf("%.2e\n", r); for (int i = 0; i < b.length; i++) { StdOut.printf("%11.4e %11.4e %11.4e %11.4e %11.4e %12s\n", b[i].xxPos, b[i].yyPos, b[i].xxVel, b[i].yyVel, b[i].mass, b[i].imgFileName); } } } <file_sep>package Lecture0405.Project01; public class LinkedListDeque<LocheNess> { /** Project 1A code is below * @author xerfat (at 2021.03.18) */ private class StuffNode { public LocheNess item; public StuffNode prev; public StuffNode next; public StuffNode(StuffNode p, LocheNess i, StuffNode n) { item = i; prev = p; next = n; } } private StuffNode sentinel; private int size; // if (t instanceof String) { // t = "a"; // } else if (t instanceof Integer) { // t = 66; // } public LinkedListDeque() { //错误写法 //sentinel = new StuffNode(sentinel,66,sentinel);、、在实例化sentinel时, //sentinel本身还只是null,用sentinel和sent.next去实例化sentinel当然是行不通的。 sentinel = new StuffNode(null, null, null); sentinel.next = sentinel; sentinel.prev = sentinel; size = 0; } // public LinkedListDeque(LocheNess x) { // sentinel = new StuffNode(null,66,null); // sentinel.next = new StuffNode(sentinel, x, null); // sentinel.prev = sentinel.next; // size = 1; // } public void addFirst(LocheNess x) { sentinel.next = new StuffNode(sentinel, x, sentinel.next); sentinel.next.next.prev = sentinel.next; size += 1; } public void addLast(LocheNess x) { sentinel.prev = new StuffNode(sentinel.prev, x, sentinel); sentinel.prev.prev.next = sentinel.prev; size += 1; } public boolean isEmpty() { // if (size == 0) { // return true; // } else { // return false; // } return size == 0; } public int size() { return size; } public void printDeque() { StuffNode ptr = sentinel.next; for (int i = 0; i < size; i += 1) { System.out.print(ptr.item + " "); ptr = ptr.next; } System.out.println(); } public LocheNess removeFirst() { if (size == 0) { return null; } else { LocheNess r = sentinel.next.item; sentinel.next = sentinel.next.next; sentinel.next.prev = sentinel; size -= 1; return r; /** 另一种写法 */ // LochNess r = sentinel.next.item; // sentinel.next.next.prev = sentinel; // sentinel.next = sentinel.next.next; // size -= 1; // return r; } } public LocheNess removeLast() { if (size == 0) { return null; } else { LocheNess r = sentinel.prev.item; sentinel.prev = sentinel.prev.prev; sentinel.prev.next = sentinel; size -= 1; return r; /** 另一种写法 */ // LochNess r = sentinel.next.item; // sentinel.prev.prev.next = sentinel; // sentinel.prev = sentinel.prev.prev; // size -= 1; // return r; } } /** get must use iteration, not recursion. */ public LocheNess get(int index) { int i = 0; StuffNode ptr = sentinel; if (index > size) { return null; } while (i != index) { ptr = ptr.next; i += 1; // if (ptr == null) { // return null; // } } return ptr.item; } public LocheNess getRecursiveHelp(StuffNode p, int i) { if (i == 0) { return p.item; } return getRecursiveHelp(p.next, i - 1); } public LocheNess getRecursive(int index) { if (index > size) { return null; } StuffNode ptr = sentinel; return getRecursiveHelp(ptr, index); } /** Creating a deep copy means that you create an entirely new LinkedListDeque, * with the exact same items as other. * However, they should be different objects. */ public LinkedListDeque(LinkedListDeque other) { sentinel = new StuffNode(null, null, null); sentinel.next = sentinel; sentinel.prev = sentinel; size = 0; for (int i = 1; i <= other.size(); i += 1) { addLast((LocheNess)other.get(i)); } } public static void main(String[] args) { LinkedListDeque<Integer> L = new LinkedListDeque<>(); L.addFirst(3); L.addFirst(2); L.addFirst(1); L.addLast(4); L.addLast(5); System.out.println(L.size()); System.out.println(L.get(1)); L.printDeque(); L.removeFirst(); L.removeLast(); L.printDeque(); System.out.println(L.getRecursive(3)); System.out.println("L1"); LinkedListDeque<Integer> L1 = new LinkedListDeque(L); System.out.println(L1.getRecursive(3)); System.out.println(L1.size()); System.out.println(L1.get(1)); L1.printDeque(); L1.removeFirst(); L1.removeLast(); L1.printDeque(); } } <file_sep>// package Lecture01; /** @author xerfat */ import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput; import java.util.Arrays; public class HelloWorld { public static void main(String[] args){ // public 这是一个公有的方法 // static 这是一个静态的方法 // void 没有返回值 // main 方法名 // String[] args,这是参数,程序运行的时候可以加上参数的,参数的类型是字符串数组,放在args这个参数中 System.out.println("Hello World!"); } } // Java considers classes very important !!!! // All code must be in classes, which forces you to be object-oriented // Java vs Python // In general, Java is much faster than Python, though the startup time for a new Java program is longer /* Teaching conclusion: 1. In Java, all code must be part of a class. 2. Classes are defined with "public class CLASSNAME" 3. We use '{ }'(curly braces) to delineate the beginning and ending of things. 4. We must end lines with a ';'(semicolon) 5. The code we want to run must be inside 'public static void main(String[] args)' */<file_sep>package Lecture07.Project1B; /** Project 1B code is below * @author xerfat (at 2021.04.01) */ public class OffByN implements CharacterComparator { public int n; public OffByN(int N) { n = N; } @Override public boolean equalChars(char x, char y) { return Math.abs(x - y) == n; // return x - y == n || y - x == n; } } <file_sep>package Lecture07.Project1B; import Lecture040506.Project1A.LinkedListDeque; import org.junit.Test; /** Project 1B * @author xerfat (2021.03.31) * 用三种方法实现isPalindrome,且按照作业要求不调用get() */ public class Palindrome { public Deque<Character> wordToDeque(String word) { Deque<Character> wordList = new LinkedListDeque<>(); for (int i = 0; i < word.length(); i += 1) { wordList.addLast(word.charAt(i)); //get the i-th character in a String. } return wordList; } /* A palindrome is defined as a word that is the same whether it is read forwards or backwards. 即,“回文” */ /* isPalindrome solution 0: use recursion and private helper method * j<NAME>建议用recursion+helper method,这里把deque转化为string似乎没有可以调用的方法? **/ /* 引申 String, StringBuilder, StringBuffer * String 的值是不可变的,这就导致每次对String的操作都会生成新的String对象,不仅效率低下,而且浪费大量优先的内存空间 * * StringBuffer 是可变类,和线程安全的字符串操作类,任何对它指向的字符串的操作都不会产生新的对象。每个StringBuffer对 * 象都有一定的缓冲区容量,当字符串大小没有超过容量时,不会分配新的容量,当字符串大小超过容量时,会自动增加容量 * * StringBuilder 可变类,速度更快 * 此外还涉及线程安全的区别,目前看不懂 **/ private String dequeToString(Deque d) { StringBuilder s = new StringBuilder(); for (int i = 0; i < d.size(); i += 1) { char temp = (char) d.removeFirst(); s.append(temp); //append是在尾部添加,一开始不知道,以为在首部 //所以之前跑通纯属是因为对称 d.addLast(temp); //删除首元素后立刻在尾位补回 } return s.toString(); } /* Overloading allows different methods to have the same name, but different signatures where the signature can differ by the number of input parameters or type of input parameters or both. Overloading is related to compile-time (or static) polymorphism. */ /** 对单输入为String的isPalindrome进行重载,变成offByOne的Palindrome,写在前面方便看 */ public boolean isPalindrome(String word, CharacterComparator cc) { if (word.length() == 0 || word.length() == 1) { return true; } Deque<Character> t = wordToDeque(word); if (!cc.equalChars(t.removeFirst(), t.removeLast())) { return false; } else { return isPalindrome(dequeToString(t), cc); } } public boolean isPalindrome(String word) { if (word.length() == 0 || word.length() == 1) { // 此处必须加上等于1的条件,不然字符数为奇数时, // t.removeLast() != t.removeFirst(),会将最后一个字符和null比较 return true; } Deque<Character> t = wordToDeque(word); if (t.removeLast() != t.removeFirst()) { return false; } else { return isPalindrome(dequeToString(t)); } } /* isPalindrome solution1: use wordToDeque * 好处:可以直接将反过来的deque和正序deque比较,但是比较次数会加倍 **/ // public boolean isPalindrome(String word) { // if (word.length() == 0) { // return true; // } // Deque<Character> reverse = wordToDeque(word); // for (int i = 0; i < word.length(); i += 1) { // if (!reverse.removeLast().equals(word.charAt(i))) { // return false; // } // } // return true; // } /* isPalindrome solution2: not use wordToDeque */ // public boolean isPalindrome(String word) { // if (word.length() == 0 || word.length() == 1) { // return true; // } // for (int i = 0; i < word.length() / 2; i += 1) { // if (word.charAt(i) == word.charAt(word.length() - i -1)) { // continue; // } else { // return false; // } // } // return true; // } } <file_sep>package Lecture07.Project1B; import org.junit.Test; import static org.junit.Assert.*; /** Project 1B code is below * @author xerfat (at 2021.04.01) */ public class TestOffByN { static CharacterComparator offByN = new OffByOne(); @Test public void testIsPalindromeOffByN() { OffByN offBy5 = new OffByN(5); assertTrue(offBy5.equalChars('a', 'f')); // true assertTrue(offBy5.equalChars('f', 'a')); // true assertFalse(offBy5.equalChars('f', 'h')); // false } } <file_sep>package Lecture07.Project1B; import Lecture03.Lab02.DebugPractice.In; import Lecture040506.Project1A.AList; import Lecture040506.Project1A.ArrayDeque; import java.util.Arrays; /** Project 1B code is below * @author xerfat (at 2021.04.01) */ /** This class outputs all palindromes in the words file in the current directory. */ public class PalindromeFinder { public static void main(String[] args) { int minLength = 4; int N; In in = new In("/Lecture07/Project1B/words.txt"); Palindrome palindrome = new Palindrome(); CharacterComparator cc = new OffByOne(); int[] countN = new int[26]; Deque<String> longest = new ArrayDeque<>(); longest.addFirst(""); while (!in.isEmpty()) { String word = in.readString(); for (int i = 0; i < 26; i += 1) { if (word.length() >= minLength && palindrome.isPalindrome(word, new OffByN(i))) { if (word.length() > longest.get(0).length()) { longest = new ArrayDeque<>(); longest.addFirst(word); } else if (word.length() == longest.get(0).length()) { //获得字符串的长度是s.length() 是方法 //获得数组长度是s.length 是属性 longest.addLast(word); } System.out.println(word); countN[i] += 1; break; } } } System.out.println("The longest palindrome(s) is(are):"); for (int i = 0; i < longest.size(); i += 1) { System.out.print(longest.get(i) + " "); //用printDeque会打印出null } System.out.println(); int max = countN[0]; int mIndex = 0; for (int i = 0; i < countN.length; i++) { if (max < countN[i]){ max = countN[i]; mIndex = i; } } System.out.println("There are the most palindromes when N = "+ mIndex + ", and the number is " + max); } } //Uncomment this class once you've written isPalindrome.
c4506682dce9fa779d53dc9c35018c95b8e8c50f
[ "Java" ]
8
Java
xerfat/CS61B-sp19
a596b6d36da685463165218e2cfa135b5a55be3c
0248580612485eacebb5d97836501313c578bed3
refs/heads/master
<repo_name>tihandjan/codica-test-client-side<file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { MaterializeModule } from 'angular2-materialize'; import { Angular2TokenService } from 'angular2-token'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AuthService } from '../app/services/auth.service'; import { HttpModule } from '@angular/http'; import { MainComponent } from './components/main/main.component'; import { HeaderComponent } from './components/shared/header/header.component'; import { MainSidenavComponent } from './components/shared/main-sidenav/main-sidenav.component'; import { BookCardComponent } from './components/shared/cards/book-card/book-card.component'; @NgModule({ declarations: [ AppComponent, MainComponent, HeaderComponent, MainSidenavComponent, BookCardComponent ], imports: [ BrowserModule, AppRoutingModule, MaterializeModule, HttpModule ], providers: [Angular2TokenService, AuthService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/admin/admin.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LoginComponent } from './components/login/login.component'; import { DashboardComponent } from './components/dashboard/dashboard.component'; import { AdminComponent } from './admin.component'; import { AdminRoutingModule } from './admin-routing.module'; import { AdminGuard } from '../guards/admin.guard'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AuthService } from '../services/auth.service'; import { AuthorsComponent } from './components/authors/authors.component'; @NgModule({ imports: [ CommonModule, AdminRoutingModule, FormsModule, ReactiveFormsModule ], declarations: [ LoginComponent, DashboardComponent, AdminComponent, AuthorsComponent ], providers: [ AdminGuard, AuthService ] }) export class AdminModule { } <file_sep>/src/app/services/auth.service.ts import { Injectable } from '@angular/core'; import { Angular2TokenService } from 'angular2-token' import { Subject, Observable, Subscription } from 'rxjs'; import { map } from 'rxjs/operators/map'; import { User } from '../models/user' import { Response, RequestOptions, Headers } from '@angular/http'; import { BehaviorSubject } from 'rxjs'; import { environment } from '../../environments/environment'; declare var Materialize; @Injectable() export class AuthService { constructor( private auth: Angular2TokenService, ) { this.auth.init(environment.auth_routes); this.auth.validateToken().subscribe(res => { console.log(res.json().data); }) } validateUser() { return this.auth.validateToken() } userSignedIn(): boolean { return this.auth.userSignedIn(); } signUp(user):Observable<Response> { return this.auth.registerAccount(user).pipe( map(res => { let data = res.json().data; return data; }) ) } signIn(user: {email: string, password: string}): Observable<Response> { return this.auth.signIn(user).pipe( map( res => { let data = res.json().data; return res.json().data; } )) } signOut(): Observable<Response> { Materialize.toast('Hope to see you soon :)', 3000, 'red rounded'); return this.auth.signOut().pipe( map( res => { return res; } )) } get headers() { const tokens = { accessToken: this.auth.currentAuthData['accessToken'] || null, client: this.auth.currentAuthData['client'] || null, uid: this.auth.currentAuthData['uid'] || null, expiry: this.auth.currentAuthData['expiry'] || null, tokenType: this.auth.currentAuthData['tokenType'] || null, } const headers = new Headers(); headers.append('Accept','application/json'); headers.append('access-token', tokens.accessToken); headers.append('client', tokens.client); headers.append('uid', tokens.uid); headers.append('expiry', tokens.expiry); headers.append('token-type', tokens.tokenType); headers.append('content-type', 'application/json'); return new RequestOptions({headers: headers}); } } <file_sep>/src/app/guards/admin.guard.ts import { Injectable } from '@angular/core'; import { CanActivate, Router } from '@angular/router'; import { map } from 'rxjs/operators'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/of'; import { AuthService } from '../services/auth.service'; import { catchError } from 'rxjs/operators/catchError'; declare var Materialize; @Injectable() export class AdminGuard implements CanActivate { constructor( private router: Router, private auth: AuthService ) { } canActivate() { return this.auth.validateUser().pipe( map(res => { if (res.json().data.id === 1) { return true; } }), catchError(err => { this.router.navigate(['admin', 'login']) return Observable.of(false); }) ) } }<file_sep>/src/app/components/shared/main-sidenav/main-sidenav.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main-sidenav', templateUrl: './main-sidenav.component.html', styles: [] }) export class MainSidenavComponent implements OnInit { constructor() { } ngOnInit() { } }
fb9f8f7dd681a0d05c8694a2e7c976898ae64aef
[ "TypeScript" ]
5
TypeScript
tihandjan/codica-test-client-side
32bf7e10dfadd66be6addf0cb1cf4c9d44d689bb
8aebfd6699a23b71c57e091fa24a5282b55075a3
refs/heads/master
<repo_name>stevenalexander/node-addressbase-example<file_sep>/README.md # Node AddressBase example Sample NodeJS application to consume [OS AddressBase](https://www.ordnancesurvey.co.uk/business-and-government/products/addressbase-products.html) data into a Database and provide a simple location lookup service displaying a searched location on a map. Uses the AddressBase plus sample file (available for download [here](https://www.ordnancesurvey.co.uk/business-and-government/products/addressbase-plus.html)), processes it into a PostGres database and uses it for location searches. This file is limited to a section of Devon, use exact postcodes like 'EX2 9HD' to search. Requires: * NodeJS (v8+) * [OS AddressBase Plus](https://www.ordnancesurvey.co.uk/business-and-government/products/addressbase-plus.html) sample in GML format, `sx9090.gml`, downloaded and extracted in `data` folder. * PostGres instance with PostGIS extensions installed (for mac recommend [PostGres.app](http://postgresapp.com/)) * [GDAL tools - ogr2ogr](http://www.gdal.org/), for converting GML to PostGIS SQL ## Run ### 1. Setup database On a clean PostGres database with PostGIS extensions installed: ``` # add postgis extensions and create schema psql -d MYDATABASENAME -c 'CREATE EXTENSION postgis;' psql -d MYDATABASENAME -c 'CREATE SCHEMA data_import;' # translate and import data from GML file ogr2ogr -f "PostgreSQL" PG:"host=localhost port=5432 user=MYUSERNAME password=<PASSWORD> dbname=MYDATABASENAME" sx9090.gml -nln data_import.osgb_address_base_gml -geomfield geom ``` ### 2. Run Application ``` # envs (values for docker PostGIS) export PGHOST="localhost" export PGDATABASE="gis" export PGUSER="docker" export PGPASSWORD="<PASSWORD>" # app npm install npm start # http://localhost:3000 ``` ## Debug ``` node --inspect bin/www # open chrome://inspect and connect to debugger ``` ## Docker Run PostGIS exposing connection on 5432 locally with default db/user/pass - gis/docker/docker: ``` docker run --name "postgis" -p 5432:5432 -d -t kartoza/postgis:9.6-2.4 ``` ## Notes *Notes* * ogr2ogr arguments don't allow using a custom schema for PostGres, so need to use default schema name `data_import` *Useful info:* * Book - "Mastering PostGIS: Modern ways to create, analyze, and implement spatial" by <NAME>, <NAME>, <NAME> * [GDAL - ogr2ogr format translator tools](http://www.gdal.org/) * [Blog - OS AddressBase and ogr2ogr](https://jonathanjstokes.wordpress.com/2014/04/02/os-addressbase-and-ogr2ogr/) * [Knex PostGIS extension](https://www.npmjs.com/package/knex-postgis) and [cheatsheet](http://www.g9labs.com/2016/04/08/knex-dot-js-and-bookshelf-dot-js-cheat-sheet/) *Possible enhancements* * Fulltext search on joined together address fields, e.g. match "COWICK" to "1 COWICK LANE..." * Use JQuery autocomplete to replace table results with AJAX driven dropdown * Allow prefixes on search to search specific address fields like UPRN and USRN, e.g. "UPRN:990040239484" * Try AddressBase Premium sample, which includes some street and lifecycle details<file_sep>/routes/index.js var express = require('express') var router = express.Router() var config = require('../knexfile').development var knex = require('knex')(config) var knexPostgis = require('knex-postgis')(knex) /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { locations: [] }) }) router.post('/', function (req, res, next) { let searchText = req.body.searchText if (searchText) { knex .select('uprn', 'buildingnumber', 'streetdescription', 'townname', 'administrativearea', 'postcode', knexPostgis.asGeoJSON('wkb_geometry')) .from('data_import.osgb_address_base_gml') .where('postcode', searchText) .limit(20) .then((results) => { let locations = results.map(result => { return { location: [ result['uprn'], result['buildingnumber'], result['streetdescription'], result['townname'], result['administrativearea'], result['postcode'] ].join(', '), coordinates: result['wkb_geometry'], coordinatesString: JSON.parse(result['wkb_geometry']).coordinates.join(',') } }) res.render('index', { locations: locations, searchText: searchText }) }) .catch((error) => { next(error) }) } else { res.render('index', { locations: [] }) } }) module.exports = router
c86b060e220696b3406a59b3b7504424f9a81fd6
[ "Markdown", "JavaScript" ]
2
Markdown
stevenalexander/node-addressbase-example
0fe196549906023284fb38195daace88e70b6894
22ae361726db664cc0d4e52611af39dc17ccf2f2
refs/heads/master
<file_sep>package by.gsyrov.regex; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SearchWithRegEx { private ArrayList<String> matchesArray= new ArrayList<String>(); private String regValue; protected SearchWithRegEx(String regValue) { this.regValue = regValue; } protected SearchWithRegEx(String str, String regValue) { this(regValue); getMatchesFromStr(str); } public ArrayList<String> getMatchesArray() { return matchesArray; } public void print() { for(String match : matchesArray) { System.out.println(match); } } public void getMatchesFromStr(String str) { Pattern regexp = Pattern.compile(regValue); Matcher matcher = regexp.matcher(str); while (matcher.find()) { matchesArray.add(matcher.group()); } } } <file_sep>package by.gsyrov.directory.analyze; import java.io.File; public class Main { public static void main (String[] args) throws InterruptedException { File directory = new File("D:\\Git\\study\\Catalog"); if(directory.isDirectory()) { while(directory.exists()) { String[] files = directory.list(); for(String fileName : files) { System.out.println(fileName); } Thread.sleep(600000); } } } }
1448b3e3fb6802766b7466695294b6e747bee72f
[ "Java" ]
2
Java
OSmol/study
e24d72ce37fb0abf7c4890c10a5bede7465b2d7c
c9b744324cbd7d1a59b5d8794855fa745b043998
refs/heads/master
<file_sep># zinit plugin configuration files for oh-my-zsh **backup .zshrc** - incr-0.2.zsh - alias.zsh <file_sep># Add Program environment path test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh" export PATH="/usr/local/opt/python@3.10/bin:$PATH" <file_sep>#---------------------------- # custom alias - #---------------------------- alias rmr='rm -rf' alias ~.='cd ~' alias ..='cd ../' alias ...='cd ../../' alias ....='cd ../../../' alias tarc='tar cvf' alias tgz='tar zcvf' alias tbz2='tar jcvf' alias ipy='python3 -m ipython' alias gita='git add' alias gitco='git commit -m' alias gitpu='git pull' alias gitps='git push' <file_sep># If you come from bash you might have to change your $PATH. # export PATH=$HOME/bin:/usr/local/bin:$PATH # Path to your oh-my-zsh installation. export ZSH="/Users/jake/.oh-my-zsh" source ~/.zinit/bin/zinit.zsh autoload -Uz _zinit (( ${+_comps} )) && _comps[zinit]=_zinit ######################-------------------------------------------------######################## #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # > # oh-my-zsh 框架、插件 > # > #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> zinit for \ OMZ::lib/completion.zsh \ OMZ::lib/history.zsh \ OMZ::lib/key-bindings.zsh \ OMZ::lib/theme-and-appearance.zsh \ OMZ::plugins/colored-man-pages/colored-man-pages.plugin.zsh \ OMZ::plugins/sudo/sudo.plugin.zsh #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # < # snippet files < # < #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # 解压缩 zinit ice svn zinit snippet OMZ::plugins/extract # alias zinit ice licid wait='2' zinit snippet 'https://github.com/JakeYue/p-zinit/blob/master/alias.zsh' # git zinit ice lucid wait='2' zinit snippet OMZ::plugins/git/git.plugin.zsh # incr autocomplete zinit ice lucid wait"1" zinit snippet 'https://github.com/JakeYue/p-zinit/blob/master/incr-0.2.zsh' # search zinit ice lucid wait"2" zinit snippet OMZ::plugins/web-search/web-search.plugin.zsh # docker zinit ice as"completion" zinit snippet 'https://github.com/ohmyzsh/ohmyzsh/blob/master/plugins/docker/_docker' #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # > # light-mode > # > #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # 语法高亮 zinit light-mode wait='1' lucid for \ rupa/z \ atinit='zpcompinit' zdharma/fast-syntax-highlighting \ atload='_zsh_autosuggest_start' zsh-users/zsh-autosuggestions \ # zsh-users/zsh-completions # dracula 主题 zinit light dracula/zsh # vim zinit ice as"program" atclone"rm -f src/auto/config.cache; ./configure" \ atpull"%atclone" make pick"src/vim" zinit light vim/vim #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> # > # iTrem2 > # > #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> test -e "${HOME}/.iterm2_shell_integration.zsh" && source "${HOME}/.iterm2_shell_integration.zsh"
a5fee9cea5bfe9a906714d9ad72dc39a4a6bf2a8
[ "Markdown", "Shell" ]
4
Markdown
JakeYue/misc
6dd4f81a2af278f217f5cd7bd912594305da1cca
9f2f377f44a85190b4a595c260f5f735926d9b8e
refs/heads/master
<file_sep><?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App; use Session; use DB; class dasboardController extends Controller { public function index(Request $request) { //if(!Session::get('login')) { return redirect('login'); } Session::put('locale', 'id'); App::setlocale(Session::get('locale')); $data = []; $data['router'] = ['']; return view('dashboard.index')->with('data',$data); } }
6c5dd7cbdc74b672457c370c5e8741d4e3d95e0d
[ "PHP" ]
1
PHP
SepianusGulo/nms-master
fac2c31d9434e25be5d099830f771ba6b5f38122
4440384b2252cd77eee32b78d99042ea95c0e120
refs/heads/master
<file_sep>#!/bin/bash DROPLET_NAME="do-sshuttle-server" DROPLET_FILE=/tmp/droplet-vpn.json echo "do-shuttle v0.0.1" echo "<NAME> <<EMAIL>>" echo "Transparent Proxying over DigitalOcean Droplets" prefix="[ds]" echo if [ ! -f $DROPLET_FILE ]; then echo "$prefix <--- Getting $DROPLET_NAME Droplet information..." DROPLET_INFO=`doctl compute droplet list $DROPLET_NAME --output json` echo $DROPLET_INFO > $DROPLET_FILE fi DROPLET_IP=`cat $DROPLET_FILE | python -c 'import sys, json; print json.load(sys.stdin)[0]["networks"]["v4"][0]["ip_address"]'` DROPLET_ID=`cat $DROPLET_FILE | python -c 'import sys, json; print json.load(sys.stdin)[0]["id"]'` echo "$prefix ---> Powering on $DROPLET_NAME (root@$DROPLET_IP) Droplet..." doctl compute droplet-action power-on $DROPLET_ID > /dev/null echo "$prefix ---> Power-on Request sent..." echo "$prefix ---> Allow server 10 seconds to boot..." sleep 10 echo "$prefix ---> Proxying network via sshuttle..." sshuttle -r root@$DROPLET_IP 0.0.0.0/0 > /dev/null echo "$prefix ---> sshuttle stopped..." echo "$prefix ---> Powering off $DROPLET_NAME (root@$DROPLET_IP) Droplet..." doctl compute droplet-action power-off $DROPLET_ID > /dev/null echo "$prefix ---> Power-off Request sent..." echo "$prefix ---> Bye."<file_sep># DO-sshuttle Transparent your Proxy your connection over your DigitalOcean Droplet. ## Installation ### 1. Install Requirements ```sh # Install DigitalOcean CLI Tool brew install doctl # Install sshuttle brew install sshuttle ``` ### 2. Generate DigitalOcean API Key Generate a key from [https://cloud.digitalocean.com/settings/api/tokens](https://cloud.digitalocean.com/settings/api/tokens) ### 3. Login via `doctl` ```sh doctl auth login # Enter your API key you generated. ``` ### 4. Create a Droplet called `do-sshuttle-server` Create a Droplet on your DigitalOcean account. Name it `do-sshuttle-server`. ### 5. Start Proxying. ```sh $ ./do-sshuttle do-shuttle v0.0.1 <NAME> <<EMAIL>> Transparent Proxying over DigitalOcean Droplets [ds] <--- Getting do-sshuttle-server Droplet information... [ds] ---> Powering on do-sshuttle-server (root@<IP ADDRESS>) Droplet... [ds] ---> Power-on Request sent... [ds] ---> Allow server 10 seconds to boot... [ds] ---> Proxying network via sshuttle... client: Connected. ``` ## LICENSE WTFPL.
747d3a22e00ae0baa6898501a63d1fe60a106fdd
[ "Markdown", "Shell" ]
2
Shell
f/do-sshuttle
91a94154d0e9d4309bf62357a5d7dad91750e077
c48666d6f7850abbb2c0d5f016ff71792e5a4ed5
refs/heads/main
<repo_name>GabrielCampos07/lessashoes<file_sep>/Front/LessaShoes-APP/src/app/app-routing.module.ts import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { AuthGuard } from './auth/auth.guard'; import { DashboardComponent} from './components/paginainicial/paginainicial.component'; import { TenisComponent } from './components/tenis/tenis.component'; import { TenisaddComponent } from './components/tenis/tenisadd/tenisadd.component'; import { TenislistaComponent } from './components/tenis/tenislista/tenislista.component'; import { LoginComponent } from './components/user/login/login.component'; import { RegistrarComponent } from './components/user/registrar/registrar.component'; import { UserComponent } from './components/user/user.component'; const routes: Routes = [ { path: 'user', component: UserComponent, children: [ { path: 'login', component: LoginComponent }, { path: 'registrar', component: RegistrarComponent } ], }, { path: 'tenis', component: TenisComponent, children: [ { path: 'detalhe/:id', component: TenisaddComponent, canActivate: [AuthGuard] }, { path: 'detalhe', component: TenisaddComponent, canActivate: [AuthGuard] }, { path: 'lista', component: TenislistaComponent, canActivate: [AuthGuard] }, ], }, { path: 'paginainicial', component: DashboardComponent, canActivate: [AuthGuard] }, { path: '', redirectTo: 'paginainicial', pathMatch: 'full' }, { path: '**', redirectTo: 'paginainicial', pathMatch: 'full' }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {} <file_sep>/Front/LessaShoes-APP/src/app/services/tenis.service.ts import { Tenis } from './../Models/Tenis' import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable } from 'rxjs'; import { take } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; @Injectable() export class tenis { BaseURL = environment.apiURL + 'api/tenis'; constructor(private http: HttpClient) { } public getTenis() : Observable<Tenis[]> { return this.http.get<Tenis[]>(this.BaseURL); } public getTenisByNome(nome: string) : Observable<Tenis[]> { return this.http.get<Tenis[]>(`${this.BaseURL}/${nome}/nome`); } public getTenisById(id: number) : Observable<Tenis> { return this.http.get<Tenis>(`${this.BaseURL}/${id}`); } public post(tenis: Tenis) : Observable<Tenis> { return this.http .post<Tenis>(this.BaseURL, tenis) .pipe(take(1)); } public put(id: number, tenis: Tenis) : Observable<Tenis> { return this.http .put<Tenis>(`${this.BaseURL}/${id}`, tenis) .pipe(take(1)); } public delete(id: number) : Observable<any> { return this.http .delete(`${this.BaseURL}/${id}`) .pipe(take(1)); } public postUpload(tenisId: number, arquivo: File[]): Observable<Tenis> { const arquivoUpload = arquivo[0] as File; const formData = new FormData(); formData.append('arquivo', arquivoUpload); return this.http .post<Tenis>(`${this.BaseURL}/upload/${tenisId}`, formData) .pipe(take(1)); } } <file_sep>/back/LessaShoes.API/Controllers/UsuarioController.cs using AutoMapper; using LessaShoes.Application.Dtos; using LessaShoes.Domain.Identity; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace LessaShoes.API.Controllers { [ApiController] [Route("/api/usuario")] public class UsuarioController : ControllerBase { private readonly IConfiguration _config; private readonly UserManager<Usuario> _userManager; private readonly SignInManager<Usuario> _signInManager; private readonly IMapper _mapper; public UsuarioController(IConfiguration config, UserManager<Usuario> userManager, SignInManager<Usuario> signInManager, IMapper mapper) { _config = config; _userManager = userManager; _signInManager = signInManager; _mapper = mapper; } [HttpGet("CarregarUsuario")] public async Task<IActionResult> CarregarUsuario() { return Ok(new UsuarioDto()); } [HttpPost("Registrar")] [AllowAnonymous] public async Task<IActionResult> RegistrarUsuario(UsuarioDto usuarioDto) { try { var usuario = _mapper.Map<Usuario>(usuarioDto); var resultado = await _userManager.CreateAsync(usuario, usuarioDto.Password); var retornarUsuario = _mapper.Map<UsuarioDto>(usuario); if (resultado.Succeeded) { return Created("CarregarUsuario", retornarUsuario); } return BadRequest(resultado.Errors); } catch (Exception ex) { throw new Exception(ex.Message); } } [HttpPost("Login")] [AllowAnonymous] public async Task<IActionResult> Login(UsuarioLoginDto usuarioLogin) { try { var usuario = await _userManager.FindByNameAsync(usuarioLogin.UserName); var resultado = await _signInManager.CheckPasswordSignInAsync(usuario, usuarioLogin.Password, false); if(resultado.Succeeded) { var appUsuario = await _userManager.Users .FirstOrDefaultAsync(u => u.NormalizedUserName == usuarioLogin.UserName.ToUpper()); var usuarioRetorno = _mapper.Map<UsuarioLoginDto>(appUsuario); ; return Ok(new { token = GenerateJWToken(appUsuario).Result, usuario = usuarioRetorno }); } return Unauthorized(); } catch (Exception ex) { throw new Exception(ex.Message); } } private async Task<string> GenerateJWToken(Usuario usuario) { var claims = new List<Claim> { new Claim(ClaimTypes.NameIdentifier, usuario.Id.ToString()), new Claim(ClaimTypes.Name, usuario.UserName) }; var cargos = await _userManager.GetRolesAsync(usuario); foreach (var cargo in cargos) { claims.Add(new Claim(ClaimTypes.Role, cargo)); } var chave = new SymmetricSecurityKey(Encoding.ASCII .GetBytes(_config.GetSection("AppSettings:Token").Value)); var creds = new SigningCredentials(chave, SecurityAlgorithms.HmacSha512Signature); var tokenDescritor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.Now.AddDays(1), SigningCredentials = creds }; var tokenManipulador = new JwtSecurityTokenHandler(); var token = tokenManipulador.CreateToken(tokenDescritor); return tokenManipulador.WriteToken(token); } } } <file_sep>/Front/LessaShoes-APP/src/app/services/autenticacao.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { JwtHelperService } from '@auth0/angular-jwt'; import { map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; @Injectable({ providedIn: 'root' }) export class AutenticacaoService { BaseURL = environment.apiURL + 'api/usuario/'; ajudaJwt = new JwtHelperService(); tokenDeco: any; constructor(private http: HttpClient) { } login(model: any) { return this.http.post(`${this.BaseURL}Login`, model).pipe( map((Response: any) => { const usuario = Response; if(usuario) { localStorage.setItem('token', usuario.token); this.tokenDeco = this.ajudaJwt.decodeToken(usuario.token); sessionStorage.setItem('username', this.tokenDeco.unique_name); } }) ) } registrar(model: any) { return this.http.post(`${this.BaseURL}Registrar`, model); } } <file_sep>/back/LessaShoes.Application/Dtos/TenisDto.cs using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace LessaShoes.Application.Dtos { public class TenisDto { public int TenisID { get; set; } public string ImagemURL { get; set; } [Required(ErrorMessage = "O campo {0} é obrigatório")] public string NomeTenis { get; set; } [Required(ErrorMessage = "O campo {0} é obrigatório")] public int Tamanho { get; set; } [Range(0, 1200, ErrorMessage = "Não pode ser menor que zero e maior que 1200")] public int QtdTenis { get; set; } public string Marca { get; set; } } } <file_sep>/back/LessaShoes.Application/TenisService.cs using System; using System.Threading.Tasks; using AutoMapper; using LessaShoes.Application.Contratos; using LessaShoes.Application.Dtos; using LessaShoes.Domain; using LessaShoes.Persistance.Contratos; namespace LessaShoes.Application { public class TenisService : ITenisService { private IGeralPersist _GeralPersist; private readonly ITenisPersist _TenisPersist; private readonly IMapper _mapper; public TenisService(IGeralPersist GeralPersist, ITenisPersist TenisPersist, IMapper mapper) { _GeralPersist = GeralPersist; _TenisPersist = TenisPersist; _mapper = mapper; } public async Task<TenisDto> AddTenis(TenisDto model) { try { var tenis = _mapper.Map<Tenis>(model); _GeralPersist.add<Tenis>(tenis); if (await _GeralPersist.SaveChangesAsync()) { var tenisRetorno = await _TenisPersist.GetTenisByIDAsync(tenis.TenisID); return _mapper.Map<TenisDto>(tenisRetorno); } return null; } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<TenisDto> UpdateTenis(int tenisID, TenisDto model) { try { var tenis = await _TenisPersist.GetTenisByIDAsync(tenisID); if (tenis == null) throw new Exception("O ID para atualização não foi encontrado"); model.TenisID = tenisID; _mapper.Map(model, tenis); _GeralPersist.Update<Tenis>(tenis); if (await _GeralPersist.SaveChangesAsync()) { var tenisRetorno = await _TenisPersist.GetTenisByIDAsync(tenis.TenisID); return _mapper.Map<TenisDto>(tenisRetorno); } return null; } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<TenisDto[]> GetAllTenisAsync() { try { var tenis = await _TenisPersist.GetAllTenisAsync(); if (tenis == null) return null; var resultado = _mapper.Map<TenisDto[]>(tenis); return resultado; } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<TenisDto[]> GetAllTenisByNameAsync(string nome) { var tenis = await _TenisPersist.GetAllTenisByNameAsync(nome); if (tenis == null) return null; var resultado = _mapper.Map<TenisDto[]>(tenis); return resultado; } public async Task<TenisDto> GetTenisByIDAsync(int tenisID) { try { var tenis = await _TenisPersist.GetTenisByIDAsync(tenisID); if (tenis == null) return null; var resultado = _mapper.Map<TenisDto>(tenis); return resultado; } catch (Exception ex) { throw new Exception(ex.Message); } } public async Task<bool> Delete(int tenisID) { try { var tenis = await _TenisPersist.GetTenisByIDAsync(tenisID); if (tenis == null) throw new Exception("Não foi possível excluir o tenis"); _GeralPersist.Delete(tenis); return await _GeralPersist.SaveChangesAsync(); } catch (Exception ex) { throw new Exception(ex.Message); } } } }<file_sep>/Front/LessaShoes-APP/src/app/components/tenis/tenisadd/tenisadd.component.ts import { ActivatedRoute, Router } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { NgxSpinnerService, Spinner } from 'ngx-spinner'; import { ToastrService } from 'ngx-toastr'; import { Tenis } from 'src/app/Models/Tenis'; import { tenis } from 'src/app/services/tenis.service'; import { environment } from 'src/environments/environment'; @Component({ selector: 'app-tenisadd', templateUrl: './tenisadd.component.html', styleUrls: ['./tenisadd.component.scss'], }) export class TenisaddComponent implements OnInit { constructor( private TenisService: tenis, private toastr: ToastrService, private router: ActivatedRoute, private spinner: NgxSpinnerService, private formB: FormBuilder, private route: Router ) {} ngOnInit() { this.carregarTenis(); this.validacao(); } public imagemURL = 'assets/thais2.png'; public arquivo: File[] = []; public idUsuario!: number; tenis = {} as Tenis; // Código do form public estadoSalvar = 'post'; form = {} as FormGroup; public id = 0; get fb(): any { return this.form.controls; } public validacao(): void { this.form = this.formB.group({ nomeTenis: [ '', [ Validators.required, Validators.minLength(4), Validators.maxLength(20), ], ], marca: ['', [Validators.required]], tamanho: [ '', [Validators.required, Validators.minLength(2), Validators.maxLength(2)], ], qtdTenis: ['', [Validators.required, Validators.minLength(1)]], imagemURL: [''], }); } public cancelarForm(): void { this.form.reset(); } public salvarAlteracao(): void { this.spinner.show(); if (this.form.valid) { if (this.estadoSalvar === 'post') { this.tenis = { ...this.form.value }; this.TenisService.post(this.tenis).subscribe( (tenisRetorno: Tenis) => { this.route.navigate([`tenis/detalhe/${tenisRetorno.tenisID}`]); this.toastr.success('Tênis salvo com sucesso'); }, (error: any) => { this.toastr.error('Erro ao salvar o tênis', 'Erro!'), this.spinner.hide(); }, () => this.spinner.hide() ); } else { this.id = this.tenis.tenisID; this.tenis = { ...this.form.value }; this.TenisService.put(+this.id, this.tenis).subscribe( (tenisRetorno: Tenis) => { this.route.navigate([`tenis/lista`]); this.toastr.success('Tênis salvo com sucesso') }, (error: any) => { console.error(error); this.toastr.error('Erro ao salvar o tênis', 'Erro!'), this.spinner.hide(); }, () => this.spinner.hide() ); } } } public carregarTenis(): void { const tenisIdParam = this.router.snapshot.paramMap.get('id'); if (tenisIdParam !== null) { this.spinner.show(); this.estadoSalvar = 'put'; this.TenisService .getTenisById(+tenisIdParam) .subscribe( (tenis: Tenis) => { this.tenis = { ...tenis }; this.form.patchValue(this.tenis); if (this.tenis.imagemURL !== null) { this.imagemURL = environment.apiURL + 'Recursos/imagens/' + this.tenis.imagemURL; } }, (error: any) => { console.error(error); } ) .add(() => this.spinner.hide()); } } public mudarImagem(ev: any) { const leitor = new FileReader(); leitor.onload = (evento: any) => (this.imagemURL = evento.target.result); this.arquivo = ev.target.files; leitor.readAsDataURL(this.arquivo[0]); this.uploadImagem(); } public uploadImagem(): void { this.idUsuario = this.tenis.tenisID; this.spinner.show(); this.TenisService.postUpload(this.idUsuario, this.arquivo) .subscribe( () => { this.carregarTenis(); this.toastr.success('Sucesso ao atualizar a imagem', 'Sucesso'); }, (error: any) => { console.error(error); this.toastr.error('Não foi possível atualizar a imagem', 'Erro!'); } ) .add(() => this.spinner.hide()); } } <file_sep>/back/LessaShoes.Persistance/Contratados/TenisPersist.cs using System.Linq; using System.Threading.Tasks; using LessaShoes.Domain; using LessaShoes.Persistance.Contratos; using Microsoft.EntityFrameworkCore; namespace LessaShoes.Persistance.Contratados { public class TenisPersist : ITenisPersist { private readonly LessaShoesContext _context; public TenisPersist(LessaShoesContext context) { _context = context; } public async Task<Tenis[]> GetAllTenisAsync() { IQueryable<Tenis> query = _context.Tenis; query = query.AsNoTracking().OrderBy(e => e.TenisID); return await query.ToArrayAsync(); } public async Task<Tenis[]> GetAllTenisByNameAsync(string nome) { IQueryable<Tenis> query = _context.Tenis; query = query.AsNoTracking().OrderBy(e => e.NomeTenis) .Where(e => e.NomeTenis.ToLower().Contains(nome.ToLower())); return await query.ToArrayAsync(); } public async Task<Tenis> GetTenisByIDAsync(int tenisID) { IQueryable<Tenis> query = _context.Tenis; query = query.AsNoTracking().OrderBy(e => e.TenisID) .Where(e => e.TenisID == tenisID); return await query.FirstOrDefaultAsync(); } } }<file_sep>/Front/LessaShoes-APP/src/app/components/user/registrar/registrar.component.ts import { AbstractControlOptions, FormBuilder, FormControl, FormGroup, Validators, } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; import { CamposValidacao } from 'src/app/Helpers/CamposValidacao'; import { ToastrService } from 'ngx-toastr'; import { Usuario } from 'src/app/Models/Usuario'; import { AutenticacaoService } from 'src/app/services/autenticacao.service'; import { Router } from '@angular/router'; import { NgxSpinnerService, Spinner } from 'ngx-spinner'; import { Element } from '@angular/compiler'; import { elementAt } from 'rxjs/operators'; import { error } from '@angular/compiler/src/util'; import { NgElement } from '@angular/elements'; @Component({ selector: 'app-registrar', templateUrl: './registrar.component.html', styleUrls: ['./registrar.component.scss'], }) export class RegistrarComponent implements OnInit { constructor( private formB: FormBuilder, private toastr: ToastrService, private authService: AutenticacaoService, private router: Router, private spinner: NgxSpinnerService ) {} ngOnInit(): void { this.validacao(); } imagem = 'assets/thais2.png'; usuario = {} as Usuario; form = {} as FormGroup; get fb(): any { return this.form.controls; } public cadastrarUsuario() { if (this.form.valid) { this.usuario = Object.assign( { Password: this.form.get('password.password')?.value }, this.form.value ); this.authService .registrar(this.usuario) .subscribe( () => { this.spinner.show(); this.router.navigate(['/user/login']); this.toastr.success('Cadastro realizado com sucesso', 'sucesso'); }, (error: any) => { this.toastr.error('Erro ao criar o usuário', 'Erro'); } ) .add(() => this.spinner.hide()); } } public cssValidador(campo: FormControl): any { return { 'is-invalid': campo?.errors && campo?.touched }; } public validacao(): void { const formOptions: AbstractControlOptions = { validators: CamposValidacao.ConfirmarCampo('Password', 'ConfirmPassword'), }; this.form = this.formB.group( { NomeCompleto: ['', [Validators.required]], UserName: ['', [Validators.required]], Email: ['', [Validators.required, Validators.email]], Password: ['', [Validators.required, Validators.minLength(8)]], ConfirmPassword: ['', [Validators.required, Validators.minLength(8)]], }, formOptions ); } } <file_sep>/Front/LessaShoes-APP/src/app/components/tenis/tenislista/tenislista.component.ts import { Component, OnInit, TemplateRef } from '@angular/core'; import { Router } from '@angular/router'; import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal'; import { NgxSpinnerService } from 'ngx-spinner'; import { ToastrService } from 'ngx-toastr'; import { Tenis } from 'src/app/Models/Tenis'; import { tenis } from 'src/app/services/tenis.service'; import { environment } from 'src/environments/environment'; @Component({ selector: 'app-tenislista', templateUrl: './tenislista.component.html', styleUrls: ['./tenislista.component.scss'], }) export class TenislistaComponent implements OnInit { constructor( private TenisService: tenis, private toastr: ToastrService, private modalService: BsModalService, private spinner: NgxSpinnerService, private router: Router ) {} public tenisFiltrados: Tenis[] = []; public tenis: Tenis[] = []; public tenisID = 0; public margemImagem: number = 30; public larguraImagem: number = 30; public exibirImagem: boolean = true; public corBranca: string = 'white'; public fundoPreto: string = 'black'; public botaoPadrao: string[] = [ 'border-radius: 50px', 'background: black', 'color: white', ]; private _filtroLista: string = ''; public ngOnInit() { this.carregarTenis(); this.spinner.show(); } public get filtroLista(): string { return this._filtroLista; } public set filtroLista(value: string) { this._filtroLista = value; } public Buscar(): Tenis[] { return (this.tenisFiltrados = this.filtroLista ? this.filtrarTenis(this.filtroLista) : this.tenis); } public filtrarTenis(filtrarPor: string): Tenis[] { filtrarPor = filtrarPor.toLocaleLowerCase(); return this.tenis.filter( (tenis) => tenis.nomeTenis.toLocaleLowerCase().indexOf(filtrarPor) != -1 ); } public mostraImagem(imagemURL: string): string { return (imagemURL !== null) ? `${environment.apiURL}Recursos/imagens/${imagemURL}` : 'assets/thais2.png'; } public alternarImagem(): void { if (!this.exibirImagem) { this.corBranca = 'white'; this.fundoPreto = 'black'; } else { this.corBranca = 'black'; this.fundoPreto = 'white'; } this.exibirImagem = !this.exibirImagem; } public carregarTenis(): void { this.TenisService.getTenis() .subscribe( (_Tenis: Tenis[]) => { this.tenis = _Tenis; this.tenisFiltrados = this.tenis; }, (error) => { this.toastr.error('Erro ao carregar os Tenis'); } ) .add(() => this.spinner.hide()); } public detalheID(id:number) { this.router.navigate([`tenis/detalhe/${id}`]); } modalRef = {} as BsModalRef; public openModal(template: TemplateRef<any>, tenisID: number): void { this.tenisID = tenisID; this.modalRef = this.modalService.show(template, { class: 'modal-sm' }); } public tenisAtulizar(id: number): void { this.router.navigate([`tenis/detalhe/${id}`]); } public confirm(): void { this.modalRef.hide(); this.spinner.show(); this.TenisService.delete(this.tenisID) .subscribe( (result: any) => { this.toastr.success('O tenis foi excluido.', 'Sucesso!'); this.carregarTenis(); }, (error: any) => { console.error(error); this.toastr.error( `Erro ao tentar deletar o evento ${this.tenisID}`, 'Erro' ); } ) .add(() => this.spinner.hide()); } public decline(): void { this.modalRef.hide(); } } <file_sep>/back/LessaShoes.Domain/tenis.cs using System.ComponentModel.DataAnnotations; namespace LessaShoes.Domain { public class Tenis { public int TenisID { get; set; } public string ImagemURL { get; set; } [Required] public string NomeTenis { get; set; } [Required] public int Tamanho { get; set; } [Required] public int QtdTenis { get; set; } public string Marca {get; set;} } }<file_sep>/Front/LessaShoes-APP/src/app/Shared/nav/nav.component.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { ToastrService } from 'ngx-toastr'; import { AutenticacaoService } from 'src/app/services/autenticacao.service'; @Component({ selector: 'app-nav', templateUrl: './nav.component.html', styleUrls: ['./nav.component.scss'], }) export class NavComponent implements OnInit { larguraImagem: number = 80; alturaImagem: number = 80; bgBlack: string = 'background: black'; isCollapsed: boolean = true; constructor( public authService: AutenticacaoService, public router: Router, private toastr: ToastrService ) {} ngOnInit() {} logado() { if (localStorage.getItem('token')) return true; else return false; } logout() { localStorage.removeItem('token'); this.router.navigate(['user/login']); } userName() { return sessionStorage.getItem('username'); } } <file_sep>/Front/LessaShoes-APP/src/app/Helpers/CamposValidacao.ts import { AbstractControl, FormGroup } from '@angular/forms'; export class CamposValidacao { static ConfirmarCampo(senha: string, confirmacaoSenha: string): any { return (group: AbstractControl) => { const formGroup = group as FormGroup; const primeiraSenha = formGroup.controls[senha]; const confirmarSenha = formGroup.controls[confirmacaoSenha]; if (confirmarSenha.errors && !confirmarSenha.errors.mustMatch) { return null; } if (primeiraSenha.value !== confirmarSenha.value) { confirmarSenha.setErrors({ mustMatch: true }); } else { confirmarSenha.setErrors(null); } return null; }; } } <file_sep>/back/LessaShoes.Application/Ajudantes/AutoMapperProf.cs using AutoMapper; using LessaShoes.Application.Dtos; using LessaShoes.Domain; using LessaShoes.Domain.Identity; namespace LessaShoes.Application.Ajudantes { public class AutoMapperProf : Profile { public AutoMapperProf() { CreateMap<Tenis, TenisDto>().ReverseMap(); CreateMap<Usuario, UsuarioDto>().ReverseMap(); CreateMap<Usuario, UsuarioLoginDto>().ReverseMap(); } } } <file_sep>/back/LessaShoes.Application/Contratos/ITenisService.cs using System.Threading.Tasks; using LessaShoes.Application.Dtos; namespace LessaShoes.Application.Contratos { public interface ITenisService { Task<TenisDto> AddTenis(TenisDto model); Task<TenisDto> UpdateTenis(int tenisID, TenisDto model); Task<bool> Delete(int tenisID); Task<TenisDto[]> GetAllTenisAsync(); Task<TenisDto> GetTenisByIDAsync(int tenisID); Task<TenisDto[]> GetAllTenisByNameAsync(string nome); } }<file_sep>/back/LessaShoes.Domain/Identity/Cargo.cs using System.Collections.Generic; using Microsoft.AspNetCore.Identity; namespace LessaShoes.Domain.Identity { public class Cargo : IdentityRole<int> { public List<UsuarioCargo> UsuarioCargos { get; set; } } }<file_sep>/back/LessaShoes.Domain/Identity/Usuario.cs using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using Microsoft.AspNetCore.Identity; namespace LessaShoes.Domain.Identity { public class Usuario : IdentityUser<int> { [Column(TypeName = "varchar(150)")] public string NomeCompleto { get; set; } public List<UsuarioCargo> UsuarioCargos { get; set; } } }<file_sep>/Front/LessaShoes-APP/src/app/Models/Tenis.ts export interface Tenis { tenisID: number nomeTenis: string marca: string imagemURL: string tamanho: number qtdTenis: number } <file_sep>/Front/LessaShoes-APP/src/app/app.module.ts import { AppComponent } from './app.component'; import { CabecalhoComponent } from './Shared/cabecalho/cabecalho.component'; import { DashboardComponent } from './components/paginainicial/paginainicial.component'; import { NavComponent } from './Shared/nav/nav.component'; import { LoginComponent } from './components/user/login/login.component'; import { UserComponent } from './components/user/user.component'; import { RegistrarComponent } from './components/user/registrar/registrar.component'; import { TenisComponent } from './components/tenis/tenis.component'; import { TenisaddComponent } from './components/tenis/tenisadd/tenisadd.component'; import { TenislistaComponent } from './components/tenis/tenislista/tenislista.component'; import { AppRoutingModule } from './app-routing.module'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { BsDropdownModule, BsDropdownConfig } from 'ngx-bootstrap/dropdown'; import { CollapseModule } from 'ngx-bootstrap/collapse'; import { ModalModule, BsModalService } from 'ngx-bootstrap/modal'; import { TooltipModule } from 'ngx-bootstrap/tooltip'; import { CommonModule } from '@angular/common'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NgModule } from '@angular/core'; import { ToastrModule } from 'ngx-toastr'; import { NgxSpinnerModule } from 'ngx-spinner'; import { tenis } from './services/tenis.service'; import { AuthInterceptador } from './auth/auth.interceptador'; @NgModule({ declarations: [ AppComponent, NavComponent, CabecalhoComponent, DashboardComponent, TenisComponent, TenisaddComponent, TenislistaComponent, UserComponent, LoginComponent, RegistrarComponent, ], imports: [ CommonModule, BrowserModule, AppRoutingModule, HttpClientModule, ReactiveFormsModule, BrowserAnimationsModule, FormsModule, BsDropdownModule, CollapseModule, NgxSpinnerModule, ModalModule.forRoot(), CollapseModule.forRoot(), TooltipModule.forRoot(), ToastrModule.forRoot({ timeOut: 3000, positionClass: 'toast-bottom-right', preventDuplicates: true, progressBar: true, }), ], providers: [tenis, { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptador, multi: true }], bootstrap: [AppComponent], }) export class AppModule {} <file_sep>/Front/LessaShoes-APP/src/app/Shared/cabecalho/cabecalho.component.ts import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector: 'cabecalho', templateUrl: './cabecalho.component.html', styleUrls: ['./cabecalho.component.scss'] }) export class CabecalhoComponent implements OnInit { @Input() titulo: string = ""; @Input() iconeClasse = 'fas fa-user'; @Input() mostrarBotao : boolean = false; @Input() subtitulo : string = ""; public fundoPreto: string = 'black'; public corBranca: string = 'white'; public mostrarLista : boolean = true; constructor(private router: Router) { } ngOnInit() { } listar() : void { if (this.mostrarLista) { this.router.navigate([`/${this.titulo.toLocaleLowerCase()}/lista`]); } else { this.router.navigate([`/${this.titulo.toLocaleLowerCase()}`]); } this.mostrarLista = !this.mostrarLista; } } <file_sep>/back/LessaShoes.Persistance/LessaShoesContext.cs using LessaShoes.Domain; using LessaShoes.Domain.Identity; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; namespace LessaShoes.Persistance { public class LessaShoesContext : IdentityDbContext<Usuario, Cargo, int, IdentityUserClaim<int>, UsuarioCargo, IdentityUserLogin<int>, IdentityRoleClaim<int>, IdentityUserToken<int>> { public LessaShoesContext(DbContextOptions<LessaShoesContext> options) : base(options) { } public DbSet<Tenis> Tenis { get; set; } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<UsuarioCargo>(UsuarioCargo => { UsuarioCargo.HasKey(uc => new { uc.UserId, uc.RoleId }); UsuarioCargo.HasOne(uc => uc.Cargo) .WithMany(c => c.UsuarioCargos) .HasForeignKey(uc => uc.RoleId) .IsRequired(); UsuarioCargo.HasOne(uc => uc.Usuario) .WithMany(c => c.UsuarioCargos) .HasForeignKey(uc => uc.UserId) .IsRequired(); } ); } } }<file_sep>/back/LessaShoes.API/Startup.cs using System.IO; using System.Text; using LessaShoes.Application; using LessaShoes.Application.Contratos; using LessaShoes.Domain.Identity; using LessaShoes.Persistance; using LessaShoes.Persistance.Contratados; using LessaShoes.Persistance.Contratos; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using AutoMapper; using System; namespace LessaShoes.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<LessaShoesContext>( x => x.UseSqlite(Configuration.GetConnectionString("DefaultConnection")) ); IdentityBuilder builder = services.AddIdentityCore<Usuario>(options => { options.Password.RequireDigit = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; }); builder = new IdentityBuilder(builder.UserType, typeof(Cargo), builder.Services); builder.AddEntityFrameworkStores<LessaShoesContext>(); builder.AddRoleValidator<RoleValidator<Cargo>>(); builder.AddRoleManager<RoleManager<Cargo>>(); builder.AddSignInManager<SignInManager<Usuario>>(); services.AddControllers(opcoes => { var politica = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); opcoes.Filters .Add(new AuthorizeFilter(politica)); }).AddNewtonsoftJson(opc => opc.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(opcoes => { opcoes.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII .GetBytes(Configuration.GetSection("AppSettings:Token").Value)), ValidateIssuer = false, ValidateAudience = false }; }); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); services.AddScoped<IGeralPersist, GeralPersist>(); services.AddScoped<ITenisPersist, TenisPersist>(); services.AddScoped<ITenisService, TenisService>(); services.AddCors(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "LessaShoes.API", Version = "v1" }); }); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "LessaShoes.API v1")); } app.UseHttpsRedirection(); app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); app.UseCors(x => x .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin()); app.UseStaticFiles(new StaticFileOptions() { FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Recursos")), RequestPath = new PathString("/Recursos") }); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } } <file_sep>/back/LessaShoes.Domain/Identity/UsuarioCargo.cs using Microsoft.AspNetCore.Identity; namespace LessaShoes.Domain.Identity { public class UsuarioCargo : IdentityUserRole<int> { public Usuario Usuario { get; set; } public Cargo Cargo { get; set; } } }<file_sep>/Front/LessaShoes-APP/src/app/components/tenis/tenis.component.ts import { style } from '@angular/animations'; import { HttpClient } from '@angular/common/http'; import { Component, Input, OnInit, TemplateRef } from '@angular/core'; import { ToastrModule, ToastrService } from 'ngx-toastr'; import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal'; import { NgxSpinnerService } from "ngx-spinner"; import { Tenis } from 'src/app/Models/Tenis'; import { tenis } from 'src/app/services/tenis.service'; @Component({ selector: 'app-tenis', templateUrl: './tenis.component.html', styleUrls: [ './tenis.component.css',], }) export class TenisComponent implements OnInit { ngOnInit() : void { } } <file_sep>/back/LessaShoes.API/Controllers/TenisController.cs using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using LessaShoes.Application.Contratos; using Microsoft.AspNetCore.Http; using System.IO; using Microsoft.AspNetCore.Hosting; using System.Linq; using LessaShoes.Application.Dtos; using Microsoft.AspNetCore.Authorization; namespace LessaShoes.API.Controllers { [ApiController] [Route("/api/tenis")] public class TenisController : ControllerBase { private readonly ITenisService _TenisService; private readonly IWebHostEnvironment _hostEnvironment; public TenisController(ITenisService tenisService, IWebHostEnvironment hostEnvironment) { _hostEnvironment = hostEnvironment; _TenisService = tenisService; } [HttpGet] public async Task<IActionResult> Get() { try { var tenis = await _TenisService.GetAllTenisAsync(); if (tenis == null) return NoContent(); return Ok(tenis); } catch (Exception ex) { return this.StatusCode(StatusCodes.Status500InternalServerError, $"Erro ao tentar procurar os tenis. Erro{ex.Message}"); } } [HttpGet("{id}")] public async Task<IActionResult> GetByID(int id) { try { var tenis = await _TenisService.GetTenisByIDAsync(id); if (tenis == null) return NoContent(); return Ok(tenis); } catch (Exception ex) { return this.StatusCode(StatusCodes.Status500InternalServerError, $"Erro ao tentar procurar o tenis pelo ID. Erro{ex.Message}"); } } [HttpGet("{nome}/nome")] public async Task<IActionResult> GetByName(string nome) { try { var tenis = await _TenisService.GetAllTenisByNameAsync(nome); if (tenis == null) return NoContent(); return Ok(tenis); } catch (Exception ex) { return this.StatusCode(StatusCodes.Status500InternalServerError, $"Erro ao tentar procurar o tenis pelo nome. Erro{ex.Message}"); } } [HttpPost("upload/{tenisId}")] public async Task<IActionResult> UploadImagem(int tenisId) { try { var tenis = await _TenisService.GetTenisByIDAsync(tenisId); if (tenis == null) return NoContent(); var arquivo = Request.Form.Files[0]; if (arquivo.Length > 0) { DeletarImagem(tenis.ImagemURL); tenis.ImagemURL = await SalvarImagem(arquivo); } var tenisRetorno = await _TenisService.UpdateTenis(tenisId, tenis); return Ok(tenisRetorno); } catch (Exception ex) { throw new Exception(ex.Message); } } [HttpPost] public async Task<IActionResult> AddTenis(TenisDto model) { try { var tenis = await _TenisService.AddTenis(model); if (tenis == null) return NoContent(); return Ok(tenis); } catch (Exception ex) { return this.StatusCode(StatusCodes.Status500InternalServerError, $"Erro ao tentar adicionar um novo tenis. Erro{ex.Message}"); } } [HttpPut("{id}")] public async Task<IActionResult> Put(int id, TenisDto model) { try { var tenis = await _TenisService.UpdateTenis(id, model); if (tenis == null) return NoContent(); return Ok(tenis); } catch (Exception ex) { return this.StatusCode(StatusCodes.Status500InternalServerError, $"Erro ao tentar atualizar o tenis. Erro{ex.Message}"); } } [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { try { var tenis = await _TenisService.GetTenisByIDAsync(id); if (tenis == null) return NoContent(); if (await _TenisService.Delete(id)) { DeletarImagem(tenis.ImagemURL); return Ok(new { message = "Deletado" }); } else { throw new Exception("Ocorreu um erro ao deletar o tênis"); } } catch (Exception ex) { return this.StatusCode(StatusCodes.Status500InternalServerError, $"Erro ao tentar atualizar o tenis. Erro{ex.Message}"); } } [NonAction] public async Task<string> SalvarImagem(IFormFile arquivoImagem) { string nomeImagem = new string(Path.GetFileNameWithoutExtension(arquivoImagem.FileName) .Take(10) .ToArray()) .Replace(' ', '-'); nomeImagem = $"{nomeImagem}{DateTime.UtcNow.ToString("yymmssfff")}{Path.GetExtension(arquivoImagem.FileName)}"; var caminhoImagem = Path.Combine(_hostEnvironment.ContentRootPath, @"Recursos/imagens", nomeImagem); using (var arquivoStream = new FileStream(caminhoImagem, FileMode.Create)) { await arquivoImagem.CopyToAsync(arquivoStream); } return nomeImagem; } [NonAction] public void DeletarImagem(string nomeImagem) { var caminhoImagem = Path.Combine(_hostEnvironment.ContentRootPath, @"Recursos/imagens", nomeImagem); if (System.IO.File.Exists(caminhoImagem)) System.IO.File.Delete(caminhoImagem); } } } <file_sep>/README.md <img src="https://github.com/GabrielCampos07/scientificcalculator/blob/93a04ead56de916b71948775b3359d3fba779ad8/readmeimg/logocampos.png" width="60" height="65" /> # LessaShoes ## Utilizados: 1. C# (ASP.Net Core) 2. Angular(Typescript, Javascript, HTML e SCSS) 3. SQLite ### Exemplar: <img src="https://github.com/GabrielCampos07/justthings/blob/main/readlessashoesgif.gif" width="600" height="450" /> <file_sep>/back/LessaShoes.Persistance/Contratos/ITenisPersist.cs using System.Threading.Tasks; using LessaShoes.Domain; namespace LessaShoes.Persistance.Contratos { public interface ITenisPersist { Task<Tenis[]> GetAllTenisAsync(); Task<Tenis> GetTenisByIDAsync(int tenisID); Task<Tenis[]> GetAllTenisByNameAsync(string nome); } }
80549ce68c7fdd6bddd27e98fe72ba86636b0f85
[ "Markdown", "C#", "TypeScript" ]
27
TypeScript
GabrielCampos07/lessashoes
c201fe126a93e3dec2187543c8fb1821c113f46c
9e24d33d1a60669465d250090d642bd08f8cab33
refs/heads/main
<file_sep>class StrainFinder::Strains attr_accessor :id, :name, :race, :flavors, :effects @@all = [] def initialize(attributes) @name = attributes[0] attributes[1].each {|k, v| self.send("#{k}=", v)} save end def self.all @@all end def save @@all << self end def self.select_by_race(race) race_array = all.select {|s| s.race == race} race_array.each {|strain| puts "#{strain.id}.""#{strain.name}"} end def self.new_from_collection(strains) strains.each {|attributes| self.new(attributes)} end #def self.find_by_name(name) #all.find {|s| s.name == name} #end #def self.find_by_flavor(flavor) #all.find {|s| s.flavor == flavor} #end #def self.find_by_effect(effect) #all.find {|s| s.effects == effect} #end end <file_sep>#!/usr/bin/env ruby require 'bundler/setup' require './lib/environment' StrainFinder::Scraper.fetch_all_strains StrainFinder::CLI.new.call #StrainFinder::Strains.find_by_effect("sleepy") <file_sep>source "https://rubygems.org" # Specify your gem's dependencies in strain_finder.gemspec gemspec <file_sep>require_relative "./strain_finder/version" require_relative "./strain_finder/cli" require_relative "./strain_finder/scraper" require_relative "./strain_finder/strains" module StrainFinder class Error < StandardError; end # Your code goes here... end <file_sep>require 'pry' require 'httparty' class StrainFinder::Scraper def self.fetch_all_strains url = "http://strainapi.evanbusse.com/y4hQMu2/strains/search/all" resources = HTTParty.get(url) StrainFinder::Strains.new_from_collection(resources) end def self.fetch_description(id) url = "http://strainapi.evanbusse.com/y4hQMu2/strains/data/desc/#{id}" description = HTTParty.get(url) puts description end #def self.fetch_strains_by_name(name) #@name = name #url = "http://strainapi.evanbusse.com/y4hQMu2/strains/search/name/#{@name}" #resources = HTTParty.get(url) #StrainFinder::Strains.new_from_collection(resources) #end #def self.fetch_strains_by_race(race) #@race = race #url = "http://strainapi.evanbusse.com/y4hQMu2/strains/search/race/#{@race}" #resources = HTTParty.get(url) #StrainFinder::Strains.new_from_collection(resources) #end #def self.fetch_strains_by_effect(effect) #@effect = effect #url = "http://strainapi.evanbusse.com/y4hQMu2/strains/search/effect/#{@effect}" #resources = HTTParty.get(url) #resources.each {StrainFinder::Strains.new_from_collection(resources)} #end #def self.fetch_strains_by_flavor(flavor) #@flavor = flavor #url = "http://strainapi.evanbusse.com/y4hQMu2/strains/search/flavor/#{@flavor}" #resources = HTTParty.get(url) #StrainFinder::Strains.new_from_collection(resources) #end end <file_sep>class StrainFinder::CLI def call puts "Hello, welcome to the Cannabis Strain Finder." race_search end def race_search input = nil puts "Would you like to search by:" puts "1. Indica - Relaxing effects, Shorter stature, Broader leaves, Shorter growing cycle." puts "2. Sativa - Energizing effects, Taller stature, Thinner leaves, Longer growing cycle." puts "3. Hybrid - A cross of Indica and Sativa." puts "To exit type exit." input = gets.strip.downcase.to_s case input when "1" || "indica" StrainFinder::Strains.select_by_race("indica") when "2" || "sativa" StrainFinder::Strains.select_by_race("sativa") when "3" || "hybrid" StrainFinder::Strains.select_by_race("hybrid") when "exit" goodbye else puts "Please input valid selection" race_search end description_search end def description_search id_input = nil puts "Enter the number of the strain you would like to know more about." id_input = gets.strip.downcase.to_s StrainFinder::Scraper.fetch_description(id_input) loop_back end def loop_back loop_back_input = nil puts "Would you like to search again?" puts "[y/n]" loop_back_input = gets.strip.downcase case loop_back_input when "y" || "yes" race_search when "n" || "no" goodbye end end def goodbye puts "Goodbye! Thank You for exploring!!" end end #def search_by # puts "Would you like to search by:" # puts "1. Name" # puts "2. Race" # puts "3. Flavor" # puts "4. Effects" #end #def search_input # input = nil # puts "Enter the number you would like to search by, type list to see your options again, type exit to leave the program." # input = gets.strip.downcase # case input # when "1" # name_search # when "2" # race_search # when "3" # flavor_search # when "4" # effect_search # when "list" # search_by # search_input # when "exit" # goodbye # else # puts "Please input valid option" # search_by # search_input # end #end # def name_search # input = nil # puts "Please enter the name of the strain you are searching for:" # puts "To restart search type restart. Or to exit type exit." # input = gets.strip.downcase # case input # when "restart" # call # when "exit" # goodbye # else # puts "Please Try Valid Strain Name" # name_search # end # end #def flavor_search # input = nil # puts "Please enter the desired flavor:" # puts "To restart search type exit." # while input != "exit" # input = gets.strip.downcase # case input # when condition # else # puts "Please input valid selection" # flavor_search # end # end #end #def effect_search # input = nil # puts "Please enter the desired effect:" # puts "To restart search type exit." # input = gets.strip.downcase # case input # when condition # else # puts "Please input valid selection" # effect_search # end # end #end
8ef8934d23c8f4bd298de3bc8bbe78bf43d159a7
[ "Ruby" ]
6
Ruby
burns1916/strain_finder
f1420f944963b647138aad5d7ecbc4a1042b7960
7a33cecf30f4776057fe9ceb51dea66616be1b7a
refs/heads/master
<file_sep>//app.js //Create flight module var flightApp = angular.module("appModule", []); //Register controller with module flightApp.controller("appController", appController); flightApp.controller("headerController", headerController); function appController($scope) { $scope.title = "InsureFlight | Flight Delay Insurance"; $scope.name = "<NAME>"; $scope.appVersion = "V0.1" $scope.policies = [ { name: 'zfirst', city: 'Kitchener', phone: '12345689' }, { name: 'second', city: 'Waterloo' }, { name: 'athird', city: 'Cambridge' } ]; }; function headerController($scope) { $scope.headerTitle = "InsureFlight"; $scope.menu = ['Step1', 'Step2']; }; // flightController.$inject = ['$scope']; //Using explicit annotations using $inject property, respectively.<file_sep>npm init npm install --save jason-server http-server mkdir <folder> git clone <> . cd into >http-server -o chrome git init git add . git commit -m "Intial Draft"
4588b8ec749ca3ad257233aed51af0b533dc0686
[ "JavaScript", "Markdown" ]
2
JavaScript
Dicondur/client
6e61584b2d932c8ec238e6031bfa158543faf5b8
c34cd28f6ac8f7a6f72928cc6a2938b566d30189
refs/heads/master
<file_sep>module.exports = (req, res, next) => { if(req.user && req.user.usertypeId && req.user.usertypeId !== 1) { next() } else{ req.flash('error', 'You must be logged in as an instructor or an administrator to view this page'); res.render('403'); } } <file_sep>var express = require('express'); var moment = require('moment'); var passport = require('../config/passportConfig'); var staffLoggedIn = require('../middleware/staffLoggedIn'); var db = require('../models'); var router = express.Router(); router.get('/', function(req, res){ db.course.findAll().then(function(courses){ console.log(courses); res.render('profile', {courses: courses}); }).catch(function(err){ console.log('error in /profile', err); res.redirect('/'); }); }); router.get('/:id', function(req, res){ db.user.findById(req.params.id).then(function(otherUser){ res.render('guestProfile', {otherUser: otherUser}); }).catch(function(err){ console.log('error in /profile/:id', err); res.redirect('/'); }); }); module.exports = router; <file_sep>'use strict'; var bcrypt = require('bcryptjs'); module.exports = (sequelize, DataTypes) => { var user = sequelize.define('user', { firstname: DataTypes.STRING, lastname: DataTypes.STRING, preferredname: DataTypes.STRING, email: DataTypes.STRING, phone: DataTypes.STRING, password: DataTypes.STRING, usertypeId: { type: DataTypes.INTEGER, defaultValue: 1 }, image: DataTypes.TEXT, location: DataTypes.STRING }, { hooks: { beforeCreate: function(pendingUser, options){ if(pendingUser && pendingUser.password){ var hash = bcrypt.hashSync(pendingUser.password, 10); pendingUser.password = hash; } } } }); user.associate = function(models) { models.user.belongsTo(models.usertype); models.user.hasMany(models.course, {as: 'teacher',foreignKey: 'teacherId'}); models.user.belongsToMany(models.course, {through: "enrollment"}); } user.prototype.isValidPassword = function(passwordTyped){ return bcrypt.compareSync(passwordTyped, this.password); } user.prototype.toJSON = function(){ var user = this.get(); delete user.password; return user; } return user; }; <file_sep>'use strict'; module.exports = (sequelize, DataTypes) => { var course = sequelize.define('course', { name: DataTypes.STRING, cohort: DataTypes.STRING, start: DataTypes.DATE, end: DataTypes.DATE, location: DataTypes.STRING, teacherId: DataTypes.INTEGER }, {}); course.associate = function(models) { models.course.belongsToMany(models.user, {through: "enrollment"}); models.course.belongsTo(models.user, {as: 'teacher', foreignKey: 'teacherId'}); }; return course; }; <file_sep>// Package Requirements require('dotenv').config(); let express = require('express'); let ejsLayouts = require('express-ejs-layouts'); let flash = require('connect-flash'); let moment = require('moment') let path = require('path'); let session = require('express-session'); // Middleware let isLoggedIn = require('./middleware/isLoggedIn'); let passport = require('./config/passportConfig'); let staffLoggedIn = require('./middleware/staffLoggedIn'); let app = express(); // Middleware set-up app.set('view engine', 'ejs'); app.use('/public', express.static(path.join(__dirname, 'public'))); app.use(express.urlencoded({ extended: false })); app.use(ejsLayouts); app.use(session({ secret: process.env.SESSION_SECRET, resave: false, saveUninitialized: true })); app.use(flash()); app.use(passport.initialize()); app.use(passport.session()); app.use((req, res, next) => { res.locals.currentUser = req.user; res.locals.alerts = req.flash(); res.locals.moment = moment; next(); }); // Routers app.use('/auth', require('./controllers/auth')); app.use('/profile', isLoggedIn, require('./controllers/profile')); app.use('/courses', isLoggedIn, require('./controllers/courses')); // Home route app.get('/', (req, res) => { res.render('home'); }); // Catch-all route app.get('*', (req, res) => { res.render('404'); }) app.listen(process.env.PORT || 3000);
dcc803b601721c84f308aa0bc3da4a59af35e9e3
[ "JavaScript" ]
5
JavaScript
brandiw/school_tool
6d8224e0429866873eaba4da83a235c358da5dad
eb74312ac3dd001064d3d19eb36700b1e0db2874
refs/heads/main
<repo_name>dansal182/clt_simulation<file_sep>/t_test_sim.py import numpy as np import pandas as pd import matplotlib.pyplot as plt from math import sqrt, gamma, pi from matplotlib.animation import FuncAnimation def get_t_val(simvalues): return (simvalues.mean()) / (simvalues.std() / sqrt(len(simvalues))) def get_s_error(simvalues): return simvalues.std() / sqrt(len(simvalues)) def get_mu_est(simvalues): return simvalues.mean() def sim_experiment(sample_size, nsim, mu, sigma): t_values = np.linspace(0, 100, nsim) x_values = np.linspace(0, 100, nsim) s_errors = np.linspace(0, 100, nsim) for i, i0 in enumerate(t_values): x = np.random.normal(mu, sigma, sample_size) t_values[i] = get_t_val(x) x_values[i] = get_mu_est(x) s_errors[i] = get_s_error(x) out = pd.DataFrame() out['valor_T'] = t_values out['Estimador'] = x_values out['error_std'] = s_errors return out def t_den_fun(t, df): return gamma((df + 1) / 2) / (sqrt(df * pi) * gamma(df / 2)) * (1 + t ** 2 / df) ** (-(df + 1) / 2) def norm_den(x, mu, sig): return (1 / sqrt(2 * pi * sig * sig)) * np.exp(- 1 / (2 * sig * sig) * (x - mu) ** 2) def gamma_den(x, alpha, lam): return lam**alpha / gamma(alpha) * x**(alpha - 1) * np.exp(-lam*x) def get_hist(t_values, n_bin): fig, ax = plt.subplots() ax.hist(t_values, bins=n_bin, density=True) t_supp = np.linspace(min(t_values), max(t_values), len(t_values)) y = t_den_fun(t_supp, len(t_values) - 1) ax.plot(t_supp, y, '--') ax.set_xlabel('Valor t') ax.set_ylabel('Likelihood/Verosimilitud') ax.set_title('Histograma del valor t') fig.tight_layout() plt.show() class UpdateSample: def __init__(self, ax, mu, sigma, size): self.line, = ax.plot([], [], 'k-') self.ax = ax self.ax.set_xlim(-1.5, 1.5) self.ax.set_ylim(0, 5) self.ax.grid(False) self.ax.axvline(mu, linestyle='--', color='red') self.mu = mu self.sigma = sigma self.size = size self.x = np.linspace(-2, 2, 250) def __call__(self, i): if i == 0: self.line.set_data([], []) return self.line, else: self.size = i y = norm_den(self.x, self.mu, self.sigma / sqrt(i)) self.line.set_data(self.x, y) return self.line, def create_movie(kseed, frms, ints): np.random.seed(kseed) fig, ax = plt.subplots() ud = UpdateSample(ax, 0, 1, 1) anm = FuncAnimation(fig, ud, frames=frms, interval=ints, blit=True) plt.show() return anm class UpdateCLT: def __init__(self, ax, mu, sigma, size): self.line, = ax.plot([], [], 'k-') self.ax = ax self.ax.set_xlim(0, 4) self.ax.set_ylim(0, 2) self.ax.grid(False) self.ax.axvline(mu, linestyle='--', color='red') self.mu = mu self.sigma = sigma self.size = size self.x = np.linspace(0, 5, 150) def __call__(self, i): if i == 0: self.line.set_data([], []) return self.line, else: self.size = i y = gamma_den(self.x, i, 1/self.mu * i) self.line.set_data(self.x, y) return self.line, def create_movie_clt(kseed, frms, ints): np.random.seed(kseed) fig, ax = plt.subplots() fig.suptitle('CLT Animation', fontsize=16) ud = UpdateCLT(ax, 2, 1, 1) anm = FuncAnimation(fig, ud, frames=frms, interval=ints, blit=True) plt.show() return anm
4fe307255fc8f0315dc72c501eab53456377ee4c
[ "Python" ]
1
Python
dansal182/clt_simulation
07346345fbe5052086aa2ec8cfd0638f797f3909
a892481cd432df2b8cdc98d6bb27d2dcd3787e31
refs/heads/master
<file_sep>using PearXLib; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using xRandomer.Properties; namespace xRandomer { public partial class Main : Form { Random rand = new Random(); public Main() { InitializeComponent(); } private void Main_Load(object sender, EventArgs e) { FileUtils.createDir(d.pxDir + PXL.s + "xRandomer"); this.Icon = Resources.icon; } private void textCode_KeyDown(object sender, KeyEventArgs e) { if (!e.Control) { e.SuppressKeyPress = true; } } string Gen() { string str = textFormat.Text; while (str.Contains("%char%")) { str = PXL.ReplaceFirst(str, "%char%", RandomUtils.GenChar(rand).ToString()); } while (str.Contains("%CHAR%")) { str = PXL.ReplaceFirst(str, "%CHAR%", RandomUtils.GenChar(rand).ToString().ToUpper()); } while (str.Contains("%num%")) { str = PXL.ReplaceFirst(str, "%num%", RandomUtils.GenNumber(rand).ToString()); } while (str.Contains("%rand%")) { str = PXL.ReplaceFirst(str, "%rand%", RandomUtils.GenRandom(rand, true).ToString()); } while (str.Contains("%randws%")) { str = PXL.ReplaceFirst(str, "%randws%", RandomUtils.GenRandom(rand, false).ToString()); } while (str.Contains("%sym%")) { str = PXL.ReplaceFirst(str, "%sym%", RandomUtils.GenSymbol(rand).ToString()); } return str; } private void buttonGenerate_Click(object sender, EventArgs e) { buttonGenerate.Enabled = false; Gen(); textCode.Text = Gen(); buttonGenerate.Enabled = true; } private void listBoxDefaultFormat_SelectedIndexChanged(object sender, EventArgs e) { switch(listBoxDefaultFormat.SelectedIndex) { case 0: textFormat.Text = "%num%%num%%num%%num%"; break; case 1: textFormat.Text = "%CHAR%%num%%CHAR%%num%-%CHAR%%num%%CHAR%%num%-%CHAR%%num%%CHAR%%num%-%CHAR%%num%%CHAR%%num%"; break; case 2: textFormat.Text = "+%num% (%num%%num%%num%) %num%%num%%num% %num%%num% %num%%num%"; break; case 3: textFormat.Text = "%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%"; break; case 4: textFormat.Text = "%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%"; break; case 5: textFormat.Text = "%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%%randws%"; break; case 6: textFormat.Text = "%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%%rand%"; break; } } private void buttonCopy_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(textCode.Text)) { Clipboard.SetText(textCode.Text); } } private void buttonClearFormat_Click(object sender, EventArgs e) { textFormat.Clear(); } private void backgroundWorkerAutoRandom_DoWork(object sender, DoWorkEventArgs e) { int repeat = Convert.ToInt32(textBoxCount.Text); string dt = DateTime.Now.Day.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Year + "_" + DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString(); for (int i = 0; i < repeat; i++) { File.AppendAllText(d.pxDir + PXL.s + "xRandomer" + PXL.s + "Generated_" + dt + ".txt", Gen() + "\n"); } } private void buttonAutoGenStart_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(textBoxCount.Text)) { backgroundWorkerAutoRandom.RunWorkerAsync(); pictureBoxLoading.Image = Resources.loading; } } private void buttonAutoGenStop_Click(object sender, EventArgs e) { backgroundWorkerAutoRandom.CancelAsync(); } private void backgroundWorkerAutoRandom_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { pictureBoxLoading.Image = null; } private void buttonOpenFolder_Click(object sender, EventArgs e) { Process.Start(d.pxDir + PXL.s + "xRandomer"); } private void textBoxCount_KeyPress(object sender, KeyPressEventArgs e) { if (PXL.isNumberKey(e)) { e.Handled = true; } } bool isAutoGenOpened = false; private void buttonPlus_Click(object sender, EventArgs e) { if (isAutoGenOpened) { isAutoGenOpened = false; groupBoxAutoGen.Visible = false; buttonPlus.Image = Resources.plus; } else { isAutoGenOpened = true; groupBoxAutoGen.Visible = true; buttonPlus.Image = Resources.minus; } } } } <file_sep># Requires PearXLib ([Get it](http://github.com/mrAppleXZ/PearXLib)).
b548a06e9c204faab7877d347f2dd9a1ac9486b8
[ "Markdown", "C#" ]
2
C#
PearXTeamLegacy/old_xRandomer
0ced4b2f61aa7c43c725ea2fe62fcb80ca315a3e
f00554b4a98f368a4fdaf07859c040804e888b84
refs/heads/master
<file_sep> $('body').scrollspy({ target: '.navmenu' }); // When we click on the LI $("ul.qcontrols li").click(function(){ // If this isn't already active if (!$(this).hasClass("active")) { // Remove the class from anything that is active $("ul.qcontrols li.active").removeClass("active"); // And make this active $(this).addClass("active"); } }); //WOW Scroll Spy var wow = new WOW({ //disabled for mobile mobile: false }); wow.init(); jQuery(document).ready(function( $ ) { //popups $("a.modal-ajax").click(function(event) { event.preventDefault(); }); $("a.modal-ajax").modal({ draggable : false, buttons : {Close : 'hide'}, title : true, overlay : true, width : 600, height : 400, showSpeed : 200, closeSpeed : 200, shadow : true }); //Clients carousel Slider $('#clients-carousel').owlCarousel({ navigation: false, // Show next and prev buttons slideSpeed: 400, paginationSpeed: 800, autoPlay: true, pagination : false, items : 4, itemsCustom : false, itemsDesktop : [1199,4], itemsDesktopSmall : [980,3], itemsTablet: [768,2], itemsTabletSmall: false, itemsMobile : [479,1], }); $('#menu').click(function(){ $('#menu').not(this).removeClass("active"); $(this).toggleClass("active"); }); }); //ScrollTop $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); <file_sep># spandan2015 After all optimizations and UI changes.
d296d75a9a34184d55c2cb6008dcd95dd2d00692
[ "JavaScript", "Markdown" ]
2
JavaScript
nitinkul/spandan2015
10feea0b31f39ce5269bf015cc45c605e3f83d22
6a32966f5d50a55f5151d21ef0bf5644869793f7
refs/heads/master
<file_sep>def ivarsmooth(flux, ivar, width, weight=None, profile=None): """Generates an inverse variance weighted 1d spectrum. flux- science spectrum to be smoothed ivar- inverse variance spectrum of the science spectrum width- the number of pixels to be smoothed weight- weight to be applied per pixel (default=1) profile- profile to be applied (default=1) NOTE: This is expected to give similar results as ivarsmooth.pro from ucolick: http://tinyurl.com/nm5udej @themiyan 16/06/2015 """ import scipy.ndimage.filters as fil if weight == None: weight=1 if profile == None: profile=1 width = np.ones((1,width), dtype=float)[0] numerator = flux * ivar * weight * profile convolved_numerator = fil.convolve1d(numerator , width, axis=-1, mode='reflect', cval=0.0, origin=0 ) denominator = ivar * weight * profile convolved_denominator = fil.convolve1d( denominator, width, axis=-1, mode='reflect', cval=0.0, origin=0 ) smoothed_flux = convolved_numerator / convolved_denominator smoothed_ivar = convolved_denominator return smoothed_flux, smoothed_ivar <file_sep># astronomy General astronomy codes <file_sep>import glob import numpy as np from astropy.io import ascii, fits import matplotlib.pyplot as plt import pandas as pd from lmfit.models import GaussianModel class generate_telluric: def __init__(self, band, star_name , path_A, path_C, star_temperature, obs_date, cen_lp): self.star_name = star_name self.star_file_A = path_A self.star_file_C = path_C self.star_temp = star_temperature self.band = band self.obs_date = obs_date self.center_of_spatial_profile = cen_lp ### until issues with long2pos is sorted out use only posA self.star_flux, self.star_wave, self.star_error = self.combine_pA_and_pC() ### mask out unobsrved region of the star ### this should be a temporary measure (confirm when long2pos delta_lambda is checked) ### so the slit position dependant wavelength coverage is taken into account ### the main reason for this is for the stellar H line masking observed_range_mask = [self.star_error!=0] self.star_flux, self.star_wave, self.star_error = self.star_flux[observed_range_mask], self.star_wave[observed_range_mask], self.star_error[observed_range_mask] def combine_pA_and_pC(self): """ Combine the poA and posC together THERE ARE ISSUES WITH VARIABLE FLUXES So ideally the code should check if fluxes are with 10% between A and B for combining: mainly only relavant for the flux standard: need to investigate if normalization issues in telluric """ import copy import pdb star_flux_A, star_wave_A, star_error_A = extract_1d(self, self.star_file_A, long2pos='_posA') star_flux_C, star_wave_C, star_error_C = extract_1d(self, self.star_file_C, long2pos='_posC') assert (star_wave_A.all()==star_wave_C.all()), 'wavelength solution of the two stars does not match' ### band centre + (FWHM/2) is chosen as the range to be the common area between A and C AC_mask = [(star_wave_A>(band_center_wave-(band_fwhm/2))) & (star_wave_A<(band_center_wave+(band_fwhm/2)))] AC_mask = np.asarray(AC_mask)[0] # pdb.set_trace() ### check what is the accuracy of the total flux between the two positions A_mask_flux = np.nansum(star_flux_A[AC_mask] * np.diff(star_wave_A[AC_mask])[0]) C_mask_flux = np.nansum(star_flux_C[AC_mask] * np.diff(star_wave_C[AC_mask])[0]) A_C_flux_diff = ((A_mask_flux - C_mask_flux)/C_mask_flux) print('Flux difference between A an C is ', A_C_flux_diff) assert A_C_flux_diff<0.30, 'Pos A and C flux around band centre differs by >30%' star_flux, star_error = copy.deepcopy(star_flux_C), copy.deepcopy(star_error_C) # pdb.set_trace() star_flux[AC_mask] = np.nanmean([star_flux_A[AC_mask], star_flux_C[AC_mask]], axis=0) star_error[AC_mask] = ((star_error_A[AC_mask]**2)+(star_error_C[AC_mask]**2))**0.5 # pdb.set_trace() #### IMPORTANT VERIFY THAT C COVERS THE BLUE END #### Need a better way to generalize this #### Error is generally nan for uncovered regions star_flux[(~AC_mask) & (star_wave_A>band_center_wave)] = star_flux_A[(~AC_mask) & (star_wave_A>band_center_wave)] star_flux[(~AC_mask) & (star_wave_C<band_center_wave)] = star_flux_C[(~AC_mask) & (star_wave_C<band_center_wave)] ### Check error propogation...actually this error spectrum is only used for optimal 1D extraction star_error[(~AC_mask) & (star_wave_A>band_center_wave)] = star_error_A[(~AC_mask) & (star_wave_A>band_center_wave)] star_error[(~AC_mask) & (star_wave_C<band_center_wave)] = star_error_C[(~AC_mask) & (star_wave_C<band_center_wave)] # pdb.set_trace() return star_flux, star_wave_A, star_error def smooth_stellar_spectra(self): """ smooth a 1D spectrum using a gaussian kernel from astropy smoothing is done using a stddev=3 kernel. This seems to give a good balance between smoothing and retaining atmosphereic features. Change this as required. Note: if the stdev is too low the solution will be have too much stellar features incoporated. input: self returns: smoothed flux, smoothed error """ from astropy.convolution import Gaussian1DKernel, convolve g = Gaussian1DKernel(stddev=3) self.star_flux_smoothed = convolve(np.interp(self.star_wave, self.star_wave, self.star_flux), g) self.star_error_smoothed = convolve(np.interp(self.star_wave, self.star_wave, self.star_flux), g) def compute_blackbody(self): """ Compute a blackbody spectrum using the astropy BlackBody1D function input: self returns: flux of the blackbody function normalized to the mean flux within the spectroscopic window of the star """ from astropy.modeling.models import BlackBody1D from astropy.modeling.blackbody import FLAM from astropy import units as u bb = BlackBody1D(temperature=self.star_temp*u.K) bb_wav = self.star_wave * u.AA bb_flux = bb(bb_wav).to(FLAM, u.spectral_density(bb_wav)) bb_flux = bb_flux / np.mean(bb_flux) return bb_flux def mask_stellar_H_lines(self): """ compare the wavelength coverage in terms of the Paschen and Brackett series and mask out the relevant H absorption lines in the stellar spectra. 1. check which lines are within the wavelength window 2. fit a gaussian to the abs line/s 3. fit a ploynomial across the abs feature masking 3*sigma for the gaussian Once all H lines are masked and interpolated over, the resulting spectrum will be trated as the 'real' telluric star for the correction purposes. """ def mask_and_interpolate(self, line, delta ): """ Mask the specified H line and interpolate over it. """ import copy from astropy.modeling import models, fitting # This selectes a cutout around the H line line_mask = [(self.star_wave>(line-delta)) & (self.star_wave<(line+delta))] H_line_masked_wave = self.star_wave[line_mask] H_line_masked_flux = self.star_flux_smoothed[line_mask] # fit a polynomial around the H line to remove the continuum # this is done by selecting the first 20 and last 20 indexes # of the cutout pf_val_initial = np.polyfit(H_line_masked_wave[np.r_[0:20, -21:-1]], H_line_masked_flux[np.r_[0:20, -21:-1]], 1 ) pf_initial = np.polyval(pf_val_initial,H_line_masked_wave ) # fit a gaussian sp = -pf_initial+H_line_masked_flux x = H_line_masked_wave g_init = models.Gaussian1D(amplitude=-1.0, mean=line, stddev=1.) fit_g = fitting.LevMarLSQFitter() g = fit_g(g_init, x, sp) # select the 3-sigma window as the mask # and repeat the polynomial fitting start = int(g.mean.value - (g.stddev.value*3)) end = int(g.mean.value + (g.stddev.value*3)) H_polynomial_mask = [(H_line_masked_wave<(start)) | (H_line_masked_wave>(end))] pf_val_best_fit = np.polyfit(H_line_masked_wave[H_polynomial_mask], H_line_masked_flux[H_polynomial_mask], 1 ) pf_best_fit = np.polyval(pf_val_best_fit, H_line_masked_wave[~H_polynomial_mask[0]]) # now replace the stellar flux within this range using the polynomial replace_mask = [(self.star_wave>start) & (self.star_wave<end)] self.star_flux_H_interpolated = copy.deepcopy(self.star_flux_smoothed) self.star_flux_H_interpolated[replace_mask]= pf_best_fit return x, g(x) + pf_initial #Paschen and Brackett series # https://www.gemini.edu/sciops/instruments/nearir-resources/astronomical-lines/h-lines H_lines = 10 * np.array([901.2,922.6,954.3,1004.6,1093.5, 1282.4, 1874.5, 1570.7, 1588.7, 1611.5, 1641.3, 1681.3, 1736.9, 1818.1, 1945.1, 2166.1]) ## what lines of the abs falls within the spectral window of the tell star lines_within_spectra = H_lines[(np.min(self.star_wave) < H_lines) & (np.max(self.star_wave)> H_lines)] print("There are %s lines within the observed spectral range"%len(lines_within_spectra)) print("We will now go through each one of them and perfom a single gaussian fit") gauss_waves, gauss_fluxes = [], [] result = [mask_and_interpolate(self, line, delta) for line in lines_within_spectra] gauss_waves, gauss_fluxes = zip(*result) self.make_H_mask_spectra(len(lines_within_spectra), gauss_waves, gauss_fluxes) def make_H_mask_spectra(self, N_of_lines, gauss_waves, gauss_fluxes): """ Once the H stellar H lines are masked, this function will generate a figure to the user to show if the masking + interpolation is successful. """ def make_plot(self, ax, gauss_wave, gauss_flux): ax.plot( self.star_wave, self.star_flux, color='k', ls='-', label='Observed spectrum') ax.plot( self.star_wave, self.star_flux_smoothed, color='orange', ls='-', label='Smoothed spectrum') ax.plot( gauss_wave, gauss_flux, color='r', ls='--', label='Gaussian Fit') ax.plot( self.star_wave, self.star_flux_H_interpolated, color='blue', ls='-', label='Interpolated spectrum') ax.set_xlabel('wavelength (Angstroms)') ax.set_ylabel('flux (counts)') ax.set_xlim(np.min(gauss_wave)*0.95, np.max(gauss_wave)*1.05) ax.set_ylim(np.min(gauss_flux)*0.5, np.max(gauss_flux)*2) ax.legend() import matplotlib.pyplot as plt from matplotlib import gridspec import math cols = 2 rows = int(math.ceil(N_of_lines / cols)) fig = plt.figure(figsize=(8,4)) gs = gridspec.GridSpec(rows, cols) for n in range(N_of_lines): ax = fig.add_subplot(gs[n]) make_plot(self, ax, gauss_waves[n], gauss_fluxes[n]) fig.tight_layout() plt.savefig(out_path + 'star_H_mask_'+self.star_name+'_'+self.obs_date+'_'+self.band+'.pdf') plt.show() def fit_ploynomial(self, flux, wave, error): """ NOT USED ATM Fit an polynomial to the smoothed stellar spectra to average over the H absorption lines (and some other stellar features). The error spectrum is used as the weights. input: smoothed flux, wavelength, smoothed error returns: """ wave_mask = [(wave>15000) & (wave<18000)] pf_val = np.polyfit(n2_ts_pC_wave[n2_ts_pC_mask],n2_ts_pC_flux[n2_ts_pC_mask], 6 ) pf = np.polyval(pf_val,n2_ts_pC_wave[n2_ts_pC_mask] ) pf_wave = n2_ts_pC_wave[n2_ts_pC_mask] def write_spectra_to_disk(self, corrected_star_flux, blackbody_flux, correction): """ Write the telluric corrected spectra to disk as a csv file. """ df = pd.DataFrame() df['wavelength'] = self.star_wave df['star_extracted_1d_flux'] = self.star_flux df['star_extracted_1d_flux_smooth'] = self.star_flux_smoothed df['star_extracted_1d_H_interpolated'] = self.star_flux_H_interpolated df['star_telluric_corrected'] = corrected_star_flux df['blackbody_flux'] = blackbody_flux df['derived_sensitivity'] = correction df.set_index('wavelength', inplace=True) df.to_csv(out_path + 'sensitivity_curve_telluric_'+self.star_name+'_'+self.obs_date+'_'+self.band+'.csv') return def make_comparison_figure(self,corrected_star_flux, blackbody_flux, correction, sky_transmission, filter_transmission): """ Make a figure for the telluric correcction routine """ ## first write the derived values to disk self.write_spectra_to_disk(corrected_star_flux,blackbody_flux, correction) import matplotlib.pyplot as plt # plt.plot(pf_wave, pf/np.median(pf), c='b') fig = plt.subplots(figsize=(8,4)) plt.plot(self.star_wave, self.star_flux/np.median(self.star_flux), c='brown', lw=0.5, label='original stellar spectra') plt.plot(self.star_wave, self.star_flux_H_interpolated/np.median(self.star_flux_H_interpolated), c='red', lw=0.5, label='stellar spectra H lines interpolated') plt.plot(self.star_wave, self.star_flux_smoothed/np.median(self.star_flux_smoothed), c='b', lw=0.5, label='smoothed stellar spectra') plt.plot(self.star_wave, blackbody_flux, c='orange', label='blackbody function') plt.plot(self.star_wave, correction, c='g', lw=0.5, label='derived sensitivity') plt.plot(self.star_wave, corrected_star_flux/np.nanmedian(corrected_star_flux), c='magenta', lw=0.5, label='Telluric corrected star') plt.plot(sky_transmission['wavelength(micron)']*1e4, sky_transmission['transmission'], c='k', label='sky transmission') plt.plot(filter_transmission['wavelength']*1e4, filter_transmission['response'], c='cyan', label='filter transmission') plt.legend(loc='best', ncol=2) plt.xlim(self.star_wave.min() *0.99 , self.star_wave.max()*1.01) plt.xlabel('wavelength (A)') plt.ylabel('N') plt.axhline(y=1.0, ls='--', c='k') plt.savefig(out_path + 'comp_fig_'+self.star_name+'_'+self.obs_date+'_'+self.band+'.pdf') plt.show() return def cal_values(star_file, header=False): """ Extract the flux, wavelength, and error information from the DRP 1D fits files input: fits object: IMPORTANT: need to be the 1D extracted fits object from the DRP returns: flux, wavelength, error """ print('opening ' + star_file) eps = fits.open(star_file) star_error_file = star_file.replace('_eps', '_sig') print('opening' + star_error_file) eps_error = fits.open(star_error_file) scidata, hdr_sci , sddata, hdr_err = eps[0].data, eps[0].header, eps_error[0].data, eps_error[0].header CRVAL1, CD1_1 , CRPIX1 = hdr_sci['CRVAL1'], hdr_sci['CD1_1'], hdr_sci['CRPIX1'] i_w = np.arange(len(scidata[0]))+1 #i_w should start from 1 wavelength = ((i_w - CRPIX1) * CD1_1 ) + CRVAL1 flux = scidata; error = sddata if header: return flux, wavelength, error, hdr_sci, hdr_err else: return flux, wavelength, error def make_spatial_plot(data_obj, sp_x,sp_y , fit, flux, wave, error, long2pos): """ Make a spatial profile of the optimal 1D extraction """ import matplotlib.pyplot as plt fig, axs = plt.subplots(figsize=(6,3), nrows=1, ncols=2) axs[0].plot(sp_x, sp_y , c='k' , ls='-', label='spatial profile') axs[0].plot(sp_x, fit(sp_x), c='r', ls='-', label='Fit' ) axs[0].set_xlabel('y') axs[0].set_ylabel('counts') axs[0].legend(loc='best') axs[0].set_title(long2pos) axs[1].plot(wave, flux, c='b', label='flux') axs[1].plot(wave, error, c='r', label='error') axs[1].set_xlabel('wavelength (A)') axs[1].set_ylabel('counts') axs[1].legend(loc='best') axs[1].set_title(long2pos) plt.tight_layout() plt.savefig(out_path + 'sp_'+str(data_obj.star_name)+'_'+str(data_obj.obs_date)+'_'+str(data_obj.band)+long2pos+'.pdf') plt.show() return def extract_1d(data_obj, star_file, long2pos=None): """ Extract a 1D spectrum from a 2D spectrum. Follows Horne1986 prescription. """ from astropy.modeling import models, fitting flux, wave, error = cal_values(star_file) sp = np.nansum(flux[:, 1000:1500], axis=1) x = np.arange(len(sp)) g_init = models.Gaussian1D(amplitude=1., mean=data_obj.center_of_spatial_profile, stddev=1.) fit_g = fitting.LevMarLSQFitter() g = fit_g(g_init, x, sp) start = int(g.mean.value - (g.stddev.value*5)) end = int(g.mean.value + (g.stddev.value*5)) weights = 1./(abs(g.mean.value-np.arange(start, end+1, 1))/g.stddev.value) print(np.nansum(weights)) weights = weights/np.nansum(weights) print(weights) ### This is what i had before # flux_1d = np.nansum(flux[start:end+1,:] * weights[:, None], axis=0) # error_1d = np.nansum(error[start:end+1,:] ** 2, axis=0)**0.5 flux_numerator = np.nansum(flux[start:end+1,:] * weights[:, None]/(error[start:end+1,:]**2), axis=0) flux_denominator = np.nansum((weights[:, None]**2)/(error[start:end+1,:]**2), axis=0) flux_1d = flux_numerator/flux_denominator error_1d = np.nansum(1./(weights[:, None]**2)/(error[start:end+1,:]**2), axis=0)**0.5 make_spatial_plot(data_obj, x, sp , g, flux_1d, wave, error_1d, long2pos) return flux_1d, wave, error_1d def find_nearest(array,value): idx = (np.abs(array-value)).argmin() return idx def compute_flux_convt_factor(star_flux, star_wave, band_center_wave, band_zero, band_mag): """ compute a conversion factor to convert eps to ers/s/A. """ wave_index=find_nearest(star_wave, band_center_wave) star_flux_center = star_flux[wave_index] # bb_j is the centre of the band--> matches the centre of the band with the centre of the 2mass mag band_flux = band_zero*(10**(band_mag/(-2.5))) # convert the 2mass mag to abs flux, erg/s/cm^2/A gain = 1.0 exposure_star = 1.0 fluxconvt=(exposure_star/gain)*band_flux/star_flux_center # the conversion factor return fluxconvt def apply_calibs_to_data(eps_fluxes, tel_sens_wave, tel_sens_curve, flux_conversion_factor): """ Apply the telluric corrections and flux calibrations to the observed 2D spectra. This is done in a single step for now. """ for index, files in enumerate(eps_fluxes): flux, wave, error, header_flux, header_error = cal_values(eps_fluxes[index], header=True) tel_sens_curve_interp = np.interp(wave, tel_sens_wave, tel_sens_curve) flux = flux * tel_sens_curve_interp * flux_conversion_factor error = error * tel_sens_curve_interp * flux_conversion_factor primary_hdu = fits.PrimaryHDU(flux, header=header_flux) new_hdul = fits.HDUList([primary_hdu]) new_hdul.writeto(eps_fluxes[index].replace('.fits', '_tc_fc.fits')) new_hdul.close() eps_error = eps_fluxes[index].replace('_eps', '_sig') primary_hdu = fits.PrimaryHDU(error, header=header_error) new_hdul = fits.HDUList([primary_hdu]) new_hdul.writeto(eps_error.replace('.fits', '_tc_fc.fits')) new_hdul.close() return def main(): """ 1. load the 2D extracted spectra and extract 1D spectra of the standard 1.1 if long2pos combine the positions to generate a single 1d spectra 2. smooth the spectra 3. fit a ploynomial around H absorption lines to remove strong absorption intrinsic to the star 4. generate a blackbody function to the star 5. generate a sensitivity correction 5.1 apply sensitivity curve to telluric star 6. generate flux conversion factor for standard star 6.1 apply the flux calibration to standard star 7. apply telluric corrections + flux calibrations to the data """ global out_path, band_center_wave, band_fwhm, delta ######USER INPUTS####### band ='K' date ='2018nov29' star_name='HD201941' star_temperature = 5000 #The temperature of the star in K (average AoV star T=9600K) csp = 100 #centre of the spatial profile of the positive image (used as the first guess for the gaussian) # this is the width used for H masking of the star # if you are not happy with the continnum this value should be changed as required # the main issue is the balance when there is a H line abs close to a telluric line delta=75 magJ = 6.678 magH = 6.673 magK = 6.602 out_path = '../outputs/' #where the outputs will be written to sky_transmission = ascii.read('/Users/themiya/Dropbox/mosdrp/analysis/Tables/instrument_throughputs/trans_16_15.dat') ### night2 H band Telluric star path_A = '../reduced/long2pos/'+str(date)+'/'+str(band)+'/'+str(star_name)+'_POSA_NARROW_'+str(band)+'_POSA_eps.fits' path_C = '../reduced/long2pos/'+str(date)+'/'+str(band)+'/'+str(star_name)+'_POSC_NARROW_'+str(band)+'_POSC_eps.fits' twod_flux_names = glob.glob('../reduced/H_band_COSMOS/2019apr25/H/H_band_COSMOS_H_*_eps.fits') # twod_error_names = glob.glob('../reduced/H_band_COSMOS/2019apr25/H/H_band_COSMOS_H_*_sig.fits') j_zero = 3.129e-09*1e7/1e4/1e4 # convert from W/m2/um -> erg/cm2/A j_wave = 1.2350*1e4 # 1.25 um to Ang, of effective J-band wavelength j_fwhm = 2000 h_zero = 1.133e-09*1e7/1e4/1e4 # convert from W/m2/um -> erg/cm2/A h_wave = 1.662*1e4 # 1.25 um to Ang, of effective J-band wavelength h_fwhm = 3410 k_zero = 0.4283e-09*1e7/1e4/1e4 # convert from W/m2/um -> erg/cm2/A k_wave = 2.159*1e4 # 1.25 um to Ang, of effective J-band wavelength k_fwhm = 4830 if band =='J': band_mag = magJ band_center_wave = j_wave band_zero = j_zero band_fwhm = j_fwhm mosfire_tp = ascii.read('/Users/themiya/Dropbox/mosdrp/analysis/Tables/instrument_throughputs/MOSFIRE/J.dat') elif band =='H': band_mag = magH band_center_wave = h_wave band_zero = h_zero band_fwhm = j_fwhm mosfire_tp = ascii.read('/Users/themiya/Dropbox/mosdrp/analysis/Tables/instrument_throughputs/MOSFIRE/H.dat') elif band =='K': band_mag = magK band_center_wave = k_wave band_zero = k_zero band_fwhm = j_fwhm mosfire_tp = ascii.read('/Users/themiya/Dropbox/mosdrp/analysis/Tables/instrument_throughputs/MOSFIRE/K.dat') ####STEP 1#################### telluric_star = generate_telluric(band, star_name, path_A, path_C, star_temperature, date, csp ) ###STEP 2#################### telluric_star.smooth_stellar_spectra() # ###STEP 3#################### # ### This is not correct telluric_star.mask_stellar_H_lines() # ###STEP 4#################### blackbody_flux = telluric_star.compute_blackbody() # ###STEP 5 ################## ## where should this normalization go? correction = (telluric_star.star_flux_H_interpolated/np.median(telluric_star.star_flux_H_interpolated))/blackbody_flux # correction = (telluric_star_smoothed_flux/np.median(telluric_star_smoothed_flux))/blackbody_flux # ascii.write( {'wavelength': telluric_star.star_wave, 'sensitivity':correction } , # '../outputs/tel_corr_function'+str(star_name)+'_'+str(date)+'_'+str(band)+'.dat' ) corrected_star_flux = telluric_star.star_flux /correction telluric_star.make_comparison_figure(corrected_star_flux, blackbody_flux, correction, sky_transmission, mosfire_tp) # ###STEP 6 ################## flux_convt_factor = compute_flux_convt_factor(telluric_star.star_flux, telluric_star.star_wave, band_center_wave, band_zero, band_mag) flux_calibrated_star = corrected_star_flux * flux_convt_factor # ###STEP 8 ################## # apply_calibs_to_data(twod_flux_names, telluric_star.star_wave, # correction, flux_convt_factor) if __name__ == '__main__': main()
f3ea0b33ace007475efbcd12cf8210f0974a102c
[ "Markdown", "Python" ]
3
Python
themiyan/astronomy
5a80be11b48283d38c75100f085ea04d4a236ca9
00d423d238b24b2668866306a00adf4225da2319
refs/heads/master
<file_sep>package br.com.mussumlanguis.ast; import java.util.ArrayList; public class WhileCommand extends AbstractCommand { private String condition; private ArrayList<AbstractCommand> commandList; public WhileCommand(String condition, ArrayList<AbstractCommand> commandList) { this.condition = condition; this.commandList = commandList; } @Override public String generateJavaCode() { StringBuilder generatedCode = new StringBuilder(); generatedCode.append(" while ( " + this.condition + " ) {\n"); for (AbstractCommand cmd: commandList) { generatedCode.append(" " + cmd.generateJavaCode()); } generatedCode.append(" }\n"); return generatedCode.toString(); } @Override public String toString() { return String.format("WhileCommand [condition=%s, commandList=%s]", this.condition, this.commandList); } } <file_sep>package br.com.mussumlanguis.datastructures; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; public class MussumSymbolTable { private HashMap<String, MussumSymbol> map; public MussumSymbolTable() { map = new HashMap<String, MussumSymbol>(); } public void add(MussumSymbol symbol) { map.put(symbol.getName(), symbol); } public boolean exists(String symbolName) { return map.get(symbolName) != null; } public MussumSymbol get(String symbolName) { return map.get(symbolName); } public Set<String> keySet() { return map.keySet(); } public ArrayList<MussumSymbol> getAllSymbols() { return new ArrayList<MussumSymbol>(map.values()); } } <file_sep>package br.com.mussumlanguis.datastructures; public class MussumVariable extends MussumSymbol{ public static final int INT = 0; public static final int TEXT = 1; public static final int DOUBLE = 2; public static final int BOOLEAN = 3; public static final int CHAR = 4; private int type; private String value; public MussumVariable(String name, int type, String value) { super(name); this.type = type; this.value = value; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "MussumVariable [name=" + name + ", type=" + type + ", value=" + value + "]"; } @Override public String generateJavaCode() { return String.format(" %s %s;\n", generateTypeCode(), super.name); } private String generateTypeCode() { switch (this.type) { case INT: return "int"; case TEXT: return "String"; case DOUBLE: return "double"; case BOOLEAN: return "boolean"; case CHAR: return "char"; default: throw new RuntimeException("tipis não definidis"); } } public static String getMussumType(int type) { switch (type) { case INT: return "inteiris"; case TEXT: return "textis"; case DOUBLE: return "quebradis"; case BOOLEAN: return "booleanis"; case CHAR: return "caracteris"; default: throw new RuntimeException("tipis não definidis"); } } } <file_sep>package br.com.mussumlanguis.ast; public class AttrCommand extends AbstractCommand { private String id; private String expression; public AttrCommand(String id, String expression) { this.id = id; this.expression = expression; } @Override public String generateJavaCode() { return String.format(" %s = %s;\n", this.id, this.expression); } } <file_sep>package br.com.mussumlanguis.ast; import br.com.mussumlanguis.datastructures.MussumVariable; import br.com.mussumlanguis.exceptions.MussumSemanticException; public class ReadCommand extends AbstractCommand { private String id; private MussumVariable var; public ReadCommand(String id, MussumVariable var) { this.id = id; this.var = var; } @Override public String generateJavaCode() throws MussumSemanticException { return String.format(" %s = %s;\n", this.id, getOperationCode()); } private String getOperationCode() throws MussumSemanticException { switch (this.var.getType()) { case MussumVariable.INT: return "_key.nextInt()"; case MussumVariable.DOUBLE: return "_key.nextDouble()"; case MussumVariable.TEXT: return "_key.nextLine()"; case MussumVariable.CHAR: return "_key.next(\".\").charAt(0)"; case MussumVariable.BOOLEAN: throw new MussumSemanticException("Não é possívis ler uma variávis booleanis"); default: throw new RuntimeException("tipis não definidis"); } } } <file_sep>package br.com.mussumlanguis.ast; import java.util.ArrayList; public class DecisionCommand extends AbstractCommand { private String condition; private ArrayList<AbstractCommand> trueList; private ArrayList<AbstractCommand> falseList; public DecisionCommand( String condition, ArrayList<AbstractCommand> trueList, ArrayList<AbstractCommand> falseList) { this.condition = condition; this.trueList = trueList; this.falseList = falseList; } @Override public String generateJavaCode() { StringBuilder generatedCode = new StringBuilder(); generatedCode.append(" if ( " + this.condition + " ) {\n"); for (AbstractCommand cmd: trueList) { generatedCode.append(" " + cmd.generateJavaCode()); } generatedCode.append(" }\n"); if (falseList != null && falseList.size() > 0) { generatedCode.append(" else {\n"); for (AbstractCommand cmd: falseList) { generatedCode.append(" " + cmd.generateJavaCode()); } generatedCode.append(" }\n"); } return generatedCode.toString(); } @Override public String toString() { return String.format("DecisionCOmmand [condition=%s, trueList=%s, falseList=%s]", this.condition, this.trueList, this.falseList); } } <file_sep>import java.util.Scanner; public class MainClass{ public static void main(String args[]) { Scanner _key = new Scanner(System.in); int a; String ab; int b; int c; String text; boolean bol; a = 4; c = 5; bol = false; a = 5; b = 10; for ( c = 0;c<3;c-- ) { System.out.println(a); } while ( a==10 ) { while ( b==50 ) { System.out.println(a); if ( b==a ) { b = _key.nextInt(); } } } do { while ( b==50 ) { System.out.println(a); if ( b==a ) { b = _key.nextInt(); } } } while (a==10 ); ab = "textinho teste"; }}<file_sep>package br.com.mussumlanguis.main; import org.antlr.v4.runtime.CharStreams; import org.antlr.v4.runtime.CommonTokenStream; import br.com.mussumlanguis.exceptions.MussumSemanticException; import br.com.mussumlanguis.parser.MussumLanguisLexer; import br.com.mussumlanguis.parser.MussumLanguisParser; //Classe responsável pela interação com o usuário public class MainClass { public static void main(String[] args) { try { MussumLanguisLexer lexer; MussumLanguisParser parser; lexer = new MussumLanguisLexer(CharStreams.fromFileName("input.mus")); CommonTokenStream tokenStream = new CommonTokenStream(lexer); parser = new MussumLanguisParser(tokenStream); parser.prog(); System.out.println("Programis Compiladis!! Cacildis"); parser.generateCode(); } catch (MussumSemanticException ex) { System.err.println("Semantic error - " + ex.getMessage()); } catch (Exception ex){ System.err.println("Error " + ex.getMessage()); } } } <file_sep># mussum-languis <img src="mussum.jpg" alt="Mussum" width="200"/> A linguagem de programação preferida de todo trapalhão. O resultado é um arquivo Java. # Regras básiquis ## Fluxis do programis ``` programis ... cacildis ``` ## Variávis ``` inteiris int_var = 5; quebradis double_var = 5.50; textis string_var = "example"; booleanis true_bool = verdadeiris, false_bool = falsis; caractéris char_var = "a"; ``` ## Operações Operações aritméticas: Soma (+), Subtração (-), Divisão(/), Multiplicação (*) Operações Relacionais (>, <, >=, <=, ==, !=) ## Estruturis de decisão if → se else → senãozis ## Entradis/saídis output → escrevis input → inputis ## Estruturis de repetição while → enquantis do/while → facis {...} enquantis (...) ## Comentáris ``` #COMENTIS ... #DESCOMENTIS ``` # Começandis Abaixo temos um exemplo correto de como declarar três variáveis inteiras, atribuir valores à elas, somar e exibir o valor. ``` programis inteiris a, b, c; a = 1; b = 2; c = a+b; escrevis(c) cacildis; ``` O bloco de declaração de variáveis pode ser feito antes ou depois do bloco com os comandos de Entrada/Saída, Estruturas de Repetição ou atribuição de variável. ``` programis inteiris a, b; a = 1; inputis(b); inteiris c = a + b; escrevis(c) cacildis; ``` É possível declarar uma variável já atribuindo valor à ela: ``` programis inteiris a = 1, b; b = 2; inteiris c; c = a+b; escrevis(c) cacildis; ``` Para **Estruturas de Decisão**, fazemos o seguinte: ``` programis inteiris a = 1, b = 2; se (a < b) { escrevis(a); } senãozis { escrevis(b); } cacildis; ``` Para **Estruturas de Repetição**, temos: ### Laço 'Paris' ``` programis inteiris a, c; a = 1; paris (c = 0;c < 3; c++){ escrevis(a); } cacildis; ``` ### Laço 'Enquantis' ``` programis inteiris a, b; a = 1; b = 2; enquantis (a < b) { escrevis(b); } cacildis; ``` ### Laço 'Facis...Enquantis' ``` programis inteiris a, b; a = 1; b = 2; facis { escrevis(a); } enquantis(b == 2) cacildis; ``` Tentar fazer ```paris(inteiris c=0;c<3;c++)```, entretanto, gera erro de compilação. Não é possível declarar uma variável dentro do laço. ## Autores * [<NAME>](https://github.com/arthurhf/) * [<NAME>](https://github.com/igornerest)
845db1c4a300a693c1399a526627904b7c8fe7d4
[ "Markdown", "Java" ]
9
Java
arthurhf/mussum-languis
dd8228b39ef5d7cc7eec95eb9af37b5ffbe1fe95
6826569bd921d2208e413721aa7881c34912a30a
refs/heads/master
<file_sep>* Helm Chart * Better comparison for when to update stateful set * Add webhook to reject changes which would cause a failure to update the statefulset (immutable containers, etc) * Controller references for all child resources * CRD for "docker image", will ensure a Cluster has an image present in the kind container loaded from the base docker daemon * Field for custom docker config to be added to configmap and mounted as well as loaded from external tarball (e.g. ReadWriteMany extra mount) * Watch for changes to statefulset to trigger reconcile of matching cluster * Configurable requeue delay * Conditions * Events * Figure out how to avoid privlledged containers * Configurable kind exe path * Add option to not export docker tls data in secret and port in service for potential security improvements * Put labels on everything, update labels when they change * Add option for annotations * Add webhook to validate kind config, as it can't be included directly in the CRD as it doesn't have json tags * Add DOCKER\_HOST to secret * Remove k8sMasterPort from cluster CRD, as it can be inferred from the kind config * Expose extra ports on the service based on kind config * Set the k8s master port to a default if not set, as it chooses a random port otherwise * Set the kind cluster name to the cluster resource name if not set <file_sep>package model import ( "fmt" kindmeln5674v0 "github.com/meln5674/kind-operator.git/api/v0" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" ) func ClusterHostname(cluster *kindmeln5674v0.Cluster) string { return fmt.Sprintf("%s.%s", ClusterServiceMeta(cluster).Name, cluster.Namespace) } func ClusterK8sAPIAddress(cluster *kindmeln5674v0.Cluster) string { return fmt.Sprintf("%s:%d", ClusterHostname(cluster), ClusterK8sAPIPort(cluster)) } func ClusterK8sAPIURL(cluster *kindmeln5674v0.Cluster) string { return fmt.Sprintf("https://%s", ClusterK8sAPIAddress(cluster)) } func ClusterDockerAddress(cluster *kindmeln5674v0.Cluster) string { return fmt.Sprintf("%s:%d", ClusterHostname(cluster), ClusterDockerPort(cluster)) } func ClusterDockerRawAddress(cluster *kindmeln5674v0.Cluster, pod *corev1.Pod) string { return fmt.Sprintf("%s:%d", pod.Status.PodIPs[0].IP, ClusterDockerPort(cluster)) } func ClusterDockerURL(cluster *kindmeln5674v0.Cluster) string { return fmt.Sprintf("tcp://%s", ClusterDockerAddress(cluster)) } func ClusterDockerRawURL(cluster *kindmeln5674v0.Cluster, pod *corev1.Pod) string { return fmt.Sprintf("tcp://%s", ClusterDockerRawAddress(cluster, pod)) } func ClusterServiceMeta(cluster *kindmeln5674v0.Cluster) metav1.ObjectMeta { return metav1.ObjectMeta{ Namespace: cluster.Namespace, Name: cluster.Name, Labels: cluster.ObjectMeta.Labels, } } func ClusterService(cluster *kindmeln5674v0.Cluster) corev1.Service { return corev1.Service{ ObjectMeta: ClusterServiceMeta(cluster), Spec: corev1.ServiceSpec{ // TODO: Configurable? Type: corev1.ServiceTypeClusterIP, Selector: ClusterPodLabelSelector(cluster), Ports: []corev1.ServicePort{ { Name: dockerPortName, Protocol: corev1.ProtocolTCP, Port: ClusterDockerPort(cluster), TargetPort: intstr.FromString(dockerPortName), }, { Name: k8sAPIPortName, Protocol: corev1.ProtocolTCP, Port: ClusterK8sAPIPort(cluster), TargetPort: intstr.FromString(k8sAPIPortName), }, }, }, } } <file_sep>/* Copyright © 2021 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package cmd import ( goflag "flag" "context" "github.com/spf13/cobra" "os" "os/exec" "time" // Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.) // to ensure that exec-entrypoint and run can make use of them. _ "k8s.io/client-go/plugin/pkg/client/auth" "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" clientgoscheme "k8s.io/client-go/kubernetes/scheme" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/healthz" "sigs.k8s.io/controller-runtime/pkg/log/zap" kindmeln5674v0 "github.com/meln5674/kind-operator.git/api/v0" "github.com/meln5674/kind-operator.git/controllers" corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" k8srest "k8s.io/client-go/rest" "k8s.io/client-go/tools/remotecommand" //+kubebuilder:scaffold:imports ) type execWrapper struct { config *k8srest.Config clientset *kubernetes.Clientset scheme *runtime.Scheme } func (e *execWrapper) Exec(ctx context.Context, pod client.ObjectKey, opts corev1.PodExecOptions) (remotecommand.Executor, error) { req := e.clientset. CoreV1(). RESTClient(). Post(). Resource("pods"). Name(pod.Name). Namespace(pod.Namespace). SubResource("exec"). VersionedParams(&opts, runtime.NewParameterCodec(scheme)) return remotecommand.NewSPDYExecutor(e.config, "POST", req.URL()) } var ( metricsAddr string enableLeaderElection bool probeAddr string opts zap.Options = zap.Options{ Development: true, } scheme = runtime.NewScheme() setupLog = ctrl.Log.WithName("setup") // managerCmd represents the manager command managerCmd = &cobra.Command{ Use: "manager", Short: "The Kind Operator", Long: `Manage Kubernetes-in-Kubernetes using Kind, controlled via the Kubernetes API`, Run: func(cmd *cobra.Command, args []string) { if dockerPath, err := exec.LookPath("docker"); err != nil { setupLog.Error(err, "Docker is not on $PATH, this is not supported", "PATH", os.Getenv("PATH")) os.Exit(1) } else { setupLog.Info("Found docker cli on $PATH", "docker", dockerPath) } config := ctrl.GetConfigOrDie() client := kubernetes.NewForConfigOrDie(config) ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts))) mgr, err := ctrl.NewManager(config, ctrl.Options{ Scheme: scheme, MetricsBindAddress: metricsAddr, Port: 9443, HealthProbeBindAddress: probeAddr, LeaderElection: enableLeaderElection, LeaderElectionID: "8e674aa7.kind-operator.meln5674", }) if err != nil { setupLog.Error(err, "unable to start manager") os.Exit(1) } if err = (&controllers.ClusterReconciler{ Client: mgr.GetClient(), Scheme: mgr.GetScheme(), PodExecutor: &execWrapper{ clientset: client, config: config, scheme: scheme, }, KindPath: "kind", RequeueDelay: time.Second * 30, }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "Fleet") os.Exit(1) } //+kubebuilder:scaffold:builder if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up health check") os.Exit(1) } if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil { setupLog.Error(err, "unable to set up ready check") os.Exit(1) } setupLog.Info("starting manager") if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil { setupLog.Error(err, "problem running manager") os.Exit(1) } }, } ) func init() { rootCmd.AddCommand(managerCmd) // Here you will define your flags and configuration settings. // Cobra supports Persistent Flags which will work for this command // and all subcommands, e.g.: // managerCmd.PersistentFlags().String("foo", "", "A help for foo") // Cobra supports local flags which will only run when this command // is called directly, e.g.: // managerCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") utilruntime.Must(clientgoscheme.AddToScheme(scheme)) utilruntime.Must(kindmeln5674v0.AddToScheme(scheme)) //+kubebuilder:scaffold:scheme managerCmd.Flags().StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.") managerCmd.Flags().StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.") managerCmd.Flags().BoolVar(&enableLeaderElection, "leader-elect", false, "Enable leader election for controller manager. "+ "Enabling this will ensure there is only one active controller manager.") tmpflags := goflag.NewFlagSet("", goflag.ContinueOnError) opts.BindFlags(tmpflags) managerCmd.Flags().AddGoFlagSet(tmpflags) } <file_sep>package model import ( kindv0 "github.com/meln5674/kind-operator.git/api/v0" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "path/filepath" ) const ( defaultKindContainerName = "kind" defaultKindImage = "docker:dind" dockerVolumeName = "docker" //dockerVolumeClaimNameSuffix = "-docker" defaultDockerVolumeMount = "/var/lib/docker" provisionerVolumeName = "pvcs" //provisionerVolumeClaimNameSuffix = "-pvcs" defaultProvisionerVolumeMount = "/var/local-path-provisioner" k8sAPIPortName = "api-server" dockerPortName = "docker" kindConfigVolumeName = "kind-config" KindConfigMountPath = "/etc/kind/config.yaml" ) var ( defaultDockerVolumeStorage = resource.MustParse("8Gi") defaultProvisionerVolumeStorage = resource.MustParse("8Gi") ) func ClusterStatefulSetMeta(cluster *kindv0.Cluster) metav1.ObjectMeta { return metav1.ObjectMeta{ Namespace: cluster.Namespace, Name: cluster.Name, Labels: cluster.ObjectMeta.Labels, } } func ClusterStatefulSet(cluster *kindv0.Cluster) appsv1.StatefulSet { podSpec := corev1.PodSpec{} if cluster.Spec.PodSpec != nil { podSpec = *cluster.Spec.PodSpec } kindContainerName := KindContainerName(cluster) var kindContainer *corev1.Container for ix := range podSpec.Containers { if podSpec.Containers[ix].Name == kindContainerName { kindContainer = &podSpec.Containers[ix] } } if kindContainer == nil { podSpec.Containers = append(podSpec.Containers, corev1.Container{ Name: kindContainerName, }) kindContainer = &podSpec.Containers[len(podSpec.Containers)-1] } if kindContainer.Image == "" { kindContainer.Image = defaultKindImage } // TODO: Find a way around this if kindContainer.SecurityContext == nil { kindContainer.SecurityContext = &corev1.SecurityContext{} } kindContainer.SecurityContext.Privileged = new(bool) *kindContainer.SecurityContext.Privileged = true k8sAPIPort := ClusterK8sAPIPort(cluster) dockerPort := ClusterDockerPort(cluster) hasDockerPort := false hasAPIServerPort := false for ix := range kindContainer.Ports { if kindContainer.Ports[ix].Name == k8sAPIPortName { hasAPIServerPort = true if hasDockerPort { break } } if kindContainer.Ports[ix].ContainerPort == dockerPort { hasDockerPort = true if hasAPIServerPort { break } } } if !hasAPIServerPort { kindContainer.Ports = append(kindContainer.Ports, corev1.ContainerPort{ Name: k8sAPIPortName, ContainerPort: k8sAPIPort, Protocol: corev1.ProtocolTCP, }) } if !hasDockerPort { kindContainer.Ports = append(kindContainer.Ports, corev1.ContainerPort{ Name: dockerPortName, ContainerPort: dockerPort, Protocol: corev1.ProtocolTCP, }) } hasDockerVolumeMount := false hasProvisionerVolumeMount := false for ix := range kindContainer.VolumeMounts { if kindContainer.VolumeMounts[ix].Name == dockerVolumeName { hasDockerVolumeMount = true if hasProvisionerVolumeMount { break } } if kindContainer.VolumeMounts[ix].Name == provisionerVolumeName { hasProvisionerVolumeMount = true if hasDockerVolumeMount { break } } } if !hasDockerVolumeMount { kindContainer.VolumeMounts = append(kindContainer.VolumeMounts, corev1.VolumeMount{ Name: dockerVolumeName, MountPath: defaultDockerVolumeMount, }) } if !hasProvisionerVolumeMount { kindContainer.VolumeMounts = append(kindContainer.VolumeMounts, corev1.VolumeMount{ Name: provisionerVolumeName, MountPath: defaultProvisionerVolumeMount, }) } kindContainer.VolumeMounts = append(kindContainer.VolumeMounts, corev1.VolumeMount{ Name: kindConfigVolumeName, MountPath: KindConfigMountPath, SubPath: filepath.Base(KindConfigMountPath), }) blank := corev1.Handler{} if kindContainer.LivenessProbe == nil { kindContainer.LivenessProbe = &corev1.Probe{} } if kindContainer.LivenessProbe.Handler == blank { kindContainer.LivenessProbe = &corev1.Probe{ Handler: corev1.Handler{ Exec: &corev1.ExecAction{ Command: []string{"docker", "ps"}, }, }, } } if kindContainer.ReadinessProbe == nil { kindContainer.ReadinessProbe = &corev1.Probe{} } if kindContainer.ReadinessProbe.Handler == blank { kindContainer.ReadinessProbe = &corev1.Probe{ Handler: corev1.Handler{ HTTPGet: &corev1.HTTPGetAction{ Port: intstr.FromString(k8sAPIPortName), Path: "/readyz", Scheme: corev1.URISchemeHTTPS, }, }, } } podSpec.Volumes = append(podSpec.Volumes, corev1.Volume{ Name: kindConfigVolumeName, VolumeSource: corev1.VolumeSource{ ConfigMap: &corev1.ConfigMapVolumeSource{ LocalObjectReference: corev1.LocalObjectReference{ Name: ClusterKindConfigConfigMapMeta(cluster).Name, }, }, }, }) volumeClaimTemplates := cluster.Spec.VolumeClaimTemplates hasDockerVolumeClaim := false hasProvisionerVolumeClaim := false for ix := range volumeClaimTemplates { if volumeClaimTemplates[ix].Name == dockerVolumeName { hasDockerVolumeClaim = true if hasProvisionerVolumeClaim { break } } if volumeClaimTemplates[ix].Name == provisionerVolumeName { hasProvisionerVolumeClaim = true if hasDockerVolumeClaim { break } } } if !hasDockerVolumeClaim { volumeClaimTemplates = append(volumeClaimTemplates, corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: dockerVolumeName, }, Spec: corev1.PersistentVolumeClaimSpec{ AccessModes: []corev1.PersistentVolumeAccessMode{ corev1.ReadWriteOnce, }, Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceStorage: defaultDockerVolumeStorage, }, }, }, }) } if !hasProvisionerVolumeClaim { volumeClaimTemplates = append(volumeClaimTemplates, corev1.PersistentVolumeClaim{ ObjectMeta: metav1.ObjectMeta{ Name: provisionerVolumeName, }, Spec: corev1.PersistentVolumeClaimSpec{ AccessModes: []corev1.PersistentVolumeAccessMode{ corev1.ReadWriteOnce, }, Resources: corev1.ResourceRequirements{ Requests: corev1.ResourceList{ corev1.ResourceStorage: defaultProvisionerVolumeStorage, }, }, }, }) } selector := ClusterPodLabelSelector(cluster) one := int32(1) return appsv1.StatefulSet{ ObjectMeta: ClusterStatefulSetMeta(cluster), Spec: appsv1.StatefulSetSpec{ Replicas: &one, Selector: &metav1.LabelSelector{MatchLabels: selector}, ServiceName: ClusterServiceMeta(cluster).Name, Template: corev1.PodTemplateSpec{ ObjectMeta: metav1.ObjectMeta{ Labels: selector, }, Spec: podSpec, }, VolumeClaimTemplates: volumeClaimTemplates, }, } } <file_sep>#!/bin/bash -e REGISTRY=$1 ARCH=$2 OS=$3 DOCKER_VERSION=$4 KIND_VERSION=$5 shift 5 if [ -n "${REGISTRY}" ]; then REGISTRY+="/" fi docker build \ -f kind.Dockerfile \ --build-arg "OS=${OS}" \ --build-arg "ARCH=${ARCH}" \ --build-arg "DOCKER_VERSION=${DOCKER_VERSION}" \ --build-arg "KIND_VERSION=${KIND_VERSION}" \ --tag "${REGISTRY}meln5674/kind:${KIND_VERSION}-docker-${DOCKER_VERSION}" \ "$@" \ . <file_sep> FROM alpine AS downloader ARG OS=linux ARG DOCKER_VERSION=20.10.9 ARG DOCKERARCH=x86_64 RUN apk add curl \ && curl -vL https://download.docker.com/${OS}/static/stable/${DOCKERARCH}/docker-${DOCKER_VERSION}.tgz \ | tar xz -C /tmp/ docker/docker \ && chmod +x /tmp/docker/docker ARG ARCH=amd64 ARG KIND_MIRROR=https://github.com/kubernetes-sigs/kind/releases/download ARG KIND_VERSION=v0.11.1 RUN curl -vL ${KIND_MIRROR}/${KIND_VERSION}/kind-${OS}-${ARCH} \ > /tmp/kind \ && chmod +x /tmp/kind RUN mkdir -p /tmp/tmp FROM scratch ARG OS=linux ARG ARCH=amd64 COPY --from=downloader /tmp/docker/docker /docker COPY --from=downloader /tmp/kind /kind COPY --from=downloader /tmp/tmp /tmp COPY --from=downloader /etc/ssl/cert.pem /etc/ssl/cert.pem COPY bin/kind-operator-${OS}-${ARCH} /kind-operator ENV PATH=/ ENTRYPOINT ["/kind-operator"] CMD ["manager"] <file_sep>package model import ( kindmeln5674v0 "github.com/meln5674/kind-operator.git/api/v0" dumbyaml "gopkg.in/yaml.v3" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kindv1alpha4 "sigs.k8s.io/kind/pkg/apis/config/v1alpha4" ) func ClusterKindConfigConfigMapMeta(cluster *kindmeln5674v0.Cluster) metav1.ObjectMeta { return metav1.ObjectMeta{ Name: cluster.Name, Namespace: cluster.Namespace, } } func CompleteKindConfig(cluster *kindmeln5674v0.Cluster) ([]byte, error) { kindCluster := kindv1alpha4.Cluster{} if cluster.Spec.KindConfig != nil { if err := dumbyaml.Unmarshal([]byte(cluster.Spec.KindConfig), &kindCluster); err != nil { return nil, err } } if kindCluster.APIVersion == "" { kindCluster.APIVersion = "kind.x-k8s.io/v1alpha4" } if kindCluster.Kind == "" { kindCluster.Kind = "Cluster" } var err error if kindCluster.Name, err = KindClusterName(cluster); err != nil { return nil, err } if kindCluster.Networking.APIServerPort == 0 { kindCluster.Networking.APIServerPort = defaultK8sAPIPort } if kindCluster.Networking.APIServerAddress == "" { kindCluster.Networking.APIServerAddress = "0.0.0.0" } return dumbyaml.Marshal(&kindCluster) } func ClusterKindConfigConfigMap(cluster *kindmeln5674v0.Cluster) (corev1.ConfigMap, error) { cfgBytes, err := CompleteKindConfig(cluster) if err != nil { return corev1.ConfigMap{}, err } return corev1.ConfigMap{ ObjectMeta: ClusterKindConfigConfigMapMeta(cluster), Data: map[string]string{ "kind.yaml": string(cfgBytes), }, }, nil } <file_sep># KinD operator This tool implements the operator pattern to manage Kubernetes-in-Kubernetes via Kubernetes-in-Docker (KinD). This tool is intended to be used to create isolated k8s clusters for use in CI/CD, testing, and debugging. **WARNING**: This tool is in alpha, it has not been tested thoroughly, use at your own risk. **WARNING**: This tool ***creates privileged containers***, and there is currently no known way around this. It is the user's responsibility to ensure that these containers are secure against potential abuse. Users and sevice accounts with privileges to pods/exec to the pods created by this tool will effectively have root access to the node these containers run on. Pods which can mount the secrets created by this tool will likewise effectively have root access. ## Building ```bash # For debugging make build # For containerizing make build-static docker build . ``` ## Deploying ```bash make deploy ``` ## Usage After deploying, create a `Cluster` Resource. ```yaml apiVersion: kind.meln5674/v0 kind: Cluster metadata: name: my-cluster spec: {} ``` Deploy a pod able to communicate with your cluster ```yaml apiVersion: v1 kind: Pod metadata: name: my-cluster-client spec: containers: - name: kubectl image: bitnami/kubectl command: [bash, -c] args: - | kubectl get nodes kubectl get pods --all-namespaces volumeMounts: - name: kubeconfig mountPath: /etc/kubernetes/config subPath: config env: - name: KUBECONFIG value: /etc/kubernetes/config volumes: - name: kubeconfig secret: secretName: my-cluster ``` <file_sep>/* Copyright 2021 <NAME>. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package controllers import ( "context" "fmt" "github.com/go-logr/logr" kindmeln5674v0 "github.com/meln5674/kind-operator.git/api/v0" "github.com/meln5674/kind-operator.git/model" "github.com/pkg/errors" "io/ioutil" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime" kubeconfig "k8s.io/client-go/tools/clientcmd/api/v1" "k8s.io/client-go/tools/remotecommand" "os" "os/exec" "path/filepath" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil" "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/yaml" "strings" "time" ) const ( clusterFinalizerName = "cluster.kind.meln5674.github.com/finalizer" kubeconfigExportPath = "/tmp/kube.config" dockerCAPath = "/certs/client/ca.pem" dockerClientCertPath = "/certs/client/cert.pem" dockerClientKeyPath = "/certs/client/key.pem" dockerCertPathEnv = "DOCKER_CERT_PATH" dockerHostEnv = "DOCKER_HOST" ) type PodExecutor interface { Exec(context.Context, client.ObjectKey, corev1.PodExecOptions) (remotecommand.Executor, error) } // ClusterReconciler reconciles a Cluster object type ClusterReconciler struct { client.Client PodExecutor Scheme *runtime.Scheme RequeueDelay time.Duration KindPath string } type ClusterReconcilerRun struct { *ClusterReconciler ctx context.Context log logr.Logger cluster kindmeln5674v0.Cluster kubeconfig *kubeconfig.Config dockerCA []byte dockerClientCert []byte dockerClientKey []byte service *corev1.Service statefulSet *appsv1.StatefulSet pod *corev1.Pod kubeconfigSecret *corev1.Secret kindConfigConfigMap *corev1.ConfigMap } func (r *ClusterReconcilerRun) kubeconfigSecretKey() client.ObjectKey { obj := model.ClusterSecretMeta(&r.cluster) return client.ObjectKey{Namespace: obj.GetNamespace(), Name: obj.GetName()} } func (r *ClusterReconcilerRun) serviceKey() client.ObjectKey { obj := model.ClusterServiceMeta(&r.cluster) return client.ObjectKey{Namespace: obj.GetNamespace(), Name: obj.GetName()} } func (r *ClusterReconcilerRun) statefulSetKey() client.ObjectKey { obj := model.ClusterStatefulSetMeta(&r.cluster) return client.ObjectKey{Namespace: obj.GetNamespace(), Name: obj.GetName()} } func (r *ClusterReconcilerRun) kindConfigConfigMapKey() client.ObjectKey { obj := model.ClusterKindConfigConfigMapMeta(&r.cluster) return client.ObjectKey{Namespace: obj.GetNamespace(), Name: obj.GetName()} } func (r *ClusterReconcilerRun) fetchResources(req ctrl.Request) error { if err := r.Get(r.ctx, req.NamespacedName, &r.cluster); err != nil { return err } r.log.Info("Fetched cluster") kubeconfigSecret := new(corev1.Secret) kubeconfigSecretKey := r.kubeconfigSecretKey() if err := r.Get(r.ctx, kubeconfigSecretKey, kubeconfigSecret); client.IgnoreNotFound(err) != nil { return errors.Wrap(err, "Failed to fetch secret") } else if err == nil { r.log.Info("Fetched secret", "secret", kubeconfigSecretKey) r.kubeconfigSecret = kubeconfigSecret } else { r.log.Info("Secret does not exist yet", "secret", kubeconfigSecretKey) } service := new(corev1.Service) serviceKey := r.serviceKey() if err := r.Get(r.ctx, serviceKey, service); client.IgnoreNotFound(err) != nil { return errors.Wrap(err, "Failed to fetch service") } else if err == nil { r.log.Info("Fetched service", "service", serviceKey) r.service = service } else { r.log.Info("Service does not exist yet", "service", serviceKey) } statefulSet := new(appsv1.StatefulSet) statefulSetKey := r.statefulSetKey() if err := r.Get(r.ctx, statefulSetKey, statefulSet); client.IgnoreNotFound(err) != nil { return errors.Wrap(err, "Failed to fetch stateful set") } else if err == nil { r.log.Info("Fetched stateful set", "statefulset", statefulSetKey) r.statefulSet = statefulSet } else { r.log.Info("Stateful set does not exist yet", "statefulset", statefulSetKey) } if r.statefulSet != nil { pods := new(corev1.PodList) if err := r.List(r.ctx, pods, client.MatchingLabels(r.statefulSet.Spec.Selector.MatchLabels)); client.IgnoreNotFound(err) != nil { return errors.Wrap(err, "Failed to fetch stateful set pod") } if len(pods.Items) != 0 { r.log.Info("Found stateful set pod", "pod", client.ObjectKeyFromObject(&pods.Items[0]), "podCount", len(pods.Items)) r.pod = new(corev1.Pod) *r.pod = pods.Items[0] } else { r.log.Info("No pods found for stateful set") } } kindConfigConfigMap := new(corev1.ConfigMap) kindConfigConfigMapKey := r.kindConfigConfigMapKey() if err := r.Get(r.ctx, kindConfigConfigMapKey, kindConfigConfigMap); client.IgnoreNotFound(err) != nil { return errors.Wrap(err, "Failed to fetch config map") } else if err == nil { r.log.Info("Fetched config map", "configmap", kindConfigConfigMapKey) r.kindConfigConfigMap = kindConfigConfigMap } else { r.log.Info("Config map does not exist yet", "configmap", kindConfigConfigMapKey) } r.log.Info("Fetched all resources") return nil } func containsString(slice []string, s string) bool { for _, item := range slice { if item == s { return true } } return false } func removeString(slice []string, s string) (result []string) { for _, item := range slice { if item == s { continue } result = append(result, item) } return } func (r *ClusterReconcilerRun) ensureResourcesDeleted() error { if r.kubeconfigSecret != nil { if err := r.Delete(r.ctx, r.kubeconfigSecret); err != nil { return errors.Wrap(err, "Failed to delete secret") } r.log.Info("Secret deleted") } if r.service != nil { if err := r.Delete(r.ctx, r.service); err != nil { return errors.Wrap(err, "Failed to delete service") } r.log.Info("Service deleted") } if r.statefulSet != nil { if err := r.Delete(r.ctx, r.statefulSet); err != nil { return errors.Wrap(err, "Failed to delete stateful set") } r.log.Info("Stateful set deleted") } if r.kindConfigConfigMap != nil { if err := r.Delete(r.ctx, r.kindConfigConfigMap); err != nil { return errors.Wrap(err, "Failed to delete config map") } r.log.Info("Failed to delete config map") } r.log.Info("All resources deleted") return nil } func (r *ClusterReconcilerRun) handleFinalizer() (deleted bool, err error) { if r.cluster.ObjectMeta.DeletionTimestamp.IsZero() { if !containsString(r.cluster.GetFinalizers(), clusterFinalizerName) { controllerutil.AddFinalizer(&r.cluster, clusterFinalizerName) if err := r.Update(r.ctx, &r.cluster); err != nil { return false, errors.Wrap(err, "Failed to add finalizer") } } r.log.Info("Finalizer added") } else { r.log.Info("Cluster marked for deletion") if err := r.fetchDockerFiles(); err != nil { return false, errors.Wrap(err, "Failed to fetch docker files for deletion. You may need to manually delete this cluster's statefulset. Note that containers running in docker-in-docker may continue to run if this happens") } if containsString(r.cluster.GetFinalizers(), clusterFinalizerName) { if r.statefulSet != nil { r.log.Info("Stateful set stil exists, ensuring kind cluster doesn't exist") if err := r.ensureKindClusterDeleted(); err != nil { return false, errors.Wrap(err, "Failed to delete kind cluster") } r.log.Info("Kind cluster deleted") } if err := r.ensureResourcesDeleted(); err != nil { return false, errors.Wrap(err, "Failed to delete child resources") } controllerutil.RemoveFinalizer(&r.cluster, clusterFinalizerName) if err := r.Update(r.ctx, &r.cluster); err != nil { return false, errors.Wrap(err, "Failed to remove finalizer") } } r.log.Info("Cluster resource ready for deletion") return true, nil } return false, nil } func (r *ClusterReconcilerRun) ensureClusterKindConfigConfigMapExists() error { expected, err := model.ClusterKindConfigConfigMap(&r.cluster) if err != nil { return err } if r.kindConfigConfigMap == nil { r.log.Info("Creating config map") r.kindConfigConfigMap = &expected return r.Create(r.ctx, r.kindConfigConfigMap) } for key := range expected.Data { if r.kindConfigConfigMap.Data[key] != expected.Data[key] { r.kindConfigConfigMap.Data = expected.Data r.log.Info("Config map missing field, updating", "field", key) return r.Update(r.ctx, r.kindConfigConfigMap) } } r.log.Info("Config map up to date") return nil } func (r *ClusterReconcilerRun) ensureClusterServiceExists() error { expected := model.ClusterService(&r.cluster) if r.service == nil { r.log.Info("Creating service") r.service = &expected return r.Create(r.ctx, r.service) } outOfSync := false for key := range expected.Spec.Selector { if r.service.Spec.Selector[key] != expected.Spec.Selector[key] { r.service.Spec.Selector = expected.Spec.Selector outOfSync = true break } } if len(r.service.Spec.Ports) != len(r.service.Spec.Ports) { outOfSync = true } else { for ix := range r.service.Spec.Ports { if r.service.Spec.Ports[ix] != expected.Spec.Ports[ix] { outOfSync = true break } } } if outOfSync { r.log.Info("Service out of sync, updating") return r.Update(r.ctx, r.service) } r.log.Info("Service up to date") return nil } func (r *ClusterReconcilerRun) ensureClusterStatefulSetExists() error { expected := model.ClusterStatefulSet(&r.cluster) if r.statefulSet == nil { r.log.Info("Stateful set doesn't exist, creating it") r.statefulSet = &expected return r.Create(r.ctx, r.statefulSet) } if true { //r.statefulSet.Spec.Template.Spec != expected.Spec.Template.Spec || r.statefulSet.Spec.Replicas != expected.Spec.Replicas { r.statefulSet.Spec.Template.Spec = expected.Spec.Template.Spec r.statefulSet.Spec.Replicas = expected.Spec.Replicas r.log.Info("Stateful set out of sync, updating") return r.Update(r.ctx, r.statefulSet) } r.log.Info("Stateful set up to date") return nil } func (r *ClusterReconcilerRun) ensureClusterSecretExists() error { expected, err := model.ClusterSecret(&r.cluster, r.kubeconfig, r.dockerCA, r.dockerClientCert, r.dockerClientKey) if err != nil { return err } if r.kubeconfigSecret == nil { r.log.Info("Secret doesn't exist, creating") r.kubeconfigSecret = &expected return r.Create(r.ctx, r.kubeconfigSecret) } for key, _ := range expected.Data { if string(r.kubeconfigSecret.Data[key]) != string(expected.Data[key]) { r.log.Info("Secret missing field, updating", "field", key) r.kubeconfigSecret.Data = expected.Data return r.Update(r.ctx, r.kubeconfigSecret) } } r.log.Info("Secret up to date") return nil } func (r *ClusterReconcilerRun) ensureClusterStatefulSetLive() (live bool, err error) { if r.statefulSet.Status.Replicas == 0 || r.pod == nil { r.log.Info("Stateful set has no pods yet", "replicas", r.statefulSet.Status.Replicas) return false, nil } for _, cond := range r.pod.Status.Conditions { if cond.Type == corev1.PodInitialized && cond.Status == corev1.ConditionTrue { r.log.Info("Stateful set pod is Initialized") return true, nil } } r.log.Info("Stateful set pod is not yet initialized") return false, nil } func (r *ClusterReconcilerRun) execPosixScript(script, stdin string) (stdout, stderr string, err error) { r.log.Info("Executing script on cluster pod", "pod", r.pod, "script", script, "stdin", stdin) stdinWrapper := strings.NewReader(stdin) stdoutWrapper := strings.Builder{} stderrWrapper := strings.Builder{} exec, err := r.Exec(r.ctx, client.ObjectKeyFromObject(r.pod), corev1.PodExecOptions{ Stdin: true, Stdout: true, Stderr: true, TTY: false, Container: model.KindContainerName(&r.cluster), Command: []string{"/bin/sh", "-c", script}, }) if err != nil { return "", "", errors.Wrap(err, "Failed to execute posix shell script") } err = exec.Stream(remotecommand.StreamOptions{ Stdin: stdinWrapper, Stdout: &stdoutWrapper, Stderr: &stderrWrapper, }) if err != nil { return "", "", errors.Wrap(err, "Failed to stream from posix shell script") } stdout = stdoutWrapper.String() stderr = stderrWrapper.String() r.log.Info("Executed script on cluster pod", "pod", r.pod, "script", script, "stdin", stdin, "stdout", stdout, "stderr", stderr) return stdout, stderr, nil } func (r *ClusterReconcilerRun) kind(configSubPath string, args ...string) (stdout, stderr string, err error) { dir, err := os.MkdirTemp(os.TempDir(), "") if err != nil { return "", "", err } defer os.RemoveAll(dir) if configSubPath != "" { cfgBytes, err := model.CompleteKindConfig(&r.cluster) if err != nil { return "", "", err } if err := ioutil.WriteFile(filepath.Join(dir, configSubPath), cfgBytes, 0700); err != nil { return "", "", err } } if r.dockerCA != nil { if err := ioutil.WriteFile(filepath.Join(dir, "ca.pem"), r.dockerCA, 0700); err != nil { return "", "", err } } if r.dockerClientCert != nil { if err := ioutil.WriteFile(filepath.Join(dir, "cert.pem"), r.dockerClientCert, 0700); err != nil { return "", "", err } } if r.dockerClientKey != nil { if err := ioutil.WriteFile(filepath.Join(dir, "key.pem"), r.dockerClientKey, 0700); err != nil { return "", "", err } } r.log.Info("Executing kind command", "kind", r.KindPath, "args", args) cmd := exec.Command(r.KindPath, args...) cmd.Env = os.Environ() cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", dockerCertPathEnv, dir)) // We use the raw (pod) URL because the pod will not be marked ready until the k8s api is ready cmd.Env = append(cmd.Env, fmt.Sprintf("%s=%s", dockerHostEnv, model.ClusterDockerRawURL(&r.cluster, r.pod))) cmd.Env = append(cmd.Env, "DOCKER_TLS_VERIFY=yes") stdoutWrapper := strings.Builder{} stderrWrapper := strings.Builder{} cmd.Stdout = &stdoutWrapper cmd.Stderr = &stderrWrapper cmd.Dir = dir err = cmd.Run() stdout = stdoutWrapper.String() stderr = stderrWrapper.String() r.log.Info("Kind command finished", "stdout", stdout, "stderr", stderr, "err", err) return } func (r *ClusterReconcilerRun) fetchFileFromCluster(path string) (contents string, err error) { stdout, stderr, err := r.execPosixScript( fmt.Sprintf( ` set -e cat '%s' echo yes 1>&2 `, path, ), "", ) if err != nil { return "", err } if stderr != "yes\n" { err = fmt.Errorf("Did not get expected result from fetching file.\nBEGIN STDOUT\n%s\nEND STDOUT\nBEGIN STDERR\n%s\nEND STDERR", stdout, stderr) return } contents = stdout return } func (r *ClusterReconcilerRun) fetchDockerFiles() error { dockerCA, err := r.fetchFileFromCluster(dockerCAPath) if err != nil { return err } dockerClientCert, err := r.fetchFileFromCluster(dockerClientCertPath) if err != nil { return err } dockerClientKey, err := r.fetchFileFromCluster(dockerClientKeyPath) if err != nil { return err } r.dockerCA = []byte(dockerCA) r.dockerClientCert = []byte(dockerClientCert) r.dockerClientKey = []byte(dockerClientKey) return nil } func (r *ClusterReconcilerRun) checkClusterExists(clusterName string) (bool, error) { clusterList, stderr, err := r.kind("", "get", "clusters") if err != nil { return false, errors.Wrap(err, fmt.Sprintf("Failed to list kind clusters: %s", stderr)) } clusters := strings.Split(clusterList, "\n") r.log.Info("Found clusters", "clusters", clusters) for _, name := range clusters { if name == clusterName { r.log.Info("Kind cluster exists") return true, nil } } r.log.Info("Kind cluster doesn't exist") return false, nil } func (r *ClusterReconcilerRun) ensureKindClusterCreated() error { clusterName, err := model.KindClusterName(&r.cluster) if err != nil { return err } clusterExists, err := r.checkClusterExists(clusterName) if err != nil { return errors.Wrap(err, "Failed to check if kind cluser exists") } f, err := os.CreateTemp(os.TempDir(), "kubeconfig-*.yaml") if err != nil { return err } f.Close() defer os.Remove(f.Name()) if !clusterExists { r.log.Info("Kind cluser doesn't exist, creating") configPath := "kind.yaml" args := []string{"create", "cluster", "--kubeconfig", f.Name(), "--config", configPath} if stdout, stderr, err := r.kind(configPath, args...); err != nil { return errors.Wrap(err, fmt.Sprintf("Failed to create cluster. Stdout: %s, Stderr: %s", stdout, stderr)) } } else { r.log.Info("Kind cluser exists, exporting kubeconfig for sync") if stdout, stderr, err := r.kind("", "export", "kubeconfig", "--name", clusterName, "--kubeconfig", f.Name()); err != nil { return errors.Wrap(err, fmt.Sprintf("Failed to export kubeconfig. Stdout: %s, Stderr: %s", stdout, stderr)) } } kubeconfigBytes, err := ioutil.ReadFile(f.Name()) if err != nil { return err } if err := yaml.Unmarshal(kubeconfigBytes, &r.kubeconfig); err != nil { return err } return nil } func (r *ClusterReconcilerRun) ensureKindClusterDeleted() error { clusterName, err := model.KindClusterName(&r.cluster) if err != nil { return err } clusterExists, err := r.checkClusterExists(clusterName) if err != nil { return errors.Wrap(err, "Failed to check if kind cluster exists") } if clusterExists { r.log.Info("Kind cluster exists, deleting") if stdout, stderr, err := r.kind("", "delete", "cluster", "--name", clusterName); err != nil { return errors.Wrap(err, fmt.Sprintf("Failed to delete cluster. Stdout: %s, Stderr: %s", stdout, stderr)) } } r.log.Info("Kind cluster deleted") return nil } //+kubebuilder:rbac:groups=kind.meln5674,resources=clusters,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=kind.meln5674,resources=clusters/status,verbs=get;update;patch //+kubebuilder:rbac:groups=kind.meln5674,resources=clusters/finalizers,verbs=update //+kubebuilder:rbac:groups=,resources=secrets;configmaps;services,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=,resources=pods,verbs=get;list;watch //+kubebuilder:rbac:groups=,resources=pods/exec,verbs=create,get func (r *ClusterReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { run := ClusterReconcilerRun{ ClusterReconciler: r, log: log.FromContext(ctx).WithValues("cluster", req), ctx: ctx, cluster: kindmeln5674v0.Cluster{}, } run.log.Info("Reconciling") if err := run.fetchResources(req); err != nil { if client.IgnoreNotFound(err) == nil { run.log.Info("Got a request for a cluster that doesn't exist, assuming deleted") return ctrl.Result{Requeue: false}, nil } return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } if deleted, err := run.handleFinalizer(); err != nil { return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } else if deleted { return ctrl.Result{Requeue: false}, nil } if err := run.ensureClusterKindConfigConfigMapExists(); err != nil { return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } if err := run.ensureClusterServiceExists(); err != nil { return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } if err := run.ensureClusterStatefulSetExists(); err != nil { return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } if live, err := run.ensureClusterStatefulSetLive(); err != nil || !live { return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } if err := run.fetchDockerFiles(); err != nil { return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } if err := run.ensureKindClusterCreated(); err != nil { return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } if err := run.ensureClusterSecretExists(); err != nil { return ctrl.Result{Requeue: true, RequeueAfter: r.RequeueDelay}, err } run.log.Info("Cluster ready") return ctrl.Result{Requeue: false}, nil } // SetupWithManager sets up the controller with the Manager. func (r *ClusterReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). For(&kindmeln5674v0.Cluster{}). Complete(r) } <file_sep>package model import ( kindmeln5674v0 "github.com/meln5674/kind-operator.git/api/v0" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kubeconfig "k8s.io/client-go/tools/clientcmd/api/v1" "sigs.k8s.io/yaml" ) func ClusterSecretMeta(cluster *kindmeln5674v0.Cluster) metav1.ObjectMeta { return metav1.ObjectMeta{ Name: cluster.Name, Namespace: cluster.Namespace, } } func ClusterSecret(cluster *kindmeln5674v0.Cluster, cfg *kubeconfig.Config, dockerCA, dockerClientCert, dockerClientKey []byte) (corev1.Secret, error) { // https://github.com/kubernetes-sigs/kind/blob/v0.11.1/pkg/cluster/internal/kubeconfig/internal/kubeconfig/helpers.go#L25 clusterName, err := KindClusterName(cluster) if err != nil { return corev1.Secret{}, err } contextName := "kind-" + clusterName var cfgClusterName string for _, context := range cfg.Contexts { if context.Name == contextName { cfgClusterName = context.Context.Cluster } } for ix := range cfg.Clusters { if cfg.Clusters[ix].Name == cfgClusterName { cfg.Clusters[ix].Cluster.Server = ClusterK8sAPIURL(cluster) cfg.Clusters[ix].Cluster.TLSServerName = ClusterHostname(cluster) } } cfgBytes, err := yaml.Marshal(&cfg) if err != nil { return corev1.Secret{}, err } return corev1.Secret{ ObjectMeta: ClusterSecretMeta(cluster), Data: map[string][]byte{ "config": cfgBytes, "ca.pem": dockerCA, "cert.pem": dockerClientCert, "key.pem": dockerClientKey, }, }, nil } <file_sep>ARG GO_VERSION=1.17 FROM golang:${GO_VERSION} ARG KUBEBUILDER_VERSION=3.1.0 RUN curl -vL "https://github.com/kubernetes-sigs/kubebuilder/releases/download/v${KUBEBUILDER_VERSION}/kubebuilder_$(go env GOOS)_$(go env GOARCH)" -o /usr/local/bin/kubebuilder ARG K8S_VERSION=1.19.2 RUN curl -sSL "https://storage.googleapis.com/kubebuilder-tools/kubebuilder-tools-${K8S_VERSION}-$(go env GOOS)-$(go env GOARCH).tar.gz" \ | tar -xz --strip-components=1 -C /usr/local/bin/ RUN chmod -R +x /usr/local/bin/ ARG COBRA_VERSION=1.2.1 RUN go install github.com/spf13/cobra/cobra@v${COBRA_VERSION} RUN find / -name cobra && which cobra ENV PATH="${PATH}:/usr/local/bin:/go/bin" RUN apt-get update && apt-get install -y vim <file_sep>#!/bin/bash -xe mkdir -p .tmp docker build -f dev-env.Dockerfile . docker build -q -f dev-env.Dockerfile . > .tmp/dev-env-image docker run \ --rm \ -it \ -v "$PWD:$PWD" \ -v "$HOME:$HOME" \ -v /etc/passwd:/etc/passwd:ro \ -v /etc/group:/etc/group:ro \ -e HOME \ -e GOPATH \ -w "$PWD" \ -u "$(id -u):$(id -g)" \ $(cat .tmp/dev-env-image) <file_sep>package model import ( kindmeln5674v0 "github.com/meln5674/kind-operator.git/api/v0" kindv1alpha4 "sigs.k8s.io/kind/pkg/apis/config/v1alpha4" "sigs.k8s.io/yaml" ) const ( defaultK8sAPIPort = int32(6443) defaultDockerPort = int32(2376) ClusterLabel = "kind-operator/cluster" ) func KindContainerName(cluster *kindmeln5674v0.Cluster) string { if cluster.Spec.KindContainerName == nil { return defaultKindContainerName } return *cluster.Spec.KindContainerName } func KindClusterName(cluster *kindmeln5674v0.Cluster) (string, error) { if cluster.Spec.KindConfig == nil { return cluster.Name, nil } kindConfig := kindv1alpha4.Cluster{} if err := yaml.Unmarshal([]byte(cluster.Spec.KindConfig), &kindConfig); err != nil { return "", err } clusterName := kindConfig.Name if clusterName == "" { return cluster.Name, nil } return clusterName, nil } func ClusterDockerPort(cluster *kindmeln5674v0.Cluster) int32 { // TODO: Configurable return defaultDockerPort } func ClusterK8sAPIPort(cluster *kindmeln5674v0.Cluster) int32 { if cluster.Spec.K8sAPIPort == nil { return defaultK8sAPIPort } return *cluster.Spec.K8sAPIPort } func ClusterPodLabelSelector(cluster *kindmeln5674v0.Cluster) map[string]string { selector := map[string]string{ClusterLabel: cluster.Name} for key, value := range cluster.Labels { selector[key] = value } return selector }
4be495059facbdeab77c8fc1cafb23fdb50b05e9
[ "Markdown", "Go", "Dockerfile", "Shell" ]
13
Markdown
meln5674/kind-operator
1a08c3b30dc30b36b06b3f6f086a7ae5e2d1bbc7
34a66a9f232fa951dece012f5a16ce22e1222437
refs/heads/master
<file_sep>import React from 'react'; import './Body.css'; import ImageArray from './ImageArray'; class Body extends React.Component { constructor() { super(); } renderContent = i => { console.log(); }; render() { const mpZero = { margin: 0, padding: 0 }; const active = { borderTop: '1px solid black' }; return ( <div id="body"> <div id="body-container"> <div id="profile-image"> <img src="https://www.absoluteanime.com/naruto/sasuke.jpg" /> </div> <div id="profile-user-info"> <h2><NAME></h2> <button>Edit Profile</button> <a> <i className="big cog icon"></i> </a> <ul> <li> <span>11 </span> post </li> <li> <span>19 </span> followers </li> <li style={mpZero}> <span>3 </span> following </li> </ul> </div> </div> <div id="post-nav"> <ul> <a style={active}> <li> <i className=" images outline icon" ></i> <h5>POSTS</h5> </li> </a> <a> <li> <i className="tv icon"></i> <h5>IGTV</h5> </li> </a> <a> <li> <i className="flag outline icon"></i> <h5>SAVED</h5> </li> </a> <a> <li style={mpZero}> <i className="id badge outline icon"></i> <h5>TAGGED</h5> </li> </a> </ul> </div> <div id="image-array"> <ul>{ImageArray}</ul> </div> </div> ); } } export default Body; <file_sep>import React from 'react'; console.log('hi'); const images = [ '/images/1.png', '/images/2.jpeg', '/images/3.jpeg', '/images/4.jpg', '/images/5.jpeg', '/images/6.jpg', '/images/7.jpg', '/images/8.jpeg', '/images/9.jpg' ]; const ImageArray = images.map(image => { return ( <a className="post-images"> <li> <img src={image} /> </li> </a> ); }); export default ImageArray; <file_sep>import React from 'react'; import '/public/src/components'; console.log('hi'); console.log("{process.env.PUBLIC_URL + '/yourPathHere.jpg'} "); const emptyArray = []; const images = [ '1.png', '2.jpeg', '3.jpeg', '4.jpg', '5.jpeg', '6.jpg', '7.jpg', '8.jpeg', '9.jpg' ]; const ImageArray = i => {}; export default ImageArray; <file_sep>import React from 'react'; import './Header.css'; class Header extends React.Component { render() { return ( <div id="wrap-all-header"> <div id="header-container"> <div className="header-sections"> <i className="big instagram icon"></i> <div id="vl"></div> <h2>Samagram</h2> </div> <div className="header-sections"> <div className="input-icons"> <i className="small search icon search-icon"></i> <input className="input-field" type="input" placeholder="Search" ></input> </div> </div> <div className="header-sections"> <a href="#" className="nav-icon-anchor"> <i className="big compass outline icon"></i> </a> <a href="#" className="nav-icon-anchor"> <i className="big heart outline icon"></i> </a> <a href="#" className="nav-icon-anchor"> <i className="big user outline icon"></i> </a> </div> </div> </div> ); } } export default Header;
0265c745482c10be308adba89a67e651fff9971a
[ "JavaScript" ]
4
JavaScript
sam3106/Samagram
8a7e450a29610605ce292060b50fd4aaa5da9451
2fd26403db20acf654677acdd1411db7de246b54
refs/heads/master
<repo_name>kitori-kitori/Online-faculty-feedback-system<file_sep>/README.md # Online-faculty-feedback-system an online system for university students to rate their Lecturers/ faculty <file_sep>/dbconfig.php <?php $conn=mysqli_connect("localhost","root","kitori","feedback_system")or die(mysqli_error()); ?>
51c3d78f99c0f7ab4b201a1bf6920f376c6b7e8c
[ "Markdown", "PHP" ]
2
Markdown
kitori-kitori/Online-faculty-feedback-system
39339cfcf5597200d8b7137f4161f19f888dce30
860887aee1e5e97d431765402645efaeb51e7232
refs/heads/master
<repo_name>Foina/yishu<file_sep>/app/routes.php <?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::get('/', array('as' => 'home', 'uses' => 'SiteController@getHome')); //login,register, logout Route::post('signin/auth', 'SiteController@postSignin'); Route::post('signup/auth', 'SiteController@postSignup'); Route::get('signout', array('as' => 'signout', 'uses' => 'SiteController@getSignout')); //admin Route::get('admin/login',array('as'=>'admin/login','uses'=>'AdminController@getLogin')); Route::post('admin/login','AdminController@postLogin'); Route::get('admin',array('as'=>'admin','uses'=>'AdminController@getAdmin')); Route::get('admin/logout',array('as'=>'admin/logout','uses'=>'AdminController@getLogout')); //book Route::get('book',array('as'=>'book','uses'=>'BookController@getIndex')); Route::get('delete/Book/{id}',array('as'=>'delete/Book','uses'=>'BookController@getDelete'))->where('{id}', '\d+'); Route::get('bookshow/{id}/{name}',array('as'=>'bookshow','uses'=>'BookController@bookShow')); Route::get('article/{id}/{title}',array('as'=>'article','uses'=>'ArticleController@getIndex')); //categories Route::get('categories',array('as'=>'categories','uses'=>'CategoriesController@getIndex')); Route::get('tags/{id}/{name}',array('as'=>'tags','uses'=>'TagController@getIndex')); //About Route::get('about',array('as'=>'about','uses'=>'AboutController@getIndex')); Route::get('local',array('as'=>'local','uses'=>'LocalController@getIndex')); //search Route::get('search/{word}', array('as'=>'search','uses'=>'SearchController@getIndex')) ->where('{word}', '\S+'); //book Route::get('create/BookList',array('as'=>'create/BookList','uses'=>'BookController@bookList')); Route::get('create',array('as'=>'create','uses'=>'BookController@getCreate')); Route::post('create','BookController@postCreate'); //article Route::get('create/ArticleList',array('as'=>'create/ArticleList','uses'=>'ArticleController@articleList')); Route::get('create/ArticleCreate',array('as'=>'create/ArticleCreate','uses'=>'ArticleController@articleCreate')); Route::post('create/ArticleCreate','ArticleController@postCreate'); Route::get('delete/Article/{id}',array('as'=>'delete/Article','uses'=>'ArticleController@getDelete'))->where('{id}', '\d+'); Route::get('edit/Article/{id}',array('as'=>'edit/Article','uses'=>'ArticleController@getEdit')); Route::post('edit/Article/{id}','ArticleController@postEdit'); Route::get('edit/Book/{id}',array('as'=>'edit/Book','uses'=>'BookController@getEdit')); Route::post('edit/Book/{id}','BookController@postEdit'); <file_sep>/app/controllers/SiteController.php <?php class SiteController extends BaseController { public function getHome() { $books = Book::orderBy('id', 'DESC')->orderBy('created_at', 'DESC')->take(5)->get(); $viewbooks = Book::orderBy('id', 'DESC')->orderBy('viewNum', 'DESC')->take(5)->get(); $articles=DB::table('articles')->orderBy('id','DESC')->orderBy('created_at','DESC')->take(5)->get(); $comments=DB::table('comments')->orderBy('id','DESC')->orderBy('created_at','DESC')->take(5)->get(); $tags=DB::table('tags')->join('tag_book', 'tags.id', '=', 'tag_book.tag_id')->orderBy('tag_book.frequency', 'DESC')->get(); $states=DB::table('states')->orderBy('created_at','DESC')->get(); return View::make('home',compact('books'))->with(compact('articles'))->with(compact('comments'))->with(compact('viewbooks'))->with($this->view_data); } public function postSignin() { $rules = array( 'email' => 'required|email|exists:users,email', 'password' => '<PASSWORD>', 'remember' => 'in:0,1', ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()){ return Response::json(array( 'success' => false, 'errors' => $validator->messages()->first('email'), )); } if (!Auth::attempt(array( 'email' => Input::get('email'), 'password' =>Input::get('password'), ), Input::get('remember'))) { return Response::json(array( 'success' => false, 'errors' => 'user or password invalid.', )); } return Response::json(array( 'success' => true, 'errors' => '', )); } public function postSignup() { $rules = array( 'name' => 'required|min:3|max:64', 'pd' => 'required|min:6|max:64', 'sex' => 'in:male,female', 'el'=>'required|email|unique:users,email', 'year' => 'integer|between:1900,2013', 'month' => 'integer|between:1,12', 'day' => 'integer|between:1,31', 'phone' => 'max:15', 'qq' => 'min:5|max:15', ); $validator = Validator::make(Input::all(), $rules); if ($validator->fails()){ return Response::json(array( 'success' => false, 'errors' => $validator->messages()->toArray(), )); } $birthday = Input::get('year').Input::get('month').Input::get('day'); $user = new User; $user->fill(array( 'name' => Input::get('name'), 'password' => <PASSWORD>(Input::get('pd')), 'email' => Input::get('el'), 'role_id' => 1, 'sex' => Input::get('sex','male'), 'birthday'=> $birthday, 'address' => Input::get('address'), 'phone'=>Input::get('phone'), 'qq'=>Input::get('qq'), 'activation_code' => md5(Hash::make(time())), )); $user->save(); return Response::json(array( 'success' => true, 'errors' => '', )); } public function getSignout() { if (Auth::check()) { Auth::logout(); } return Redirect::home(); } }<file_sep>/app/controllers/AdminController.php <?php class AdminController extends BaseController { public function getAdmin(){ if(Auth::check()&& Auth::user()->role_id==2) { $users=User::All(); $books=Book::All(); return View::make('Admin/index',compact('users'),compact('books')); } else { return Redirect::back()->withErrors( '无权限访问'); } } public function getLogin(){ return View::make('Admin/login'); } public function postLogin() { $rules = array( 'email' => 'required|email|exists:users,email', 'password' => '<PASSWORD>', 'remember' => 'in:0,1', ); $messages= array( 'email.required' => '用户名必须填', 'password.required' =>'<PASSWORD>', ); $validator = Validator::make(Input::all(), $rules,$messages); if ($validator->fails()){ return Redirect::back()->withInput()->withErrors($validator); } if (!Auth::attempt(array( 'email' => Input::get('email'), 'password' =>Input::get('<PASSWORD>'), ), Input::get('remember'))) { return Redirect::back()->withErrors( '用户名或密码错误'); } return Redirect::route('admin'); } public function getLogout() { Auth::logout(); return Redirect::route('admin/login'); } }<file_sep>/app/controllers/ArticleController.php <?php class ArticleController extends BaseController { public function getIndex($id=null,$title=null) { $article= DB::table('articles')->where('id','=',$id)->first(); $user_id=$article->user_id; $_user=DB::table('users')->where('id','=',$user_id)->first(); $article->views++; DB::table('articles')->where('id','=',$id)->update(array('views'=>$article->views)); return View::make('articles.article',compact('article','title','_user'))->with($this->view_data); } public function articleList() { $books=DB::table('books')->orderBy('id', 'DESC')->paginate(10); return View::make('articles.articlelist',compact('books')); } public function articleCreate() { if(Auth::check()){ $books=DB::table('books')->where('user_id','=',Auth::user()->id)->get(); return View::make('articles.create',compact('books')); }else{ return View::make('articles.create'); } } public function postCreate() { $rules=array( 'title'=>'required|min:3|max:64', 'content'=>'min:3|max:255', 'book_id'=>'required|integer', 'pagenum'=>'integer', ); $messages=array( 'title.required'=>'请填写文章标题', 'content.min'=>'内容至少3个字', 'content.max'=>'内容不得超过255个字', 'pagenum.integer'=>'页数只能是整数', 'book_id.required'=>'请选择该文章所属图书', ); $validator = Validator::make(Input::all(), $rules,$messages); $userid=Auth::user()->id; if ($validator->fails()){ return Redirect::back()->withInput()->withErrors($validator); /* return Response::json(array( 'success' => false, 'errors' => $validator->messages()->toArray(), )); */ } $article=new Article; $article->fill(array( 'title'=>Input::get('title'), 'content'=>Input::get('content'), 'user_id'=>$userid, 'book_id'=>Input::get('book_id'), 'page_num'=>Input::get('pagenum'), ) ); $article->save(); $success="文章创建成功"; return Redirect::route('create/ArticleList')->with('success', $success); } public function getEdit($id=null){ if(Auth::check()){ $books=DB::table('books')->where('user_id','=',Auth::user()->id)->get(); $article=DB::table('articles')->where('id',$id)->first(); $oldbook=Book::where('id',$article->book_id)->first(); return View::make('articles.Edit',compact('books'),compact('oldbook'))->with(compact('article')); }else{ return View::make('home'); } } public function postEdit(){ if(is_null($article = Article::find($articleId = Input::get('article_id')))){ /* return Response::json(array( 'success' => false, 'errors' => '该文章不存在', )); */ return Redirect::to('articles.articlelist')->with('error', '该文章不存在'); } $rules=array( 'title'=>'required|min:3|max:64', 'content'=>'min:3|max:64', 'book_id'=>'integer', 'pagenum'=>'integer', ); $messages=array( 'title.required'=>'请填写文章标题', 'content.min'=>'内容至少3个字', 'content.max'=>'内容不得超过255个字', 'pagenum.integer'=>'页数只能是整数', 'book_id.required'=>'请选择该文章所属图书', ); $userid=Auth::user()->id; $validator = Validator::make(Input::all(), $rules,$messages); if ($validator->fails()){ return Redirect::back()->withInput()->withErrors($validator); /* return Response::json(array( 'success' => false, 'errors' => $validator->messages(), )); */ } $article->fill(array( 'title'=>Input::get('title'), 'content'=>Input::get('content'), 'user_id'=>$userid, 'book_id'=>Input::get('book_id'), 'page_num'=>Input::get('pagenum'), ) ); $article->save(); $success="文章修改成功"; return Redirect::route('create/ArticleList')->with('success', $success); /* return Response::json(array( 'success' => true, 'errors' => '', )); */ } public function getDelete($id=null){ if(is_null(DB::table('articles')->where('id','=',$id)->get())){ return Response::json(array( 'success' => false, )); } DB::table('articles')->where('id','=',$id)->delete(); return Response::json(array( 'success' => true, 'errors' => '', )); } }<file_sep>/app/models/book.php <?php class Book extends Eloquent { protected $fillable = array('path', 'cover', 'name','user_id','category_id','info'); public function category() { return $this->belongsTo('Category'); } public function article() { return $this->hasMany('Article','book_id'); } public function user() { return $this->belongsTo('User'); } public function tags() { return $this->belongsToMany('Tag_book', 'tag_book', 'tag_id', 'book_id'); } }<file_sep>/app/controllers/SearchController.php <?php class SearchController extends BaseController { public function getIndex($word){ $word = trim(urldecode($word)); $results = array(); if ($word) { $results = Article::where('title', 'LIKE', "%{$word}%")->orderBy('id', 'DESC')->get(); } return View::make('search.search', $this->view_data)->with(compact('results')); //return View::make('search.search',compact('results'))->with(compact('tags'))->with(compact('states')); } }<file_sep>/app/controllers/BookController.php <?php class BookController extends BaseController { public function getIndex() { $books = Book::orderBy('id', 'DESC')->orderBy('created_at', 'DESC')->take(5)->get(); $viewbooks = Book::orderBy('id', 'DESC')->orderBy('viewNum', 'DESC')->take(5)->get(); return View::make('book.book',compact('books','viewbooks'))->with($this->view_data); } public function bookList() { $books = Book::orderBy('id', 'DESC')->orderBy('created_at', 'DESC')->paginate(10); return View::make('book.booklist',compact('books')); } public function bookShow($id=null,$name=null){ $book=DB::table('books')->where('id','=',$id)->first(); $book->viewNum++; DB::table('books')->where('id','=',$id)->update(array('viewNum'=>$book->viewNum)); $user=DB::table('users')->where('id','=',$book->user_id)->first(); $articles=DB::table('articles')->where('book_id','=',$id)->get(); return View::make('book.bookshow',compact('book','name','user','articles'))->with($this->view_data); } public function getCreate(){ if(Auth::check()) { $categories=DB::table('categories')->orderBy('id','DESC')->get(); return View::make('book.create',compact('categories')); } else{ return View::make('home'); } } public function postCreate(){ $rules=array( 'image'=>'image', 'bookname'=>'required|min:3|max:64', 'category_id'=>'integer', 'info'=>'min:3|max:255' ); $messages = array( 'bookname.required'=> '请填写图书名称', 'info.min' => '简介最少3个字', 'info.max' => '介绍不能多于255个字', 'category_id.required' => '图书分类必须选', 'category_id.integer' => '图书分类只能是数字', ); $validator = Validator::make(Input::all(), $rules, $messages); if ($validator->fails()){ return Redirect::back()->withInput()->withErrors($validator); } $userid=Auth::user()->id; if (Input::hasFile('image')) { $file = Input::file('image'); $destinationPath = public_path().'/img/'; $filename = str_random(6) . '_' . $file->getClientOriginalName(); $uploadSuccess = $file->move($destinationPath, $filename); } $book=Book::create([ 'path'=>'public/img/', 'cover'=>$filename, 'name'=>Input::get('bookname'), 'category_id'=>Input::get('bookcategory'), 'user_id'=>$userid, 'info'=>Input::get('info')] ); $success="图书创建成功"; if($book) { return Redirect::route('book')->with('success', $success); } } public function getEdit($id=null){ if(Auth::check()){ $book=DB::table('books')->where('id','=',$id)->first(); $category=DB::table('categories')->where('id','=',$book->category_id)->first(); return View::make('book.Edit',compact('book','category')); } else{ return View::make('home'); } } public function postEdit($id=null){ $rules=array( 'image'=>'image', 'bookname'=>'required|min:3|max:64', 'category_id'=>'integer', 'info'=>'min:3|max:255' ); $messages = array( 'bookname.required'=> '请填写图书名称', 'info.min' => '简介最少3个字', 'info.max' => '介绍不能多于255个字', 'category_id.required' => '图书分类必须选', 'category_id.integer' => '图书分类只能是数字', ); $validator = Validator::make(Input::all(), $rules, $messages); if ($validator->fails()){ return Redirect::back()->withInput()->withErrors($validator); } $userid=Auth::user()->id; if (Input::hasFile('image')) { $file = Input::file('image'); $destinationPath = public_path().'/img/'; $filename = str_random(6) . '_' . $file->getClientOriginalName(); $uploadSuccess = $file->move($destinationPath, $filename); } $book = Book::find( Input::get('book_id')); $book->fill(array( 'path'=>'public/img/', 'cover'=>$filename, 'name'=>Input::get('bookname'), 'category_id'=>Input::get('bookcategory'), 'user_id'=>$userid, 'info'=>Input::get('info')) ); $book->save(); if($book) { return Redirect::route('book'); } } public function getDelete($id=null){ if(is_null(DB::table('books')->where('id','=',$id)->get())){ return Response::json(array( 'success' => false, )); } DB::table('books')->where('id','=',$id)->delete(); DB::table('articles')->where('book_id','=',$id)->delete(); return Response::json(array( 'success' => true, 'errors' => '', )); } }<file_sep>/app/controllers/AboutController.php <?php class AboutController extends BaseController { public function getIndex(){ return View::make('About.about',$this->view_data); } }<file_sep>/app/models/category.php <?php class Category extends Eloquent { public function tags() { return $this->hasMany('Tags'); } }<file_sep>/app/models/article.php <?php class Article extends Eloquent{ protected $fillable = array('title', 'content','user_id','book_id','page_num'); public function books() { return $this->belongsTo('Books','Book_id'); } }<file_sep>/app/controllers/CategoriesController.php <?php class CategoriesController extends BaseController { public function getIndex() { $categories=DB::table('categories')->orderBy('id','DESC')->get(); return View::make('categories.categories',compact('categories'))->with($this->view_data); } }<file_sep>/app/controllers/LocalController.php <?php class LocalController extends BaseController { public function getIndex(){ return View::make('local.local',$this->view_data); } }<file_sep>/app/controllers/TagController.php <?php class TagController extends BaseController{ public function getIndex($id=null,$name=null){ $tag_books=DB::table('books')->where('tag_id','=',$id)->paginate(10); return View::make('tags.tag',compact('tag_books','name'))->with($this->view_data); } }<file_sep>/app/lang/cn/validation.php <?php return array( /* |-------------------------------------------------------------------------- | Validation Language Lines |-------------------------------------------------------------------------- | | The following language lines contain the default error messages used | by the validator class. Some of the rules contain multiple versions, | such as the size (max, min, between) rules. These versions are used | for different input types such as strings and files. | | These language lines may be easily changed to provide custom error | messages in your application. Error messages for custom validation | rules may also be added to this file. | */ "accepted" => "您必须同意 :attribute 才能继续.", "active_url" => "链接 :attribute 不合法.", "after" => " :attribute 时间必须晚于 :date.", "alpha" => "字段 :attribute 只能包含字母.", "alpha_dash" => "字段 :attribute 只能包含 字母, 数字, 中横线.", "alpha_num" => "字段 :attribute 只能包含 字母, 数字.", "array" => "字段 :attribute 必须选择.", "before" => " :attribute 日期必须早于 :date.", "between" => array( "numeric" => "数字 :attribute 必须大于 :min 且小于 :max.", "file" => "文件 :attribute 大小必须大于 :min 且小于 :max KB.", "string" => "字段 :attribute 长度必须大于 :min 且小于 :max .", ), "confirmed" => " :attribute 确认项不匹配.", "count" => " :attribute 必须只能包含 :count 项.", "countbetween" => " :attribute 至少要有 :min 项,最多 :max 项.", "countmax" => " :attribute 不能超过 :max 项.", "countmin" => " :attribute 至少要选择 :min 项.", "date_format" => " :attribute 不是合法的日期格式.", "different" => " :attribute 和 :other 不能一样.", "email" => " :attribute 不是合法的邮箱地址.", "exists" => " :attribute 不合法或不存在.", "image" => " :attribute 必须为图片类型.", "in" => " 选择的 :attribute 不正确.", "integer" => " :attribute 必须为整数.", "ip" => " :attribute 必须为合法的IP地址.", "match" => " :attribute 格式不正确.", "max" => array( "numeric" => "数字 :attribute 不能大于 :max.", "file" => "文件 :attribute 不能超过 :max KB.", "string" => "字段 :attribute 不能超过 :max 字符.", ), "mimes" => "文件 :attribute 只能为类型: :values.", "min" => array( "numeric" => "数字 :attribute 不能小于 :min.", "file" => "文件 :attribute 不能小于 :min KB.", "string" => "字段 :attribute 不能少于 :min 字符.", ), "not_in" => "选择的 :attribute 不正确.", "numeric" => " :attribute 必须的是数字.", "required" => " :attribute 不能为空.", "required_with" => "字段 :attribute field is required with :field", "same" => "The :attribute and :other must match.", "size" => array( "numeric" => "数字 :attribute 只能是 :size.", "file" => "文件 :attribute 只能是 :size KB.", "string" => "字段 :attribute 只能包含 :size 字符.", ), "unique" => ":attribute 已经被占用.", "url" => ":attribute 不合法.", /* |-------------------------------------------------------------------------- | Custom Validation Language Lines |-------------------------------------------------------------------------- | | Here you may specify custom validation messages for attributes using the | convention "attribute_rule" to name the lines. This helps keep your | custom validation clean and tidy. | | So, say you want to use a custom validation message when validating that | the "email" attribute is unique. Just add "email_unique" to this array | with your custom message. The Validator will handle the rest! | */ 'custom' => array(), /* |-------------------------------------------------------------------------- | Validation Attributes |-------------------------------------------------------------------------- | | The following language lines are used to swap attribute place-holders | with something more reader friendly such as "E-Mail Address" instead | of "email". Your users will thank you. | | The Validator class will automatically search this array of lines it | is attempting to replace the :attribute place-holder in messages. | It's pretty slick. We think you'll like it. | */ 'attributes' => array(), );<file_sep>/app/models/tag_book.php <?php class Tag_book extends Eloquent { }<file_sep>/app/controllers/BaseController.php <?php class BaseController extends Controller { // protected $restful = true; //protected $layout = 'layouts.head'; protected $view_data = array(); public function __construct() { $tags=DB::table('tags')->join('tag_book', 'tags.id', '=', 'tag_book.tag_id')->orderBy('tag_book.frequency', 'DESC')->get(); $states=DB::table('states')->orderBy('created_at','DESC')->get(); $this->view_data=[ 'tags' => $tags, 'states'=>$states, ]; $this->beforeFilter('csrf', array( 'on' => array( 'post', ), )); } /** * Setup the layout used by the controller. * * @return void */ protected function setupLayout() { if ( ! is_null($this->layout)) { $this->layout = View::make($this->layout); } } }<file_sep>/app/models/Tag.php <?php class Tag extends Eloquent{ public function books() { return $this->hasMany('Books'); } public function categories() { return $this->belongsToMany('Categories'); } }
7ced4745fb5af3531d8a2c83c84be2307b79d375
[ "PHP" ]
17
PHP
Foina/yishu
774da949b700bf804f8ae2065c704eff0928572a
5f1a3d940aef9dbe3eea9f69e92dbb16aa4972e7
refs/heads/main
<file_sep>package com.nefertiti.service; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.nefertiti.domain.User; import com.nefertiti.repository.UserRepository; @Service public class ShowUserService { @Autowired private UserRepository userRepo; public List<User> getAllUsers() { List<User> result = (List<User>) userRepo.findAll(); if (result.size() > 0) { return result; } else { return new ArrayList<User>(); } } public User getUserById(Long id) throws Exception { Optional<User> employee = userRepo.findById(id); if (employee.isPresent()) { return employee.get(); } else { throw new Exception("No employee record exist for given id"); } } public User updateUser(User entity) { if (entity.getId() == null) { entity = userRepo.save(entity); return entity; } else { Optional<User> employee = userRepo.findById(entity.getId()); if (employee.isPresent()) { User newEntity = employee.get(); newEntity.setEmail(entity.getEmail()); newEntity.setFirstName(entity.getFirstName()); newEntity.setLastName(entity.getLastName()); userRepo.save(newEntity); return newEntity; } else { entity = userRepo.save(entity); return entity; } } } } <file_sep># storyservice with authentication <file_sep>package com.nefertiti.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.nefertiti.domain.User; import com.nefertiti.repository.UserRepository; public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepo; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User existsUser = userRepo.findByEmail(username); if(existsUser == null) { throw new UsernameNotFoundException ("User not foud"); } return new CustomUserDetails(existsUser); } } <file_sep><!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title th:text="${pageTitle}">Napi SFJ</title> <link rel="stylesheet" th:href="@{/css/main.css}" href="../static/css/main.css"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" /> <link href='https://fonts.googleapis.com/css?family=Calibri' rel='stylesheet' type='text/css' /> <link href='https://fonts.googleapis.com/css?family=Exo' rel='stylesheet' type='text/css' /> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <nav class="navbar navbar-default"> <div class="container-fluid"> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li class=""><a href="/">Sztorik</a></li> <li class=""><a href="/bloggers">Bloggerek</a></li> <li class="" ><a th:href="@{/register}"> <span sec:authorize="!isAuthenticated()"> Regisztrálok</span></a></li> <li class="" ><a th:href="@{/login}"> <span sec:authorize="!isAuthenticated()"> Bejelentkezem</span></a></li> <li class="" ><a th:href="@{/add_story}"> <span sec:authorize="isAuthenticated()"> Új blog bejegyzés</span></a></li> </ul> <div class="navbar-text navbar-right"> Üdvözlünk <span sec:authentication="name">Anonymous </span> <form sec:authorize="isAuthenticated()" id="frmlogout" th:action="@{/logout}" method="post" class="form-inline"> | <a href="javascript:{}" onclick="document.getElementById('frmlogout').submit(); return false;">Kijelentkezés</a> </form> </div> </div> </div> </nav> <article> <header> <h1 th:text="${story.title}">Ez itt a cím</h1> <p th:text="${#dates.format(story.posted, 'yyyy.MM.dd HH:mm')}"> Posted on September 31, 2015 at 10:00 PM</p> </header> <p th:text="${story.shortDescription}">Ez itt a rövid leírás</p> <section th:utext="${story.content}"> <p><NAME>sszeráncolta szemöldökét, és felnézett az égre. Bármennyire is erőlködött, nem tudott egyetlen másodpercnél tovább a nap felé nézni. Az égitest vakító ereje bevilágította a környéket, emellett pedig szúrós meleg pontként szurkálta halántékát mind a két oldalról.</p> <p> -Feladom… - gondolta, majd tekintetét a játszótérre emelte. Innen a nyolcadik emeletről tökéletesen be lehetett látni az egész grundot. A háztömbök által körülölelt focipályán a gyerekek nyüzsögtek reggeltől estig. Ha az egyiket elhívták a szülei, szinte azonnal jött a helyére egy másik. A hajnalban még négy fős csapatok délutánra nyolc tagúra dagadtak, naplemente előtt pedig már nem is lehetett pontosan megállapítani, hogy melyik térfelen hány gyerek szaladgál fel-alá.</p> <p></p> </section> <footer> <address> <!-- <span th:text="${story.user.firstName}+${story.user.lastName}">Anonymous</span> --> Beküldte: <span th:text="${story.user}">Anonymous</span> </address> </footer> <hr/> </article> <footer> <p>©2021 Nefertiti</p> </footer> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js" ></script> </body> </html>
fd05d979d619a0ed7b8f24e1208127db54cfb6a4
[ "Markdown", "Java", "HTML" ]
4
Java
klara333/storyservice
d4b438eeddb3596b193fc836e226c58a7b50abbd
870310c427002acbc1a973708c304613bb813297
refs/heads/main
<file_sep> import SwiftUI import CoreML struct ContentView: View { let images = ["cat", "person", "berries", "car", "orange", "spider"] @State private var currentIndex: Int = 0 let model: MobileNetV2 = { do { let config = MLModelConfiguration() return try MobileNetV2(configuration: config) } catch { print(error) fatalError("Couldn't create MobileNetV2") } }() private func classifyImage() { //let currentImage = images[currentIndex] } var body: some View { VStack { Text("Image Classifier") .padding() Image(images[currentIndex]) .resizable() .aspectRatio(contentMode: .fit) Button("Next Image >") { if self.currentIndex < self.images.count - 1 { self.currentIndex = self.currentIndex + 1 } else { self.currentIndex = 0 } }.padding() Button("Classify") { classifyImage() } } .font(.system(size: 60)) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } } <file_sep># Use-CoreML-Model-in-SwiftUI Import CoreML model into SwiftUI view. Instantiate CoreML model into SwiftUI view the right way! Use CoreML in SwiftUI. Watch the video: [![Video](https://img.youtube.com/vi/8Gl33PpOlJg/maxresdefault.jpg)](https://www.youtube.com/watch?v=8Gl33PpOlJg)
6b1bb4603347e5f5312a19ff20e4f204b10fc80a
[ "Swift", "Markdown" ]
2
Swift
mammothtraining/Use-CoreML-Model-in-SwiftUI
83a08596d9b7af8b98c3478d6ed480da7fde3047
caa3429554318d46a0d07ddd35a287a798850a4f
refs/heads/master
<repo_name>nickyungyung/probability<file_sep>/tensorflow_probability/python/math/interpolation.py # Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """Interpolation Ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function # Dependency imports import numpy as np import tensorflow as tf from tensorflow_probability.python.internal import distribution_util from tensorflow_probability.python.internal import dtype_util __all__ = [ 'interp_regular_1d_grid', ] def interp_regular_1d_grid(x, x_ref_min, x_ref_max, y_ref, axis=-1, fill_value='constant_extension', fill_value_below=None, fill_value_above=None, grid_regularizing_transform=None, name=None): """Linear `1-D` interpolation on a regular (constant spacing) grid. Given reference values, this function computes a piecewise linear interpolant and evaluates it on a new set of `x` values. The interpolant is built from `M` reference values indexed by one dimension of `y_ref` (specified by the `axis` kwarg). If `y_ref` is a vector, then each value `y_ref[i]` is considered to be equal to `f(x_ref[i])`, for `M` (implicitly defined) reference values between `x_ref_min` and `x_ref_max`: ```none x_ref[i] = x_ref_min + i * (x_ref_max - x_ref_min) / (M - 1), i = 0, ..., M - 1. ``` If `rank(y_ref) > 1`, then `y_ref` contains `M` reference values of a `rank(y_ref) - 1` rank tensor valued function of one variable. `x_ref` is a `Tensor` of values of that variable (any shape allowed). Args: x: Numeric `Tensor` The x-coordinates of the interpolated output values. x_ref_min: `Tensor` of same `dtype` as `x`. The minimum value of the (implicitly defined) reference `x_ref`. x_ref_max: `Tensor` of same `dtype` as `x`. The maximum value of the (implicitly defined) reference `x_ref`. y_ref: `N-D` `Tensor` (`N > 0`) of same `dtype` as `x`. The reference output values. axis: Scalar `Tensor` designating the dimension of `y_ref` that indexes values of the interpolation variable. Default value: `-1`, the rightmost axis. fill_value: Determines what values output should take for `x` values that are below `x_ref_min` or above `x_ref_max`. `Tensor` or one of the strings "constant_extension" ==> Extend as constant function. "extrapolate" ==> Extrapolate in a linear fashion. Default value: `"constant_extension"` fill_value_below: Optional override of `fill_value` for `x < x_ref_min`. fill_value_above: Optional override of `fill_value` for `x > x_ref_max`. grid_regularizing_transform: Optional transformation `g` which regularizes the implied spacing of the x reference points. In other words, if provided, we assume `g(x_ref_i)` is a regular grid between `g(x_ref_min)` and `g(x_ref_max)`. name: A name to prepend to created ops. Default value: `"interp_regular_1d_grid"`. Returns: y_interp: Interpolation between members of `y_ref`, at points `x`. `Tensor` of same `dtype` as `x`, and shape `y.shape[:axis] + x.shape + y.shape[axis + 1:]` Raises: ValueError: If `fill_value` is not an allowed string. ValueError: If `axis` is not a scalar. #### Examples Interpolate a function of one variable: ```python y_ref = tf.exp(tf.linspace(start=0., stop=10., 20)) interp_regular_1d_grid( x=[6.0, 0.5, 3.3], x_ref_min=0., x_ref_max=1., y_ref=y_ref) ==> approx [exp(6.0), exp(0.5), exp(3.3)] ``` Interpolate a matrix-valued function of one variable: ```python mat_0 = [[1., 0.], [0., 1.]] mat_1 = [[0., -1], [1, 0]] y_ref = [mat_0, mat_1] # Get three output matrices at once. tfp.math.interp_regular_1d_grid( x=[0., 0.5, 1.], x_ref_min=0., x_ref_max=1., y_ref=y_ref, axis=0) ==> [mat_0, 0.5 * mat_0 + 0.5 * mat_1, mat_1] ``` Interpolate a function of one variable on a log-spaced grid: ```python x_ref = tf.exp(tf.linspace(tf.log(1.), tf.log(100000.), num_pts)) y_ref = tf.log(x_ref + x_ref**2) interp_regular_1d_grid(x=[1.1, 2.2], x_ref_min=1., x_ref_max=100000., y_ref, grid_regularizing_transform=tf.log) ==> [tf.log(1.1 + 1.1**2), tf.log(2.2 + 2.2**2)] ``` """ with tf.name_scope( name, 'interp_regular_1d_grid', values=[ x, x_ref_min, x_ref_max, y_ref, axis, fill_value, fill_value_below, fill_value_above ]): # Arg checking. allowed_fv_st = ('constant_extension', 'extrapolate') for fv in (fill_value, fill_value_below, fill_value_above): if isinstance(fv, str) and fv not in allowed_fv_st: raise ValueError( 'A fill value ({}) was not an allowed string ({})'.format( fv, allowed_fv_st)) # Separate value fills for below/above incurs extra cost, so keep track of # whether this is needed. need_separate_fills = ( fill_value_above is not None or fill_value_below is not None or fill_value == 'extrapolate' # always requries separate below/above ) if need_separate_fills and fill_value_above is None: fill_value_above = fill_value if need_separate_fills and fill_value_below is None: fill_value_below = fill_value axis = tf.convert_to_tensor(axis, name='axis', dtype=tf.int32) _assert_ndims_statically(axis, expect_ndims=0) axis = distribution_util.make_non_negative_axis(axis, tf.rank(y_ref)) dtype = dtype_util.common_dtype([x, x_ref_min, x_ref_max, y_ref], preferred_dtype=tf.float32) x = tf.convert_to_tensor(x, name='x', dtype=dtype) x_ref_min = tf.convert_to_tensor(x_ref_min, name='x_ref_min', dtype=dtype) x_ref_max = tf.convert_to_tensor(x_ref_max, name='x_ref_max', dtype=dtype) y_ref = tf.convert_to_tensor(y_ref, name='y_ref', dtype=dtype) ny = tf.cast(tf.shape(y_ref)[axis], dtype) # Map [x_ref_min, x_ref_max] to [0, ny - 1]. # This is the (fractional) index of x. if grid_regularizing_transform is None: g = lambda x: x else: g = grid_regularizing_transform fractional_idx = ((g(x) - g(x_ref_min)) / (g(x_ref_max) - g(x_ref_min))) x_idx_unclipped = fractional_idx * (ny - 1) # Wherever x is NaN, x_idx_unclipped will be NaN as well. # Keep track of the nan indices here (so we can impute NaN later). # Also eliminate any NaN indices, since there is not NaN in 32bit. nan_idx = tf.is_nan(x_idx_unclipped) x_idx_unclipped = tf.where(nan_idx, tf.zeros_like(x_idx_unclipped), x_idx_unclipped) x_idx = tf.clip_by_value(x_idx_unclipped, tf.zeros((), dtype=dtype), ny - 1) # Get the index above and below x_idx. # Naively we could set idx_below = floor(x_idx), idx_above = ceil(x_idx), # however, this results in idx_below == idx_above whenever x is on a grid. # This in turn results in y_ref_below == y_ref_above, and then the gradient # at this point is zero. So here we "jitter" one of idx_below, idx_above, # so that they are at different values. This jittering does not affect the # interpolated value, but does make the gradient nonzero (unless of course # the y_ref values are the same). idx_below = tf.floor(x_idx) idx_above = tf.minimum(idx_below + 1, ny - 1) idx_below = tf.maximum(idx_above - 1, 0) # These are the values of y_ref corresponding to above/below indices. idx_below_int32 = tf.to_int32(idx_below) idx_above_int32 = tf.to_int32(idx_above) y_ref_below = tf.gather(y_ref, idx_below_int32, axis=axis) y_ref_above = tf.gather(y_ref, idx_above_int32, axis=axis) # out_shape = y_ref.shape[:axis] + x.shape + y_ref.shape[axis + 1:] out_shape = tf.shape(y_ref_below) # Return a convex combination. t = x_idx - idx_below t = _expand_ends(t, out_shape, axis) y = t * y_ref_above + (1 - t) * y_ref_below # Now begins a long excursion to fill values outside [x_min, x_max]. # Re-insert NaN wherever x was NaN. y = tf.where( _expand_ends(nan_idx, out_shape, axis, broadcast=True), tf.fill(tf.shape(y), tf.constant(np.nan, y.dtype)), y) x_idx_unclipped = _expand_ends( x_idx_unclipped, out_shape, axis, broadcast=True) if not need_separate_fills: if fill_value == 'constant_extension': pass # Already handled by clipping x_idx_unclipped. else: y = tf.where((x_idx_unclipped < 0) | (x_idx_unclipped > ny - 1), fill_value + tf.zeros_like(y), y) else: # Fill values below x_ref_min <==> x_idx_unclipped < 0. if fill_value_below == 'constant_extension': pass # Already handled by the clipping that created x_idx_unclipped. elif fill_value_below == 'extrapolate': y_0 = tf.gather(y_ref, tf.zeros(tf.shape(x), dtype=tf.int32), axis=axis) y_1 = tf.gather(y_ref, tf.ones(tf.shape(x), dtype=tf.int32), axis=axis) x_delta = (x_ref_max - x_ref_min) / (ny - 1) x_factor = (x - x_ref_min) / x_delta x_factor = _expand_ends(x_factor, out_shape, axis, broadcast=True) y = tf.where(x_idx_unclipped < 0, y_0 + x_factor * (y_1 - y_0), y) else: y = tf.where(x_idx_unclipped < 0, fill_value_below + tf.zeros_like(y), y) # Fill values above x_ref_min <==> x_idx_unclipped > ny - 1. if fill_value_above == 'constant_extension': pass # Already handled by the clipping that created x_idx_unclipped. elif fill_value_above == 'extrapolate': ny_int32 = tf.shape(y_ref)[axis] y_n1 = tf.gather(y_ref, tf.fill(tf.shape(x), ny_int32 - 1), axis=axis) y_n2 = tf.gather(y_ref, tf.fill(tf.shape(x), ny_int32 - 2), axis=axis) x_delta = (x_ref_max - x_ref_min) / (ny - 1) x_factor = (x - x_ref_max) / x_delta x_factor = _expand_ends(x_factor, out_shape, axis, broadcast=True) y = tf.where(x_idx_unclipped > ny - 1, y_n1 + x_factor * (y_n1 - y_n2), y) else: y = tf.where(x_idx_unclipped > ny - 1, fill_value_above + tf.zeros_like(y), y) return y def _assert_ndims_statically(x, expect_ndims=None): ndims = x.shape.ndims if ndims is None: return if expect_ndims is not None and ndims != expect_ndims: raise ValueError('ndims must be {}. Found: {}'.format(expect_ndims, ndims)) def _expand_ends(x, out_shape, axis, broadcast=False): """Expand x with singletons so it can bcast w/ tensors of shape out_shape.""" # Assume out_shape = A + x.shape + B, and rank(A) = axis. # Expand with singletons with same rank as A, B. new_shape = tf.concat(( tf.ones([axis], dtype=tf.int32), tf.shape(x), tf.ones([tf.size(out_shape) - axis - tf.rank(x)], dtype=tf.int32), ), axis=0) x_expanded = tf.reshape(x, new_shape) if broadcast: if x.dtype.is_bool: x_expanded = x_expanded | tf.cast(tf.zeros(out_shape), tf.bool) else: x_expanded += tf.zeros(out_shape, dtype=x.dtype) return x_expanded
88e66784e38fa6dc2e573abb301e3c5229c32243
[ "Python" ]
1
Python
nickyungyung/probability
7705eb960935b6ca94e125ae4c58b6f54e4084b5
bb2c339f5547e8a24575df3d3ff5bdbc8ecd49b8
refs/heads/master
<file_sep># coding=utf-8 import socket import time server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ip = '0.0.0.0' port = int(raw_input('select a port: ')) file = open('shell.php', 'w') try: server.bind((ip, port)) server.listen(5) print 'ouvindo em:' + ip + ': ' + str(port) (client_socket, address) = server.accept() client_socket.send("server found\n") print "Client found" time.sleep(3) client_socket.send("connecting...\n\n") print "connecting...\n\n" time.sleep(10) print 'connection with:' + address[0] client_socket.send("#############\n# connected #\n#############\n\n\n") print "#############\n# connected #\n#############\n\n" client_socket.send("enter your nick. (n) to defaut nick)\n") client_socket.send("enter your nick: ") select = (client_socket.recv(800)) nick = select + "→" if select == "n": while True: client_socket.send("\n##User 2\n→") print "##User 2:##", client_socket.recv(8000) client_socket.send("##User 1\n→") #WRITE YOUR NICK client_socket.send(raw_input("##User 1\n→") + "\n") #WRITE YOUR NICK else: while True: client_socket.send ('\n##' + nick) print nick , client_socket.recv(8000) client_socket.send("##User 1\n→") #WRITE YOUR NICK client_socket.send(raw_input("User 1\n→") + "\n") #WRITE YOUR NICK except Exception as Erro: print Erro ###
76c11476f4125188f5976961681244692ab2d3f4
[ "Python" ]
1
Python
Lolixprofanos/ServerTCP
b75760bef1c033c56b333c03e8fa1529298e10b8
bcfce2136ff8817abad84f2c0efec087f7834240
refs/heads/master
<repo_name>stevenmcsorley/PopulasThemeWP<file_sep>/template-demo.php <?php /* Template Name: Homepage */ ?> <?php get_header(); ?> <div class="container-fluid no_padding"> <!-- SLIDER --> <div id="carousel" class="carousel slide carousel-fade" data-ride="carousel"> <!-- Wrapper for slides --> <div class="carousel-inner"> <div class="item active"> <img src="<?php echo get_template_directory_uri(); ?>/images/slides/sliderOne.jpg" alt="..."> </div> <div class="item"> <img src="<?php echo get_template_directory_uri(); ?>/images/slides/sliderTwo.jpg" alt="..."> </div> <div class="item"> <img src="<?php echo get_template_directory_uri(); ?>/images/slides/sliderThree.jpg" alt="..."> </div> </div> </div> <!-- Carousel --> </div> <div class="container-fluid random_wrap no_padding"> <div class="outer_randomposts_header"> <div class="randomposts_header"> <h3>Random Bog Posts</h3> </div> </div> <div class="randomposts"> <?php the_random_posts(); /** * Send random posts to the browser (STDOUT). */ function the_random_posts() { // Use your own category ids. $random_posts_one = array_merge( get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ) ); // Use your own category ids. $random_posts_two = array_merge( get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ) ); // Use your own category ids. $random_posts_three = array_merge( get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ), get_random_posts( 93, 3 ) ); ?> <div class="col-md-4"> <div class="banner"> <ul> <?php foreach ( $random_posts_one as $post ) { // Change this line to code you want to output. print "<li>"; $featimage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' ); print "<img src='".$featimage[0]."' class='random_img' alt='' />"; print "<a href='".get_permalink( $post->ID )."' ><h4>".wp_trim_words( get_the_title( $post->ID ), 5, '...')."</h4></a>"; print "<div class='cat_list'>"; $category_detail=get_the_category($post->ID); foreach($category_detail as $cd){ $category_id = get_cat_ID( $cd->cat_name); echo "<p>From: <a href='".get_category_link( $category_id)."'>".$cd->cat_name."</a><p>"; } print "</div>"; print "<p class='excerpt'>".wp_trim_words( $post->post_content, 20, '<br /><a href="'. get_permalink( $post->ID ).'" class="more">&#187; Read More</a>' )."</p>"; print "</li>"; } ?> </ul> </div> </div> <?php ?> <div class="col-md-4"> <div class="banner"> <ul> <?php foreach ( $random_posts_two as $post ) { // Change this line to code you want to output. print "<li>"; $featimage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' ); print "<img src='".$featimage[0]."' class='random_img' alt='' />"; print "<a href='".get_permalink( $post->ID )."' ><h4>".wp_trim_words( get_the_title( $post->ID ), 5, '...')."</h4></a>"; print "<div class='cat_list'>"; $category_detail=get_the_category($post->ID); foreach($category_detail as $cd){ $category_id = get_cat_ID( $cd->cat_name); echo "<p>From: <a href='".get_category_link( $category_id)."'>".$cd->cat_name."</a><p>"; } print "</div>"; print "<p class='excerpt'>".wp_trim_words( $post->post_content, 20, '<br /><a href="'. get_permalink( $post->ID ).'" class="more">&#187; Read More</a>' )."</p>"; print "</li>"; } ?> </ul> </div> </div> <?php ?><div class="col-md-4"> <div class="banner"> <ul> <?php foreach ( $random_posts_three as $post ) { // Change this line to code you want to output. print "<li>"; $featimage = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' ); print "<img src='".$featimage[0]."' class='random_img' alt='' />"; print "<a href='".get_permalink( $post->ID )."' ><h4>".wp_trim_words( get_the_title( $post->ID ), 5, '...')."</h4></a>"; print "<div class='cat_list'>"; $category_detail=get_the_category($post->ID); foreach($category_detail as $cd){ $category_id = get_cat_ID( $cd->cat_name); echo "<p>From: <a href='".get_category_link( $category_id)."'>".$cd->cat_name."</a><p>"; } print "</div>"; print "<p class='excerpt'>".wp_trim_words( $post->post_content, 20, '<br /><a href="'. get_permalink( $post->ID ).'" class="more">&#187; Read More</a>' )."</p>"; print "</li>"; } ?> </ul> </div> </div> <?php } /** * Get $post_count random posts from $category_id. * * @param int $post_count Number of random posts to retrieve. * @param int $category_id ID of the category. */ function get_random_posts( $category_id, $post_count ) { $posts = get_posts( array( 'posts_per_page' => $post_count, 'orderby' => 'rand', 'cat' => $category_id, 'post_status' => 'publish', ) ); return $posts; } ?> </div> </div><!--end of fluid random --> <?php if(is_front_page() ) { ?> <div class="wrapper"> <?php } else { ?> <!-- wrapper --> <?php } ?> <main role="main"> <!-- section --> <section> <!-- <h1><?php //the_title(); ?></h1> --> <?php if (have_posts()): while (have_posts()) : the_post(); ?> <!-- article --> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php the_content(); ?> <?php comments_template( '', true ); // Remove if you don't want comments ?> <br class="clear"> <?php edit_post_link(); ?> </article> <!-- /article --> <?php endwhile; ?> <?php else: ?> <!-- article --> <article> <h2><?php _e( 'Sorry, nothing to display.', 'populas' ); ?></h2> </article> <!-- /article --> <?php endif; ?> </section> <!-- /section --> </main> <?php //get_sidebar(); ?> <?php get_footer(); ?> <file_sep>/js/scripts.js (function ($, root, undefined) { $(function () { 'use strict'; // DOM ready, take it away $( document ).ready(function() { $('.carousel').carousel({ interval: 8000 }) $('#outsideCaptions').carousel({ interval: 3000 }) }); $( document ).ready(function() { $("#boxOne").inViewport(function(px){ if(px) $(this).addClass("triggerBoxOne") ; }); $("#boxTwo").inViewport(function(px){ if(px) $(this).addClass("triggerBoxTwo") ; }); $("#boxThree").inViewport(function(px){ if(px) $(this).addClass("triggerBoxThree") ; }); $("#boxFour").inViewport(function(px){ if(px) $(this).addClass("triggerBoxFour") ; }); $(".featureBlockOne").inViewport(function(px){ if(px) $(this).addClass("triggerBoxFeatOne") ; }); $(".featureBlockTwo").inViewport(function(px){ if(px) $(this).addClass("triggerBoxFeatTwo") ; }); $(".featureBlockThree").inViewport(function(px){ if(px) $(this).addClass("triggerBoxFeatThree") ; }); $(".top_wrapper").inViewport(function(px){ if(px) $(this).addClass("triggerTopBox") ; }); }); $( document ).ready(function() { $(".nav li a").hover(function () { $(this).children(".nav li a span").toggleClass("onHover"); }); }); // Back To Top $( document ).ready(function() { $('a.top').click(function(){ $("html, body").animate({scrollTop : 0},800); return false; }); }); // Smooth Scroll Too Snippit $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); $('.banner').unslider({ speed: 500, // The speed to animate each slide (in milliseconds) delay: 3000, // The delay between slide animations (in milliseconds) complete: function() {}, // A function that gets called after every slide animation keys: true, // Enable keyboard (left, right) arrow shortcuts dots: false, // Display dot navigation fluid: false // Support responsive design. May break non-responsive designs }); }); })(jQuery, this);
942015fbbc905cc92f10088f3e66b3ff4dfbf8da
[ "JavaScript", "PHP" ]
2
PHP
stevenmcsorley/PopulasThemeWP
149dab0ca8cd8c893a83c2aca3118bbdbdff5379
7abd83d94f563ac1e9b13c55f51ca5d6b7ce1960
refs/heads/master
<file_sep># prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(name_hash) minimum = nil smin_thing = "" if name_hash == nil min_thing = nil else name_hash.each do |(thing, amount)| if minimum == nil minimum = amount min_thing = thing end if amount < minimum minimum = amount min_thing = thing end min_thing end min_thing end min_thing end
c242c6d438d555431f54f85fd41894247e9dcb05
[ "Ruby" ]
1
Ruby
DevDaveFrame/key-for-min-value-wdc01-seng-ft-060120
d52b65d921297fd2a4e9fee90d7368f3ef217529
e9a23acf9db55c5d431676110b64458f46d44e31
refs/heads/master
<repo_name>flozano/mock-aws-java-sdk<file_sep>/src/main/java/org/flite/mock/amazonaws/sqs/AmazonSQSMock.java package org.flite.mock.amazonaws.sqs; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang.StringUtils; import com.amazonaws.AmazonClientException; import com.amazonaws.AmazonServiceException; import com.amazonaws.AmazonWebServiceRequest; import com.amazonaws.ResponseMetadata; import com.amazonaws.regions.Region; import com.amazonaws.services.sqs.AmazonSQS; import com.amazonaws.services.sqs.model.AddPermissionRequest; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequest; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchRequestEntry; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityBatchResult; import com.amazonaws.services.sqs.model.ChangeMessageVisibilityRequest; import com.amazonaws.services.sqs.model.CreateQueueRequest; import com.amazonaws.services.sqs.model.CreateQueueResult; import com.amazonaws.services.sqs.model.DeleteMessageBatchRequest; import com.amazonaws.services.sqs.model.DeleteMessageBatchRequestEntry; import com.amazonaws.services.sqs.model.DeleteMessageBatchResult; import com.amazonaws.services.sqs.model.DeleteMessageRequest; import com.amazonaws.services.sqs.model.DeleteQueueRequest; import com.amazonaws.services.sqs.model.GetQueueAttributesRequest; import com.amazonaws.services.sqs.model.GetQueueAttributesResult; import com.amazonaws.services.sqs.model.GetQueueUrlRequest; import com.amazonaws.services.sqs.model.GetQueueUrlResult; import com.amazonaws.services.sqs.model.InvalidAttributeNameException; import com.amazonaws.services.sqs.model.ListDeadLetterSourceQueuesRequest; import com.amazonaws.services.sqs.model.ListDeadLetterSourceQueuesResult; import com.amazonaws.services.sqs.model.ListQueuesRequest; import com.amazonaws.services.sqs.model.ListQueuesResult; import com.amazonaws.services.sqs.model.Message; import com.amazonaws.services.sqs.model.PurgeQueueRequest; import com.amazonaws.services.sqs.model.ReceiptHandleIsInvalidException; import com.amazonaws.services.sqs.model.ReceiveMessageRequest; import com.amazonaws.services.sqs.model.ReceiveMessageResult; import com.amazonaws.services.sqs.model.RemovePermissionRequest; import com.amazonaws.services.sqs.model.SendMessageBatchRequest; import com.amazonaws.services.sqs.model.SendMessageBatchRequestEntry; import com.amazonaws.services.sqs.model.SendMessageBatchResult; import com.amazonaws.services.sqs.model.SendMessageRequest; import com.amazonaws.services.sqs.model.SendMessageResult; import com.amazonaws.services.sqs.model.SetQueueAttributesRequest; import com.amazonaws.util.Md5Utils; /** * Copyright (c) 2012 Flite, Inc * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * * Currently, there is <em>NO</em> plan to implement any time-based features in this mock: * - scheduling * - delays * - retrieved messages returning to the queue */ public class AmazonSQSMock implements AmazonSQS { public static final String NYI_EXCEPTION = "Not Yet Implemented!\n" + "If you'd like to contribute your code, please send a pull request to our repo:\n" + "https://github.com/flite/mock-aws-java-sdk"; public static final String QUEUE_URL_PREFIX = "https://mock.flite.com/mockaws/"; public static final String MARKER_CLIENT_EXCEPTION = "mock-aws-client-exception"; public static final String QUEUE_URL_CLIENT_EXCEPTION = QUEUE_URL_PREFIX + MARKER_CLIENT_EXCEPTION; public static final String MARKER_SERVICE_EXCEPTION = "mock-aws-service-exception"; public static final String QUEUE_URL_SERVICE_EXCEPTION = QUEUE_URL_PREFIX + MARKER_SERVICE_EXCEPTION; public static final String MESSAGE_ID_PREFIX = "mock-aws-message-id-"; public static final String RECEIPT_ID_PREFIX = "mock-aws-receipt-id-"; public static final String ARN_PREFIX = "arn:aws:"; private AtomicLong incrementer = new AtomicLong(System.currentTimeMillis() * 1000); private Map<String, List<Message>> allQueues = new ConcurrentHashMap<String, List<Message>>(); private Map<String, Map<String, Message>> retrievedMessages = new ConcurrentHashMap<String, Map<String,Message>>(); //@Override public GetQueueUrlResult getQueueUrl(final GetQueueUrlRequest request) throws AmazonServiceException, AmazonClientException { if (request == null) { throw new AmazonClientException("Null GetQueueUrlRequest"); } final String queueName = request.getQueueName(); final String queueUrl = QUEUE_URL_PREFIX + queueName; checkURLForException(queueUrl); // Per documentation, supposedly throws QueueDoesNotExistException, // but in my tests, they actually just throw AmazonServiceException if (!allQueues.containsKey(queueUrl)) { throw new AmazonServiceException("Queue Not Found: " + queueUrl); } return new GetQueueUrlResult().withQueueUrl(queueUrl); } //@Override public CreateQueueResult createQueue(final CreateQueueRequest request) throws AmazonServiceException, AmazonClientException { if (request == null) { throw new AmazonClientException("Null CreateQueueRequest"); } final String queueName = request.getQueueName(); if (StringUtils.isBlank(queueName) || queueName.length() > 80) { throw new AmazonServiceException("Invalid queue name: " + queueName); } final String queueUrl = QUEUE_URL_PREFIX + queueName; checkURLForException(queueUrl); // Per documentation, throws QueueNameExistsException, but in my testing, they actually // just quietly return the CreateQueueResult // (Also note: we are ignoring the documented exception: QueueDeletedRecentlyException) if (!allQueues.containsKey(queueUrl)) { allQueues.put(queueUrl, Collections.synchronizedList(new ArrayList<Message>())); retrievedMessages.put(queueUrl, new ConcurrentHashMap<String, Message>()); } return new CreateQueueResult().withQueueUrl(queueUrl); } //@Override public SendMessageResult sendMessage(final SendMessageRequest request) throws AmazonServiceException, AmazonClientException { if (request == null) { throw new AmazonClientException("Null SendMessageRequest"); } final String queueUrl = request.getQueueUrl(); checkURLForException(queueUrl); checkStringForExceptionMarker(request.getMessageBody()); // Ignoring the following exception: InvalidMessageContentsException (thrown for character set conditions?) if (!allQueues.containsKey(queueUrl)) { throw new AmazonServiceException("Queue Not Found: " + queueUrl); } final Long seq = incrementer.getAndIncrement(); final Message msg = new Message() .withMessageAttributes(request.getMessageAttributes()) .withBody(StringUtils.defaultString(request.getMessageBody())) .withMD5OfBody(makeMD5(request.getMessageBody())) .withMessageId(MESSAGE_ID_PREFIX + seq); allQueues.get(queueUrl).add(msg); return new SendMessageResult().withMD5OfMessageBody(msg.getMD5OfBody()).withMessageId(msg.getMessageId()); } //@Override public void deleteMessage(final DeleteMessageRequest request) throws AmazonServiceException, AmazonClientException { if (request == null) { throw new AmazonClientException("Null DeleteMessageRequest"); } final String queueUrl = request.getQueueUrl(); checkURLForException(queueUrl); checkStringForExceptionMarker(request.getReceiptHandle()); // Ignoring the documented exception: InvalidIdFormatException if (!allQueues.containsKey(queueUrl)) { throw new AmazonServiceException("Queue Not Found: " + queueUrl); } if (!retrievedMessages.containsKey(queueUrl)) { throw new AmazonServiceException("Queue Not Found: " + queueUrl); } if (!retrievedMessages.get(queueUrl).containsKey(request.getReceiptHandle())) { throw new ReceiptHandleIsInvalidException("Reciept Handle Not Found: " + request.getReceiptHandle()); } retrievedMessages.get(queueUrl).remove(request.getReceiptHandle()); } //@Override public ReceiveMessageResult receiveMessage(final ReceiveMessageRequest request) throws AmazonServiceException, AmazonClientException { if (request == null) { throw new AmazonClientException("Null ReceiveMessageRequest"); } final String queueUrl = request.getQueueUrl(); checkURLForException(queueUrl); // Per documentation throws OverLimitException, but in my testing, // they actually only throw AmazonServiceException final Integer max = request.getMaxNumberOfMessages(); if (max == null || max < 1 || max > 10) { throw new AmazonServiceException("MaxNumberOfMessages must be a value between [1,10]"); } final ReceiveMessageResult result = new ReceiveMessageResult(); int received = 0; boolean avail = true; while (received < request.getMaxNumberOfMessages() && avail) { try { final Message msg = allQueues.get(queueUrl).remove(0); received++; msg.setReceiptHandle(RECEIPT_ID_PREFIX + incrementer.getAndIncrement()); retrievedMessages.get(queueUrl).put(msg.getReceiptHandle(), msg); result.withMessages(msg); } catch (Exception ex) { avail = false; } } return result; } //@Override public ListQueuesResult listQueues(final ListQueuesRequest request) throws AmazonServiceException, AmazonClientException { if (request == null) { throw new AmazonClientException("Null ListQueuesRequest"); } checkStringForExceptionMarker(request.getQueueNamePrefix()); final String effectivePrefix = QUEUE_URL_PREFIX + (request.getQueueNamePrefix() == null ? "" : request.getQueueNamePrefix()); final ListQueuesResult result = new ListQueuesResult(); for (final String url : allQueues.keySet()) { if (StringUtils.startsWith(url, effectivePrefix)) { result.withQueueUrls(url); } } return result; } //@Override public ListQueuesResult listQueues() throws AmazonServiceException, AmazonClientException { return listQueues(new ListQueuesRequest("")); } //@Override public void deleteQueue(final DeleteQueueRequest request) throws AmazonServiceException, AmazonClientException { if (request == null) { throw new AmazonClientException("Null DeleteQueueRequest"); } final String queueUrl = request.getQueueUrl(); checkURLForException(queueUrl); if (!allQueues.containsKey(queueUrl)) { throw new AmazonServiceException("Queue Not Found: " + queueUrl); } allQueues.remove(queueUrl); if (retrievedMessages.containsKey(queueUrl)) { retrievedMessages.remove(queueUrl); } } public static final String ALL = "All"; public static final String NUM_MSGS = "ApproximateNumberOfMessages"; public static final String NUM_NOT_VISIBLE = "ApproximateNumberOfMessagesNotVisible"; public static final String VIS_TIMEOUT = "VisibilityTimeout"; public static final String CREATED_TIMESTAMP = "CreatedTimestamp"; public static final String MODIFIED_TIMESTAMP = "LastModifiedTimestamp"; public static final String POLICY = "Policy"; public static final String MAX_SIZE = "MaximumMessageSize"; public static final String RETENTION = "MessageRetentionPeriod"; public static final String ARN = "QueueArn"; public static final String MSGS_DELAYED = "ApproximateNumberOfMessagesDelayed"; public static final String DELAY_SEC = "DelaySeconds"; public static final String REDRIVE_POLICY = "RedrivePolicy"; private static final List<String> attbs = Arrays.asList(ALL, NUM_MSGS, NUM_NOT_VISIBLE, VIS_TIMEOUT, CREATED_TIMESTAMP, MODIFIED_TIMESTAMP, POLICY, MAX_SIZE, RETENTION, ARN, MSGS_DELAYED, DELAY_SEC, REDRIVE_POLICY); //@Override public GetQueueAttributesResult getQueueAttributes(final GetQueueAttributesRequest request) throws AmazonServiceException, AmazonClientException { if (request == null) { throw new AmazonClientException("Null GetQueueAttributesRequest"); } final String queueUrl = request.getQueueUrl(); checkURLForException(queueUrl); for (final String attb : request.getAttributeNames()) { checkStringForExceptionMarker(attb); if (!attbs.contains(attb)) { throw new InvalidAttributeNameException("Invalid Attribute Name: " + attb); } } final Map<String, String> results = new ConcurrentHashMap<String, String>(); final boolean hasAll = request.getAttributeNames().contains(ALL); if (hasAll || request.getAttributeNames().contains(NUM_MSGS)) { results.put(NUM_MSGS, allQueues.get(queueUrl) == null ? "0" : allQueues.get(queueUrl).size()+""); } if (hasAll || request.getAttributeNames().contains(NUM_NOT_VISIBLE)) { results.put(NUM_NOT_VISIBLE, retrievedMessages.get(queueUrl) == null ? "0" : retrievedMessages.get(queueUrl).size()+""); } if (hasAll || request.getAttributeNames().contains(ARN)) { results.put(ARN, ARN_PREFIX + queueUrl); } if (hasAll || request.getAttributeNames().contains(VIS_TIMEOUT)) { throw new RuntimeException(NYI_EXCEPTION); } if (hasAll || request.getAttributeNames().contains(CREATED_TIMESTAMP)) { throw new RuntimeException(NYI_EXCEPTION); } if (hasAll || request.getAttributeNames().contains(MODIFIED_TIMESTAMP)) { throw new RuntimeException(NYI_EXCEPTION); } if (hasAll || request.getAttributeNames().contains(POLICY)) { throw new RuntimeException(NYI_EXCEPTION); } if (hasAll || request.getAttributeNames().contains(MAX_SIZE)) { throw new RuntimeException(NYI_EXCEPTION); } if (hasAll || request.getAttributeNames().contains(RETENTION)) { throw new RuntimeException(NYI_EXCEPTION); } if (hasAll || request.getAttributeNames().contains(MSGS_DELAYED)) { throw new RuntimeException(NYI_EXCEPTION); } if (hasAll || request.getAttributeNames().contains(DELAY_SEC)) { throw new RuntimeException(NYI_EXCEPTION); } return new GetQueueAttributesResult().withAttributes(results); } //@Override public void setQueueAttributes(SetQueueAttributesRequest setQueueAttributesRequest) throws AmazonServiceException, AmazonClientException { if (setQueueAttributesRequest == null){ throw new AmazonClientException("Null SetQueueAttributesRequest");} final String queueUrl = setQueueAttributesRequest.getQueueUrl(); checkURLForException(queueUrl); Map<String, String> attributesMap = setQueueAttributesRequest.getAttributes(); for (final String attb : setQueueAttributesRequest.getAttributes().keySet()) { checkStringForExceptionMarker(attb); if (!attbs.contains(attb)) { throw new InvalidAttributeNameException("Invalid Attribute Name: " + attb); } } if (attributesMap.containsKey(CREATED_TIMESTAMP)) { throw new RuntimeException(NYI_EXCEPTION); } if (attributesMap.containsKey(MODIFIED_TIMESTAMP)) { throw new RuntimeException(NYI_EXCEPTION); } if (attributesMap.containsKey(POLICY)) { throw new RuntimeException(NYI_EXCEPTION); } if (attributesMap.containsKey(MAX_SIZE)) { throw new RuntimeException(NYI_EXCEPTION); } if (attributesMap.containsKey(MSGS_DELAYED)) { throw new RuntimeException(NYI_EXCEPTION); } if (attributesMap.containsKey(DELAY_SEC)) { throw new RuntimeException(NYI_EXCEPTION); } } //@Override public void setEndpoint(String endpoint) throws IllegalArgumentException { throw new RuntimeException(NYI_EXCEPTION); } //@Override public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch(ChangeMessageVisibilityBatchRequest changeMessageVisibilityBatchRequest) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } //@Override public void changeMessageVisibility(ChangeMessageVisibilityRequest changeMessageVisibilityRequest) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } //@Override public void removePermission(RemovePermissionRequest removePermissionRequest) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } //@Override public SendMessageBatchResult sendMessageBatch(SendMessageBatchRequest sendMessageBatchRequest) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } //@Override public DeleteMessageBatchResult deleteMessageBatch(DeleteMessageBatchRequest deleteMessageBatchRequest) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } //@Override public void addPermission(AddPermissionRequest addPermissionRequest) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } //@Override public void shutdown() { throw new RuntimeException(NYI_EXCEPTION); } //@Override public ResponseMetadata getCachedResponseMetadata(AmazonWebServiceRequest request) { throw new RuntimeException(NYI_EXCEPTION); } private static void checkURLForException(final String queueUrl) { checkStringForExceptionMarker(queueUrl); } private static void checkStringForExceptionMarker(final String str) { final String src = StringUtils.isBlank(str) ? "" : str.toLowerCase(); if (src.contains(MARKER_CLIENT_EXCEPTION)) { throw new AmazonClientException("Forced AmazonClientException"); } if (src.contains(MARKER_SERVICE_EXCEPTION)) { throw new AmazonServiceException("Forced AmazonServiceException"); } } private static String makeMD5(final String input) { try { return new String(Md5Utils.computeMD5Hash(StringUtils.defaultString(input).getBytes())); } catch (Exception ex) { throw new RuntimeException(ex); } } public void setRegion(Region region) throws IllegalArgumentException { } public void purgeQueue(PurgeQueueRequest purgeQueueRequest) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public ListDeadLetterSourceQueuesResult listDeadLetterSourceQueues( ListDeadLetterSourceQueuesRequest listDeadLetterSourceQueuesRequest) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public void setQueueAttributes(String queueUrl, Map<String, String> attributes) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public ChangeMessageVisibilityBatchResult changeMessageVisibilityBatch( String queueUrl, List<ChangeMessageVisibilityBatchRequestEntry> entries) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public void changeMessageVisibility(String queueUrl, String receiptHandle, Integer visibilityTimeout) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public GetQueueUrlResult getQueueUrl(String queueName) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public void removePermission(String queueUrl, String label) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public GetQueueAttributesResult getQueueAttributes(String queueUrl, List<String> attributeNames) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public SendMessageBatchResult sendMessageBatch(String queueUrl, List<SendMessageBatchRequestEntry> entries) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public void deleteQueue(String queueUrl) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public SendMessageResult sendMessage(String queueUrl, String messageBody) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public ReceiveMessageResult receiveMessage(String queueUrl) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public ListQueuesResult listQueues(String queueNamePrefix) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public DeleteMessageBatchResult deleteMessageBatch(String queueUrl, List<DeleteMessageBatchRequestEntry> entries) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public CreateQueueResult createQueue(String queueName) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public void addPermission(String queueUrl, String label, List<String> aWSAccountIds, List<String> actions) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } public void deleteMessage(String queueUrl, String receiptHandle) throws AmazonServiceException, AmazonClientException { throw new RuntimeException(NYI_EXCEPTION); } }
413689716d96a6ae3df66bec9d48069800540fbe
[ "Java" ]
1
Java
flozano/mock-aws-java-sdk
0035b5647ef33d076b9efa2b2561ca4f1371b197
c1766cecd13c14fd6a1b2d3accf54ab1ee79d70d
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine; public class DrawerBase : MonoBehaviour, IDrawer { public IGame game { get; set; } public Dictionary<IPos, GameObject> goMap { get; set; } public bool init; public GameObject pfTileSquare, pfTileHex; private GameObject pfTile; // Start is called before the first frame update void Start() { init = false; goMap = new Dictionary<IPos, GameObject>(); } // Update is called once per frame void Update() { } public void SetTile() { switch (game.tileShape) { case TileShape.SQUARE: pfTile = pfTileSquare; break; case TileShape.HEX: //pfTile = pfTileSquare; pfTile = pfTileHex; break; } } public void InitCamera() { IPos midPos = game.map.GetCenterPos(); Vector3 p = goMap[midPos].transform.position; if (game.tileShape == TileShape.SQUARE) { Camera.main.transform.position = new Vector3(p.x, 1, p.z); Camera.main.orthographicSize = game.map.dim / 1.75f; } else { Camera.main.transform.position = new Vector3(p.x * 3 / 2, 1, p.z * 3 / 2); Camera.main.orthographicSize = (3 / 2) * game.map.dim / 1.75f; } } public void Init() { SetTile(); DrawFrame(); if (!init) { init = true; InitCamera(); } } public void DrawTakeTurn() { DrawTerrainUpdate(); } void DrawTerrainUpdate() { foreach (IPos p in game.map.lands.Keys) { if (!goMap.ContainsKey(p)) { goMap[p] = InstantiateGo(pfTile, p.mapLoc, Color.white); goMap[p].GetComponentInChildren<Clickable>().setPos(p); } Renderer r = goMap[p].GetComponentInChildren<Renderer>(); ILand thisLand = game.map.lands[p]; r.material.color = thisLand.GetColor(); } } GameObject InstantiateGo(GameObject pf, Loc l, Color c) { Vector3 pos = new Vector3(l.x(), l.z(), l.y()); GameObject go = Instantiate(pf, pos, Quaternion.identity); go.GetComponentInChildren<Renderer>().material.color = c; return go; } public void DrawFrame() { //if (!game.paused) //{ // foreach (bbAgent a in game.playerAgents) // { // StartCoroutine(AnimateAgent(a)); // } //} } //IEnumerator AnimateAgent(bbAgent a) //{ // if (!a.animating) // { // if (goAgents.ContainsKey(a) && goMap.ContainsKey(a.pos)) // { // a.animating = true; // float nextTurn = game.nextTurn; // float lastTurn = game.lastTurn; // Transform agentTransform = goAgents[a].transform; // Transform targetTransform = goMap[a.pos].transform; // float percent = 0; // while (percent < 1) // { // if (!goAgents.ContainsKey(a)) // { // break; // } // else // { // percent = Mathf.InverseLerp(lastTurn, nextTurn, Time.time); // goAgents[a].transform.position = Vector3.Lerp(agentTransform.position, targetTransform.position, percent); // if (percent == 1) // { // a.animating = false; // } // } // yield return null; // } // } // } //} } public class ExodusDrawer : DrawerBase, IDrawer { } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SamizdatEngine.GE { public interface GEDrawer { GoEsque game { get; set; } Dictionary<Stone, GameObject> stones { get; set; } Dictionary<Intersection, GameObject> intersections { get; set; } void Draw(); void DrawInit(GoEsque game); void SetBasicColors(); void SetTerritoryColors(Dictionary<Intersection, Player> territory); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine; public interface IGame { GameManagerBase gameManager { get; set; } bool HandleClick(IPos _pos, bool _leftClick, bool _rightClick); int turnNumber { get; set; } IMap map { get; set; } TileShape tileShape { get; set; } PosType posType { get; set; } LandType landType { get; set; } } public class GameBase : IGame { public int turnNumber { get; set; } public TileShape tileShape { get; set; } public PosType posType { get; set; } public LandType landType { get; set; } public IMap map { get; set; } public GameManagerBase gameManager { get; set; } public bool HandleClick(IPos _pos, bool _leftClick, bool _rightClick) { return true; } public GameBase(TileShape _tileShape = TileShape.SQUARE, PosType _posType = PosType.GridPos, LandType _landType = LandType.BasicLand) { turnNumber = 0; tileShape = _tileShape; posType = _posType; landType = _landType; } } public class ExodusGame : GameBase, IGame { public ExodusGame(TileShape _tileShape = TileShape.SQUARE, PosType _posType = PosType.GridPos, LandType _landType = LandType.BasicLand) : base(_tileShape, _posType, _landType) { map = new ExodusMap(this); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine; public interface IMap { IGame game { get; set; } int dim { get; set; } bool wrapEastWest { get; set; } bool wrapNorthSouth { get; set; } Dictionary<IPos, ILand> lands { get; set; } Dictionary<IPos, ILand> MakeLands(int _N); IPos GetCenterPos(); } public abstract class MapAbstract { public IGame game { get; set; } public bool wrapEastWest { get; set; } public bool wrapNorthSouth { get; set; } public Dictionary<IPos, ILand> lands { get; set; } public Dictionary<string, IPos> pathMap { get; set; } public int dim { get; set; } public TileShape tileShape; public Dictionary<IPos, IOccupant> occupants { get; set; } public MapAbstract(IGame _game, int _N = 5, bool _wrapEastWest = true, bool _wrapNorthSouth = true) { game = _game; wrapEastWest = _wrapEastWest; wrapNorthSouth = _wrapNorthSouth; tileShape = game.tileShape; occupants = new Dictionary<IPos, IOccupant>(); dim = 1 + (int)Mathf.Pow(2, _N); lands = MakeLands(_N); } public abstract Dictionary<IPos, ILand> MakeLands(int _N); public float[,] NoiseGrid(int _N) { MidpointDisplacement mpd = new MidpointDisplacement(_N, wrapEastWest, wrapNorthSouth); float[,] elevation = mpd.Elevation; return elevation; } #region BUILD GRID public Dictionary<string, IPos> GenerateBasicMap(int _N) { int _dim = 1 + (int)Mathf.Pow(2, _N); Dictionary<string, IPos> map = Generate2DGrid(_dim); map = SetNeighborsFor2DGrid(map); return map; } public Dictionary<string, IPos> Generate2DGrid(int _dim) { Dictionary<string, IPos> map = new Dictionary<string, IPos>(); for (int x = 0; x < _dim; x++) { for (int y = 0; y < _dim; y++) { Loc l = new Loc(x, y); IPos p = PosFactory.CreatePos(l, game); map[p.gridLoc.key()] = p; } } return map; } public Dictionary<string, IPos> SetNeighborsFor2DGrid(Dictionary<string, IPos> map) { foreach (string k in map.Keys) { IPos p = map[k]; if (tileShape == TileShape.SQUARE) { p.neighbors = SetNeighborsSquare(p, map); } else if (tileShape == TileShape.HEX) { p.neighbors = SetNeighborsHex(p, map); } } return map; } public List<IPos> SetNeighborsSquare(IPos p, Dictionary<string, IPos> map) { float x = p.gridLoc.x(); float y = p.gridLoc.y(); List<IPos> neighbors = new List<IPos>(); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (i != 0 || j != 0) { float X = wrapEastWest ? (dim + x + i) % dim : x + i; float Y = wrapNorthSouth ? (dim + y + j) % dim : y + j; Loc l2 = new Loc(X, Y); if (map.ContainsKey(l2.key())) { neighbors.Add(map[l2.key()]); } else { Debug.Log("Map doesn't contain " + l2.x() + "," + l2.y()); } } } } return neighbors; } public List<IPos> SetNeighborsHex(IPos p, Dictionary<string, IPos> map) { List<IPos> neighbors = new List<IPos>(); List<int[]> hexNeighbors = new List<int[]>(); if (p.gridLoc.y() % 2 == 0) { hexNeighbors.Add(new int[] { 1, 0 }); hexNeighbors.Add(new int[] { 1, -1 }); hexNeighbors.Add(new int[] { 0, -1 }); hexNeighbors.Add(new int[] { -1, 0 }); hexNeighbors.Add(new int[] { 0, 1 }); hexNeighbors.Add(new int[] { 1, 1 }); } else { hexNeighbors.Add(new int[] { 1, 0 }); hexNeighbors.Add(new int[] { -1, -1 }); hexNeighbors.Add(new int[] { 0, -1 }); hexNeighbors.Add(new int[] { -1, 0 }); hexNeighbors.Add(new int[] { 0, 1 }); hexNeighbors.Add(new int[] { -1, 1 }); } float x = p.gridLoc.x(); float y = p.gridLoc.y(); for (int k = 0; k < hexNeighbors.Count; k++) { int i = hexNeighbors[k][0]; int j = hexNeighbors[k][1]; float X = wrapEastWest ? (dim + x + i) % dim : x + i; float Y = wrapNorthSouth ? (dim + y + j) % dim : y + j; Loc l2 = new Loc(X, Y); if (map.ContainsKey(l2.key())) { neighbors.Add(map[l2.key()]); } else { Debug.Log("Map doesn't contain " + l2.x() + "," + l2.y()); } } return neighbors; } #endregion #region INITIALIZE LANDS public Dictionary<IPos, ILand> InitializeLandsFromMidpointDisplacement(int _N, Dictionary<string, IPos> pm) { Dictionary<IPos, ILand> landsDict = new Dictionary<IPos, ILand>(); float[,] elevation = NoiseGrid(_N); MapUtil.TransformMapMinMax(ref elevation, MapUtil.dNormalize); foreach (IPos p in pm.Values) { Dictionary<string, float> _val = new Dictionary<string, float>() { { "elevation", elevation[(int)p.gridLoc.x(), (int)p.gridLoc.y()] } }; ILand newLand = LandFactory.CreateLand(p, _val, game.landType); landsDict[p] = newLand; } return landsDict; } #endregion public IPos GetCenterPos() { Loc MidLoc = new Loc(game.map.dim / 2 - 1, game.map.dim / 2 - 1); return pathMap[MidLoc.key()]; } } public class MapBasic : MapAbstract, IMap { public MapBasic(IGame _game, int _N = 5, bool _wrapEastWest = true, bool _wrapNorthSouth = true) : base(_game, _N, _wrapEastWest, _wrapNorthSouth) { } public override Dictionary<IPos, ILand> MakeLands(int _N) { pathMap = GenerateBasicMap(_N); return InitializeLandsFromMidpointDisplacement(_N, pathMap); } } public class ExodusMap : MapAbstract, IMap { public ExodusMap(IGame _game, int _N = 5, bool _wrapEastWest = true, bool _wrapNorthSouth = true) : base(_game, _N, _wrapEastWest, _wrapNorthSouth) { } public override Dictionary<IPos, ILand> MakeLands (int _N) { Dictionary<string, IPos> pm = GenerateBasicMap(_N); Dictionary<IPos, ILand> landsDict = new Dictionary<IPos, ILand>(); float[,] elevation = NoiseGrid(_N); float[,] temperature = NoiseGrid(_N); MapUtil.TransformMapMinMax(ref elevation, MapUtil.dNormalize); MapUtil.TransformMapMinMax(ref temperature, MapUtil.dNormalize); foreach (IPos p in pm.Values) { float elev = elevation[(int)p.gridLoc.x(), (int)p.gridLoc.y()]; float temp = temperature[(int)p.gridLoc.x(), (int)p.gridLoc.y()]; Dictionary<string, float> _val = new Dictionary<string, float>(){ { "elevation", elev }, { "temperature", temp } }; ILand newLand = LandFactory.CreateLand(p, _val, game.landType); landsDict[p] = newLand; } return landsDict; } } public interface IOccupant { } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public static class ErosionBuilder { public static void HydraulicErosion(float[,] Elevation, float[,] WaterFlux, float erosionRate, Benchmark bench = null) { if (bench != null) { bench.StartBenchmark("Erode"); } int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Elevation[x, y] -= erosionRate * WaterFlux[x, y]; } } if (bench != null) { bench.EndBenchmark("Erode"); } } public static void ThermalErosion(float[,] Elevation, float talusAngle = 0.5f, int iterations = 1, Benchmark bench = null) { if (bench != null) { bench.StartBenchmark("Thermal Erosion"); } int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int i = 0; i < iterations; i++) { for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { ThermalWorkhorse(Elevation, new Loc(x,y), talusAngle); } } MapUtil.TransformMapMinMax(ref Elevation, MapUtil.dNormalize, bench); } if (bench != null) { bench.EndBenchmark("Thermal Erosion"); } } public static void ThermalWorkhorse(float[,] Elevation, Loc l, float talusAngle) { Dictionary<Loc, float> n = MapUtil.GetValidNeighbors(Elevation, l); // Thermal Erosion float di; float dtotal = 0f; float dmax = float.NegativeInfinity; foreach (KeyValuePair<Loc, float> kvp in n) { di = Elevation[l.x, l.y] - Elevation[kvp.Key.x, kvp.Key.y]; if (di > talusAngle) { dtotal += di; di = di > dmax ? dmax : di; } } float startingElev = Elevation[l.x, l.y]; foreach (KeyValuePair<Loc, float> kvp in n) { di = startingElev - Elevation[kvp.Key.x, kvp.Key.y]; float delta = 0.5f * (dmax - talusAngle) * di / dtotal; Elevation[kvp.Key.x, kvp.Key.y] += delta; Elevation[l.x, l.y] -= delta; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Linq; public struct MapLoc { public int x, y; public float v; public MapLoc(int _x, int _y) { x = _x; y = _y; v = 0f; } } public static class MapUtil { public static void GetMapMaxMinValues(float[,] Elevation, out float maxVal, out float minVal) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); minVal = float.PositiveInfinity; maxVal = float.NegativeInfinity; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { maxVal = Elevation[x, y] > maxVal ? Elevation[x, y] : maxVal; minVal = Elevation[x, y] < minVal ? Elevation[x, y] : minVal; } } } public static void GetMapMaxIndices(float[,] Elevation, out int xMaxIndex, out int yMaxIndex) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float maxVal = float.NegativeInfinity; xMaxIndex = 0; yMaxIndex = 0; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] > maxVal) { maxVal = Elevation[x, y]; xMaxIndex = x; yMaxIndex = y; } } } } public static void GetMapMinIndices(float[,] Elevation, out int xMinIndex, out int yMinIndex) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float maxVal = float.PositiveInfinity; xMinIndex = 0; yMinIndex = 0; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] < maxVal) { maxVal = Elevation[x, y]; xMinIndex = x; yMinIndex = y; } } } } public static void TransformMap(ref float[,] Elevation, dTransform dFunc, float c, Benchmark bench = null) { if (bench != null) { bench.StartBenchmark("TransformMap:" + dFunc.ToString()); } int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] dElev = new float[xDim, yDim]; float f; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { f = Elevation[x, y]; f = dFunc(f,c); dElev[x, y] = f; } } Elevation = dElev; if (bench != null) { bench.EndBenchmark("TransformMap:" + dFunc.ToString()); } } public delegate float dTransform(float f, float c); public static float dInvert(float f, float c) { return 1.0f - f; } public static float dExponentiate(float f, float c) { return (float)Math.Pow(f, c); } public static void TransformMapSpecialNormalize(ref float[,] Elevation, float[,] WaterFlux) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] dElev = new float[xDim, yDim]; float f; float minVal, maxVal; GetMapMaxMinValues(Elevation, out maxVal, out minVal); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { f = Elevation[x, y]; f = dNormalize(f, minVal, maxVal); if (WaterFlux[x,y] > 0.0f) { dElev[x, y] = f; } } } Elevation = dElev; } public static void TransformMapMinMax(ref float[,] Elevation, dTransformMinMax dFunc, Benchmark bm = null) { if (!(bm == null)) { bm.StartBenchmark("TransformMapMinMax"); } int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] dElev = new float[xDim, yDim]; float f; float minVal, maxVal; GetMapMaxMinValues(Elevation, out maxVal, out minVal); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { f = Elevation[x, y]; f = dFunc(f, minVal, maxVal); dElev[x, y] = f; } } Elevation = dElev; if (!(bm == null)) { bm.EndBenchmark("TransformMapMinMax"); } } public delegate float dTransformMinMax(float f, float fMin, float fMax, float newMinVal = 0f, float newMaxVal = 1f); public static float dNormalize(float f, float oldMinVal, float oldMaxVal, float newMinVal = 0f, float newMaxVal = 1f) { return (((f - oldMinVal) * (newMaxVal - newMinVal)) / (oldMaxVal - oldMinVal)) + newMinVal; } public static void TransformMapWithMap(ref float[,] Elevation, dTransformWithMap dFunc) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float f; float minVal, maxVal; GetMapMaxMinValues(Elevation, out maxVal, out minVal); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { f = dFunc(x,y,Elevation); Elevation[x, y] = f; } } } public delegate float dTransformWithMap(int xIndex, int yIndex, float[,] Elevation); public static float dSmooth(int xIndex, int yIndex, float[,] Elevation) { float coeff = 0.5f; // value between 0 and 1; 0 doesnt change anything float nAvg = GetNeighborAverage(Elevation, new MapLoc(xIndex, yIndex)); float r = coeff * nAvg + (1 - coeff) * Elevation[xIndex, yIndex]; return r; } public static float dSmoothKeep1(int xIndex, int yIndex, float[,] Elevation) { float coeff = 0.5f; // value between 0 and 1; 0 doesnt change anything float nAvg = GetNeighborAverage(Elevation, new MapLoc(xIndex, yIndex)); float r = coeff * nAvg + (1 - coeff) * Elevation[xIndex, yIndex]; r = Elevation[xIndex, yIndex] == 1f ? 1f : r; return Math.Max(r, Elevation[xIndex, yIndex]); } public static void TransformMapWithMapLoop(ref float[,] Elevation, int iterations, dTransformWithMap dFunc) { for (int i = 0; i < iterations; i++) { TransformMapWithMap(ref Elevation, dFunc); } } public static void TransformEqualizeMapByLevel(ref float seaLevel, ref float[,] Elevation, float target, Benchmark bm = null, float tolerance = 0.01f, bool equalizeByExponentiation = false) { if (!(bm == null)) { bm.StartBenchmark("Equalize Level to " + target); } float percentAbove = GetPercentAbove(Elevation, seaLevel); int iter = 0; while (Math.Abs(percentAbove - target) > tolerance && iter < 10000) { if (percentAbove > target + tolerance) { if ( seaLevel > 0.0f) { if (equalizeByExponentiation) { TransformMap(ref Elevation, dExponentiate, 2f); } else { seaLevel += tolerance / 2f; } } else { break; } } if (percentAbove < target - tolerance) { if (seaLevel < 1.0f) { if (equalizeByExponentiation) { TransformMap(ref Elevation, dExponentiate, 0.5f); } else { seaLevel -= tolerance / 2f; } } else { break; } } percentAbove = GetPercentAbove(Elevation, seaLevel); iter++; } if (!(bm == null)) { bm.EndBenchmark("Equalize Level to " + target); } } public static void TransformEqualizeMapByLevelAboveSea(ref float riverLevel, ref float[,] WaterFlux, float target, float[,] Elevation, float seaLevel, float tolerance = 0.01f, bool equalizeByExponentiation = false) { float percentAbove = GetPercentAboveSeaLevel(WaterFlux, riverLevel, Elevation, seaLevel); int iter = 0; while (Math.Abs(percentAbove - target) > tolerance && iter < 1000) { //Debug.Log("Percent Above SeaLevel is " + percentAbove); if (percentAbove > target + tolerance) { if (riverLevel < 1.0f) { if (equalizeByExponentiation) { TransformMap(ref WaterFlux, dExponentiate, 2f); } else { riverLevel += tolerance; } } else { break; } } if (percentAbove < target - tolerance) { if (riverLevel > 0f) { if (equalizeByExponentiation) { TransformMap(ref WaterFlux, dExponentiate, 0.5f); } else { riverLevel -= tolerance; } } else { break; } } percentAbove = GetPercentAboveSeaLevel(WaterFlux, riverLevel, Elevation, seaLevel); iter++; } } public static float GetPercentAboveSeaLevel(float[,] WaterFlux, float thresh, float[,] Elevation, float seaLevel) { List<float> listAbove = new List<float>(); int xDim = WaterFlux.GetLength(0); int yDim = WaterFlux.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] > seaLevel) { if (WaterFlux[x, y] > thresh) { listAbove.Add(1.0f); } else { listAbove.Add(0.0f); } } } } float avg = listAbove.Count > 0 ? listAbove.Average() : 0f; return avg; } public static int OceanNeighbors(MapLoc l, float[,] Elevation, float seaLevel) { Dictionary<MapLoc, float> neighbors = GetValidNeighbors(Elevation, l); int numberOceanNeighbors = 0; foreach (KeyValuePair<MapLoc, float> kvp in neighbors) { if (kvp.Value < seaLevel) { numberOceanNeighbors++; } } return numberOceanNeighbors; } public static int RiverNeighbors(MapLoc l, float[,] WaterFlux, float riverLevel) { Dictionary<MapLoc, float> neighbors = GetValidNeighbors(WaterFlux, l); int numberRiverNeighbors = 0; foreach (KeyValuePair<MapLoc, float> kvp in neighbors) { if (kvp.Value > riverLevel) { numberRiverNeighbors++; } } return numberRiverNeighbors; } public static List<MapLoc> GetCoastMapLocs(float[,] Elevation, float seaLevel) { List<MapLoc> coast = new List<MapLoc>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] > seaLevel) { MapLoc l = new MapLoc(x, y); int numberOfOceanNeighbors = OceanNeighbors(l, Elevation, seaLevel); if (numberOfOceanNeighbors > 0) { coast.Add(l); } } } } return coast; } public static bool IsBorder(MapLoc l, float[,] Elevation) { int x = l.x; int y = l.y; int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); bool isBorder = (x == 0 || y == 0 || x == xDim - 1 || y == yDim - 1) ? true : false; return isBorder; } public static float GetMapBorderAverage(float[,] Elevation) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); List<float> listBorder = new List<float>(); MapLoc l; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { l = new MapLoc(x, y); if (IsBorder(l, Elevation)) { listBorder.Add(Elevation[x, y]); } } } return listBorder.Average(); } public static float GetMapMedian(float[,] Elevation) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); List<float> listValues = new List<float>(); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { listValues.Add(Elevation[x, y]); } } return GetMedian(listValues); // change it to median } public static float GetMedian(List<float> x) { x.Sort(); int i = (x.Count - 1) / 2; return x[i]; } public static float GetPercentAbove(float[,] Elevation, float thresh) { List<float> listAbove = new List<float>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x,y] > thresh) { listAbove.Add(1.0f); } else { listAbove.Add(0.0f); } } } return listAbove.Average(); } public static float GetSlope(float[,] Elevation, MapLoc l) { Dictionary<MapLoc, float> neighbors = GetValidNeighbors(Elevation, l); // Get Slope float maxDiff = float.NegativeInfinity; float MapLocalDiff; foreach (KeyValuePair<MapLoc, float> n in neighbors) { MapLocalDiff = Math.Abs(Elevation[l.x, l.y] - Elevation[n.Key.x, n.Key.y]); if (MapLocalDiff > maxDiff) { maxDiff = MapLocalDiff; } } return maxDiff; } public static float[,] GetSlopeMap(float[,] Elevation) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] Slopes = new float[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Slopes[x, y] = GetSlope(Elevation, new MapLoc(x, y)); } } return Slopes; } public static void GetCoordinates(int xDim, int yDim, int _X, int _Y, ref int X, ref int Y, bool Wrapped = true) { if (Wrapped) { X = (1000 * xDim + _X) % xDim; Y = (1000 * yDim + _Y) % yDim; } else { X = _X; Y = _Y; } } public static void GetCoordinates(int xDim, int yDim, float _X, float _Y, ref float X, ref float Y, bool Wrapped = true) { if (Wrapped) { X = (1000 * xDim + _X) % xDim; Y = (1000 * yDim + _Y) % yDim; } else { X = _X; Y = _Y; } } public static Dictionary<MapLoc,float> GetValidNeighbors(float[,] Elevation, MapLoc l, bool excludeSelf = true, bool includeDiagonal = false, bool Wrap = true) { Dictionary<MapLoc, float> neighbors = new Dictionary<MapLoc, float>(); int x = 0; int y = 0; int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (excludeSelf && i == 0 && j == 0) { } else { GetCoordinates(xDim, yDim, l.x+i, l.y+j, ref x, ref y, Wrap); if (x >= 0 && y >= 0 && x < xDim && y < yDim) { if (includeDiagonal || Math.Sqrt(i*i+j*j) <= 1) { neighbors[new MapLoc(x, y)] = Elevation[x, y]; } } } } } return neighbors; } public static MapLoc GetLowestNeighbor(float[,] Elevation, MapLoc l, bool excludeSelf) { Dictionary<MapLoc, float> neighbors = GetValidNeighbors(Elevation, l, excludeSelf); // Get Lowest Neighbor MapLoc minMapLoc = new MapLoc(0, 0); float minVal = float.PositiveInfinity; foreach (KeyValuePair<MapLoc,float> kvp in neighbors) { if (kvp.Value < minVal) { minVal = kvp.Value; minMapLoc = kvp.Key; } } return minMapLoc; } public static MapLoc GetHighestNeighbor(float[,] Elevation, MapLoc l, bool includeSelf) { Dictionary<MapLoc, float> neighbors = GetValidNeighbors(Elevation, l, includeSelf); // Get Highest Neighbor MapLoc maxMapLoc = new MapLoc(0, 0); float maxVal = float.NegativeInfinity; foreach (KeyValuePair<MapLoc, float> kvp in neighbors) { if (kvp.Value > maxVal) { maxVal = kvp.Value; maxMapLoc = kvp.Key; } } return maxMapLoc; } public static float GetNeighborAverage(float[,] Elevation, MapLoc l) { Dictionary<MapLoc, float> neighbors = GetValidNeighbors(Elevation, l); // GetNeighborAversge List<float> NeighborHeights = new List<float>(); foreach (KeyValuePair<MapLoc, float> kvp in neighbors) { NeighborHeights.Add(kvp.Value); } return NeighborHeights.Average(); } public static MapLoc[,] GetDownhillMap(float[,] Elevation) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); MapLoc[,] Downhill = new MapLoc[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { MapLoc ln = GetLowestNeighbor(Elevation, new MapLoc(x, y), false); Downhill[x, y] = ln; //Debug.Log("Lowest Neighbor of [" + x + "," + y + "] at " + Elevation[x, y] + " is [" + ln.x + "," + ln.y + "] at " + Elevation[ln.x, ln.y]); } } return Downhill; } public static Vec[,] GetDownhillVectors(float[,] Elevation) { MapLoc[,] Downhills = GetDownhillMap(Elevation); int xDim = Downhills.GetLength(0); int yDim = Downhills.GetLength(1); Vec[,] dhVectors = new Vec[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (x == Downhills[x, y].x && y == Downhills[x, y].y) { } else { Vec v = VectorBetween(new MapLoc(x, y), Downhills[x, y]); dhVectors[x, y] = v; //Debug.Log("Vector at [" + x + "," + y + "] is [" + v.x + "," + v.y + "]"); } } } return dhVectors; } public static Vec VectorBetween(MapLoc l1, MapLoc l2) { float x = l2.x - l1.x; float y = l1.y - l2.y; return new Vec(x, y); } public static List<MapLoc> GetMapLocsDescending(float[,] Elevation, Benchmark bench = null) { if (bench != null) { bench.StartBenchmark("GetMapLocsDescending"); } List<MapLoc> dMapLocs = new List<MapLoc>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { MapLoc l = new MapLoc(x, y); l.v = Elevation[x, y]; dMapLocs.Add(l); } } dMapLocs.OrderBy(l => l.v); dMapLocs.Reverse(); if (bench != null) { bench.EndBenchmark("GetMapLocsDescending"); } return dMapLocs; } public static void TransformApplyPreferencesWaterBody(ref float[,] Elevation, float seaLevel, WaterBodyPrefence prefWaterBody, Benchmark bench = null) { if (!(bench == null)) { bench.StartBenchmark("Water Bodies"); } if (prefWaterBody == WaterBodyPrefence.Islands) { if (GetMapBorderAverage(Elevation) > 0.5f) { TransformMap(ref Elevation, dInvert, 0f); } } else if (prefWaterBody == WaterBodyPrefence.Continent) { AddMaskIsland(ref Elevation, 0.1f); if (GetMapBorderAverage(Elevation) > 0.5f) { TransformMap(ref Elevation, dInvert, 0f); } } else if (prefWaterBody == WaterBodyPrefence.Lakes) { if (GetMapBorderAverage(Elevation) < 0.5f) { TransformMap(ref Elevation, dInvert, 0f); } } else if (prefWaterBody == WaterBodyPrefence.Coast) { AddMaskCoast(ref Elevation); if (GetMapBorderAverage(Elevation) > 0.5f) { TransformMap(ref Elevation, dInvert, 0f); } } if (!(bench == null)) { bench.EndBenchmark("Water Bodies"); } TransformMapMinMax(ref Elevation, dNormalize); TransformEqualizeMapByLevel(ref seaLevel, ref Elevation, 0.5f, bench); } public static void TransformResolveDepressions(ref float[,] Elevation, int maxIter = 1000, Benchmark bench = null, bool normalize = true) { if (!(bench == null)) { bench.StartBenchmark("Resolve Depression" + maxIter); } List<MapLoc> depressedMapLocs = GetListOfDepressedMapLocs(Elevation); int iter = 0; while (depressedMapLocs.Count > 0 && iter < maxIter) { SortMapLocs(ref depressedMapLocs, Elevation); depressedMapLocs.Reverse(); foreach (MapLoc l in depressedMapLocs) { Elevation[l.x, l.y] = GetNeighborAverage(Elevation, l); } depressedMapLocs = GetListOfDepressedMapLocs(Elevation); iter++; } if (!(bench == null)) { bench.EndBenchmark("Resolve Depression" + maxIter); } if (normalize) { TransformMapMinMax(ref Elevation, dNormalize, bench); } } public static List<MapLoc> GetListOfDepressedMapLocs(float[,] Elevation) { List<MapLoc> depressedMapLocs = new List<MapLoc>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); MapLoc l; float e; bool lIsDepressed; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { l = new MapLoc(x, y); e = Elevation[x, y]; lIsDepressed = true; Dictionary<MapLoc,float> lNeighbors = GetValidNeighbors(Elevation, l); // Get Depressed MapLocs foreach (KeyValuePair<MapLoc,float> n in lNeighbors) { if (n.Value <= e) { lIsDepressed = false; break; } } if (lIsDepressed) { depressedMapLocs.Add(l); } } } return depressedMapLocs; } public static void SortMapLocs(ref List<MapLoc> MapLocs, float[,] Elevation) { MapLocs.OrderBy(p => Elevation[p.x, p.y]); } public static List<MapLoc> GetCircleMapLocs(float[,] Elevation, MapLoc center, float radius) { List<MapLoc> circleMapLocs = new List<MapLoc>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { float d = Distance(center, new MapLoc(x, y)); if (d < radius) { circleMapLocs.Add(new MapLoc(x, y)); } } } return circleMapLocs; } public static void AddMaskCircle(ref float[,] Elevation, MapLoc center, float radius, float height) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { float d = Distance(center, new MapLoc(x, y)); if (d < radius) { Elevation[x, y] += height * (float)(1 - Math.Pow(d / radius,2)); } } } TransformMapMinMax(ref Elevation, dNormalize); } public static void AddMaskIsland(ref float[,] Elevation, float height = 0.5f) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); int xi = (xDim - 1) / 2; int yi = (yDim - 1) / 2; int ri = (int)Math.Min(xi, yi); AddMaskCircle(ref Elevation, new MapLoc(xi, yi), ri, height); } public static void AddMaskCoast(ref float[,] Elevation, float height = 0.5f) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Elevation[x, y] += height * x / xDim; } } TransformMapMinMax(ref Elevation, dNormalize); } public static float Distance(MapLoc l1, MapLoc l2) { float d = (float)Math.Sqrt(Math.Pow(l1.x - l2.x, 2) + Math.Pow(l1.y - l2.y, 2)); return d; } public static int nFromDims(int xDim, int yDim) { int N = 1; int resultDim = (int)Mathf.Pow(2, N) + 1; int maxDim = Mathf.Max(xDim, yDim); while (resultDim < maxDim) { N++; resultDim = (int)Mathf.Pow(2, N) + 1; } return N; } public static float DegreesToRadians(float degrees) { return (float)(degrees * (Math.PI / 180)); } public static float RadiansToDegrees(float radians) { return (float)(radians * (180 / Math.PI)); } public static float VectorToRadians(float x, float y) { return (float)Math.Atan2(y,x); } public static void PrintElevationToDebug(float[,] Elevation) { int Dim = Elevation.GetLength(0); string sLine; for (int y = 0; y < Dim; y++) { sLine = ""; for (int x = 0; x < Dim; x++) { sLine += Math.Round(Elevation[x, y], 2).ToString() + ","; } sLine = sLine.TrimEnd(','); Debug.Log(sLine); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Linq; //https://www.codeproject.com/Articles/1221034/Pathfinding-Algorithms-in-Csharp public class Node { public Loc loc; public int x, y; public Dictionary<Node, float> neighborWeights; public List<Node> neighbors; public Dictionary<Loc, float> distanceTo; public Dictionary<Loc, float> distanceFrom; public Dictionary<Loc, Node> NearestTo; public Dictionary<PathOD, float> distanceBetween; public bool Visited; public int iRegion; public Node(int _x, int _y) { x = _x; y = _y; loc = new Loc(_x, _y); distanceTo = new Dictionary<Loc, float>(); distanceFrom = new Dictionary<Loc, float>(); distanceBetween = new Dictionary<PathOD, float>(); neighbors = new List<Node>(); NearestTo = new Dictionary<Loc, Node>(); neighborWeights = new Dictionary<Node, float>(); } } public struct PathOD { public Loc origin, destination; public PathOD(Loc _origin, Loc _destination) { origin = _origin; destination = _destination; } } public struct Path { public Loc originLoc, destinationLoc; public float distancePath, distanceEuclidean; public List<Node> path; public Path(Loc _origin, Loc _destination, List<Node> _path, float _distancePath, float _distanceEuclidean) { originLoc = _origin; destinationLoc = _destination; distancePath = _distancePath; distanceEuclidean = _distanceEuclidean; path = _path; } } public class Pathfinder { List<Node> nodelist = new List<Node>(); public Dictionary<Loc, Node> nodeDict = new Dictionary<Loc, Node>(); public Dictionary<PathOD, Path> PathDict = new Dictionary<PathOD, Path>(); public Pathfinder() { } public void SetNodeList(float[,] _elevation, float _seaLevel, delCost fCost, float _seaTravelCost = 0f) { int xDim = _elevation.GetLength(0); int yDim = _elevation.GetLength(1); Node[,] nodes = new Node[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { nodes[x, y] = new Node(x, y); nodeDict[new Loc(x, y)] = nodes[x, y]; } } for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Node n = nodes[x, y]; n.Visited = false; Loc l = new Loc(x, y); Dictionary<Loc, float> d = MapUtil.GetValidNeighbors(_elevation, l); foreach (KeyValuePair<Loc, float> kvp in d) { n.neighborWeights[nodes[kvp.Key.x, kvp.Key.y]] = fCost(l,kvp.Key,_elevation,_seaLevel,_seaTravelCost); n.neighbors.Add(nodes[kvp.Key.x, kvp.Key.y]); } nodelist.Add(n); } } } public void SetNodeList(List<Node> _nodes) { nodelist = _nodes; foreach (Node n in nodelist) { nodeDict[n.loc] = n; } } public Path GetPath(Loc origin, Loc destination) { PathOD p = new PathOD(origin, destination); bool pathFound = false; if (!PathDict.ContainsKey(p)) { pathFound = AStarSearch(origin, destination); } return PathDict[p]; } private bool AStarSearch(Loc origin, Loc destination) { List<Node> prioQueue; bool PathFound = false; AStarInit(out prioQueue, origin, destination); while (prioQueue.Any()) { AStarWorkhorse(ref prioQueue, ref PathFound, origin, destination); } if (PathFound) { AddPath(origin, destination); } return PathFound; } private void AStarInit(out List<Node> prioQueue, Loc originLoc, Loc destinationLoc) { foreach (Node n in nodelist) { n.distanceTo[destinationLoc] = MapUtil.Distance(n.loc, destinationLoc); } nodeDict[originLoc].distanceFrom[originLoc] = 0f; prioQueue = new List<Node>(); prioQueue.Add(nodeDict[originLoc]); } private void AStarWorkhorse(ref List<Node> prioQueue, ref bool PathFound, Loc originLoc, Loc destinationLoc) { prioQueue = prioQueue.OrderBy(x => x.distanceFrom[originLoc] + x.distanceTo[destinationLoc]).ToList(); Node n = prioQueue.First(); prioQueue.Remove(n); foreach (Node neighbor in n.neighbors) { if (!neighbor.Visited) { float newCost = n.distanceFrom[originLoc] + n.neighborWeights[neighbor]; if (!neighbor.distanceFrom.ContainsKey(originLoc) || newCost < neighbor.distanceFrom[originLoc]) // this will cause problems if there is ever no cost between nodes! { neighbor.distanceFrom[originLoc] = newCost; neighbor.NearestTo[originLoc] = n; if (!prioQueue.Contains(neighbor)) { prioQueue.Add(neighbor); } } } } n.Visited = true; if (n.loc.Equals(destinationLoc)) { PathFound = true; } } private void AddPath(Loc origin, Loc destination, bool addBetweenPaths = false) { float dP = 0f; List<Node> shortestPath = new List<Node>(); Node thisNode = nodeDict[destination]; shortestPath.Add(thisNode); while (!thisNode.loc.Equals(origin)) { dP += thisNode.neighborWeights[thisNode.NearestTo[origin]]; thisNode = thisNode.NearestTo[origin]; shortestPath.Add(thisNode); } shortestPath.Reverse(); float dE = MapUtil.Distance(origin, destination); Path p = new Path(origin, destination, shortestPath, dP, dE); PathDict[new PathOD(origin, destination)] = p; if (addBetweenPaths) { List<PathOD> betweenPaths = new List<PathOD>(); int iWindow = shortestPath.Count - 2; while (iWindow > 0) { for (int i = 0; i < (shortestPath.Count - iWindow); i++) { PathOD betweenPath = new PathOD(shortestPath[i].loc, shortestPath[i + iWindow].loc); betweenPaths.Add(betweenPath); } iWindow--; } foreach (PathOD pOD in betweenPaths) { AddPath(pOD.origin, pOD.destination, false); } } } public delegate float delCost(Loc l, Loc n, float[,] _elevation, float _seaLevel, float _seaTravelCost); public static float CostStandard(Loc l, Loc n, float[,] _elevation, float _seaLevel, float _seaTravelCost) { float nelev = _elevation[n.x, n.y]; float lelev = _elevation[l.x, l.y]; float diff = (nelev > _seaLevel && lelev > _seaLevel) ? Math.Abs(nelev - lelev) : _seaTravelCost; float dist = MapUtil.Distance(n, l); diff *= dist; diff += dist; return diff; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using BBMVP; public class bbClickable : MonoBehaviour { public bbPos pos; // Use this for initialization void Start () { } // Update is called once per frame void Update() { } public void setPos(bbPos _pos) { pos = _pos; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Linq; public struct Loc { public int x, y; public float v; public Loc(int _x, int _y) { x = _x; y = _y; v = 0f; } } public static class MapUtil { public static void GetMapMaxMinValues(float[,] Elevation, out float maxVal, out float minVal) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); minVal = float.PositiveInfinity; maxVal = float.NegativeInfinity; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { maxVal = Elevation[x, y] > maxVal ? Elevation[x, y] : maxVal; minVal = Elevation[x, y] < minVal ? Elevation[x, y] : minVal; } } } public static void GetMapMaxIndices(float[,] Elevation, out int xMaxIndex, out int yMaxIndex) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float maxVal = float.NegativeInfinity; xMaxIndex = 0; yMaxIndex = 0; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] > maxVal) { maxVal = Elevation[x, y]; xMaxIndex = x; yMaxIndex = y; } } } } public static void GetMapMinIndices(float[,] Elevation, out int xMinIndex, out int yMinIndex) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float maxVal = float.PositiveInfinity; xMinIndex = 0; yMinIndex = 0; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] < maxVal) { maxVal = Elevation[x, y]; xMinIndex = x; yMinIndex = y; } } } } public static void TransformMap(ref float[,] Elevation, dTransform dFunc, float c, Benchmark bench = null) { if (bench != null) { bench.StartBenchmark("TransformMap:" + dFunc.ToString()); } int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] dElev = new float[xDim, yDim]; float f; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { f = Elevation[x, y]; f = dFunc(f,c); dElev[x, y] = f; } } Elevation = dElev; if (bench != null) { bench.EndBenchmark("TransformMap:" + dFunc.ToString()); } } public delegate float dTransform(float f, float c); public static float dInvert(float f, float c) { return 1.0f - f; } public static float dExponentiate(float f, float c) { return (float)Math.Pow(f, c); } public static void TransformMapSpecialNormalize(ref float[,] Elevation, float[,] WaterFlux) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] dElev = new float[xDim, yDim]; float f; float minVal, maxVal; GetMapMaxMinValues(Elevation, out maxVal, out minVal); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { f = Elevation[x, y]; f = dNormalize(f, minVal, maxVal); if (WaterFlux[x,y] > 0.0f) { dElev[x, y] = f; } } } Elevation = dElev; } public static void TransformMapMinMax(ref float[,] Elevation, dTransformMinMax dFunc, Benchmark bm = null) { if (!(bm == null)) { bm.StartBenchmark("TransformMapMinMax"); } int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] dElev = new float[xDim, yDim]; float f; float minVal, maxVal; GetMapMaxMinValues(Elevation, out maxVal, out minVal); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { f = Elevation[x, y]; f = dFunc(f, minVal, maxVal); dElev[x, y] = f; } } Elevation = dElev; if (!(bm == null)) { bm.EndBenchmark("TransformMapMinMax"); } } public delegate float dTransformMinMax(float f, float fMin, float fMax, float newMinVal = 0f, float newMaxVal = 1f); public static float dNormalize(float f, float oldMinVal, float oldMaxVal, float newMinVal = 0f, float newMaxVal = 1f) { return (((f - oldMinVal) * (newMaxVal - newMinVal)) / (oldMaxVal - oldMinVal)) + newMinVal; } public static void TransformMapWithMap(ref float[,] Elevation, dTransformWithMap dFunc) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float f; float minVal, maxVal; GetMapMaxMinValues(Elevation, out maxVal, out minVal); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { f = dFunc(x,y,Elevation); Elevation[x, y] = f; } } } public delegate float dTransformWithMap(int xIndex, int yIndex, float[,] Elevation); public static float dSmooth(int xIndex, int yIndex, float[,] Elevation) { float coeff = 0.5f; // value between 0 and 1; 0 doesnt change anything float nAvg = GetNeighborAverage(Elevation, new Loc(xIndex, yIndex)); float r = coeff * nAvg + (1 - coeff) * Elevation[xIndex, yIndex]; return r; } public static float dSmoothKeep1(int xIndex, int yIndex, float[,] Elevation) { float coeff = 0.5f; // value between 0 and 1; 0 doesnt change anything float nAvg = GetNeighborAverage(Elevation, new Loc(xIndex, yIndex)); float r = coeff * nAvg + (1 - coeff) * Elevation[xIndex, yIndex]; r = Elevation[xIndex, yIndex] == 1f ? 1f : r; return Math.Max(r, Elevation[xIndex, yIndex]); } public static void TransformMapWithMapLoop(ref float[,] Elevation, int iterations, dTransformWithMap dFunc) { for (int i = 0; i < iterations; i++) { TransformMapWithMap(ref Elevation, dFunc); } } public static void TransformEqualizeMapByLevel(ref float seaLevel, ref float[,] Elevation, float target, Benchmark bm = null, float tolerance = 0.01f, bool equalizeByExponentiation = false) { if (!(bm == null)) { bm.StartBenchmark("Equalize Level to " + target); } float percentAbove = GetPercentAbove(Elevation, seaLevel); int iter = 0; while (Math.Abs(percentAbove - target) > tolerance && iter < 10000) { if (percentAbove > target + tolerance) { if ( seaLevel > 0.0f) { if (equalizeByExponentiation) { TransformMap(ref Elevation, dExponentiate, 2f); } else { seaLevel += tolerance / 2f; } } else { break; } } if (percentAbove < target - tolerance) { if (seaLevel < 1.0f) { if (equalizeByExponentiation) { TransformMap(ref Elevation, dExponentiate, 0.5f); } else { seaLevel -= tolerance / 2f; } } else { break; } } percentAbove = GetPercentAbove(Elevation, seaLevel); iter++; } if (!(bm == null)) { bm.EndBenchmark("Equalize Level to " + target); } } public static void TransformEqualizeMapByLevelAboveSea(ref float riverLevel, ref float[,] WaterFlux, float target, float[,] Elevation, float seaLevel, float tolerance = 0.01f, bool equalizeByExponentiation = false) { float percentAbove = GetPercentAboveSeaLevel(WaterFlux, riverLevel, Elevation, seaLevel); int iter = 0; while (Math.Abs(percentAbove - target) > tolerance && iter < 1000) { //Debug.Log("Percent Above SeaLevel is " + percentAbove); if (percentAbove > target + tolerance) { if (riverLevel < 1.0f) { if (equalizeByExponentiation) { TransformMap(ref WaterFlux, dExponentiate, 2f); } else { riverLevel += tolerance; } } else { break; } } if (percentAbove < target - tolerance) { if (riverLevel > 0f) { if (equalizeByExponentiation) { TransformMap(ref WaterFlux, dExponentiate, 0.5f); } else { riverLevel -= tolerance; } } else { break; } } percentAbove = GetPercentAboveSeaLevel(WaterFlux, riverLevel, Elevation, seaLevel); iter++; } } public static float GetPercentAboveSeaLevel(float[,] WaterFlux, float thresh, float[,] Elevation, float seaLevel) { List<float> listAbove = new List<float>(); int xDim = WaterFlux.GetLength(0); int yDim = WaterFlux.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] > seaLevel) { if (WaterFlux[x, y] > thresh) { listAbove.Add(1.0f); } else { listAbove.Add(0.0f); } } } } float avg = listAbove.Count > 0 ? listAbove.Average() : 0f; return avg; } public static int OceanNeighbors(Loc l, float[,] Elevation, float seaLevel) { Dictionary<Loc, float> neighbors = GetValidNeighbors(Elevation, l); int numberOceanNeighbors = 0; foreach (KeyValuePair<Loc, float> kvp in neighbors) { if (kvp.Value < seaLevel) { numberOceanNeighbors++; } } return numberOceanNeighbors; } public static int RiverNeighbors(Loc l, float[,] WaterFlux, float riverLevel) { Dictionary<Loc, float> neighbors = GetValidNeighbors(WaterFlux, l); int numberRiverNeighbors = 0; foreach (KeyValuePair<Loc, float> kvp in neighbors) { if (kvp.Value > riverLevel) { numberRiverNeighbors++; } } return numberRiverNeighbors; } public static List<Loc> GetCoastLocs(float[,] Elevation, float seaLevel) { List<Loc> coast = new List<Loc>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] > seaLevel) { Loc l = new Loc(x, y); int numberOfOceanNeighbors = OceanNeighbors(l, Elevation, seaLevel); if (numberOfOceanNeighbors > 0) { coast.Add(l); } } } } return coast; } public static bool IsBorder(Loc l, float[,] Elevation) { int x = l.x; int y = l.y; int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); bool isBorder = (x == 0 || y == 0 || x == xDim - 1 || y == yDim - 1) ? true : false; return isBorder; } public static float GetMapBorderAverage(float[,] Elevation) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); List<float> listBorder = new List<float>(); Loc l; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { l = new Loc(x, y); if (IsBorder(l, Elevation)) { listBorder.Add(Elevation[x, y]); } } } return listBorder.Average(); } public static float GetMapMedian(float[,] Elevation) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); List<float> listValues = new List<float>(); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { listValues.Add(Elevation[x, y]); } } return GetMedian(listValues); // change it to median } public static float GetMedian(List<float> x) { x.Sort(); int i = (x.Count - 1) / 2; return x[i]; } public static float GetPercentAbove(float[,] Elevation, float thresh) { List<float> listAbove = new List<float>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x,y] > thresh) { listAbove.Add(1.0f); } else { listAbove.Add(0.0f); } } } return listAbove.Average(); } public static float GetSlope(float[,] Elevation, Loc l) { Dictionary<Loc, float> neighbors = GetValidNeighbors(Elevation, l); // Get Slope float maxDiff = float.NegativeInfinity; float localDiff; foreach (KeyValuePair<Loc, float> n in neighbors) { localDiff = Math.Abs(Elevation[l.x, l.y] - Elevation[n.Key.x, n.Key.y]); if (localDiff > maxDiff) { maxDiff = localDiff; } } return maxDiff; } public static float[,] GetSlopeMap(float[,] Elevation) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] Slopes = new float[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Slopes[x, y] = GetSlope(Elevation, new Loc(x, y)); } } return Slopes; } public static void GetCoordinates(int xDim, int yDim, int _X, int _Y, ref int X, ref int Y, bool Wrapped = true) { if (Wrapped) { X = (1000 * xDim + _X) % xDim; Y = (1000 * yDim + _Y) % yDim; } else { X = _X; Y = _Y; } } public static Dictionary<Loc,float> GetValidNeighbors(float[,] Elevation, Loc l, bool excludeSelf = true, bool includeDiagonal = false, bool Wrap = true) { Dictionary<Loc, float> neighbors = new Dictionary<Loc, float>(); int x = 0; int y = 0; int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (excludeSelf && i == 0 && j == 0) { } else { GetCoordinates(xDim, yDim, l.x+i, l.y+j, ref x, ref y, Wrap); if (x >= 0 && y >= 0 && x < xDim && y < yDim) { if (includeDiagonal || Math.Sqrt(i*i+j*j) <= 1) { neighbors[new Loc(x, y)] = Elevation[x, y]; } } } } } return neighbors; } public static Loc GetLowestNeighbor(float[,] Elevation, Loc l, bool excludeSelf) { Dictionary<Loc, float> neighbors = GetValidNeighbors(Elevation, l, excludeSelf); // Get Lowest Neighbor Loc minLoc = new Loc(0, 0); float minVal = float.PositiveInfinity; foreach (KeyValuePair<Loc,float> kvp in neighbors) { if (kvp.Value < minVal) { minVal = kvp.Value; minLoc = kvp.Key; } } return minLoc; } public static Loc GetHighestNeighbor(float[,] Elevation, Loc l, bool includeSelf) { Dictionary<Loc, float> neighbors = GetValidNeighbors(Elevation, l, includeSelf); // Get Highest Neighbor Loc maxLoc = new Loc(0, 0); float maxVal = float.NegativeInfinity; foreach (KeyValuePair<Loc, float> kvp in neighbors) { if (kvp.Value > maxVal) { maxVal = kvp.Value; maxLoc = kvp.Key; } } return maxLoc; } public static float GetNeighborAverage(float[,] Elevation, Loc l) { Dictionary<Loc, float> neighbors = GetValidNeighbors(Elevation, l); // GetNeighborAversge List<float> NeighborHeights = new List<float>(); foreach (KeyValuePair<Loc, float> kvp in neighbors) { NeighborHeights.Add(kvp.Value); } return NeighborHeights.Average(); } public static Loc[,] GetDownhillMap(float[,] Elevation) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); Loc[,] Downhill = new Loc[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Loc ln = GetLowestNeighbor(Elevation, new Loc(x, y), false); Downhill[x, y] = ln; //Debug.Log("Lowest Neighbor of [" + x + "," + y + "] at " + Elevation[x, y] + " is [" + ln.x + "," + ln.y + "] at " + Elevation[ln.x, ln.y]); } } return Downhill; } public static Vec[,] GetDownhillVectors(float[,] Elevation) { Loc[,] Downhills = GetDownhillMap(Elevation); int xDim = Downhills.GetLength(0); int yDim = Downhills.GetLength(1); Vec[,] dhVectors = new Vec[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (x == Downhills[x, y].x && y == Downhills[x, y].y) { } else { Vec v = VectorBetween(new Loc(x, y), Downhills[x, y]); dhVectors[x, y] = v; //Debug.Log("Vector at [" + x + "," + y + "] is [" + v.x + "," + v.y + "]"); } } } return dhVectors; } public static Vec VectorBetween(Loc l1, Loc l2) { float x = l2.x - l1.x; float y = l1.y - l2.y; return new Vec(x, y); } public static List<Loc> GetLocsDescending(float[,] Elevation, Benchmark bench = null) { if (bench != null) { bench.StartBenchmark("GetLocsDescending"); } List<Loc> dLocs = new List<Loc>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Loc l = new Loc(x, y); l.v = Elevation[x, y]; dLocs.Add(l); } } dLocs.OrderBy(l => l.v); dLocs.Reverse(); if (bench != null) { bench.EndBenchmark("GetLocsDescending"); } return dLocs; } public static void TransformApplyPreferencesWaterBody(ref float[,] Elevation, float seaLevel, WaterBodyPrefence prefWaterBody, Benchmark bench = null) { if (!(bench == null)) { bench.StartBenchmark("Water Bodies"); } if (prefWaterBody == WaterBodyPrefence.Islands) { if (GetMapBorderAverage(Elevation) > 0.5f) { TransformMap(ref Elevation, dInvert, 0f); } } else if (prefWaterBody == WaterBodyPrefence.Continent) { AddMaskIsland(ref Elevation, 0.1f); if (GetMapBorderAverage(Elevation) > 0.5f) { TransformMap(ref Elevation, dInvert, 0f); } } else if (prefWaterBody == WaterBodyPrefence.Lakes) { if (GetMapBorderAverage(Elevation) < 0.5f) { TransformMap(ref Elevation, dInvert, 0f); } } else if (prefWaterBody == WaterBodyPrefence.Coast) { AddMaskCoast(ref Elevation); if (GetMapBorderAverage(Elevation) > 0.5f) { TransformMap(ref Elevation, dInvert, 0f); } } if (!(bench == null)) { bench.EndBenchmark("Water Bodies"); } TransformMapMinMax(ref Elevation, dNormalize); TransformEqualizeMapByLevel(ref seaLevel, ref Elevation, 0.5f, bench); } public static void TransformResolveDepressions(ref float[,] Elevation, int maxIter = 1000, Benchmark bench = null, bool normalize = true) { if (!(bench == null)) { bench.StartBenchmark("Resolve Depression" + maxIter); } List<Loc> depressedLocs = GetListOfDepressedLocs(Elevation); int iter = 0; while (depressedLocs.Count > 0 && iter < maxIter) { SortLocs(ref depressedLocs, Elevation); depressedLocs.Reverse(); foreach (Loc l in depressedLocs) { Elevation[l.x, l.y] = GetNeighborAverage(Elevation, l); } depressedLocs = GetListOfDepressedLocs(Elevation); iter++; } if (!(bench == null)) { bench.EndBenchmark("Resolve Depression" + maxIter); } if (normalize) { TransformMapMinMax(ref Elevation, dNormalize, bench); } } public static List<Loc> GetListOfDepressedLocs(float[,] Elevation) { List<Loc> depressedLocs = new List<Loc>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); Loc l; float e; bool lIsDepressed; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { l = new Loc(x, y); e = Elevation[x, y]; lIsDepressed = true; Dictionary<Loc,float> lNeighbors = GetValidNeighbors(Elevation, l); // Get Depressed Locs foreach (KeyValuePair<Loc,float> n in lNeighbors) { if (n.Value <= e) { lIsDepressed = false; break; } } if (lIsDepressed) { depressedLocs.Add(l); } } } return depressedLocs; } public static void SortLocs(ref List<Loc> locs, float[,] Elevation) { locs.OrderBy(p => Elevation[p.x, p.y]); } public static List<Loc> GetCircleLocs(float[,] Elevation, Loc center, float radius) { List<Loc> circleLocs = new List<Loc>(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { float d = Distance(center, new Loc(x, y)); if (d < radius) { circleLocs.Add(new Loc(x, y)); } } } return circleLocs; } public static void AddMaskCircle(ref float[,] Elevation, Loc center, float radius, float height) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { float d = Distance(center, new Loc(x, y)); if (d < radius) { Elevation[x, y] += height * (float)(1 - Math.Pow(d / radius,2)); } } } TransformMapMinMax(ref Elevation, dNormalize); } public static void AddMaskIsland(ref float[,] Elevation, float height = 0.5f) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); int xi = (xDim - 1) / 2; int yi = (yDim - 1) / 2; int ri = (int)Math.Min(xi, yi); AddMaskCircle(ref Elevation, new Loc(xi, yi), ri, height); } public static void AddMaskCoast(ref float[,] Elevation, float height = 0.5f) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Elevation[x, y] += height * x / xDim; } } TransformMapMinMax(ref Elevation, dNormalize); } public static float Distance(Loc l1, Loc l2) { float d = (float)Math.Sqrt(Math.Pow(l1.x - l2.x, 2) + Math.Pow(l1.y - l2.y, 2)); return d; } public static int nFromDims(int xDim, int yDim) { int N = 1; int resultDim = (int)Mathf.Pow(2, N) + 1; int maxDim = Mathf.Max(xDim, yDim); while (resultDim < maxDim) { N++; resultDim = (int)Mathf.Pow(2, N) + 1; } return N; } public static float DegreesToRadians(float degrees) { return (float)(degrees * (Math.PI / 180)); } public static float RadiansToDegrees(float radians) { return (float)(radians * (180 / Math.PI)); } public static float VectorToRadians(float x, float y) { return (float)Math.Atan2(y,x); } public static void PrintElevationToDebug(float[,] Elevation) { int Dim = Elevation.GetLength(0); string sLine; for (int y = 0; y < Dim; y++) { sLine = ""; for (int x = 0; x < Dim; x++) { sLine += Math.Round(Elevation[x, y], 2).ToString() + ","; } sLine = sLine.TrimEnd(','); Debug.Log(sLine); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class ElevationBuilder { public int Dim, N; public float[,] Elevation; public ElevationBuilder(int _N) { // Currently, Dimensions must be W = H and W = 2^N + 1 to make midpoint displacement simpler // Later, we should build the midpoint displacement map, then stretch it to the appropriate shape // OR build a bigger MPD map, then truncate to fit w and h N = _N; Dim = (int)Mathf.Pow(2, N) + 1; Elevation = new float[Dim, Dim]; } public void SetElevationWithMidpointDisplacement(int iExpand, Benchmark bench = null) { if (!(bench == null)) { bench.StartBenchmark("Midpoint Displacement"); } MidpointDisplacement mpd = new MidpointDisplacement(N); Elevation = mpd.Elevation; MapUtil.TransformMapMinMax(ref Elevation, MapUtil.dNormalize); if (iExpand > 1) { ExpandSquare(iExpand, iExpand); Smooth(); } if (!(bench == null)) { bench.EndBenchmark("Midpoint Displacement"); } } public void TrimToDimensions(int xDim, int yDim) { float[,] dElev = new float[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { dElev[x,y] = Elevation[x,y]; } } Elevation = dElev; } public void ExpandSquare(int xE, int yE, bool bNormalize = true) { PrintDims(); int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); int xl = xDim * xE; int yl = yDim * yE; float[,] newElevation = new float[xl, yl]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { for (int xi = 0; xi < xE; xi++) { for (int yi = 0; yi < yE; yi++) { int xp1 = x < xDim - 1 ? x + 1 : x; int yp1 = y < yDim - 1 ? y + 1 : y; float xLerpTop = Mathf.Lerp(Elevation[x, y], Elevation[xp1, y], (float)xi / (float)xE); float xLerpBot = Mathf.Lerp(Elevation[x, yp1], Elevation[xp1, yp1], (float)xi / (float)xE); float lerpVal = Mathf.Lerp(xLerpTop, xLerpBot, yi / yE); int xind = x * xE + xi; int yind = y * yE + yi; newElevation[xind, yind] = lerpVal; } } } } if (bNormalize) { MapUtil.TransformMapMinMax(ref newElevation, MapUtil.dNormalize); } Elevation = newElevation; PrintDims(); } public void Smooth(bool bNormalize = true) { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float[,] newElevation = new float[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { newElevation[x, y] = MapUtil.dSmooth(x, y, Elevation); } } if (bNormalize) { MapUtil.TransformMapMinMax(ref newElevation, MapUtil.dNormalize); } Elevation = newElevation; } public void PrintDims() { int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); Debug.Log("Elevation[" + xDim + "," + yDim + "]"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine.Linguistics; public class LinguisticsTester : MonoBehaviour { // Use this for initialization void Start () { int iter = 5; for (int j = 0; j < iter; j++) { List<string> words = Linguistics.GenerateWordsBasic(5); for (int i = 0; i < words.Count; i++) { words[i] = char.ToUpper(words[i][0]) + words[i].Substring(1).ToLower(); } Debug.Log(string.Join(",", words.ToArray())); } } // Update is called once per frame void Update () { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public enum ProjectName { Exodus} public class GameManagerBase : MonoBehaviour { public IGame game { get; set; } public IDrawer drawer { get; set; } public InputHandler inputHandler; [System.NonSerialized] public ProjectName projectName = ProjectName.Exodus; // Start is called before the first frame update public void Start() { IGame _game = new GameBase(); if (projectName == ProjectName.Exodus) { _game = new ExodusGame(); } Init(_game); } public void Init(IGame _game) { game = _game; game.gameManager = this; drawer.game = game; inputHandler.game = game; } // Update is called once per frame public void Update() { if (game.turnNumber == 0) { game.turnNumber++; drawer.Init(); } drawer.DrawFrame(); if (inputHandler.HandleUserInput()) { drawer.DrawTakeTurn(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BBMVP { public enum bbTerrainType { OCEAN, LAND, MOUNTAIN }; public enum bbTerrainFeature { ARABLE, MINEABLE, NONE }; public class bbLand { float TERRAIN_LEVEL = 0.25f; float TERRAIN_RARITY = 1 / 5f; float TERRAIN_UNCERTAINTY = 0.1f; public bbPos pos; public float val; public bbTerrainType terrainType; public bbTerrainFeature terrainFeature; public bbLand(bbPos _pos) { pos = _pos; terrainFeature = bbTerrainFeature.NONE; } public void setFromValue(float _val) { val = _val; terrainType = bbTerrainType.LAND; float t = Random.Range(0.0f, 1.0f); if (val < TERRAIN_LEVEL) { terrainType = bbTerrainType.OCEAN; } else if (val > (1 - TERRAIN_LEVEL)) { terrainType = bbTerrainType.MOUNTAIN; } else if (val > 0.5f) { float thresh = Mathf.Pow(Mathf.InverseLerp((1 - TERRAIN_LEVEL), 0.5f, val), TERRAIN_RARITY) + TERRAIN_UNCERTAINTY; if (t > thresh) { terrainFeature = bbTerrainFeature.MINEABLE; } } else if (val < 0.5f) { float thresh = Mathf.Pow(Mathf.InverseLerp(TERRAIN_LEVEL, 0.5f, val), TERRAIN_RARITY) + TERRAIN_UNCERTAINTY; if (t > thresh) { terrainFeature = bbTerrainFeature.ARABLE; } } } public void setRandom() { float _val = Random.Range(0.0f, 1.0f); setFromValue(_val); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine.WayfarerSettlementsMVP; public class AgentGenManager : MonoBehaviour { public GameObject PanelAgentStats, pfAgentStats; private Dictionary<Agent, GameObject> agentStatsUI; // Use this for initialization void Start () { TestAgentStatsPanel(); } // Update is called once per frame void Update () { } void TestAgentStatsPanel() { agentStatsUI = new Dictionary<Agent, GameObject>(); List<Agent> agents = GenerateAgents(3); foreach (Agent a in agents) { GameObject go = Instantiate(pfAgentStats, PanelAgentStats.transform); go.GetComponent<AgentStatsUI>().InitializeAgentStatsUI(a); agentStatsUI[a] = go; } } List<Agent> GenerateAgents(int _n) { List<Agent> agents = new List<Agent>(); for (int i = 0; i < _n; i++) { agents.Add(new Agent(i.ToString(), 10f)); } return agents; } public void ClickAgent() { Debug.Log("Clicked!"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class MidpointDisplacement{ public int N, xDim, yDim, Dim, featureSize; public float RandomInfluence; public float[,] Elevation; public MidpointDisplacement(int N) { Dim = (int)Mathf.Pow(2, N) + 1; // This indicates the height and width of the map xDim = Dim; yDim = xDim; RandomInfluence = 1.0f; // R should be between 0.0 and 1.0 featureSize = xDim; // This indicates the intricacy of detail on the map Elevation = new float[xDim, yDim]; // Most functions implicitly refer to this array BuildMap(); // The constructor calls this function to build the map } public void BuildMap() { //RandomizePoints(featureSize); int sampleSize = featureSize; float scale = RandomInfluence; while (sampleSize > 1) { DiamondSquare(sampleSize, scale); sampleSize /= 2; scale /= 2f; } } public void DiamondSquare(int stepsize, float scale) { int halfstep = stepsize / 2; //Debug.Log("Diamond Square on stepsize = " + stepsize + " and scale = " + scale + " and halfstep = " + halfstep); for (int x = halfstep; x < xDim - halfstep; x += stepsize) { for (int y = halfstep; y < yDim - halfstep; y += stepsize) { SquareStep(x, y, stepsize, GetRandom(scale)); } } for (int x = halfstep; x < xDim - halfstep; x += stepsize) { for (int y = halfstep; y < yDim - halfstep; y += stepsize) { DiamondStep(x + halfstep, y, stepsize, GetRandom(scale)); DiamondStep(x, y + halfstep, stepsize, GetRandom(scale)); } } } public void SquareStep(int x, int y, int size, float randomValue) { //Debug.Log("Square Step on [" + x + "," + y + "]"); int hs = size / 2; // a b // // x // // c d List<float> validPoints = new List<float>(); validPoints.Add(GetValueAt(x - hs, y - hs)); validPoints.Add(GetValueAt(x + hs, y - hs)); validPoints.Add(GetValueAt(x - hs, y + hs)); validPoints.Add(GetValueAt(x + hs, y + hs)); float midpointDisplacedValue = validPoints.Average() + randomValue; SetValue(x, y, midpointDisplacedValue); } public void DiamondStep(int x, int y, int size, float randomValue) { //Debug.Log("Diamond Step on [" + x + "," + y + "]"); int hs = size / 2; // c // //a x b // // d List<float> validPoints = new List<float>(); validPoints.Add(GetValueAt(x - hs, y)); validPoints.Add(GetValueAt(x + hs, y)); validPoints.Add(GetValueAt(x, y - hs)); validPoints.Add(GetValueAt(x, y + hs)); float midpointDisplacedValue = validPoints.Average() + randomValue; SetValue(x, y, midpointDisplacedValue); } public static void GetCoordinates(int xDim, int yDim, int _X, int _Y, out int X, out int Y) { X = (1000 * xDim + _X) % xDim; Y = (1000 * yDim + _Y) % yDim; } public float GetValueAt(int _X, int _Y) { int X, Y; GetCoordinates(xDim, yDim, _X, _Y, out X, out Y); return Elevation[X, Y]; } public void SetValue(int _X, int _Y, float v) { int X, Y; GetCoordinates(xDim, yDim, _X, _Y, out X, out Y); Elevation[X, Y] = v; //Debug.Log("Setting [" + X + "," + Y + "] to " + v); } public static float GetRandom(float coeff) { float r = (Random.Range(0, 100) - 50) / 100f; return r * coeff; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine; using SamizdatEngine.GE; using SamizdatEngine.GE.Basic; public class TestScript : MonoBehaviour { public GameObject goDrawer; GEDrawerBasic drawer; // Use this for initialization void Start () { TileShape tileShape = TileShape.SQUARE; Loc loci = new Loc(0, 0); Loc locj = new Loc(5, 5); Intersection i = new IntersectionBasic(loci, tileShape); Intersection j = new IntersectionBasic(locj, tileShape); drawer = goDrawer.GetComponentInChildren<GEDrawerBasic>(); //Vector3 vi = new Vector3(i.pos.gameLoc.x, i.pos.gameLoc.y+1, i.pos.gameLoc.z); //Vector3 vj = new Vector3(j.pos.gameLoc.x, j.pos.gameLoc.y+1, j.pos.gameLoc.z); Vector3 vi = i.pos.gameLoc; Vector3 vj = j.pos.gameLoc; drawer.InstantiateGo(drawer.pfIntersection, vi, Color.black); drawer.InstantiateGo(drawer.pfIntersection, vj, Color.black); drawer.DrawLine(i.pos.gameLoc, j.pos.gameLoc, Color.white); } // Update is called once per frame void Update () { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine; public interface IDrawer { void Init(); void DrawFrame(); void DrawTakeTurn(); IGame game { get; set; } } public interface IPos { Loc gridLoc { get; set; } // the location on a "square grid" Loc mapLoc { get; set; } // the location in physical space ie same for squares, but hex' mapLoc is offset on odd rows, etc. Vector3 gameLoc { get; set; } // the location in game space List<IPos> neighbors { get; set; } } public class GridPos : IPos { public Loc gridLoc { get; set; } // the location on a "square grid" public Loc mapLoc { get; set; } // the location in physical space ie same for squares, but hex' mapLoc is offset on odd rows, etc. public Vector3 gameLoc { get; set; } // the location in game space public List<IPos> neighbors { get; set; } public IGame game { get; set; } public GridPos(Loc _gridLoc, IGame _game) { game = _game; gridLoc = _gridLoc; } } public enum PosType { GridPos} public static class PosFactory { public static IPos CreatePos(Loc _gridLoc, IGame _game) { if (_game.posType == PosType.GridPos) { return new GridPos(_gridLoc, _game); } else { return new GridPos(_gridLoc, _game); } } } public interface ILand { IPos pos { get; set; } Color GetColor(); } public enum TerrainType { LAND, OCEAN, MOUNTAIN} public abstract class LandAbstract { public IPos pos { get; set; } public LandAbstract(IPos _pos) { pos = _pos; } } public class LandBasic : LandAbstract, ILand { public Color GetColor() { Color c = Color.magenta; if (terrainType == TerrainType.OCEAN) { c = Color.blue; } else if (terrainType == TerrainType.MOUNTAIN) { c = Color.black; } else { c = Color.gray; } return c; } TerrainType terrainType { get; set; } public LandBasic(IPos _pos, float val) : base(_pos) { SetTerrainType(val); } public void SetTerrainType(float val, float TERRAIN_LEVEL = 0.25f) { terrainType = TerrainType.LAND; if (val < TERRAIN_LEVEL) { terrainType = TerrainType.OCEAN; } else if (val > (1 - TERRAIN_LEVEL)) { terrainType = TerrainType.MOUNTAIN; } } } public class ExodusLand : LandAbstract , ILand { public IPos pos { get; set; } int iLand; public ExodusLand(IPos _pos, float _elevation, float _temperature) : base(_pos) { if (_elevation < 0.5f) { if (_temperature < 0.5f) { iLand = 1; } else { iLand = 2; } } else { if (_temperature < 0.5f) { iLand = 3; } else { iLand = 4; } } } public Color GetColor() { Color c = Color.magenta; if (iLand == 1) { c = Color.red; } else if (iLand == 2) { c = Color.blue; } else if (iLand == 3) { c = Color.green; } else if (iLand == 4) { c = Color.yellow; } return c; } } public enum LandType { BasicLand, ExodusLand}; public static class LandFactory { public static ILand CreateLand(IPos _pos, Dictionary<string,float> _val, LandType _landType) { if (_landType == LandType.BasicLand) { return new LandBasic(_pos, _val["elevation"]); } else if (_landType == LandType.ExodusLand) { return new ExodusLand(_pos, _val["elevation"], _val["temperature"]); } else { return new LandBasic(_pos, _val["elevation"]); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; namespace SamizdatEngine { public enum TileShape { SQUARE, HEX }; public class Pos { public Loc gridLoc { get; set; } // the location on a "square grid" public Loc mapLoc { get; set; } // the location in physical space ie same for squares, but hex' mapLoc is offset on odd rows, etc. public List<Pos> neighbors { get; set; } public Vector3 gameLoc { get { return (new Vector3(mapLoc.x(), mapLoc.z(), mapLoc.y())); } set { } } public static float DistanceMinkowski(Pos p1, Pos p2, float d = 2) { float pSum = 0f; for (int i = 0; i < p1.mapLoc.coordinates.Length; i++) { pSum += Mathf.Pow(Mathf.Abs(p1.mapLoc.coordinates[i] - p2.mapLoc.coordinates[i]), d); } return Mathf.Pow(pSum, (1 / d)); } public static float DistancePath(Pos p1, Pos p2) { List<Pos> path = Pathfinder.findAStarPath(p1, p2); float d = 0f; for (int i = 1; i < path.Count; i++) { d += path[i].getMoveToCost(path[i - 1]); } return d; } public static int EdgeCount(Pos p, int[] dims) { int count = 0; for (int i = 0; i < dims.Length; i++) { if (p.gridLoc.coordinates[i] == 0 || p.gridLoc.coordinates[i] == (dims[i]-1)) { count++; } } return count; } public Pos(Loc _loc, TileShape _tileShape) { gridLoc = _loc; neighbors = new List<Pos>(); setMapLoc(_tileShape); } public void setMapLoc(TileShape _tileShape) { switch (_tileShape) { case TileShape.SQUARE: mapLoc = new Loc(gridLoc.coordinates); break; case TileShape.HEX: float x = Mathf.Sqrt(3) * (gridLoc.x() - 0.5f * (gridLoc.y() % 2f)) / 1.9f; float y = (3 / 2) * gridLoc.y() / 1.3f; mapLoc = new Loc(x, y); break; } } public float getMoveToCost(Pos moveFrom) { if (neighbors.Contains(moveFrom)) { float distance = DistanceMinkowski(this, moveFrom); return distance; } else { return float.PositiveInfinity; } } public List<Pos> findPath(Pos pathTarget) { List<Pos> path = Pathfinder.findAStarPath(this, pathTarget); return path; } public void Write() { Debug.Log(getName()); } public string getName() { return "[" + gridLoc.x() + "," + gridLoc.y() + "]"; } public Pos GetThisPos() { return this; } } public static class Pathfinder { public static List<Pos> findAStarPath(Pos start, Pos end, int maxIter = 100000) { Dictionary<Pos, float> DistanceFromStart = new Dictionary<Pos, float>(); Dictionary<Pos, float> DistanceToEnd = new Dictionary<Pos, float>(); Dictionary<Pos, Pos> FastestPath = new Dictionary<Pos, Pos>(); List<Pos> Searched = new List<Pos>(); List<Pos> path = new List<Pos>(); if (start != end) { // Create the queue of pos to check List<Pos> nextStep = new List<Pos>(); // Add start pos' neighbors to queue foreach (Pos p in start.neighbors) { DistanceFromStart[p] = p.getMoveToCost(start); DistanceToEnd[p] = Pos.DistanceMinkowski(p, end); FastestPath[p] = start; nextStep.Add(p); } bool pathFound = false; int iter = 0; while (!pathFound && iter < maxIter) { // Order queue by distance nextStep = nextStep.OrderBy(p => DistanceFromStart[p] + DistanceToEnd[p]).ToList(); // Pull next pos to search Pos thisStep = nextStep[0]; //Debug.Log("thisStep is at " + thisStep.loc.x + " , " + thisStep.loc.y); // Mark pos as searched Searched.Add(thisStep); if (thisStep.neighbors.Contains(end)) { pathFound = true; Pos p = end; float newPathCost = p.getMoveToCost(thisStep) + DistanceFromStart[thisStep]; if (!DistanceFromStart.ContainsKey(p) || newPathCost < DistanceFromStart[p]) { DistanceFromStart[p] = newPathCost; FastestPath[p] = thisStep; } if (DistanceToEnd.ContainsKey(p)) { DistanceToEnd[p] = Pos.DistanceMinkowski(p, end); } } else { foreach (Pos p in thisStep.neighbors) { float newPathCost = p.getMoveToCost(thisStep) + DistanceFromStart[thisStep]; if (!DistanceFromStart.ContainsKey(p) || newPathCost < DistanceFromStart[p]) { DistanceFromStart[p] = newPathCost; FastestPath[p] = thisStep; } if (!DistanceToEnd.ContainsKey(p)) { DistanceToEnd[p] = Pos.DistanceMinkowski(p, end); } if (!nextStep.Contains(p) && !Searched.Contains(p)) { nextStep.Add(p); //Debug.Log("Added to nextStep Pos at " + p.loc.x + " , " + p.loc.y); } } nextStep.Remove(thisStep); //Debug.Log("Removed from nextStep Pos at " + thisStep.loc.x + " , " + thisStep.loc.y); } iter++; } //Debug.Log("Completed with " + iter + " / " + maxIter + " iterations."); Pos pathStep = end; while (pathStep != start) { path.Add(pathStep); if (FastestPath.ContainsKey(pathStep)) { pathStep = FastestPath[pathStep]; } else { return null; } } path.Add(start); path.Reverse(); } return path; } } public struct Loc { public float[] coordinates; public Loc(float _x, float _y, float _z) { coordinates = new float[] { _x, _y, _z }; } public Loc(float _x, float _y) { coordinates = new float[] { _x, _y}; } public Loc(float[] _coordinates) { coordinates = _coordinates; } public Loc(string _locKey) { coordinates = _locKey.Split(',').Select(x => float.Parse(x)).ToArray(); } public string key() { //return coordinates.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j); string[] k = coordinates.Select(x => x.ToString()).ToArray(); return string.Join(",", k); } public float x() { try { return coordinates[0]; } catch { return 0; } } public float y() { try { return coordinates[1]; } catch { return 0; } } public float z() { try { return coordinates[2]; } catch { return 0; } } public static Loc SquareToCube(Loc squareLoc) { float x = squareLoc.y() - (squareLoc.x() - (squareLoc.x() % 2f)) / 2f; float z = squareLoc.x(); float y = -x - z; return new Loc(x, y, z); } public static Loc CubeToSquare(Loc cubeLoc) { float x = cubeLoc.z(); float y = cubeLoc.x() + (cubeLoc.z() - (cubeLoc.z() % 2f)) / 2; return new Loc(x, y); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using BBMVP; public class bbUIHandler : MonoBehaviour { public BaseBuilderMVP game; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public bool HandleUserInput() { bool updateMouse = HandleMouse(); bool updateKeys = HandleKeys(); return updateMouse || updateKeys; } bool HandleClick() { bool updateClick = false; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray); if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1)) { foreach (RaycastHit hit in hits) { bbClickable clicked = hit.transform.gameObject.GetComponentInParent<bbClickable>(); if (clicked != null) { //Debug.Log("Clicked " + clicked.pos.gridLoc.key()); updateClick = game.HandleClick(clicked.pos, Input.GetMouseButtonUp(0), Input.GetMouseButtonUp(1)); } // Debug.Log("Hovering " + clicked.pos.gridLoc.key()); } } return updateClick; } void HandleScroll() { var d = Input.GetAxis("Mouse ScrollWheel"); if (d > 0f) { Camera.main.GetComponent<Camera>().orthographicSize -= 1; } else if (d < 0f) { Camera.main.GetComponent<Camera>().orthographicSize += 1; } } public bool HandleMouse() { HandleScroll(); return HandleClick(); } public bool HandleKeys() { bool updateKey = false; if (Input.GetKeyUp("space")) { game.paused = !game.paused; updateKey = true; } if (Input.GetKey("w")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x, p.y, p.z + 1); } if (Input.GetKey("s")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x, p.y, p.z - 1); } if (Input.GetKey("a")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x-1, p.y, p.z); } if (Input.GetKey("d")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x + 1, p.y, p.z); } return updateKey; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; namespace BBMVP { public class bbPos { public bbLoc gridLoc; public bbLoc mapLoc; public List<bbPos> neighbors; public BaseBuilderMVP game; public bbPos(bbLoc _loc, BaseBuilderMVP _game) { gridLoc = _loc; game = _game; setMapLoc(game.tileShape); neighbors = new List<bbPos>(); } public void setMapLoc(TileShape _tileShape) { switch (_tileShape) { case TileShape.SQUARE: mapLoc = new bbLoc(gridLoc.coordinates); break; case TileShape.HEX: float x = Mathf.Sqrt(3) * (gridLoc.x() - 0.5f * (gridLoc.y() % 2f)) / 1.9f; float y = (3 / 2) * gridLoc.y() / 1.3f; mapLoc = new bbLoc(x, y); break; } } public static float DistanceMinkowski(bbPos p1, bbPos p2, float d = 2) { float pSum = 0f; for (int i = 0; i < p1.mapLoc.coordinates.Length; i++) { pSum += Mathf.Pow(Mathf.Abs(p1.mapLoc.coordinates[i] - p2.mapLoc.coordinates[i]), d); } return Mathf.Pow(pSum, (1 / d)); } public static float DistancePath(bbPos p1, bbPos p2) { List<bbPos> path = bbPathfinder.findAStarPath(p1, p2); float d = 0f; for (int i = 1; i < path.Count; i++) { d += path[i].getMoveToCost(path[i - 1]); } return d; } public float getMoveToCost(bbPos moveFrom) { if (game.currentIsland.lands[this].terrainType == bbTerrainType.MOUNTAIN || game.currentIsland.lands[this].terrainType == bbTerrainType.OCEAN) { return float.PositiveInfinity; } else if (neighbors.Contains(moveFrom)) { float distance = DistanceMinkowski(this, moveFrom); return distance; } else { return float.PositiveInfinity; } } public List<bbPos> findPath(bbPos pathTarget) { List<bbPos> path = bbPathfinder.findAStarPath(this, pathTarget); return path; } public bbStructure findClosestStructureByRange(bbStructureType structureType) { List<bbStructure> structuresOfType = getStructuresOfType(structureType); float minDistance = float.PositiveInfinity; bbStructure closestStructure = structuresOfType[0]; foreach (bbStructure s in structuresOfType) { float sDistance = DistanceMinkowski(this, s.getPos()); if (sDistance < minDistance) { minDistance = sDistance; closestStructure = s; } } return closestStructure; } public bool findClosestStructureByPath(bbStructureType structureType, ref bbStructure closestStructure) { List<bbStructure> structuresOfType = getStructuresOfType(structureType); if (structuresOfType.Count != 0) { closestStructure = structuresOfType[0]; float minDistance = float.PositiveInfinity; foreach (bbStructure s in structuresOfType) { float sDistance = DistancePath(this, s.getPos()); if (sDistance < minDistance) { minDistance = sDistance; closestStructure = s; } } return true; } else { return false; } } List<bbStructure> getStructuresOfType(bbStructureType structureType) { List<bbStructure> structuresOfType = new List<bbStructure>(); foreach (bbStructure s in game.currentIsland.structures.Values) { if (s.getType() == structureType) { structuresOfType.Add(s); } } return structuresOfType; } public void Write() { Debug.Log(getName()); } public string getName() { return "[" + gridLoc.x() + "," + gridLoc.y() + "]"; } } public static class bbPathfinder { public static List<bbPos> findAStarPath(bbPos start, bbPos end, int maxIter = 100000) { Dictionary<bbPos, float> DistanceFromStart = new Dictionary<bbPos, float>(); Dictionary<bbPos, float> DistanceToEnd = new Dictionary<bbPos, float>(); Dictionary<bbPos, bbPos> FastestPath = new Dictionary<bbPos, bbPos>(); List<bbPos> Searched = new List<bbPos>(); List<bbPos> path = new List<bbPos>(); if (start != end) { // Create the queue of pos to check List<bbPos> nextStep = new List<bbPos>(); // Add start pos' neighbors to queue foreach (bbPos p in start.neighbors) { DistanceFromStart[p] = p.getMoveToCost(start); DistanceToEnd[p] = bbPos.DistanceMinkowski(p, end); FastestPath[p] = start; nextStep.Add(p); } bool pathFound = false; int iter = 0; while (!pathFound && iter < maxIter) { // Order queue by distance nextStep = nextStep.OrderBy(p => DistanceFromStart[p] + DistanceToEnd[p]).ToList(); // Pull next pos to search bbPos thisStep = nextStep[0]; //Debug.Log("thisStep is at " + thisStep.loc.x + " , " + thisStep.loc.y); // Mark pos as searched Searched.Add(thisStep); if (thisStep.neighbors.Contains(end)) { pathFound = true; bbPos p = end; float newPathCost = p.getMoveToCost(thisStep) + DistanceFromStart[thisStep]; if (!DistanceFromStart.ContainsKey(p) || newPathCost < DistanceFromStart[p]) { DistanceFromStart[p] = newPathCost; FastestPath[p] = thisStep; } if (DistanceToEnd.ContainsKey(p)) { DistanceToEnd[p] = bbPos.DistanceMinkowski(p, end); } } else { foreach (bbPos p in thisStep.neighbors) { float newPathCost = p.getMoveToCost(thisStep) + DistanceFromStart[thisStep]; if (!DistanceFromStart.ContainsKey(p) || newPathCost < DistanceFromStart[p]) { DistanceFromStart[p] = newPathCost; FastestPath[p] = thisStep; } if (!DistanceToEnd.ContainsKey(p)) { DistanceToEnd[p] = bbPos.DistanceMinkowski(p, end); } if (!nextStep.Contains(p) && !Searched.Contains(p)) { nextStep.Add(p); //Debug.Log("Added to nextStep Pos at " + p.loc.x + " , " + p.loc.y); } } nextStep.Remove(thisStep); //Debug.Log("Removed from nextStep Pos at " + thisStep.loc.x + " , " + thisStep.loc.y); } iter++; } //Debug.Log("Completed with " + iter + " / " + maxIter + " iterations."); bbPos pathStep = end; while (pathStep != start) { path.Add(pathStep); if (FastestPath.ContainsKey(pathStep)) { pathStep = FastestPath[pathStep]; } else { return null; } } path.Add(start); path.Reverse(); } return path; } } public struct bbLoc { public float[] coordinates; public bbLoc(float _x, float _y, float _z = 0) { coordinates = new float[] { _x, _y, _z }; } public bbLoc(float[] _coordinates) { coordinates = _coordinates; } public bbLoc(string _locKey) { coordinates = _locKey.Split(',').Select(x => float.Parse(x)).ToArray(); } public string key() { //return coordinates.Select(a => a.ToString()).Aggregate((i, j) => i + "," + j); string[] k = coordinates.Select(x => x.ToString()).ToArray(); return string.Join(",", k); } public float x() { try { return coordinates[0]; } catch { return 0; } } public float y() { try { return coordinates[1]; } catch { return 0; } } public float z() { try { return coordinates[2]; } catch { return 0; } } public static bbLoc SquareToCube(bbLoc squareLoc) { float x = squareLoc.y() - (squareLoc.x() - (squareLoc.x() % 2f)) / 2f; float z = squareLoc.x(); float y = -x - z; return new bbLoc(x, y, z); } public static bbLoc CubeToSquare(bbLoc cubeLoc) { float x = cubeLoc.z(); float y = cubeLoc.x() + (cubeLoc.z() - (cubeLoc.z() % 2f)) / 2; return new bbLoc(x, y); } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Globalization; using BBMVP; public class BaseBuilderMVPManager : MonoBehaviour { // Game BaseBuilderMVP game; // GameRenderer public bbDrawer drawer; // UI public bbUIHandler uihandler; // Constants // Use this for initialization void Start () { game = new BaseBuilderMVP(); game.gameManager = this; drawer.game = game; uihandler.game = game; } // Update is called once per frame void Update () { if (game.turnNumber == 0) { game.turnNumber++; drawer.DrawInit(); } drawer.Animate(); if (NeedsUpdate()) { drawer.DrawTakeTurn(); } } bool NeedsUpdate() { bool updateRealtime = game.RealTimeTurn(); bool updateClick = uihandler.HandleMouse(); bool updateKey = uihandler.HandleKeys(); return updateRealtime || updateClick || updateKey; } // UI public void Button_TakeTurn() { game.TakeTurn(); drawer.DrawTakeTurn(); } public void Button_TogglePause() { game.paused = !game.paused; drawer.UpdateButtons(); } public void Button_ToggleSelectedAction() { game.ToggleAction(); drawer.UpdateButtons(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BBMVP { public enum bbStructureType { STRUCTURE_HQ, STRUCTURE_MINE, STRUCTURE_FARM, STRUCTURE_HOUSE, STRUCTURE_CONSTRUCTION }; public interface bbStructure { Color getColor(); bbPos getPos(); bbStructureType getType(); bool UseStructure(bbAgent a); void TakeTurn(); } public static class bbStructureFactory { public static bbStructure GenerateStructure(bbStructureType _type, bbPos _pos, ClickType _clickType) { if (_type == bbStructureType.STRUCTURE_HQ) { return new bbStructureHQ(_type, _pos); } else if (_type == bbStructureType.STRUCTURE_MINE) { return new bbStructureMine(_type, _pos); } else if (_type == bbStructureType.STRUCTURE_FARM) { return new bbStructureFarm(_type, _pos); } else if (_type == bbStructureType.STRUCTURE_HOUSE) { return new bbStructureHouse(_type, _pos); } else if (_type == bbStructureType.STRUCTURE_CONSTRUCTION) { return new bbStructureConstruction(_type, _pos, _clickType); } else { return new bbStructureEx(_type, _pos); } } } public abstract class bbStructureBasic { public bbPos pos; public bbStructureType structureType; public bbPos getPos() { return pos; } public bbStructureType getType() { return structureType; } public virtual Color getColor() { return Color.black; } public virtual void TakeTurn() { } } public class bbStructureDummy : bbStructureBasic, bbStructure { public bbStructureDummy() { } public bool UseStructure(bbAgent a) { return true; } } public class bbStructureConstruction : bbStructureBasic, bbStructure { ClickType clickType; public bbStructureConstruction(bbStructureType _type, bbPos _pos, ClickType _clickType) { pos = _pos; structureType = _type; clickType = _clickType; } public override Color getColor() { return Color.magenta; } public bool UseStructure(bbAgent a) { // replace this with the structure pos.game.currentIsland.structures.Remove(pos); pos.game.currentIsland.AddStructure(getStructureTypeFromClickType(), pos.gridLoc.x(), pos.gridLoc.y(), clickType); return true; } bbStructureType getStructureTypeFromClickType() { if (clickType == ClickType.BUILD_FARM) { return bbStructureType.STRUCTURE_FARM; } else if (clickType == ClickType.BUILD_MINE) { return bbStructureType.STRUCTURE_MINE; } else if (clickType == ClickType.BUILD_HOUSE) { return bbStructureType.STRUCTURE_HOUSE; } else { return bbStructureType.STRUCTURE_CONSTRUCTION; } } } public class bbStructureHQ : bbStructureBasic, bbStructure { public bbStructureHQ(bbStructureType _type, bbPos _pos) { pos = _pos; structureType = _type; } public bool UseStructure(bbAgent a) { return a.Deposit(); } public override Color getColor() { return Color.blue; } } public class bbStructureFarm : bbStructureResource, bbStructure { public bbStructureFarm(bbStructureType _type, bbPos _pos) { pos = _pos; structureType = _type; hasResource = false; } public override bool UseStructure(bbAgent a) { hasResource = false; jobQueued = false; return a.Collect(ItemType.ITEM_FOOD); } } public class bbStructureMine : bbStructureResource, bbStructure { public bbStructureMine(bbStructureType _type, bbPos _pos) { pos = _pos; structureType = _type; hasResource = false; } public override bool UseStructure(bbAgent a) { hasResource = false; jobQueued = false; return a.Collect(ItemType.ITEM_GOLD); } } public abstract class bbStructureResource : bbStructureBasic, bbStructure { public bool hasResource; public bool jobQueued; int resourceTimer = 0; int resourceCooldown = 50; public abstract bool UseStructure(bbAgent a); public override void TakeTurn() { if (!hasResource) { resourceTimer++; if (resourceTimer >= resourceCooldown) { resourceTimer = 0; hasResource = true; jobQueued = false; } } if (hasResource && !jobQueued) { pos.game.gameManager.drawer.DrawEffectResource(this); List<bbJob> jobQueue = new List<bbJob>(); bbJobMoveTo moveToHere = new bbJobMoveTo(getPos()); jobQueue.Add(moveToHere); bbJobUseStructure useThis = new bbJobUseStructure(this); jobQueue.Add(useThis); bbStructure trystruct = new bbStructureDummy(); if (pos.findClosestStructureByPath(bbStructureType.STRUCTURE_HQ, ref trystruct)) { bbStructure hq = trystruct; bbJobMoveTo moveToHQ = new bbJobMoveTo(hq.getPos()); jobQueue.Add(moveToHQ); bbJobUseStructure useHQ = new bbJobUseStructure(hq); jobQueue.Add(useHQ); } pos.game.playerJobQueue.Add(jobQueue); jobQueued = true; } } public override Color getColor() { return hasResource ? Color.black : Color.white; } } public class bbStructureHouse : bbStructureBasic, bbStructure { bool spawned; public bbStructureHouse(bbStructureType _type, bbPos _pos) { pos = _pos; structureType = _type; spawned = false; } public override void TakeTurn() { if (!spawned) { spawned = true; bbAgent newAgent = new bbAgent("Agent" + (1 + pos.game.playerAgents.Count), pos, pos.game, this); pos.game.playerAgents.Add(newAgent); } } public bool UseStructure(bbAgent a) { if (pos.game.playerResources[ItemType.ITEM_FOOD] >= a.needQuantity[ItemType.ITEM_FOOD]) { pos.game.playerResources[ItemType.ITEM_FOOD] -= a.needQuantity[ItemType.ITEM_FOOD]; a.needTimer[ItemType.ITEM_FOOD] = 50; a.needsAddressing.Remove(ItemType.ITEM_FOOD); return true; } else { a.alive = false; Debug.Log(a.name + " died of starvation"); return false; } } public override Color getColor() { return Color.red; } } public class bbStructureEx : bbStructureBasic, bbStructure { public bbStructureEx(bbStructureType _structureType, bbPos _pos) { structureType = _structureType; pos = _pos; } public bool UseStructure(bbAgent a) { return true; } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Linq; //https://www.codeproject.com/Articles/1221034/Pathfinding-Algorithms-in-Csharp public class Node { public MapLoc loc; public int x, y; public Dictionary<Node, float> neighborWeights; public List<Node> neighbors; public Dictionary<MapLoc, float> distanceTo; public Dictionary<MapLoc, float> distanceFrom; public Dictionary<MapLoc, Node> NearestTo; public Dictionary<PathOD, float> distanceBetween; public bool Visited; public int iRegion; public Node(int _x, int _y) { x = _x; y = _y; loc = new MapLoc(_x, _y); distanceTo = new Dictionary<MapLoc, float>(); distanceFrom = new Dictionary<MapLoc, float>(); distanceBetween = new Dictionary<PathOD, float>(); neighbors = new List<Node>(); NearestTo = new Dictionary<MapLoc, Node>(); neighborWeights = new Dictionary<Node, float>(); } } public struct PathOD { public MapLoc origin, destination; public PathOD(MapLoc _origin, MapLoc _destination) { origin = _origin; destination = _destination; } } public struct Path { public MapLoc originMapLoc, destinationMapLoc; public float distancePath, distanceEuclidean; public List<Node> path; public Path(MapLoc _origin, MapLoc _destination, List<Node> _path, float _distancePath, float _distanceEuclidean) { originMapLoc = _origin; destinationMapLoc = _destination; distancePath = _distancePath; distanceEuclidean = _distanceEuclidean; path = _path; } } public class MapPathfinder { List<Node> nodelist = new List<Node>(); public Dictionary<MapLoc, Node> nodeDict = new Dictionary<MapLoc, Node>(); public Dictionary<PathOD, Path> PathDict = new Dictionary<PathOD, Path>(); public MapPathfinder() { } public void SetNodeList(float[,] _elevation, float _seaLevel, delCost fCost, float _seaTravelCost = 0f) { int xDim = _elevation.GetLength(0); int yDim = _elevation.GetLength(1); Node[,] nodes = new Node[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { nodes[x, y] = new Node(x, y); nodeDict[new MapLoc(x, y)] = nodes[x, y]; } } for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Node n = nodes[x, y]; n.Visited = false; MapLoc l = new MapLoc(x, y); Dictionary<MapLoc, float> d = MapUtil.GetValidNeighbors(_elevation, l); foreach (KeyValuePair<MapLoc, float> kvp in d) { n.neighborWeights[nodes[kvp.Key.x, kvp.Key.y]] = fCost(l,kvp.Key,_elevation,_seaLevel,_seaTravelCost); n.neighbors.Add(nodes[kvp.Key.x, kvp.Key.y]); } nodelist.Add(n); } } } public void SetNodeList(List<Node> _nodes) { nodelist = _nodes; foreach (Node n in nodelist) { nodeDict[n.loc] = n; } } public Path GetPath(MapLoc origin, MapLoc destination) { PathOD p = new PathOD(origin, destination); bool pathFound = false; if (!PathDict.ContainsKey(p)) { pathFound = AStarSearch(origin, destination); } return PathDict[p]; } private bool AStarSearch(MapLoc origin, MapLoc destination) { List<Node> prioQueue; bool PathFound = false; AStarInit(out prioQueue, origin, destination); while (prioQueue.Any()) { AStarWorkhorse(ref prioQueue, ref PathFound, origin, destination); } if (PathFound) { AddPath(origin, destination); } return PathFound; } private void AStarInit(out List<Node> prioQueue, MapLoc originMapLoc, MapLoc destinationMapLoc) { foreach (Node n in nodelist) { n.distanceTo[destinationMapLoc] = MapUtil.Distance(n.loc, destinationMapLoc); } nodeDict[originMapLoc].distanceFrom[originMapLoc] = 0f; prioQueue = new List<Node>(); prioQueue.Add(nodeDict[originMapLoc]); } private void AStarWorkhorse(ref List<Node> prioQueue, ref bool PathFound, MapLoc originMapLoc, MapLoc destinationMapLoc) { prioQueue = prioQueue.OrderBy(x => x.distanceFrom[originMapLoc] + x.distanceTo[destinationMapLoc]).ToList(); Node n = prioQueue.First(); prioQueue.Remove(n); foreach (Node neighbor in n.neighbors) { if (!neighbor.Visited) { float newCost = n.distanceFrom[originMapLoc] + n.neighborWeights[neighbor]; if (!neighbor.distanceFrom.ContainsKey(originMapLoc) || newCost < neighbor.distanceFrom[originMapLoc]) // this will cause problems if there is ever no cost between nodes! { neighbor.distanceFrom[originMapLoc] = newCost; neighbor.NearestTo[originMapLoc] = n; if (!prioQueue.Contains(neighbor)) { prioQueue.Add(neighbor); } } } } n.Visited = true; if (n.loc.Equals(destinationMapLoc)) { PathFound = true; } } private void AddPath(MapLoc origin, MapLoc destination, bool addBetweenPaths = false) { float dP = 0f; List<Node> shortestPath = new List<Node>(); Node thisNode = nodeDict[destination]; shortestPath.Add(thisNode); while (!thisNode.loc.Equals(origin)) { dP += thisNode.neighborWeights[thisNode.NearestTo[origin]]; thisNode = thisNode.NearestTo[origin]; shortestPath.Add(thisNode); } shortestPath.Reverse(); float dE = MapUtil.Distance(origin, destination); Path p = new Path(origin, destination, shortestPath, dP, dE); PathDict[new PathOD(origin, destination)] = p; if (addBetweenPaths) { List<PathOD> betweenPaths = new List<PathOD>(); int iWindow = shortestPath.Count - 2; while (iWindow > 0) { for (int i = 0; i < (shortestPath.Count - iWindow); i++) { PathOD betweenPath = new PathOD(shortestPath[i].loc, shortestPath[i + iWindow].loc); betweenPaths.Add(betweenPath); } iWindow--; } foreach (PathOD pOD in betweenPaths) { AddPath(pOD.origin, pOD.destination, false); } } } public delegate float delCost(MapLoc l, MapLoc n, float[,] _elevation, float _seaLevel, float _seaTravelCost); public static float CostStandard(MapLoc l, MapLoc n, float[,] _elevation, float _seaLevel, float _seaTravelCost) { float nelev = _elevation[n.x, n.y]; float lelev = _elevation[l.x, l.y]; float diff = (nelev > _seaLevel && lelev > _seaLevel) ? Math.Abs(nelev - lelev) : _seaTravelCost; float dist = MapUtil.Distance(n, l); diff *= dist; diff += dist; return diff; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SamizdatEngine.Linguistics { public class Linguistics { public static List<string> AllConsonants() { return new List<string> {"B","C","D","F","G","H","J","K","L","M","N","P","R","S","T","SH","CH","TH"}; } public static List<string> AllVowels() { return new List<string> {"A","AE","E","EE", "EA", "I", "IA", "AI", "IE", "EI","O","OO", "OA", "AO", "OE", "EO", "OI", "IO", "U", "UE", "UI", "UA", "AU", "OU"}; } public static List<string> SelectSubset(List<string> list, int n) { List<string> subset = new List<string>(); int len = list.Count; for (int i = 0; i < len; i++) { float r = Random.Range(0.0f, 1.0f); if (r < n / (len - i)) { subset.Add(list[i]); if (subset.Count == n) { break; } } } return subset; } public static List<string> GenerateWordsBasic(int nWords) { int nMorphemes = 50; List<string> morphemes = GenerateMorphemes(nMorphemes); List<string> words = new List<string>(); for (int i = 0; i < nWords; i++) { string newWord = morphemes[Random.Range(0, morphemes.Count)] + morphemes[Random.Range(0, morphemes.Count)]; words.Add(newWord); } return words; } public static List<string> GenerateMorphemes(int nMorphemes) { int nVowelSounds = 5; int nConsonantSounds = 10; float pConsonantStart = 0.5f; float pConsonantEnd = 0.5f; List<string> vowels = SelectSubset(AllVowels(), nVowelSounds); List<string> consonants = SelectSubset(AllConsonants(), nConsonantSounds); List<string> morphemes = new List<string>(); for (int i = 0; i < nMorphemes; i++) { morphemes.Add(GenerateMorpheme(consonants, vowels, pConsonantStart, pConsonantEnd)); } return morphemes; } public static string GenerateMorpheme(List<string> consonants, List<string> vowels, float pConsonantStart, float pConsonantEnd) { string morpheme = ""; float rStart = Random.Range(0.0f, 1.0f); float rEnd = Random.Range(0.0f, 1.0f); if (rStart < pConsonantStart) { morpheme += consonants[Random.Range(0, consonants.Count)]; } morpheme += vowels[Random.Range(0, vowels.Count)]; if (rEnd < pConsonantEnd) { morpheme += consonants[Random.Range(0, consonants.Count)]; } return morpheme; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BBMVP { public interface bbJob { void doJobTurn(bbAgent agent); bool checkJobComplete(bbAgent agent); } public class bbJobMoveTo : bbJob { bbPos target; List<bbPos> path; public bbJobMoveTo(bbPos _target) { target = _target; } public void doJobTurn(bbAgent _agent) { path = _agent.pos.findPath(target); if (path != null && path.Count != 0) { if (_agent.pos == path[0]) { path.Remove(_agent.pos); } _agent.lastPos = _agent.pos; _agent.pos = path[0]; } } public bool checkJobComplete(bbAgent _agent) { if (_agent.pos == target) { return true; } else { return false; } } } public class bbJobUseStructure : bbJob { bbStructure structure; bool jobComplete; public bbJobUseStructure(bbStructure _structure) { structure = _structure; jobComplete = false; } public bool checkJobComplete(bbAgent agent) { return jobComplete; } public void doJobTurn(bbAgent agent) { if (structure.getPos() == agent.pos) { jobComplete = structure.UseStructure(agent); } else { bbJobMoveTo move = new bbJobMoveTo(structure.getPos()); agent.jobQueue.Insert(0, move); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace SamizdatEngine.WayfarerSettlementsMVP { public class AgentStatsUI : MonoBehaviour { public GameObject Icon, StatsPanelName, StatsPanelValues, pfText; private Dictionary<Stat, GameObject> statsName, statsValue; private GameObject iconText, abilityTextName, abilityTextDescription; private Agent agent; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void Click() { Debug.Log("Clicked "+agent.Describe()); } public void InitializeAgentStatsUI(Agent _agent) { agent = _agent; Icon.AddComponent<Button>(); Icon.GetComponent<Button>().onClick.AddListener(() => Click()); Icon.GetComponent<Image>().color = agent.color; statsName = new Dictionary<Stat, GameObject>(); statsValue = new Dictionary<Stat, GameObject>(); iconText = Instantiate(pfText, Icon.transform); List<Stat> theseStats = Agent.GetAllStats(); foreach (Stat s in theseStats) { statsName[s] = Instantiate(pfText, StatsPanelName.transform); statsValue[s] = Instantiate(pfText, StatsPanelValues.transform); statsName[s].GetComponent<Text>().alignment = TextAnchor.MiddleRight; statsValue[s].GetComponent<Text>().alignment = TextAnchor.MiddleLeft; } abilityTextName = Instantiate(pfText, StatsPanelName.transform); abilityTextName.GetComponent<Text>().alignment = TextAnchor.MiddleRight; abilityTextDescription = Instantiate(pfText, StatsPanelValues.transform); abilityTextDescription.GetComponent<Text>().alignment = TextAnchor.MiddleLeft; UpdateAgentStatsUI(); } public void UpdateAgentStatsUI() { iconText.GetComponent<Text>().text = "Icon"; Text t = abilityTextName.GetComponent<Text>(); t.text = "Ability: "; t.fontStyle = FontStyle.Italic; Text t2 = abilityTextDescription.GetComponent<Text>(); t2.text = "-"; t2.fontStyle = FontStyle.Italic; List<Stat> theseStats = Agent.GetAllStats(); foreach (Stat s in theseStats) { float f = 0f; if (agent.stats.ContainsKey(s)) { f = agent.stats[s]; } statsName[s].GetComponent<Text>().text = s.ToString() + ": "; statsValue[s].GetComponent<Text>().text = Mathf.Round(f).ToString(); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MapPainter { List<Node> nodelist = new List<Node>(); Dictionary<MapLoc, Node> nodedict = new Dictionary<MapLoc, Node>(); Dictionary<int, List<MapLoc>> areas = new Dictionary<int, List<MapLoc>>(); List<MapLoc>[] landbodies; List<MapLoc>[] waterbodies; int xDim, yDim; float[,] elevation; float seaLevel; public MapPainter(float[,] _elevation, float _seaLevel) { nodelist = new List<Node>(); elevation = _elevation; seaLevel = _seaLevel; xDim = _elevation.GetLength(0); yDim = _elevation.GetLength(1); Node[,] nodes = new Node[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { nodes[x, y] = new Node(x, y); } } for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Node n = nodes[x, y]; n.Visited = false; MapLoc l = new MapLoc(x, y); Dictionary<MapLoc, float> d = MapUtil.GetValidNeighbors(_elevation, l); foreach (KeyValuePair<MapLoc, float> kvp in d) { if ((_elevation[x, y] > _seaLevel && _elevation[kvp.Key.x, kvp.Key.y] > _seaLevel) || (_elevation[x, y] < _seaLevel && _elevation[kvp.Key.x, kvp.Key.y] < _seaLevel)) { n.neighborWeights[nodes[kvp.Key.x, kvp.Key.y]] = MapUtil.Distance(kvp.Key, l); n.neighbors.Add(nodes[kvp.Key.x, kvp.Key.y]); } } nodelist.Add(n); nodedict[n.loc] = n; } } Paint(); } public void Paint() { int iColor = 0; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { MapLoc l = new MapLoc(x, y); Node n = nodedict[l]; iColor = n.Visited ? iColor : iColor + 1; AssignColorToNodeAndNeighbors(n, iColor); } } BuildAreasDictionaries(); } public void AssignColorToNodeAndNeighbors(Node n, int iColor) { if (!n.Visited) { n.Visited = true; n.iRegion = iColor; foreach (Node neighbor in n.neighbors) { AssignColorToNodeAndNeighbors(neighbor, iColor); } } } public void BuildAreasDictionaries() { for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { MapLoc l = new MapLoc(x, y); Node n = nodedict[l]; int iColor = n.iRegion; if (!areas.ContainsKey(iColor)) { areas[iColor] = new List<MapLoc>(); } areas[iColor].Add(l); } } List<List<MapLoc>> waterBodies = new List<List<MapLoc>>(); List<List<MapLoc>> landBodies = new List<List<MapLoc>>(); foreach (KeyValuePair<int,List<MapLoc>> kvp in areas) { int iColor = kvp.Key; List<MapLoc> locsInArea = kvp.Value; MapLoc l0 = locsInArea[0]; float e = elevation[l0.x, l0.y]; if (e > seaLevel) { landBodies.Add(locsInArea); } else { waterBodies.Add(locsInArea); } } waterbodies = waterBodies.ToArray(); landbodies = landBodies.ToArray(); } public float[,] BuildRegions() { float[,] regions = new float[xDim, yDim]; foreach (Node n in nodelist) { regions[n.loc.x, n.loc.y] = (float)n.iRegion; } return regions; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine; using SamizdatEngine.GE; using System.Linq; namespace SamizdatEngine.GE.Basic { public class GoEsqueBasic : GoEsque { enum TurnOutcome { SUCESS, FAILURE }; public TileShape tileShape { get; set; } public List<Player> players { get; set; } public Player currentPlayer { get; set; } public GEDrawer drawer { get; set; } public GEUI uihandler { get; set; } //public RuleManager ruler { get; set; } public int turn { get; set; } public int[] dims { get; set; } public Dictionary<int, string> serialization; public Dictionary<string, Intersection> intersections { get; set; } public Dictionary<Intersection, Stone> stones { get; set; } List<string> serializations = new List<string>(); bool gameRunning = true; bool territoryView = false; Dictionary<Player,bool> playerPassed; public void Pass() { if (gameRunning) { Debug.Log(currentPlayer.name + " Passed"); if (AllPlayersPassed()) { EndGame(); } else { playerPassed[currentPlayer] = true; AdvanceTurn(); } } } bool AllPlayersPassed() { bool allPassed = true; foreach (Player p in players) { if (playerPassed[p] == false) { allPassed = false; break; } } return allPassed; } void EndGame() { Debug.Log("End Game"); gameRunning = false; } public void ClickPos(Pos p) { if (gameRunning) { Intersection i = intersections[p.gridLoc.key()]; TurnOutcome outcome = TryPlay(i); if (outcome == TurnOutcome.SUCESS) { playerPassed[currentPlayer] = false; AdvanceTurn(); } } } public GoEsqueBasic(GEDrawer _drawer, GEUI _geui) { //ruler = new RuleManagerBasic(this); intersections = new Dictionary<string, Intersection>(); stones = new Dictionary<Intersection, Stone>(); serialization = new Dictionary<int, string>(); tileShape = TileShape.HEX; drawer = _drawer; uihandler = _geui; //InitializeGame(new int[] { 19, 19 }); InitializeGame(new int[] { 9, 9 }); } void InitializeGame(int[] _dims) { dims = _dims; SetIntersections(); SetNeighbors(); SetPlayers(); } void SetPlayers() { players = new List<Player>(); players.Add(new PlayerBasic("B", Color.black)); players.Add(new PlayerBasic("W", Color.white)); currentPlayer = players[0]; playerPassed = new Dictionary<Player, bool>(); foreach (Player p in players) { playerPassed[p] = false; } } void SetIntersections() { for (int x = 0; x < dims[0]; x++) { for (int y = 0; y < dims[1]; y++) { Loc newLoc = new Loc(x, y); IntersectionBasic initIntersection = new IntersectionBasic(newLoc, tileShape); intersections[newLoc.key()] = initIntersection; } } } void SetNeighbors() { foreach (Intersection i in intersections.Values) { if (tileShape == TileShape.SQUARE) { i.neighbors = SetNeighborsSquare(i, intersections, false); } else { i.neighbors = SetNeighborsHex(i, intersections); } } } public void TerritoryView() { territoryView = !territoryView; if (territoryView) { //Debug.Log("Territory View Toggled On"); Dictionary<Intersection, Player> territories = GetTerritories(); Dictionary<Player, int> score = new Dictionary<Player, int>(); foreach (Player p in players) { score[p] = p.capturedStones.Count; } foreach (Player p in territories.Values) { score[p]++; } foreach (Player p in score.Keys) { Debug.Log(p.name + " has " + score[p] + "points"); } drawer.SetTerritoryColors(territories); //Debug.Log("There are " + territories.Count + " territories with owners"); } else { drawer.SetBasicColors(); //Debug.Log("Territory View Toggled Off"); } } List<Stone> GetDeadStones() { //Debug.Log("Getting Dead Stones"); List<Stone> deadStones = new List<Stone>(); foreach (Stone s in stones.Values) { if (!s.IsAlive()) { deadStones.Add(s); } } return deadStones; } void AdvanceTurn() { int ci = (1 + players.IndexOf(currentPlayer)) % players.Count; currentPlayer = players[ci]; } TurnOutcome TryPlay(Intersection p) { if (!IllegalSpace(p)) { StoneBasic tryStone = new StoneBasic(p, this); if (IllegalMove(tryStone, p)) { tryStone.RemoveStoneFromGame(); Debug.Log("Failure"); return TurnOutcome.FAILURE; } else { PlaceStone(tryStone); //Debug.Log("Success"); return TurnOutcome.SUCESS; } } else { Debug.Log("Illegal Space"); return TurnOutcome.FAILURE; } } bool IllegalMove(Stone s, Intersection p) { Debug.Log("Checking illegal"); if (SuicidalMove(s)) { Debug.Log("Suicidal Move"); return true; } else if (KoViolation()) { Debug.Log("Ko Violation"); return true; } else { Debug.Log("Legal Move"); return false; } } bool IllegalSpace(Intersection _intersection) { return _intersection.occupant != null; } bool SuicidalMove(Stone s) { List<Stone> killedStones = GetDeadStones(); Dictionary<Player, List<Stone>> playerDeadStones = new Dictionary<Player, List<Stone>>(); foreach (Player p in players) { playerDeadStones[p] = killedStones.Where(k => k.player == p).ToList(); } if (!playerDeadStones.ContainsKey(currentPlayer) || playerDeadStones[currentPlayer].Count == 0) { return false; } foreach (Player p in players) { if (p != currentPlayer) { if (playerDeadStones.ContainsKey(p) && playerDeadStones[p].Count > 0) { return false; } } } return true; } bool KoViolation() { bool violation = false; string s = SerializeState(); if (serializations.Count > 0) { Debug.Log("Checking for " + s + " in " + serializations[serializations.Count - 1]); } violation = serializations.Contains(s); serializations.Add(SerializeState()); return violation; } string SerializeState() { List<string> series = new List<string>(); int xDim = dims[0]; int yDim = dims[1]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Loc l = new Loc(x, y); Intersection i = intersections[l.key()]; if (i.occupant != null) { series.Add(i.serialize); } } } return string.Join(",", series.ToArray()); } void PlaceStone(Stone s) { //Debug.Log("Placing Stone" + s.player + ";"+ s.intersection.serialize); List<Stone> killedStones = GetDeadStones().Where((x) => x.player != s.player).ToList(); Debug.Log("After " + s.intersection.serialize + ", #DeadStones = " + killedStones.Count.ToString()); foreach (Stone k in killedStones) { k.RemoveStoneFromGame(); } } List<Pos> SetNeighborsSquare(Intersection p, Dictionary<string, Intersection> map, bool _allowDiagonals, bool _wrapEastWest = false, bool _wrapNorthSouth = false) { float x = p.pos.gridLoc.x(); float y = p.pos.gridLoc.y(); List<Pos> neighbors = new List<Pos>(); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (((i != 0 || j != 0) && _allowDiagonals) || ((i != 0 || j != 0) && !(i != 0 && j != 0))) { float X = _wrapEastWest ? (dims[0] + x + i) % dims[0] : x + i; float Y = _wrapNorthSouth ? (dims[1] + y + j) % dims[1] : y + j; Loc l2 = new Loc(X, Y); if (map.ContainsKey(l2.key())) { neighbors.Add(map[l2.key()].pos); } else { //Debug.Log("Map doesn't contain " + l2.x() + "," + l2.y()); } } } } return neighbors; } List<Pos> SetNeighborsHex(Intersection p, Dictionary<string, Intersection> map, bool _wrapEastWest = false, bool _wrapNorthSouth = false) { List<Pos> neighbors = new List<Pos>(); List<int[]> hexNeighbors = new List<int[]>(); if (p.pos.gridLoc.y() % 2 == 0) { hexNeighbors.Add(new int[] { 1, 0 }); hexNeighbors.Add(new int[] { 1, -1 }); hexNeighbors.Add(new int[] { 0, -1 }); hexNeighbors.Add(new int[] { -1, 0 }); hexNeighbors.Add(new int[] { 0, 1 }); hexNeighbors.Add(new int[] { 1, 1 }); } else { hexNeighbors.Add(new int[] { 1, 0 }); hexNeighbors.Add(new int[] { -1, -1 }); hexNeighbors.Add(new int[] { 0, -1 }); hexNeighbors.Add(new int[] { -1, 0 }); hexNeighbors.Add(new int[] { 0, 1 }); hexNeighbors.Add(new int[] { -1, 1 }); } float x = p.pos.gridLoc.x(); float y = p.pos.gridLoc.y(); for (int k = 0; k < hexNeighbors.Count; k++) { int i = hexNeighbors[k][0]; int j = hexNeighbors[k][1]; float X = _wrapEastWest ? (dims[0] + x + i) % dims[0] : x + i; float Y = _wrapNorthSouth ? (dims[1] + y + j) % dims[1] : y + j; Loc l2 = new Loc(X, Y); if (map.ContainsKey(l2.key())) { neighbors.Add(map[l2.key()].pos); } else { Debug.Log("Map doesn't contain " + l2.x() + "," + l2.y()); } } return neighbors; } public Dictionary<Intersection, Player> GetTerritories() { Dictionary<Intersection, Player> territories = new Dictionary<Intersection, Player>(); foreach (Intersection i in intersections.Values) { List<Intersection> area = i.GetArea(); Player p = GetTerritoryOwner(area); if (p!= null) { territories[i] = p; } } return territories; } Player GetTerritoryOwner(List<Intersection> area) { Player owner = null; List<Player> stoneNeighbors = new List<Player>(); foreach (Intersection i in area) { foreach (Intersection j in i.neighbors) { if (j.occupant != null && !stoneNeighbors.Contains(j.occupant.player)) { stoneNeighbors.Add(j.occupant.player); } } } if (stoneNeighbors.Count == 1) { owner = stoneNeighbors[0]; } return owner; } } public class PlayerBasic : Player { public string name { get; set; } public Color color { get; set; } public List<Stone> capturedStones { get; set; } public bool passed { get; set; } public PlayerBasic(string _name, Color _color) { name = _name; color = _color; capturedStones = new List<Stone>(); passed = false; } } public class IntersectionBasic : Pos, Intersection { public Pos pos { get { return GetThisPos(); } } public Stone occupant { get; set; } public IntersectionBasic(Loc _loc, TileShape _tileShape) : base(_loc, _tileShape) { occupant = null; } public string serialize { get { string s = "[" + gridLoc.x() + "," + gridLoc.y() + ":" + (occupant != null ? occupant.player.name : "NULL") + "]"; return s; } } public List<Intersection> GetArea() { List<Intersection> area = new List<Intersection>(); this.GetAreaWorkhorse(ref area); return area; } public void GetAreaWorkhorse(ref List<Intersection> area) { if (!area.Contains(this) && occupant == null) { area.Add(this); foreach (Intersection i in this.neighbors) { if (i.occupant == null) { i.GetAreaWorkhorse(ref area); } } } } } public class StoneBasic : Stone { public Player player { get; set; } int liberties; public Intersection intersection { get; set; } public string serialize { get { return intersection.serialize; } } GoEsque game; public bool IsAlive() { List<Stone> Group = new List<Stone>(); GetGroup(ref Group); Debug.Log(serialize + "'s group has #" + Group.Count); bool Alive = false; foreach (Stone s in Group) { if (s.StoneIsAlive(s.GetAttackers())) { Alive = true; } } return Alive; } public bool StoneIsAlive(List<Stone> attackers) { int d = 0; foreach (Stone attacker in attackers) { d += attacker.Attack(this); } bool alive = d < liberties ? true : false; //Debug.Log(intersection.serialize + " is " + (alive ? "alive" : "dead") + ":" + d + " < "+liberties+"?"); return alive; } public void GetGroup(ref List<Stone> Group) { if (!Group.Contains(this)) { //Debug.Log("Adding " + serialize + " to the group"); Group.Add(this); foreach (Intersection i in intersection.neighbors) { if (i.occupant != null && i.occupant.player == this.player) { i.occupant.GetGroup(ref Group); } } } } public int Attack(Stone s) { return 1; } public List<Stone> GetAttackers() { List<Stone> attackers = new List<Stone>(); foreach (Intersection i in intersection.neighbors) { if (i.occupant != null) { attackers.Add(i.occupant); } } return attackers; } public StoneBasic(Intersection _intersection, GoEsque _game) { intersection = _intersection; liberties = intersection.neighbors.Count - Pos.EdgeCount(intersection.pos, _game.dims); Stone stone = this; _game.stones[intersection] = stone; _game.intersections[intersection.pos.gridLoc.key()].occupant = stone; game = _game; player = game.currentPlayer; } public void RemoveStoneFromGame() { Debug.Log("Removing " + intersection.serialize); game.stones.Remove(intersection); game.intersections[intersection.pos.gridLoc.key()].occupant = null; game.currentPlayer.capturedStones.Add(this); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public static class TemperatureBuilder { public static float[,] BuildTemperature(float[,] Elevation, float seaLevel, float elevationWeight = 0.5f, Benchmark bench = null) { if (!(bench == null)) { bench.StartBenchmark("Temperature"); } int xDim = Elevation.GetLength(0); int yDim = Elevation.GetLength(1); float Center = (yDim - 1) / 2f; float[,] Temp = new float[xDim, yDim]; float distanceFromCenterRatio; for (int y = 0; y < yDim; y++) { distanceFromCenterRatio = Mathf.Abs(Center - y)/Center; for (int x = 0; x < xDim; x++) { Temp[x, y] = GetTemp(Elevation[x, y], elevationWeight, seaLevel, distanceFromCenterRatio); } } MapUtil.TransformMapMinMax(ref Temp, MapUtil.dNormalize); if (!(bench == null)) { bench.EndBenchmark("Temperature"); } return Temp; } private static float GetTemp(float elevation, float elevationWeight, float seaLevel, float distanceFromCenterRatio) { float d = (1 - distanceFromCenterRatio); float e = elevation > seaLevel ? MapUtil.dNormalize(elevation, seaLevel, 1f, 1f, 0f) : 1f; if (true) { d = (float)Math.Pow(d,1.5); e = (float)Math.Pow(e,1.5); } float t = elevationWeight * e + (1 - elevationWeight) * d; return t; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; using System.IO; using System.Text; using System; public class Benchmark { Dictionary<string, List<DateTime>> startTimes; Dictionary<string, List<DateTime>> endTimes; Dictionary<string, TimeSpan> averageTime; Dictionary<string, TimeSpan> totalTime; Dictionary<string, int> numberOfBenchmarks; string BenchmarkFamilyName; int PadN = 30; public Benchmark(string _BenchmarkFamilyName) { BenchmarkFamilyName = _BenchmarkFamilyName; startTimes = new Dictionary<string, List<DateTime>>(); endTimes = new Dictionary<string, List<DateTime>>(); averageTime = new Dictionary<string, TimeSpan>(); totalTime = new Dictionary<string, TimeSpan>(); numberOfBenchmarks = new Dictionary<string, int>(); } public static void Start(Benchmark b, string s) { if (b != null) { b.StartBenchmark(s); } } public static void End(Benchmark b, string s) { if (b != null) { b.EndBenchmark(s); } } public static void Write(Benchmark b, string s) { if (b != null) { b.WriteBenchmarkToDebug(); } } public void StartBenchmark(string MarkName) { if (!startTimes.ContainsKey(MarkName)) { startTimes[MarkName] = new List<DateTime>(); } startTimes[MarkName].Add(DateTime.Now); } public void EndBenchmark(string MarkName) { if (!endTimes.ContainsKey(MarkName)) { endTimes[MarkName] = new List<DateTime>(); } endTimes[MarkName].Add(DateTime.Now); } private void TabulateBenchmarks() { foreach (KeyValuePair<string, List<DateTime>> kvp in startTimes) { int NumberOfBenchmarks = 0; string keyString = kvp.Key; //Debug.Log("Tabulating " + keyString); totalTime[keyString] = TimeSpan.Zero; for (int i = 0; i < kvp.Value.Count(); i++) { TimeSpan elapsedTime = endTimes[keyString][i] - startTimes[keyString][i]; totalTime[keyString] += elapsedTime; NumberOfBenchmarks++; } averageTime[keyString] = new TimeSpan(totalTime[keyString].Ticks / NumberOfBenchmarks); numberOfBenchmarks[keyString] = NumberOfBenchmarks; } } private List<string> BenchmarkText() { TabulateBenchmarks(); List<string> BenchLines = new List<string>(); string LineString = new string('-', PadN - 5); string[] titles = new string[] { "Benchmark Family", "Benchmark Name", "Total Time", "Average Time", "Number" }; string titleString = ""; string headerString = ""; foreach (string title in titles) { titleString += title.PadRight(PadN); headerString += LineString.PadRight(PadN); } BenchLines.Add("Current Time:" + DateTime.Now.ToString()); BenchLines.Add(titleString); BenchLines.Add(headerString); foreach (KeyValuePair<string, TimeSpan> kvp in totalTime) { string k = kvp.Key; string totalTimeString = FormatTimespan(totalTime[k]); string averageTimeString = FormatTimespan(averageTime[k]); string MiddleString = BenchmarkFamilyName.PadRight(PadN); MiddleString += k.PadRight(PadN); MiddleString += totalTimeString.PadRight(PadN); MiddleString += averageTimeString.PadRight(PadN); MiddleString += numberOfBenchmarks[k].ToString().PadRight(PadN); BenchLines.Add(MiddleString); } BenchLines.Add(headerString); BenchLines.Add(""); return BenchLines; } public void WriteBenchmarkToDebug() { List<string> tlines = BenchmarkText(); foreach (string t in tlines) { Debug.Log(t); } } public string FormatTimespan(TimeSpan ts) { return ts.Hours.ToString() + ":" + ts.Minutes.ToString() + ":" + ts.Seconds.ToString() + ":" + ts.Milliseconds.ToString(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BBMVP { public class bbIsland { public BaseBuilderMVP game; public Dictionary<string, bbPos> pathMap; public Dictionary<bbPos, bbStructure> structures; public Dictionary<bbPos, bbLand> lands; public int dim; bool wrapEastWest, wrapNorthSouth; public bbIsland(BaseBuilderMVP _game, int N = 5) { wrapEastWest = true; wrapNorthSouth = true; dim = 1 + (int)Mathf.Pow(2, N); game = _game; pathMap = GenerateBasicMap(dim); lands = InitializeLandsFromMidpointDisplacement(N, pathMap); //lands = InitializeLandsFromMapGen(N, pathMap); structures = new Dictionary<bbPos, bbStructure>(); } Dictionary<bbPos, bbLand> InitializeLandsFromMapGen(int _N, Dictionary<string, bbPos> pm) { Dictionary<bbPos, bbLand> landsDict = new Dictionary<bbPos, bbLand>(); MapGen map = new MapGen(dim, dim); map.GenerateMap(); float[,] elevation = map.Elevation; MapUtil.TransformMapMinMax(ref elevation, MapUtil.dNormalize); foreach (bbPos p in pm.Values) { bbLand newLand = new bbLand(p); newLand.setFromValue(elevation[(int)p.gridLoc.x(), (int)p.gridLoc.y()]); landsDict[p] = newLand; } return landsDict; } Dictionary<bbPos, bbLand> InitializeLandsFromMidpointDisplacement(int _N, Dictionary<string, bbPos> pm) { Dictionary<bbPos, bbLand> landsDict = new Dictionary<bbPos, bbLand>(); MidpointDisplacement mpd = new MidpointDisplacement(_N, wrapEastWest, wrapNorthSouth); float[,] elevation = mpd.Elevation; MapUtil.TransformMapMinMax(ref elevation, MapUtil.dNormalize); foreach (bbPos p in pm.Values) { bbLand newLand = new bbLand(p); newLand.setFromValue(elevation[(int)p.gridLoc.x(), (int)p.gridLoc.y()]); landsDict[p] = newLand; } return landsDict; } Dictionary<bbPos, bbLand> InitializeLandsRandom(Dictionary<string, bbPos> pm) { Dictionary<bbPos, bbLand> landsDict = new Dictionary<bbPos, bbLand>(); foreach (bbPos p in pm.Values) { bbLand newLand = new bbLand(p); newLand.setRandom(); landsDict[p] = newLand; } return landsDict; } void InitializeDummyStructures(int _dim) { structures = new Dictionary<bbPos, bbStructure>(); AddStructure(bbStructureType.STRUCTURE_HQ, 1, 1, game.currentClickType); AddStructure(bbStructureType.STRUCTURE_MINE, _dim - 2, _dim - 2, game.currentClickType); AddStructure(bbStructureType.STRUCTURE_HOUSE, 1, _dim - 2, game.currentClickType); AddStructure(bbStructureType.STRUCTURE_HOUSE, 3, _dim - 4, game.currentClickType); AddStructure(bbStructureType.STRUCTURE_FARM, _dim - 2, 1, game.currentClickType); } public void AddStructure(bbStructureType t, float x, float y, ClickType _clickType) { bbLoc l = new bbLoc(x, y); bbStructure s = bbStructureFactory.GenerateStructure(t, pathMap[l.key()], _clickType); structures[s.getPos()] = s; //Debug.Log("Added Structure at " + s.getPos().getName()); } public Dictionary<string, bbPos> GenerateBasicMap(int _dim) { Dictionary<string, bbPos> map = Generate2DGrid(_dim); map = SetNeighborsFor2DGrid(map, _dim, game.tileShape, wrapEastWest, wrapNorthSouth); return map; } private Dictionary<string, bbPos> Generate2DGrid(int _dim) { Dictionary<string, bbPos> map = new Dictionary<string, bbPos>(); for (int x = 0; x < _dim; x++) { for (int y = 0; y < _dim; y++) { bbLoc l = new bbLoc(x, y); bbPos p = new bbPos(l, game); map[p.gridLoc.key()] = p; } } return map; } List<bbPos> SetNeighborsSquare(bbPos p, Dictionary<string, bbPos> map, int _dim, bool _wrapEastWest = false, bool _wrapNorthSouth = false) { float x = p.gridLoc.x(); float y = p.gridLoc.y(); List<bbPos> neighbors = new List<bbPos>(); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (i != 0 || j != 0) { float X = _wrapEastWest ? (_dim + x + i) % _dim : x + i; float Y = _wrapNorthSouth ? (_dim + y + j) % _dim : y + j; bbLoc l2 = new bbLoc(X, Y); if (map.ContainsKey(l2.key())) { neighbors.Add(map[l2.key()]); } else { Debug.Log("Map doesn't contain " + l2.x() + "," + l2.y()); } } } } return neighbors; } List<bbPos> SetNeighborsHex(bbPos p, Dictionary<string, bbPos> map, int _dim, bool _wrapEastWest = false, bool _wrapNorthSouth = false) { List<bbPos> neighbors = new List<bbPos>(); List<int[]> hexNeighbors = new List<int[]>(); if (p.gridLoc.y() % 2 == 0) { hexNeighbors.Add(new int[] { 1, 0 }); hexNeighbors.Add(new int[] { 1, -1 }); hexNeighbors.Add(new int[] { 0, -1 }); hexNeighbors.Add(new int[] { -1, 0 }); hexNeighbors.Add(new int[] { 0, 1 }); hexNeighbors.Add(new int[] { 1, 1 }); } else { hexNeighbors.Add(new int[] { 1, 0 }); hexNeighbors.Add(new int[] { -1, -1 }); hexNeighbors.Add(new int[] { 0, -1 }); hexNeighbors.Add(new int[] { -1, 0 }); hexNeighbors.Add(new int[] { 0, 1 }); hexNeighbors.Add(new int[] { -1, 1 }); } float x = p.gridLoc.x(); float y = p.gridLoc.y(); for (int k = 0; k < hexNeighbors.Count; k++) { int i = hexNeighbors[k][0]; int j = hexNeighbors[k][1]; float X = _wrapEastWest ? (_dim + x + i) % _dim : x + i; float Y = _wrapNorthSouth ? (_dim + y + j) % _dim : y + j; bbLoc l2 = new bbLoc(X, Y); if (map.ContainsKey(l2.key())) { neighbors.Add(map[l2.key()]); } else { Debug.Log("Map doesn't contain " + l2.x() + "," + l2.y()); } } return neighbors; } private Dictionary<string, bbPos> SetNeighborsFor2DGrid(Dictionary<string, bbPos> map, int _dim, TileShape tileShape, bool _wrapEastWest = false, bool _wrapNorthSouth = false) { foreach (string k in map.Keys) { bbPos p = map[k]; if (tileShape == TileShape.SQUARE) { p.neighbors = SetNeighborsSquare(p, map, _dim, _wrapEastWest, _wrapNorthSouth); } else if (tileShape == TileShape.HEX) { p.neighbors = SetNeighborsHex(p, map, _dim, _wrapEastWest, _wrapNorthSouth); } } return map; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine.GE.Basic; namespace SamizdatEngine.GE { public class GEUIBasic : MonoBehaviour, GEUI { public GoEsque game { get; set; } public void HandleUI() { HandleMouse(); HandleKeys(); } void HandleMouse() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray); if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1)) { foreach (RaycastHit hit in hits) { GEClickable clicked = hit.transform.gameObject.GetComponentInParent<GEClickable>(); if (clicked != null) { //Debug.Log("Clicked " + clicked.pos.gridLoc.key()); game.ClickPos(clicked.pos); game.drawer.Draw(); } // Debug.Log("Hovering " + clicked.pos.gridLoc.key()); } } var d = Input.GetAxis("Mouse ScrollWheel"); if (d > 0f) { Camera.main.GetComponent<Camera>().orthographicSize -= 1; } else if (d < 0f) { Camera.main.GetComponent<Camera>().orthographicSize += 1; } } void HandleKeys() { if (Input.GetKeyUp("space")) { } if (Input.GetKey("w")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x, p.y, p.z + 1); } if (Input.GetKey("s")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x, p.y, p.z - 1); } if (Input.GetKey("a")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x - 1, p.y, p.z); } if (Input.GetKey("d")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x + 1, p.y, p.z); } } public void ClickPass() { game.Pass(); } public void TerritoryView() { game.TerritoryView(); } } }<file_sep>using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using UnityEngine; using System.Linq; /// <summary> /// TO DO: MapGen - Continents: Create Map by running mapgen multiple times, creating a different continent each time /// TO DO: Elevation - Fill Depressions: Planchon-Darboux algorithm /// TO DO: Elevation - Add Spikey Blob Masks: https://azgaar.wordpress.com/2017/04/01/heightmap/ /// TO DO: MapPainter - Display View that fills in different colors for different areas /// TO DO: Intermediate Colors - find a simple package w/ 20-30 colors instead of only 8. /// TO DO: Animate Generation - waits are tough in unity, so this is hard until i learn that /// TO DO: Simple City growth algorithm: each city w/ an empty neighbor builds a new city at that location which maximizes resources [f(waterFlux,Temp)] and minimizes costs [f(distance from new loc to all existing cities)] /// </summary> public enum WaterBodyPrefence { None, Islands, Continent, Lakes, Coast }; public class MapGen { public Benchmark bench; public int xDim, yDim, iExpand; public float[,] Elevation, Rain, WaterFlux, Temperature, WindMagnitude, Regions, Flatness, Fertility, Harbor; public Vec[,] WindVector, Downhill; public float seaLevel, riverLevel, iceLevel; public float percentSea, percentRiver; public ElevationBuilder elevationBuilder; public RainBuilder RainBuilder; public FlowBuilder flowBuilder; WaterBodyPrefence prefWaterBody = WaterBodyPrefence.Continent; // Use this for initialization public MapGen(int _xDim, int _yDim, int _iExpand = 1, float _percentSea = 0.5f, float _percentRiver = 0.01f) { xDim = _xDim; yDim = _yDim; iExpand = _iExpand; seaLevel = 0.5f; riverLevel = 0.5f; iceLevel = 0.3f; percentRiver = _percentRiver; percentSea = _percentSea; Elevation = new float[xDim, yDim]; WaterFlux = new float[xDim, yDim]; Rain = new float[xDim, yDim]; Temperature = new float[xDim, yDim]; WindMagnitude = new float[xDim, yDim]; Regions = new float[xDim, yDim]; Flatness = new float[xDim, yDim]; Fertility = new float[xDim, yDim]; Harbor = new float[xDim, yDim]; } // GENERATION public void GenerateMap() { bench = new Benchmark("Generate Map"); Benchmark outerBench = new Benchmark("Enitre Gen"); outerBench.StartBenchmark("Entire Gen"); CreateElevation(); ApplyPreferencesWaterBody(); CreateElevationAdjustments(35,0.5f); CreateRain(RainMethod.Wind); CreateFluxErosion(3,30); PaintRegions(); bench.WriteBenchmarkToDebug(); outerBench.EndBenchmark("Entire Gen"); outerBench.WriteBenchmarkToDebug(); } public void ApplyPreferencesWaterBody() { MapUtil.TransformApplyPreferencesWaterBody(ref Elevation, seaLevel, prefWaterBody, bench); SetTemperature(); } public void CreateElevation() { Debug.Log("Creating Elevation of Dimensions [" + xDim + "," + yDim + "]"); elevationBuilder = new ElevationBuilder(MapUtil.nFromDims(xDim,yDim)); elevationBuilder.SetElevationWithMidpointDisplacement(iExpand, bench: bench); //elevationBuilder.TrimToDimensions(xDim, yDim); Elevation = elevationBuilder.Elevation; xDim = Elevation.GetLength(0); yDim = Elevation.GetLength(1); Debug.Log("Creating Elevation of Dimensions [" + xDim + "," + yDim + "]"); WaterFlux = new float[xDim, yDim]; Rain = new float[xDim, yDim]; Temperature = new float[xDim, yDim]; WindMagnitude = new float[xDim, yDim]; Regions = new float[xDim, yDim]; Flatness = new float[xDim, yDim]; Fertility = new float[xDim, yDim]; Harbor = new float[xDim, yDim]; SetTemperature(); } public void CreateElevationAdjustments(int iterDepression = 25, float waterPercent = 0.5f) { ResolveDepression(iterDepression, waterPercent); SetTemperature(); // Temp now in case we need it for rain } public void ResolveDepression(int iterDepression = 35, float waterPercent = 0.5f) { MapUtil.TransformResolveDepressions(ref Elevation, iterDepression, bench, false); MapUtil.TransformEqualizeMapByLevel(ref seaLevel, ref Elevation, waterPercent, bench); } public void SetTemperature() { Temperature = TemperatureBuilder.BuildTemperature(Elevation, seaLevel); } public void CreateRain(RainMethod rainMethod) { RainBuilder = new RainBuilder(Elevation,Temperature,seaLevel); RainBuilder.BuildRain(rainMethod, bench); Rain = RainBuilder.Rain; WindMagnitude = RainBuilder.WindMagnitude; WindVector = RainBuilder.WindVectors; } public void CreateFluxErosion(int erosionIterations, int flowIterations) { flowBuilder = new FlowBuilder(Elevation, Rain); WaterFlux = flowBuilder.Flow; RiverErosionLoop(erosionIterations,flowIterations); MapUtil.TransformResolveDepressions(ref Elevation, 1, bench); Temperature = TemperatureBuilder.BuildTemperature(Elevation, seaLevel); Downhill = MapUtil.GetDownhillVectors(Elevation); SetFlatness(); SetFertility(); SetHarbor(); } public void ErosionStep() { ErosionBuilder.HydraulicErosion(Elevation, WaterFlux, 0.3f); } public void FlowStep(int flowIterations) { flowBuilder.FlowStep(flowIterations, bench); MapUtil.TransformMap(ref WaterFlux, MapUtil.dExponentiate, 0.5f, bench); MapUtil.TransformMapMinMax(ref WaterFlux, MapUtil.dNormalize, bench); MapUtil.TransformMapMinMax(ref Elevation, MapUtil.dNormalize, bench); } public void RiverErosionLoop(int erosionIterations, int flowIterations) { for (int i = 0; i < erosionIterations; i++) { FlowStep(flowIterations); ErosionStep(); MapUtil.TransformResolveDepressions(ref Elevation, 10, bench); } MapUtil.TransformMapMinMax(ref Elevation, MapUtil.dNormalize, bench); MapUtil.TransformEqualizeMapByLevel(ref seaLevel, ref Elevation, percentSea, bench); MapUtil.TransformEqualizeMapByLevelAboveSea(ref riverLevel, ref WaterFlux, percentRiver, Elevation, seaLevel); } public void PaintRegions() { MapPainter mp = new MapPainter(Elevation, seaLevel); Regions = mp.BuildRegions(); } public void SetFlatness() { Flatness = MapUtil.GetSlopeMap(Elevation); MapUtil.TransformMapMinMax(ref Flatness, MapUtil.dNormalize); MapUtil.TransformMap(ref Flatness, MapUtil.dInvert, 0f); MapUtil.TransformMap(ref Flatness, MapUtil.dExponentiate, 0.5f); } public void SetFertility() { for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { float fertility = WaterFlux[x,y] * Flatness[x,y] * Mathf.Abs(0.5f - Temperature[x,y]); Fertility[x, y] = fertility; } } MapUtil.TransformMapMinMax(ref Fertility, MapUtil.dNormalize); MapUtil.TransformMap(ref Fertility, MapUtil.dExponentiate, 0.5f); } public void SetHarbor() { for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (Elevation[x, y] > seaLevel && WaterFlux[x, y] < riverLevel) { int adjacentOceanCount = 0; Dictionary<Loc, float> neighbors = MapUtil.GetValidNeighbors(Elevation, new Loc(x, y)); foreach (KeyValuePair<Loc, float> kvp in neighbors) { if (kvp.Value < seaLevel) { adjacentOceanCount++; } } if (adjacentOceanCount == 0) { Harbor[x, y] = 0f; } else if (adjacentOceanCount == 1) { Harbor[x, y] = 1f; } else { Harbor[x, y] = 0.5f; } } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class InputHandler : MonoBehaviour { public IGame game; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public bool HandleUserInput() { HandleScrollWheel(); HandleScrollKeys(); bool updateClick = HandleClick(); bool updateKeys = HandleSpace(); return updateClick || updateKeys; } void HandleScrollWheel() { var d = Input.GetAxis("Mouse ScrollWheel"); if (d > 0f) { Camera.main.GetComponent<Camera>().orthographicSize -= 1; } else if (d < 0f) { Camera.main.GetComponent<Camera>().orthographicSize += 1; } } void HandleScrollKeys() { if (Input.GetKey("w")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x, p.y, p.z + 1); } if (Input.GetKey("s")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x, p.y, p.z - 1); } if (Input.GetKey("a")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x - 1, p.y, p.z); } if (Input.GetKey("d")) { Vector3 p = Camera.main.transform.position; Camera.main.transform.position = new Vector3(p.x + 1, p.y, p.z); } } bool HandleClick() { bool updateClick = false; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit[] hits = Physics.RaycastAll(ray); if (Input.GetMouseButtonUp(0) || Input.GetMouseButtonUp(1)) { foreach (RaycastHit hit in hits) { Clickable clicked = hit.transform.gameObject.GetComponentInParent<Clickable>(); if (clicked != null) { updateClick = game.HandleClick(clicked.pos, Input.GetMouseButtonUp(0), Input.GetMouseButtonUp(1)); } } } return updateClick; } bool HandleSpace() { bool updateKey = false; if (Input.GetKeyUp("space")) { //game.paused = !game.paused; updateKey = true; } return updateKey; } } public class Clickable : MonoBehaviour { public IPos pos; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public void setPos(IPos _pos) { pos = _pos; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BBMVP { public enum ItemType { ITEM_GOLD, ITEM_FOOD }; public enum ClickType { NONE, BUILD_MINE, BUILD_FARM, BUILD_HOUSE, SETTLE_HQ, SETTLE_HOUSE }; public enum TileShape { SQUARE, HEX }; public class BaseBuilderMVP { public int STARTING_FOOD = 10; public int STARTING_GOLD = 100; int STRUCTURE_COST = 10; public float timePerTurn = 0.1f; public bbIsland currentIsland; public List<bbAgent> playerAgents; public Dictionary<ItemType, int> playerResources; public List<List<bbJob>> playerJobQueue; public BaseBuilderMVPManager gameManager; //public Agent currentAgent; public ClickType currentClickType; public List<ClickType> availableActions; public bool paused = true; public float nextTurn; public float lastTurn; public int turnNumber; public TileShape tileShape = TileShape.SQUARE; public BaseBuilderMVP() { turnNumber = 0; lastTurn = 0; nextTurn = Time.time + timePerTurn; currentIsland = new bbIsland(this); playerAgents = new List<bbAgent>(); playerResources = new Dictionary<ItemType, int> { { ItemType.ITEM_FOOD, STARTING_FOOD }, { ItemType.ITEM_GOLD, STARTING_GOLD } }; playerJobQueue = new List<List<bbJob>>(); availableActions = new List<ClickType> { ClickType.BUILD_FARM, ClickType.BUILD_MINE, ClickType.BUILD_HOUSE }; currentClickType = availableActions[0]; InitializeSetup(); } public void InitializeSetup() { currentClickType = ClickType.SETTLE_HQ; } public void TakeTurn() { List<bbAgent> dead = new List<bbAgent>(); for (int i = 0; i < playerAgents.Count; i++) { bbAgent agent = playerAgents[i]; agent.takeTurn(); if (!agent.alive) { dead.Add(agent); } } foreach (bbAgent a in dead) { playerAgents.Remove(a); } foreach (bbStructure s in currentIsland.structures.Values) { s.TakeTurn(); } turnNumber++; } public bool RealTimeTurn() { bool needsUpdate = false; if (!paused) { //Debug.Log(Time.time + " < " + nextTurn.ToString() + " ? "); if (Time.time > nextTurn) { TakeTurn(); lastTurn = nextTurn; nextTurn = Time.time + timePerTurn; needsUpdate = true; gameManager.drawer.Animate(); } } return needsUpdate; } public void ToggleAction() { int index = availableActions.FindIndex(x => x == currentClickType); index = (index + 1) % availableActions.Count; currentClickType = availableActions[index]; } public bool HandleClick(bbPos pos, bool leftClick, bool rightClick) { bool clickDidSomething = false; if (leftClick) { if (!currentIsland.structures.ContainsKey(pos)) { if (CheckBuildable(pos)) { if (currentClickType == ClickType.SETTLE_HQ || currentClickType == ClickType.SETTLE_HOUSE) { if (currentClickType == ClickType.SETTLE_HQ) { currentIsland.AddStructure(bbStructureType.STRUCTURE_HQ, pos.gridLoc.x(), pos.gridLoc.y(), currentClickType); currentClickType = ClickType.SETTLE_HOUSE; } else if (currentClickType == ClickType.SETTLE_HOUSE) { currentIsland.AddStructure(bbStructureType.STRUCTURE_HOUSE, pos.gridLoc.x(), pos.gridLoc.y(), currentClickType); currentClickType = ClickType.NONE; paused = false; } clickDidSomething = true; } else if (playerResources[ItemType.ITEM_GOLD] >= STRUCTURE_COST) { playerResources[ItemType.ITEM_GOLD] -= STRUCTURE_COST; ClickType buildingType = ClickType.BUILD_HOUSE; buildingType = currentIsland.lands[pos].terrainFeature == bbTerrainFeature.ARABLE ? ClickType.BUILD_FARM : buildingType; buildingType = currentIsland.lands[pos].terrainFeature == bbTerrainFeature.MINEABLE ? ClickType.BUILD_MINE : buildingType; currentIsland.AddStructure(bbStructureType.STRUCTURE_CONSTRUCTION, pos.gridLoc.x(), pos.gridLoc.y(), buildingType); List<bbJob> jobs = new List<bbJob>(); bbStructure site = currentIsland.structures[pos]; bbJobMoveTo moveToMine = new bbJobMoveTo(site.getPos()); jobs.Add(moveToMine); bbJobUseStructure useMine = new bbJobUseStructure(site); jobs.Add(useMine); playerJobQueue.Add(jobs); clickDidSomething = true; } } } } if (rightClick) { gameManager.drawer.HighlightTile(pos); } return clickDidSomething; } bool SelectAgent(bbPos pos, out bbAgent selectedAgent) { bool clickDidSomething = false; bbAgent agentAtPos; if (GetAgentAtPos(pos, out agentAtPos)) { selectedAgent = agentAtPos; clickDidSomething = true; } else { selectedAgent = null; } return clickDidSomething; } bool CheckBuildable(bbPos pos) { bool buildable = false; if (currentIsland.lands[pos].terrainType == bbTerrainType.LAND) { buildable = true; } return buildable; } bool GetAgentAtPos(bbPos pos, out bbAgent myAgent) { foreach (bbAgent agent in playerAgents) { if (agent.pos == pos) { myAgent = agent; return true; } } myAgent = new bbAgent(); return false; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SamizdatEngine.GE.Basic { public class GEDrawerBasic : MonoBehaviour, GEDrawer { public GameObject pfStone, pfIntersection, pfStarPoint; public GoEsque game { get; set; } public Dictionary<Stone, GameObject> stones { get; set; } public Dictionary<Intersection, GameObject> intersections { get; set; } public void DrawInit(GoEsque _game) { game = _game; stones = new Dictionary<Stone, GameObject>(); intersections = new Dictionary<Intersection, GameObject>(); Draw(); Loc MidLoc = new Loc(Mathf.Ceil(game.dims[0] / 2) - 1, Mathf.Ceil(game.dims[1] / 2) - 1); // Debug.Log(MidLoc.key()); Vector3 p = intersections[game.intersections[MidLoc.key()]].transform.position; if (game.tileShape == TileShape.SQUARE) { Camera.main.transform.position = new Vector3(p.x, 10, p.z); Camera.main.orthographicSize = game.dims[0] / 1.75f; } else { Camera.main.transform.position = new Vector3(p.x * 3 / 2, 10, p.z * 3 / 2); Camera.main.orthographicSize = (3 / 2) * game.dims[0] / 1.75f; } } public void Draw() { DrawStones(); DrawIntersections(); } void DrawStones() { //Debug.Log(game); if (game.stones.Count != 0) { Debug.Log("There are " + game.stones.Count + " stones to draw"); foreach (Stone s in game.stones.Values) { if (!stones.ContainsKey(s)) { Color c = s.player.color; GameObject go = InstantiateGo(pfStone, s.intersection.pos.mapLoc, c); stones[s] = go; } } } List<Stone> CheckStones = new List<Stone>(stones.Keys); foreach (Stone s in CheckStones) { if (!game.stones.ContainsKey(s.intersection)) { Destroy(stones[s]); stones.Remove(s); } } } void DrawIntersections() { drawIntersectionsBase(); drawIntersectionLines(); drawIntersectionStarPoints(); } void drawIntersectionStarPoints() { int c = game.dims[0] > 11 ? 3 : 2; List<Loc> StarPoints = new List<Loc>(); StarPoints.Add(new Loc(c, c)); StarPoints.Add(new Loc(c, game.dims[1] - c - 1)); StarPoints.Add(new Loc(game.dims[0] - c - 1, game.dims[1] - c - 1)); StarPoints.Add(new Loc(game.dims[0] - c - 1, c)); StarPoints.Add(new Loc(Mathf.Ceil(game.dims[1] / 2), c)); StarPoints.Add(new Loc(c, Mathf.Ceil(game.dims[1] / 2))); StarPoints.Add(new Loc(game.dims[0] - c - 1, Mathf.Ceil(game.dims[1] / 2))); StarPoints.Add(new Loc(Mathf.Ceil(game.dims[0] / 2), game.dims[1] - c - 1)); StarPoints.Add(new Loc(Mathf.Ceil(game.dims[0] / 2), Mathf.Ceil(game.dims[1] / 2))); foreach (Loc l in StarPoints) { Vector3 p = game.intersections[l.key()].pos.gameLoc; p = new Vector3(p.x, p.y + 0.01f, p.z); GameObject go = InstantiateGo(pfStarPoint, p, Color.black); } } void drawIntersectionLines() { foreach (Intersection i in game.intersections.Values) { //Debug.Log(i + "'s neighbors count = " + i.neighbors.Count); foreach (Intersection j in i.neighbors) { //Debug.Log("Drawing"); Vector3 posi = intersections[i].transform.position; Vector3 posj = intersections[j].transform.position; posi = new Vector3(posi.x, posi.y+0.01f, posi.z); posj = new Vector3(posj.x, posj.y+0.01f, posj.z); DrawLine(posi, posj, Color.black); } } } void drawIntersectionsBase() { foreach (Intersection i in game.intersections.Values) { if (!intersections.ContainsKey(i)) { intersections[i] = InstantiateGo(pfIntersection, i.pos.mapLoc, Color.gray); intersections[i].GetComponentInChildren<GEClickable>().pos = i.pos; } } } public GameObject InstantiateGo(GameObject pf, Loc l, Color c) { Vector3 pos = new Vector3(l.x(), l.z(), l.y()); GameObject go = Instantiate(pf, pos, Quaternion.identity); go.GetComponentInChildren<Renderer>().material.color = c; return go; } public GameObject InstantiateGo(GameObject pf, Vector3 pos, Color c) { GameObject go = Instantiate(pf, pos, Quaternion.identity); go.GetComponentInChildren<Renderer>().material.color = c; return go; } public void DrawLine(Vector3 start, Vector3 end, Color color) { GameObject myLine = new GameObject(); myLine.transform.position = start; myLine.AddComponent<LineRenderer>(); LineRenderer lr = myLine.GetComponent<LineRenderer>(); lr.material = new Material(Shader.Find("Particles/Alpha Blended Premultiply")); lr.startWidth = 0.1f; lr.endWidth = 0.1f; lr.startColor = color; lr.endColor = color; lr.SetPosition(0, start); lr.SetPosition(1, end); } public void SetBasicColors() { foreach (GameObject go in intersections.Values) { go.GetComponentInChildren<Renderer>().material.color = Color.gray; } } public void SetTerritoryColors(Dictionary<Intersection,Player> territory) { foreach (Intersection i in territory.Keys) { Player p = territory[i]; GameObject go = intersections[i]; go.GetComponentInChildren<Renderer>().material.color = p.color; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine.GE.Basic; namespace SamizdatEngine.GE { public interface GEUI { void HandleUI(); GoEsque game { get; set; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using BBMVP; public class bbDrawer : MonoBehaviour { public GameObject pfTileSquare, pfTileHex, pfAgent, pfStructure, pfButton; public GameObject ScoreGold, ScoreFood; public GameObject buttonPaused, buttonTurn; public GameObject panelAgentStats; public GameObject effectResource; public BaseBuilderMVP game; private GameObject pfTile; Dictionary<bbPos, GameObject> goMap; Dictionary<bbAgent, GameObject> goAgents; Dictionary<bbAgent, GameObject> goAgentStats; Dictionary<bbStructure, GameObject> goStructures; bool init; // Use this for initialization void Start () { goMap = new Dictionary<bbPos, GameObject>(); goAgents = new Dictionary<bbAgent, GameObject>(); goAgentStats = new Dictionary<bbAgent, GameObject>(); goStructures = new Dictionary<bbStructure, GameObject>(); init = false; } public void SetTile() { switch (game.tileShape) { case TileShape.SQUARE: pfTile = pfTileSquare; break; case TileShape.HEX: //pfTile = pfTileSquare; pfTile = pfTileHex; break; } } public void InitCamera() { bbLoc MidLoc = new bbLoc(game.currentIsland.dim / 2 - 1, game.currentIsland.dim / 2 - 1); Vector3 p = goMap[game.currentIsland.pathMap[MidLoc.key()]].transform.position; if (game.tileShape == TileShape.SQUARE) { Camera.main.transform.position = new Vector3(p.x, 1, p.z); Camera.main.orthographicSize = game.currentIsland.dim / 1.75f; } else { Camera.main.transform.position = new Vector3(p.x * 3 / 2, 1, p.z * 3 / 2); Camera.main.orthographicSize = (3 / 2) * game.currentIsland.dim / 1.75f; } } public void DrawInit() { SetTile(); DrawTakeTurn(); if (!init) { init = true; InitCamera(); } } public void DrawTakeTurn() { DrawAgentsUpdate(); DrawStructuresUpdate(); DrawTerrainUpdate(); UpdateResources(); UpdateButtons(); } void DrawTerrainUpdate() { foreach (string k in game.currentIsland.pathMap.Keys) { bbPos p = game.currentIsland.pathMap[k]; if (!goMap.ContainsKey(p)) { goMap[p] = InstantiateGo(pfTile, p.mapLoc, Color.white); goMap[p].GetComponentInChildren<bbClickable>().setPos(game.currentIsland.pathMap[k]); } Renderer r = goMap[p].GetComponentInChildren<Renderer>(); bbLand thisLand = game.currentIsland.lands[p]; if (thisLand.terrainType == bbTerrainType.OCEAN) { r.material.color = Color.blue; } else if (thisLand.terrainType == bbTerrainType.MOUNTAIN) { r.material.color = Color.black; } else { r.material.color = Color.gray; } if (thisLand.terrainFeature == bbTerrainFeature.ARABLE) { r.material.color = Color.green; } else if (thisLand.terrainFeature == bbTerrainFeature.MINEABLE) { r.material.color = Color.yellow; } } } void DrawAgentsUpdate() { foreach (bbAgent a in game.playerAgents) { if (!goAgents.ContainsKey(a)) { goAgents[a] = InstantiateGo(pfAgent, a.pos.mapLoc, a.getColor()); } Vector3 pos = new Vector3(a.pos.mapLoc.x(), a.pos.mapLoc.z(), a.pos.mapLoc.y()); GameObject go = goAgents[a]; go.transform.position = pos; } foreach (bbAgent a in game.playerAgents) { if (!goAgentStats.ContainsKey(a)) { goAgentStats[a] = Instantiate(pfButton, panelAgentStats.transform); } goAgentStats[a].GetComponentInChildren<Text>().text = a.name.ToString() + a.pos.getName(); } List<bbAgent> agents = new List<bbAgent>(goAgents.Keys); foreach (bbAgent a in agents) { if (!game.playerAgents.Contains(a)) { GameObject go = goAgents[a]; Destroy(go); goAgents.Remove(a); } } agents = new List<bbAgent>(goAgentStats.Keys); foreach (bbAgent a in agents) { if (!game.playerAgents.Contains(a)) { GameObject go = goAgentStats[a]; Destroy(go); goAgentStats.Remove(a); } } } void DrawStructuresUpdate() { foreach (bbStructure s in game.currentIsland.structures.Values) { if (!goStructures.ContainsKey(s)) { goStructures[s] = InstantiateGo(pfStructure, s.getPos().mapLoc, s.getColor()); } goStructures[s].GetComponent<Renderer>().material.color = s.getColor(); } List<bbStructure> structures = new List<bbStructure>(goStructures.Keys); foreach (bbStructure s in structures) { if (!game.currentIsland.structures.ContainsValue(s)) { GameObject go = goStructures[s]; Destroy(go); goStructures.Remove(s); } } } GameObject InstantiateGo(GameObject pf, bbLoc l, Color c) { Vector3 pos = new Vector3(l.x(), l.z(), l.y()); GameObject go = Instantiate(pf, pos, Quaternion.identity); go.GetComponentInChildren<Renderer>().material.color = c; return go; } public void UpdateResources() { ScoreGold.GetComponentInChildren<Text>().text = "GOLD:"+game.playerResources[ItemType.ITEM_GOLD].ToString(); ScoreFood.GetComponentInChildren<Text>().text = "FOOD:"+game.playerResources[ItemType.ITEM_FOOD].ToString(); } public void UpdateButtons() { buttonPaused.GetComponentInChildren<Text>().text = game.paused ? "Paused" : "Running"; buttonTurn.GetComponentInChildren<Text>().text = "Turn " + game.turnNumber; } public void DrawEffect(GameObject _effect, Transform t) { GameObject effect = Instantiate(_effect, t) as GameObject; Destroy(effect, 1f); } public void DrawEffectResource(bbStructure s) { DrawEffect(effectResource, goStructures[s].transform); } public void Animate() { if (!game.paused) { foreach (bbAgent a in game.playerAgents) { StartCoroutine(AnimateAgent(a)); } } } IEnumerator AnimateAgent(bbAgent a) { if (!a.animating) { if (goAgents.ContainsKey(a) && goMap.ContainsKey(a.pos)) { a.animating = true; float nextTurn = game.nextTurn; float lastTurn = game.lastTurn; Transform agentTransform = goAgents[a].transform; Transform targetTransform = goMap[a.pos].transform; float percent = 0; while (percent < 1) { if (!goAgents.ContainsKey(a)) { break; } else { percent = Mathf.InverseLerp(lastTurn, nextTurn, Time.time); goAgents[a].transform.position = Vector3.Lerp(agentTransform.position, targetTransform.position, percent); if (percent == 1) { a.animating = false; } } yield return null; } } } } public void HighlightTile(bbPos p) { DrawTerrainUpdate(); goMap[p].GetComponent<Renderer>().material.color = Color.red; foreach (bbPos n in p.neighbors) { goMap[n].GetComponent<Renderer>().material.color = Color.red; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; namespace SamizdatEngine.WayfarerSettlementsMVP { public enum Stat { SCOUT, BUILD, EXTRACT, TRADE }; public enum Ability { }; public class Agent { public static List<Stat> GetAllStats() { return new List<Stat> { Stat.SCOUT, Stat.BUILD, Stat.EXTRACT, Stat.TRADE }; } public Dictionary<Stat, float> stats; public Ability ability; public string name; public Color color; public Agent(string _name, float _power) { stats = InitializeStatsRandomDiscrete(_power); name = _name; color = new Dictionary<string, Color>{ { "0" ,Color.red}, { "1", Color.blue}, { "2", Color.green} }[name]; Debug.Log(Describe()); } public string Describe() { string d = name + " - "; List<string> statstring = new List<string>(); foreach (Stat s in GetAllStats()) { statstring.Add("[" + s.ToString() + ":" + (Mathf.Round(stats[s])).ToString() + "]"); } d += string.Join(",", statstring.ToArray()); return d; } public Dictionary<Stat, float> InitializeStatsRandomContinuous(float _power) { Dictionary<Stat, float> initStats = new Dictionary<Stat, float>(); List<Stat> allStats = GetAllStats().OrderBy(x => Random.value).ToList(); for (int i = 0; i < allStats.Count; i++) { float level = i < allStats.Count - 1 ? Random.Range(0f, _power) : _power; _power -= level; initStats[allStats[i]] = level; } return initStats; } public Dictionary<Stat, float> InitializeStatsRandomDiscrete(float _power) { List<Stat> setStats = GetAllStats().OrderBy(x => Random.value).ToList(); ; float[] statStrength = new float[setStats.Count]; for (int i = 0; i < setStats.Count; i++) { _power = i < setStats.Count - 1 ? _power / 2f : _power; statStrength[i] = _power; } Dictionary<Stat, float> initStats = new Dictionary<Stat, float>(); for (int i = 0; i < setStats.Count; i++) { initStats[setStats[i]] = statStrength[i]; } return initStats; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace SamizdatEngine { public class GEClickable : MonoBehaviour { public Pos pos; } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Linq; using SamizdatEngine; using UnityEngine; namespace SamizdatEngine.GE { public interface GoEsque { TileShape tileShape { get; set; } List<Player> players { get; set; } Player currentPlayer { get; set; } int turn { get; set; } int[] dims { get; set; } Dictionary<string, Intersection> intersections { get; set; } Dictionary<Intersection, Stone> stones { get; set; } GEDrawer drawer { get; set; } GEUI uihandler { get; set; } void ClickPos(Pos clicked); void Pass(); void TerritoryView(); } public interface Intersection { Stone occupant { get; set; } List<Pos> neighbors { get; set; } Pos pos { get; } string serialize { get; } List<Intersection> GetArea(); void GetAreaWorkhorse(ref List<Intersection> area); } public interface Player { string name { get; set; } Color color { get; set; } List<Stone> capturedStones { get; set; } bool passed { get; set; } } public interface Stone { Player player { get; set; } Intersection intersection { get; set; } bool IsAlive(); bool StoneIsAlive(List<Stone> attackers); void GetGroup(ref List<Stone> Group); void RemoveStoneFromGame(); int Attack(Stone s); List<Stone> GetAttackers(); } public interface RuleManager { void ClickPos(Pos p); void Pass(); } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; //using System.Drawing; public static class MapColor { static public Color GetColorDiscrete(float value, Dictionary<float,Color> cdict) { List<float> flevels = new List<float>(); foreach (KeyValuePair<float,Color> kvp in cdict) { flevels.Add(kvp.Key); } flevels.Sort(); Color rColor = cdict[flevels[0]]; foreach (float flevel in flevels) { rColor = cdict[flevel]; if (value < flevel) { break; } } return rColor; } static public Color GetColorContinuous(float value, Dictionary<float, Color> cdict) { List<float> flevels = new List<float>(); foreach (KeyValuePair<float, Color> kvp in cdict) { flevels.Add(kvp.Key); } flevels.Sort(); Color rColor = cdict[flevels[0]]; float flerp; for (int i = 0; i < flevels.Count - 1; i++) { if (value >= flevels[i] && value <= flevels[i + 1]) { flerp = MapUtil.dNormalize(value, flevels[i], flevels[i + 1]); rColor = GetColorLerp(flerp, cdict[flevels[i]], cdict[flevels[i + 1]]); } } return rColor; } static public Color GetColorLerp(float value, Color cLower, Color cUpper) { float r = Mathf.Lerp(cLower.r, cUpper.r, value); float g = Mathf.Lerp(cLower.g, cUpper.g, value); float b = Mathf.Lerp(cLower.b, cUpper.b, value); Color C = new Color(r, g, b); return C; } static public Color GetColorCutoff(float value, float cutoff, Color cLower, Color cUpper) { Dictionary<float, Color> CutoffDict = new Dictionary<float, Color>(); CutoffDict[cutoff] = cLower; CutoffDict[1f] = cUpper; Color rColor = GetColorDiscrete(value, CutoffDict); return rColor; } static public Dictionary<float,Color> PaletteBasicSpectrum(float c) { Dictionary<float, Color> d = new Dictionary<float, Color>(); d[0f] = Color.blue; d[0.2f] = Color.cyan; d[0.4f] = Color.green; d[0.6f] = Color.yellow; d[0.8f] = Color.red; d[1f] = Color.magenta; return d; } static public Dictionary<float,Color> PaletteBasicNatural(float c) { Dictionary<float, Color> d = new Dictionary<float, Color>(); d[0f] = Color.blue; float sealerp = Mathf.Lerp(0f, c, 0.8f); d[sealerp] = Color.blue; d[c] = GetColorLerp(0.5f, Color.blue, Color.cyan); float shore = c + 0.00001f; d[shore] = Color.green; float landlerp = Mathf.Lerp(shore, 1f, 0.5f); d[landlerp] = Color.yellow; float mountain = Mathf.Lerp(shore, 1f, 0.85f); d[mountain] = Color.red; d[mountain + 0.00001f] = Color.red; d[1f] = Color.red; return d; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace BBMVP { public class bbAgent { public string name; public bbPos pos; public bbPos lastPos; public List<bbJob> jobQueue; public BaseBuilderMVP game; public Dictionary<ItemType, int> needTimer; public Dictionary<ItemType, int> needQuantity; public Dictionary<ItemType, int> inventory; public List<ItemType> needsAddressing; public bbStructure myHouse; public bool alive; public bool animating; public bbAgent() { alive = false; } public bbAgent(string _name, bbPos _pos, BaseBuilderMVP _game, bbStructure _myHouse) { alive = true; animating = false; name = _name; //Debug.Log("Created Agent named " + name); pos = _pos; game = _game; myHouse = _myHouse; jobQueue = new List<bbJob>(); needTimer = new Dictionary<ItemType, int> { { ItemType.ITEM_FOOD, 50 } }; needQuantity = new Dictionary<ItemType, int> { { ItemType.ITEM_FOOD, 1 } }; inventory = new Dictionary<ItemType, int> { { ItemType.ITEM_FOOD, 0 }, { ItemType.ITEM_GOLD, 0 } }; needsAddressing = new List<ItemType>(); } void AssertNeed(ItemType needType) { //Debug.Log("Need for " + needType.ToString() + " assigned"); List<bbJob> needJobs = new List<bbJob>(); needsAddressing.Add(needType); bbJobMoveTo moveToHouse = new bbJobMoveTo(myHouse.getPos()); needJobs.Add(moveToHouse); bbJobUseStructure useHouse = new bbJobUseStructure(myHouse); needJobs.Add(useHouse); needJobs.AddRange(jobQueue); jobQueue = needJobs; } public void takeTurn() { if (alive) { CheckNeeds(); // Do current job if (jobQueue.Count != 0) { bbJob currentJob = jobQueue[0]; currentJob.doJobTurn(this); if (currentJob.checkJobComplete(this)) { jobQueue.Remove(currentJob); } } else { // Assign new job if (pos.game.playerJobQueue.Count == 0) { } else { List<bbJob> jobs = pos.game.playerJobQueue[0]; jobQueue = jobs; pos.game.playerJobQueue.Remove(jobs); } } } } void CheckNeeds() { // Adjust Need Timer List<ItemType> needs = new List<ItemType>(needTimer.Keys); foreach (ItemType needType in needs) { if (needTimer[needType] > 0) { needTimer[needType] -= 1; } } // Check to see if any Needs are triggered foreach (ItemType needType in needs) { if (needTimer[needType] <= 0) { if (!needsAddressing.Contains(needType)) { AssertNeed(needType); } } } } void AssignDefaultJob(bbStructure assignedStructure) { bbStructure mine = assignedStructure; // Move To Mine bbJobMoveTo moveToMine = new bbJobMoveTo(mine.getPos()); jobQueue.Add(moveToMine); // Use Mine bbJobUseStructure useMine = new bbJobUseStructure(mine); jobQueue.Add(useMine); // Move To HQ bbStructure trystruct = new bbStructureDummy(); if (pos.findClosestStructureByPath(bbStructureType.STRUCTURE_HQ, ref trystruct)) { bbStructure hq = trystruct; bbJobMoveTo moveToHQ = new bbJobMoveTo(hq.getPos()); jobQueue.Add(moveToHQ); // Use HQ bbJobUseStructure useHQ = new bbJobUseStructure(hq); jobQueue.Add(useHQ); } } public Color getColor() { return Color.black; } public bool Deposit() { List<ItemType> invItems = new List<ItemType>(inventory.Keys); foreach (ItemType i in invItems) { pos.game.playerResources[i] += inventory[i]; inventory[i] = 0; } return true; } public bool Collect(ItemType type, int quantity = 1) { inventory[type] += quantity; return true; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public interface Card { void EffectWhenDrawn(); void EffectWhenPlayed(); void EffectWhenDiscarded(); GameObject Display(); } public class Deck { List<Card> deck; List<Card> hand; List<Card> library; List<Card> discard; int handMax = 0; // 0 means no max int handDraw = 0; // 0 means draw up to max int handStart = 5; public Deck(List<Card> _deck, int _handMax, int _handDraw, int _handStart) { handMax = _handMax; handDraw = _handDraw; handStart = _handStart; StartDeck(_deck); } void StartDeck(List<Card> _deck) { deck = _deck; library = deck; discard = new List<Card>(); StartHand(); } void StartHand() { hand = new List<Card>(); DrawCards(handStart); } int CardsToDiscard() { int discardNumber = 0; if (handMax != 0 && hand.Count > handMax) { discardNumber = hand.Count - handMax; Debug.Log("MUST DISCARD " + discardNumber + " CARDS"); } return discardNumber; } void DrawStep() { if (handMax == 0) { // no max DrawCards(handDraw); } else { DrawCards(handMax - hand.Count); } } void DrawCards(int n) { if ( n > 0) { for (int i = 0; i < n; i++) { DrawCard(); } } } void DrawCard() { Card drawn = library[0]; library.Remove(drawn); hand.Add(drawn); drawn.EffectWhenDrawn(); } public static List<Card> Shuffle(List<Card> aList) { System.Random _random = new System.Random(); Card myCard; int n = aList.Count; for (int i = 0; i < n; i++) { int r = i + (int)(_random.NextDouble() * (n - i)); myCard = aList[r]; aList[r] = aList[i]; aList[i] = myCard; } return aList; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using SamizdatEngine; using SamizdatEngine.GE; using SamizdatEngine.GE.Basic; public class GoEsqueManager : MonoBehaviour { public GameObject goDrawer, goUI; GoEsque game; GEDrawer drawer; GEUI ui; // Use this for initialization void Start() { drawer = goDrawer.GetComponentInChildren<GEDrawerBasic>(); ui = goUI.GetComponentInChildren<GEUIBasic>(); game = new GoEsqueBasic(drawer, ui); ui.game = game; drawer.DrawInit(game); } // Update is called once per frame void Update() { ui.HandleUI(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class MapScaler { public MapScaler() { } public Dictionary<string,float[,]> BuildSurfaces(MapGen mg) { Dictionary<string, float[,]> surfaces = new Dictionary<string, float[,]> { { "Elevation", mg.Elevation }, { "Rain", mg.Rain }, { "WaterFlux", mg.WaterFlux }, { "Temperature", mg.Temperature }, { "WindMagnitude", mg.WindMagnitude }, { "Flatness", mg.Flatness }, { "Fertility", mg.Fertility }, { "Harbor", mg.Harbor} }; return surfaces; } public void Crop(ref MapGen inputMap, int xDim, int yDim, int xTL, int yTL, bool bNormalize = false) { MapGen outputMap = new MapGen(xDim, yDim); outputMap.seaLevel = inputMap.seaLevel; outputMap.riverLevel = inputMap.riverLevel; Dictionary<string, float[,]> inputSurfaces = BuildSurfaces(inputMap); Dictionary<string, float[,]> outputSurfaces = BuildSurfaces(outputMap); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { foreach (KeyValuePair<string, float[,]> kvp in inputSurfaces) { string k = kvp.Key; outputSurfaces[k][x, y] = inputSurfaces[k][x + xTL, y + yTL]; } } } if (bNormalize) { Normalize(ref outputMap, outputSurfaces); } inputMap = outputMap; } public void ExpandSquare(ref MapGen inputMap, int xE, int yE, bool bNormalize = true) { int xDim = inputMap.Elevation.GetLength(0); int yDim = inputMap.Elevation.GetLength(1); int xl = xDim * xE; int yl = yDim * yE; MapGen outputMap = new MapGen(xl, yl); outputMap.seaLevel = inputMap.seaLevel; outputMap.riverLevel = inputMap.riverLevel; Dictionary<string, float[,]> inputSurfaces = BuildSurfaces(inputMap); Dictionary<string, float[,]> outputSurfaces = BuildSurfaces(outputMap); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { for (int xi = 0; xi < xE; xi++) { for (int yi = 0; yi < yE; yi++) { foreach (KeyValuePair<string,float[,]> kvp in inputSurfaces) { string k = kvp.Key; int xp1 = x < xDim - 1 ? x + 1 : x; int yp1 = y < yDim - 1 ? y + 1 : y; float xLerpTop = Mathf.Lerp(inputSurfaces[k][x, y], inputSurfaces[k][xp1, y], (float)xi / (float)xE); float xLerpBot = Mathf.Lerp(inputSurfaces[k][x, yp1], inputSurfaces[k][xp1, yp1], (float)xi / (float)xE); float lerpVal = Mathf.Lerp(xLerpTop, xLerpBot, yi / yE); int xind = x * xE + xi; int yind = y * yE + yi; outputSurfaces[k][xind, yind] = lerpVal; } } } } } if (bNormalize) { Normalize(ref outputMap, outputSurfaces); } inputMap = outputMap; } public void Smooth(ref MapGen inputMap, bool bNormalize = true) { int xDim = inputMap.Elevation.GetLength(0); int yDim = inputMap.Elevation.GetLength(1); MapGen outputMap = new MapGen(xDim, yDim); outputMap.seaLevel = inputMap.seaLevel; outputMap.riverLevel = inputMap.riverLevel; Dictionary<string, float[,]> inputSurfaces = BuildSurfaces(inputMap); Dictionary<string, float[,]> outputSurfaces = BuildSurfaces(outputMap); foreach (KeyValuePair<string, float[,]> kvp in inputSurfaces) { for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { outputSurfaces[kvp.Key][x, y] = MapUtil.dSmooth(x, y, inputSurfaces[kvp.Key]); } } } if (bNormalize) { Normalize(ref outputMap, outputSurfaces); } inputMap = outputMap; } private void Normalize(ref MapGen inputMap, Dictionary<string, float[,]> inputSurfaces) { foreach (KeyValuePair<string, float[,]> kvp in inputSurfaces) { float[,] surface = kvp.Value; MapUtil.TransformMapMinMax(ref surface, MapUtil.dNormalize); } MapUtil.TransformEqualizeMapByLevel(ref inputMap.seaLevel, ref inputMap.Elevation, 0.5f); MapUtil.TransformEqualizeMapByLevelAboveSea(ref inputMap.riverLevel, ref inputMap.WaterFlux, 0.05f, inputMap.Elevation, inputMap.seaLevel); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; using System; public struct Vec { public float x, y; public Vec(float _x, float _y) { x = _x; y = _y; } public Vec GetRotatedVector(float rotationInDegrees) { float rad = DegreesToRadians(rotationInDegrees); float cs = (float)Math.Cos(rad); float sn = (float)Math.Sin(rad); float px = x * cs - y * sn; float py = x * sn + y * cs; return new Vec(px, py); } private float DegreesToRadians(float degrees) { return (float)(degrees * (Math.PI / 180)); } } public enum RainMethod { Equal, Noise, Wind}; public class RainBuilder { public float[,] Elevation, Temperature, Rain, WindMagnitude; public List<Vec>[,] WindVectorsList; public Vec[,] WindVectors; public int xDim, yDim; public float seaLevel; public Wind[,] wind; public RainBuilder(float[,] _Elevation, float[,] _Temperature, float _seaLevel) { Elevation = _Elevation; Temperature = _Temperature; xDim = Elevation.GetLength(0); yDim = Elevation.GetLength(1); seaLevel = _seaLevel; Rain = new float[xDim, yDim]; WindVectors = new Vec[xDim, yDim]; WindVectorsList = new List<Vec>[xDim, yDim]; WindMagnitude = new float[xDim, yDim]; } public void BuildRain(RainMethod pm, Benchmark bench = null) { Benchmark.Start(bench, "Rain"); // etc if (pm == RainMethod.Equal) { BuildRainByEqual(); } else if (pm == RainMethod.Noise) { BuildRainByNoise(); } else if (pm == RainMethod.Wind) { WindSpawn ws = WindSpawn.TradeLinear; WindRainType rt = WindRainType.HeatBasedContinuous; WindEvaporationType et = WindEvaporationType.WaterAndHeat; WindTurnType wt = WindTurnType.TerrainBased; BuildRainByWind(1000,ws,rt,et,wt,bench); MapUtil.TransformMapMinMax(ref Rain, MapUtil.dNormalize); } if (bench != null) { bench.EndBenchmark("Rain"); } } private void BuildRainByEqual() { for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Rain[x, y] = 1f; } } } private void BuildRainByNoise() { MidpointDisplacement mpd = new MidpointDisplacement(MapUtil.nFromDims(xDim,yDim)); Rain = mpd.Elevation; MapUtil.TransformMapMinMax(ref Rain, MapUtil.dNormalize); } private void BuildRainByWind(int maxIter, WindSpawn windSpawn, WindRainType rainType, WindEvaporationType evapType, WindTurnType windTurnType, Benchmark bench = null) { Benchmark.Start(bench, "Wind"); List<Wind> winds = new List<Wind>(); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { WindVectorsList[x, y] = new List<Vec>(); Wind w = new Wind(x, y, Elevation, windSpawn); WindVectorsList[x, y].Add(new Vec(w.velocity.x, w.velocity.y)); winds.Add(w); } } int iter = 0; int numberOfWinds = winds.Count; while (iter < maxIter) { numberOfWinds = winds.Count; if (numberOfWinds == 0) { break; } else { BuildRainByWindWorkhorse(ref winds, windSpawn, rainType, evapType, windTurnType); } iter++; } MapUtil.TransformMap(ref Rain, MapUtil.dExponentiate, 0.125f); TabulateWindflow(); if (bench != null) { bench.EndBenchmark("Wind"); } } private void BuildRainByWindWorkhorse(ref List<Wind> winds, WindSpawn windSpawn, WindRainType rainType, WindEvaporationType evapType, WindTurnType windTurnType) { // Combine Winds at the same location CombineWinds(ref winds, windSpawn); // Add to WindFlow foreach (Wind w in winds) { WindVectorsList[w.approxMapLoc.x, w.approxMapLoc.y].Add(new Vec(w.velocity.x, w.velocity.y)); } // Move wind in the direction vector foreach (Wind w in winds) { w.Blow(Elevation, Temperature); } // If the wind moves off the map, remove it RemoveOffWindMaps(ref winds); // Rain foreach (Wind w in winds) { w.Rain(rainType, ref Rain, Elevation, seaLevel); } // Evaporate foreach (Wind w in winds) { w.Evaporate(evapType, Elevation, Temperature, seaLevel); } // Turn Wind foreach (Wind w in winds) { w.TurnWind(windTurnType, Elevation, seaLevel); } } private void RemoveOffWindMaps(ref List<Wind> winds) { List<Wind> newWinds = new List<Wind>(); for (int i = 0; i < winds.Count; i++) { if (winds[i].WindOnMap == true) { newWinds.Add(winds[i]); } } winds = newWinds; } private void CombineWinds(ref List<Wind> winds, WindSpawn ws, bool addNewWinds = false) { List<Wind>[,] stackedWindsList = new List<Wind>[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { stackedWindsList[x, y] = new List<Wind>(); } } foreach (Wind w in winds) { stackedWindsList[w.approxMapLoc.x, w.approxMapLoc.y].Add(w); } List<Wind> newWinds = new List<Wind>(); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { if (addNewWinds) { stackedWindsList[x, y].Add(new Wind(x, y, Elevation, ws)); } if (stackedWindsList[x,y].Count > 0) { newWinds.Add(CombineWindsAtMapLocation(stackedWindsList[x, y])); } } } winds = newWinds; } private Wind CombineWindsAtMapLocation(List<Wind> windsAtMapLocation) { List<float> xl = new List<float>(); List<float> yl = new List<float>(); List<float> xv = new List<float>(); List<float> yv = new List<float>(); List<float> water = new List<float>(); foreach (Wind w in windsAtMapLocation) { xl.Add(w.actualMapLoc.x); yl.Add(w.actualMapLoc.y); xv.Add(w.velocity.x); yv.Add(w.velocity.y); water.Add(w.Water); } float _x = xl.Average(); float _y = yl.Average(); float _xv = xv.Average(); float _yv = yv.Average(); float _water = water.Average(); return new Wind(_x, _y, _xv, _yv, _water, Elevation); } private void TabulateWindflow() { float[,] xa = new float[xDim, yDim]; float[,] ya = new float[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { List<float> xl = new List<float>(); List<float> yl = new List<float>(); foreach (Vec v in WindVectorsList[x, y]) { xl.Add(v.x); yl.Add(v.y); } float fx = xl.Sum(); float fy = yl.Sum(); xa[x, y] = fx; ya[x, y] = fy; WindMagnitude[x, y] = (float)Math.Sqrt(fx * fx + fy * fy); } } MapUtil.TransformMapMinMax(ref WindMagnitude, MapUtil.dNormalize); MapUtil.TransformMap(ref WindMagnitude, MapUtil.dExponentiate, 0.25f); for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { WindVectors[x, y] = new Vec(xa[x,y], ya[x,y]); } } } } public enum WindSpawn {Easterly, TradeSine, TradeLinear }; public enum WindEvaporationType { WaterOnly, WaterAndHeat} public enum WindRainType { UphillDiscrete, HeatBasedDiscrete, UphillContinuous, HeatBasedContinuous}; public enum WindTurnType { None, RandomWalk, TerrainBased}; public class Wind { public Vec velocity; public Vec actualMapLoc; public MapLoc approxMapLoc; public float Water, deltaHeight, deltaTemp, seaLevel; public int xDim, yDim; public bool WindOnMap, WindOverWater; public Wind(float _x, float _y, float[,] Elevation, WindSpawn ws) { Water = 0.1f; deltaHeight = 0f; deltaTemp = 0f; actualMapLoc = new Vec(_x, _y); approxMapLoc = new MapLoc((int)_x, (int)_y); WindOnMap = true; xDim = Elevation.GetLength(0); yDim = Elevation.GetLength(1); if (ws == WindSpawn.Easterly) { velocity = new Vec(1, 0); } else if (ws == WindSpawn.TradeSine) { velocity = TradeWindSine(); } else if (ws == WindSpawn.TradeLinear) { velocity = TradeWindLinear(); } } public Wind(float _x, float _y, float _xv, float _yv, float _water, float[,] Elevation) { actualMapLoc = new Vec(_x, _y); approxMapLoc = new MapLoc((int)_x, (int)_y); velocity = new Vec(_xv, _yv); Water = _water; xDim = Elevation.GetLength(0); yDim = Elevation.GetLength(1); } public void Blow(float[,] Elevation, float[,] Temperature) { deltaHeight = Elevation[approxMapLoc.x, approxMapLoc.y]; deltaTemp = Temperature[approxMapLoc.x, approxMapLoc.y]; actualMapLoc = new Vec(actualMapLoc.x + velocity.x, actualMapLoc.y + velocity.y); approxMapLoc = new MapLoc((int)actualMapLoc.x, (int)actualMapLoc.y); WindOnMap = true; WindOnMap = (actualMapLoc.x < 0 || actualMapLoc.x >= xDim) ? false : WindOnMap; WindOnMap = (approxMapLoc.x < 0 || approxMapLoc.x >= xDim) ? false : WindOnMap; WindOnMap = (actualMapLoc.y < 0 || actualMapLoc.y >= yDim) ? false : WindOnMap; WindOnMap = (approxMapLoc.y < 0 || approxMapLoc.y >= yDim) ? false : WindOnMap; if (WindOnMap) { deltaHeight = Elevation[approxMapLoc.x, approxMapLoc.y] - deltaHeight; deltaTemp = Temperature[approxMapLoc.x, approxMapLoc.y] - deltaTemp; } } public void Rain(WindRainType rt, ref float[,] Rain, float [,] Elevation, float seaLevel) { if (rt == WindRainType.UphillDiscrete) { if (deltaHeight > 0f && Elevation[approxMapLoc.x,approxMapLoc.y] > seaLevel) { float rainAmount = 0.1f * Water; RainWorkhorse(ref Rain, rainAmount); } } else if (rt == WindRainType.HeatBasedDiscrete) { if (deltaTemp < -0f && Elevation[approxMapLoc.x, approxMapLoc.y] > seaLevel) { float rainAmount = 0.1f * Water; RainWorkhorse(ref Rain, rainAmount); } } else if (rt == WindRainType.UphillContinuous) { if (deltaHeight > 0f && Elevation[approxMapLoc.x, approxMapLoc.y] > seaLevel) { float rainAmount = deltaHeight * Water; RainWorkhorse(ref Rain, rainAmount); } } else if (rt == WindRainType.HeatBasedContinuous) { if (deltaTemp < -0f && Elevation[approxMapLoc.x, approxMapLoc.y] > seaLevel) { float rainAmount = -deltaTemp * Water; RainWorkhorse(ref Rain, rainAmount); } if (Water > 10) { float rainAmount = 0.1f * Water; RainWorkhorse(ref Rain, rainAmount); } } } private void RainWorkhorse(ref float[,] Rain, float rainAmount) { Water -= rainAmount; Rain[approxMapLoc.x, approxMapLoc.y] += Water; } public void Evaporate(WindEvaporationType et, float[,] Elevation, float[,] Temperature, float seaLevel) { if (et == WindEvaporationType.WaterOnly) { if (Elevation[approxMapLoc.x,approxMapLoc.y] < seaLevel) { Water += 1f; } } else if (et == WindEvaporationType.WaterAndHeat) { if (Elevation[approxMapLoc.x, approxMapLoc.y] < seaLevel) { Water += Temperature[approxMapLoc.x,approxMapLoc.y]; } } } public void TurnWind(WindTurnType wt, float[,] Elevation, float seaLevel) { if (wt == WindTurnType.None) { // do nothing } else if (wt == WindTurnType.RandomWalk) { int r = UnityEngine.Random.Range(-1, 1); velocity = new Vec(velocity.x, r); } else if (wt == WindTurnType.TerrainBased) { if (Elevation[approxMapLoc.x, approxMapLoc.y] > seaLevel) { velocity.x -= deltaHeight; velocity.y -= deltaHeight; Vec lVec = velocity.GetRotatedVector(-90); Vec rVec = velocity.GetRotatedVector(90); MapLoc lMapLoc = new MapLoc((int)(Math.Max(1,actualMapLoc.x + lVec.x)), (int)Math.Max(1,actualMapLoc.y + lVec.y)); MapLoc rMapLoc = new MapLoc((int)(Math.Max(1,actualMapLoc.x + rVec.x)), (int)Math.Max(1,actualMapLoc.y + rVec.y)); try { float fDiff = Elevation[lMapLoc.x, lMapLoc.y] - Elevation[rMapLoc.x, rMapLoc.y]; velocity.x += lMapLoc.x * fDiff; velocity.y += lMapLoc.y * fDiff; } catch { // ¯\_(ツ)_/¯ } } } } private Vec TradeWindSine() { float yC = (yDim - 1) / 2f; float EquatorToPolePosition = Math.Abs(approxMapLoc.y - yC) / yC; float yAdjustedInput = MapUtil.dNormalize(EquatorToPolePosition, 0f, 1f, -0.499f, 0.999f); //float xDir = (float)Math.Tan(Math.PI * yAdjustedInput); //float yDir = (float)Math.Tan(Math.PI * 0.5f - Math.PI * yAdjustedInput); float xDir = (float)Math.Tan(yAdjustedInput); float yDir = (float)Math.Tan(0.5f - yAdjustedInput); //Debug.Log("Wind at " + approxMapLoc.y + "("+EquatorToPolePosition+") is "+xDir+","+yDir); return new Vec(xDir, yDir); } private Vec TradeWindLinear() { float yC = (yDim - 1) / 2f; float EquatorToPolePosition = Math.Abs(approxMapLoc.y - yC) / yC; EquatorToPolePosition = MapUtil.dNormalize(EquatorToPolePosition, 0f, 1f, -0.499f, 0.999f); float xDir, yDir; if (EquatorToPolePosition <= 0.0f) { float newLerp = MapUtil.dNormalize(EquatorToPolePosition, -0.5f, 0f); xDir = -1f + newLerp; yDir = -newLerp; } else if (EquatorToPolePosition <= 0.5f) { float newLerp = MapUtil.dNormalize(EquatorToPolePosition, 0f, 0.5f); xDir = newLerp; yDir = 1f - newLerp; } else { float newLerp = MapUtil.dNormalize(EquatorToPolePosition, 0.5f, 1.0f); xDir = -1f + newLerp; yDir = -newLerp; } //Debug.Log("Wind at " + approxMapLoc.y + "(" + EquatorToPolePosition + ") is " + xDir + "," + yDir); return new Vec(xDir, yDir); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class FlowBuilder { public float[,] Elevation; public float[,] Rain; public float[,] Flow; public float[,] Water; int xDim, yDim; public FlowBuilder(float[,] _Elevation, float[,] _Rain) { Elevation = _Elevation; Rain = _Rain; xDim = Elevation.GetLength(0); yDim = Elevation.GetLength(1); Flow = new float[xDim, yDim]; Water = new float[xDim, yDim]; } public void FlowStep(int iterations, Benchmark bench = null) { if (bench != null) { bench.StartBenchmark("Flow Step"); } RainStep(); for (int i = 0; i < iterations; i++) { AddWaterToFlow(); float[,] flowStep = new float[xDim, yDim]; for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { FlowProportional(ref flowStep, new MapLoc(x, y)); } } Water = flowStep; } if (bench != null) { bench.EndBenchmark("Flow Step"); } } public void FlowProportional(ref float[,] flowStep, MapLoc l) { Dictionary<MapLoc, float> neighbors = MapUtil.GetValidNeighbors(Elevation, l, false); // Flow Proportional float localHeight = Elevation[l.x, l.y]; Dictionary<MapLoc, float> lowerNeighbors = new Dictionary<MapLoc, float>(); float fDiff; float totalDiff = 0f; foreach (KeyValuePair<MapLoc, float> n in neighbors) { if (n.Value < localHeight) { fDiff = localHeight - n.Value; lowerNeighbors[n.Key] = fDiff; totalDiff += fDiff; } } if (lowerNeighbors.Count > 0) { foreach (KeyValuePair<MapLoc, float> n in lowerNeighbors) { flowStep[n.Key.x, n.Key.y] += Water[l.x, l.y] * n.Value / totalDiff; } } else { float newElev = MapUtil.GetNeighborAverage(Elevation, l); newElev = (newElev + Elevation[l.x, l.y]) / 2f; Elevation[l.x, l.y] = newElev; } } private void AddWaterToFlow() { for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Flow[x, y] += Water[x, y]; } } } private void RainStep() { for (int x = 0; x < xDim; x++) { for (int y = 0; y < yDim; y++) { Water[x, y] += Rain[x, y]; } } } }
0f068694912c8ab6c5c67328c615d41194119b58
[ "C#" ]
48
C#
NickSchade/SamizdatEngine
a1067ca80c7fa6752d6a1915c59cce54e5981435
4bff780a637e7e5d47bea837e140b1fcf132b312
refs/heads/master
<repo_name>KeepStudyOn/paymentWap_V1.0<file_sep>/js/xmsCore.js /* //方法名,请按照字母排序 //日期为最后修改日期 支持的库调用方法: 2015/12/07 $(obj).scrollIntoView(); 2015/12/07 $(obj).xmsAjax(options); 2016/01/04 $(obj).xmsAllpass(inputs); 2015/12/15 $(obj).xmsEnterTrigger(options); 2015/12/15 $(obj).xmsLoadHtml(options); //xmsCore的调用方法: 2016/01/04 xmsCore.basic_method; 2015/12/07 xmsCore.xmsAjax; 2015/12/24 xmsCore.xmsCustomDate; 2015/12/07 xmsCore.xmsDateFormat; 2015/12/15 xmsCore.xmsEnterTrigger; 2015/12/09 xmsCore.xmsFormSubmit; 2015/12/30 xmsCore.xmsLoadHtml; 2015/12/30 xmsCore.xmsLoadImg; 2015/12/07 xmsCore.xmsObjToStr; 2015/12/07 xmsCore.xmsQueryParam; 2015/12/07 xmsCore.xmsQueryUrl; 2015/12/07 xmsCore.xmsStrToObj; 2015/12/15 xmsCore.xmsTmplete; */ (function(window){ var $ = null; //给$赋值 if(typeof jQuery == "function"){ $ = jQuery; }else if(typeof Zepto == "function"){ $ = Zepto; }else{ //如果没有,则抛出错误 throw new Error("xmscore.js modal need jQuery/Zepto"); } //把该方法添加到xmsCore对象中去 var xmsCore = window.xmsCore; if(!xmsCore && typeof xmsCore != "object"){ window.xmsCore = {}; xmsCore = window.xmsCore; } if(!$.fn.extend){ //Zepto中,$.fn中没有extend方法,这里进行重定义 //做一层代理 $.fn.extend = function(obj){ $.extend($.fn,obj); }; } //方法扩展到$.fn对象上去 $.fn.extend({ scrollIntoView:function(){ var obj = $(this), parent = null; if(obj.size()){ parent = obj.parent(); parent.scrollTop(parent.scrollTop() + obj.position().top - parent.height() + obj.outerHeight()); } return this; }, xmsAjax:function(options){ $.each($(this),function(){ var option = $.extend({},options); option.obj = $(this); _xmsAjax(option); }); return this; }, xmsAllpass:function(inputs){ return basic_method.allpass($(this),inputs); }, xmsEnterTrigger:function(options){ var obj = $(this).eq(0); options.obj = obj; _xmsEnterTrigger(options); return this; }, xmsFormSubmit: function(options){ $.each($(this),function(){ new xmsFormSubmit($(this),options); }); return this; }, xmsLoadHtml:function(options){ $.each($(this),function(){ var option = $.extend({},options); option.obj = $(this); _xmsLoadHtml(option); }); return this; }, xmsRadio :function(options){ if(typeof options !== "object"){ options = {}; } $.each($(this),function(){ var option = $.extend({},options); option.obj = $(this); _xmsRadio(option); }); }, xmsCheckBox :function(options){ if(typeof options !== "object"){ options = {}; } $.each($(this),function(){ var option = $.extend({},options); option.obj = $(this); _xmsCheckBox(option); }); } }); xmsObjToStr.trim = $.trim; /* obj格式 {"action":"query","id":"1,2","city":"sh"} split字符串的分隔符 默认为"&" */ function xmsObjToStr(option){ var obj = "", split = "&"; if(typeof option !== "object"){ return ""; } if(typeof option.obj !== "object"){ obj = option; }else{ obj = option.obj || ""; split = option.split || "&"; } var i, arr = []; for(i in obj){ arr.push(i+"="+xmsObjToStr.trim(obj[i])); } return arr.join(split); } //为了xmsObjToStr方法,定义一个局部变量,作用域链查找更快 xmsCore.xmsObjToStr = xmsObjToStr; /* str格式 action=query&id=1&id=2&id=3&city=sh split字符串的分隔符 默认为"&" sep 为空时 key重复时取最后一个值 不为空时 key重复时值以sep作为分割符 */ function xmsStrToObj(option){ var str = "", split = "&", sep = ""; if(typeof option == "object"){ str = option.str || "", split = option.split || "&", sep = option.sep || ""; }else if(typeof option == "string"){ str = option; } if(!str){ return false; } var i, arr = str.split(split), len = arr.length, one = null, name = "", value = "", obj = {}; for(i=0;i<len;i++){ one = arr[i].split("="); name = one[0]; value = one[1] || ""; if(name){ if(obj[name]){ // 有相同参数 if(sep){ // 以sep为分割符 if(value){ obj[name] += sep + value; } }else{ // 后一个值覆盖前一个值 obj[name] = value; } }else{ obj[name] = value; } } } return obj; } xmsCore.xmsStrToObj = xmsStrToObj; function xmsQueryParam(option){ var data = option.data || "", replace = option.replace || "", param = { "split": option.split, "sep": option.sep }; if(!data || !replace){ param.str = data + replace; }else{ param.str = data+"&"+replace; } return xmsCore.xmsObjToStr(xmsCore.xmsStrToObj(param)); } xmsCore.xmsQueryParam = xmsQueryParam; //防止多次提交,有做提交信息的频率限制 function _xmsAjax(options){ //参数options支持以下参数 /* //obj:必须,触发该ajax提交的对象元素,用于处理提交太快的情况。 //dataType:可选,取值"json/html",默认为"json",返回值的数据格式 //type:可选,取值"post/get",默认为"post",请求的方式。 //data:"",发出请求时,额外提交的数据。 //url:ajax提交的地址, // 必须存在,可以直接以options.url保存, // 也可以保存在obj.attr("data-url")属性中,options.url优先 //success:成功后的回调函数,内部this指向obj, // 传入一个参数,为Ajax的返回值 //error:失败时的回调函数,内部this指向obj, // 传入参数为ajax时error传入的参数,三个值, // 请自行去jQuery的error对象中查看。 //limit:true/false,是否需要控制提交间隔,默认为true,控制间隔 */ var limit = true, limitClass = "xms-ajax-limit", limitTime = 1000, dataType = "json", url = "", obj = null; //错误验证,以及赋值。 try{ obj = options.obj; limit = options.limit === false ? false : true; dataType = options.dataType || "json"; url = options.url || obj.attr("data-url") || ""; }catch(e){ throw new TypeError("在调用xmsAjax时,传入的参数有误!"); } if(!url){ throw new Error("在调用xmsAjax时,url属性是必须的,请确认!"); } if(limit){ //限制提交频率的情况下,处理。 if(obj.hasClass(limitClass)){ alert("您提交的速度太快了,请稍后!"); return false; } obj.addClass(limitClass); } $.ajax({ url: url, type: options.type || "post", data: options.data || "", dataType: dataType, success: function(json) { var success = options.success; if(dataType == "json"){ json = typeof json == "string"?JSON.parse(json):json; } if(limit){ obj.removeClass(limitClass); } if (typeof success === "function") { success.call(obj, json); } }, error: function() { var error = options.error; //如果有自定义的错误提示,那么调用自定义的 //如果没有,那么直接提示。 if (typeof error === "function") { error.apply(obj,arguments); }else{ alert("由于网络的原因,您刚才的操作没有成功。"); } if(limit){ obj.removeClass(limitClass); } } }); if(limit){ setTimeout(function(){ obj.removeClass(limitClass); },limitTime); } } xmsCore.xmsAjax = _xmsAjax; //basic_method对象,保存一些基本的可用于该模块的小的逻辑方法, //不使用于其他文件,所以,不保存到$对象上。 var basic_method = { // 验证必填项--空值 validEmpty: function(obj){ var value = ""; if(!obj.length){ return true; } value = $.trim(obj.val()); if(value === ""){ return obj.attr("data-empty") || ("请输入" + (obj.attr("data-remind") || "")) + "!"; } return true; }, // 验证必填项 -- 数字 validNum: function(obj){ //验证是否为数字 //只验证该处的输入值是否为数字,可以为空, //为空的验证,请使用validEmpty自行验证。 var value = $.trim(obj.val()), min = "", max = ""; if(value === ""){ //如果输入值为空时,返回空字符串, //所以,当直接返回false时,表示通过验证 return ""; } //如果value值不为空,则把对应的需要进行判断的数据转换成数字 value = value - 0; min = obj.attr("data-min") - 0; max = obj.attr("data-max") - 0; // 是否为NAN if(isNaN(value)){ return (obj.attr("data-remind") || "本输入框")+"只支持数字!"; } if(!isNaN(min) && !isNaN(max)){ //如果设置了min和max if(max - min < 0){ //如果min设置值比max大,则出错 return "配置出错,请找技术进行确认问题!"; } if(max === min){ //如果设置的最大值和最小值相等 return "该输入框只支持一个数字:"+max + "!"; } if(value - min < 0 || value - max > 0){ return "请输入"+min+"-"+max+"区间的数字!" } } if(!isNaN(min) && value - min < 0){ return "请输入大于等于" + min +"的数字!"; } if(!isNaN(max) && value - max > 0){ return "请输入少于等于" + max +"的数字!"; } // 验证通过返回false return basic_method.validRegExp(obj); }, //验证必填项 -- 正则验证 validRegExp: function(obj, pattern){ //验证正则时,不进行是否为空的验证 //因为正则可以验证空输入的情况,所以不再单独的验证 var value = "", reg = pattern || obj.attr("pattern") || ""; if(reg){ reg = (reg instanceof RegExp)?reg:new RegExp(reg); value = $.trim(obj.val()) || ""; if(!reg.test(value)){ return "请输入正确的" + (obj.attr("data-remind") || "") + "格式!" } } // 验证通过返回true return true; }, // test if all passed allpass: function(obj,inputs) { var allPassed = true; obj = obj?(obj instanceof $)?obj:$(obj):$(document); inputs = (inputs?(inputs instanceof $)?inputs:$(inputs):obj.find("input,textarea,select")); errorMsgBox = obj.find('#errorMsgBox').eq(0) || ''; if(errorMsgBox.length){ errosMsgDetail = obj.find('span.error-cont-detail').eq(0)|| ''; } $.each(inputs,function(index,ele) { var obj = $(this), tip = ""; if(obj.css("display") === "none"){ return ""; } if (allPassed === true) { // 输入框有属性requir事,验证是否为空 //之所以把requir放在这里,是为了验证一些时候 //支持为空正常,支持如过输入,那么格式需要符合规定 //比如手机号:可以不输入,但是输入时,就需要符合规则 tip = basic_method.validEmpty(obj.filter("[requir]")); if(tip == true){ switch(obj.attr("data-valid")){ case "num": tip = basic_method.validNum(obj); break; default: // 不为空的输入框才需验证正则 tip = basic_method.validEmpty(obj); if(tip == true){ tip = basic_method.validRegExp(obj); }else{ tip = ""; } } } if(typeof tip === "string" && tip !== ""){ //只有tip返回为非空的字符串时,才执行错误提示的操作 // basic_method.errorTip(obj,tip); errorMsgDetail.html(tip); errorMsgBox.show(); allPassed = false; return allPassed; } }else{ allPassed = false; return false; //结束each循环 } }); return allPassed; }, errorTip:function(obj,tip,time){ var title = obj.attr("title") || "", tagName = obj[0].tagName.toUpperCase(); time = time || 1000; alert(tip); if(tagName == "INPUT" || tagName == "TEXTAREA"){ obj.focus(); }else{ obj.attr("title",tip).tooltip("show"); basic_method.scroll(obj); setTimeout(function(){ obj.tooltip("destroy").attr("title",title); },time); } }, scroll:function(obj){ var top = 0, win = null, p = obj, over = "", tagName = obj[0].tagName.toUpperCase(), winHeight = 0; if(!obj.length || tagName == "INPUT" || tagName == "TEXTAREA"){ return false; } win = $(window); winHeight = win.height(); top = obj.offset().top; if(top > winHeight/4 && top < winHeight*3/4){ // 元素在可视区域内 return false; } top = obj.offset().top - winHeight/2; while(p = p.parent()){ over = p.css("overflow-y"); if(over == "auto" || over == "scroll"){ p.scrollTop(top); break; } if(p[0].tagName.toLowerCase() == "body"){ win.scrollTop(top); break; } } } }; xmsCore.basic_method = basic_method; function xmsDateFormat(options){ //options支持两个参数 //format,返回字符串的格式,"yyyy/mm/dd hh:ii", //除了其中的字母之外,标点,分隔符等,可以随意修改 //time为一个有效的时间,可以是字符串,可以是对象 //如果只传入一个参数,那么该参数为format的值 if(!options){ throw new TypeError("调用xmsDateFormat时,传入的参数有误!"); } if(typeof options == "string"){ options = {format:options}; } if(typeof options != "object"){ throw new TypeError("调用xmsDateFormat时,传入的参数有误!"); } var format = options.format, t = xmsDateFormat.toDate(options.time), tf = xmsDateFormat.toFormatNum; if(!format || typeof format != "string"){ throw new TypeError("调用xmsDateFormat时,传入对象的format属性不合法!"); } if(t === false){ throw new TypeError("调用xmsDateFormat时,传入对象的time属性不能转换为合法的时间对象!"); } return format.replace(/yyyy|mm|dd|hh|ii/g, function(a){ switch(a){ case 'yyyy': return tf(t.getFullYear()); break; case 'mm': return tf(t.getMonth() + 1); break; case 'dd': return tf(t.getDate()); break; case 'hh': return tf(t.getHours()); break; case 'ii': return tf(t.getMinutes()) break; } }); } //把传入的对象,转换为一个有效的时间对象,并返回该事件对象 xmsDateFormat.toDate = function(date){ var type = typeof date; if(!date || type == "undefined"){ return new Date(); }else if(date instanceof Date){ return isNaN(date.getDate()) ? false : date; }else if((type == "string" || type == "number") && !isNaN(date)){ date = date - 0; }else if(type == "string"){ date = date.replace(/[^\d\s\:]+/g,"/"); } date = new Date(date); return isNaN(date.getDate()) ? false : date; }; //把数字转换为符合时间的两位字符串 xmsDateFormat.toFormatNum = function(num){ return (num < 10 ? '0' : '') + num; } xmsCore.xmsDateFormat = xmsDateFormat; //很多时候,当我们点击回车时,会触发其他的一些事件。 function _xmsEnterTrigger(options){ /* * obj 目标元素 * src obj元素按下enter时,触发src中的type类型的事件 * type src元素将被触发的事件类型 * ctrl 是否需要按下ctrl,默认为false, * alt 是否需要按下alt键,默认为false, * shift 是否需要按下shift键,默认为false * 上述三个,当为ture时,表示ctrl+enter等联合的时,才能触发 */ var objsize = 0, srcsize = 0, obj = null, src = null, type = "", ctrl = false, alt = false, shift = false; try{ obj = options.obj; src = options.src; objsize = obj.size(); srcsize = src.size(); }catch(e){ throw new TypeError("在初始化xmsEnterTrigger时,传入的参数出错!"); } if(!objsize || !srcsize){ throw new TypeError("在初始化xmsEnterTrigger时,传入的参数出错!"); return false; } type = options.type || "click"; ctrl = options.ctrl || false; alt = options.alt || false; shift = options.shift || false; obj.on("keydown",function(e){ e = e || window.event; var code = e.which || e.keyCode, flag = code == 13; if(flag){ //这个时候,判断是否需要altKey键 flag = alt?e.altKey:!e.altKey; } if(flag){ //这个时候,判断是否需要ctrlKey键 flag = ctrl?e.ctrlKey:!e.ctrlKey; } if(flag){ //这个时候,判断是否需要shiftKey键 flag = shift?e.shiftKey:!e.shiftKey; } if(flag){ src.trigger(type); } }); return this; } xmsCore.xmsEnterTrigger = _xmsEnterTrigger; //动态的去load一部分html代码 function _xmsLoadHtml(options){ /* options对象包括以下属性 obj:load的目标元素,load成功后的html,保存到该标签内部 其中,ajax请求的地址,存放在obj标签的data-url标签中 fn:请求前,是否会获取额外的数据,string或者function string或者function的返回值格式为:"name=value&name1=value1" success:loadHtml成功之后,执行的回调 内部this指向obj,传入的值为返回的html代码字符串 error:loadHtml失败时,执行的回调函数 内部this指向obj,传入error的三个参数值 */ var obj = options.obj, newUrl = obj.attr("data-url") || "", fn = options.fn, fnType = typeof fn, data = (fnType == "function")?fn():(fnType == "string")?fn:"", loadding = null; //判断合法性 try{ //只对第一个起作用,顺带判断是否为允许的格式 //不是的话,那么直接抛出一个类型错误。 obj = obj.eq(0); }catch(e){ throw new TypeError("没有找到目标元素,或者目标元素不是jQuery和Zepto对象!"); } newUrl = obj.attr("data-url") || ""; if(!newUrl || !obj.size()){ return false; } $.ajax({ url: newUrl, type: "post", data: data, timeout: 5000, dataType: "html", success: function(html) { var success = options.success; obj.html(html); if(typeof success == "function"){ success.call(obj,html); } obj.trigger("loadHtmlSucc",html); }, error: function(e1,e2,e3) { var err = options.err; loadding.addClass("dn"); if(typeof err == "function"){ err.call(obj,e1,e2,e3); } } }); loadding = _xmsLoadHtml.addOverLay(obj); loadding.removeClass("dn"); return this; } _xmsLoadHtml.addOverLay = function(obj){ var tag = "div", loadding = obj.find(".xms-loadhtml-loadding"); if(loadding.size()){ return loadding; } if(obj.prop("tagName").toLowerCase() == "ul"){ tag = "li"; } loadding = $('<'+tag+' class = "xms-loadhtml-loadding"></'+tag+'>'); if(obj.css("position") == "static"){ obj.addClass("rel"); } obj.append(loadding); return loadding; }; xmsCore.xmsLoadHtml = _xmsLoadHtml; //下载图片相关的方法,需要传入两个参数 //第一个参数为图片的src地址 //第二个参数为回调函数 //会尝试5次下载,5次下载失败,则执行error //回调函数的this对象执行成功或者失败的Image对象 //回调函数内部,可以通过this.type判断,是否成功 function _xmsLoadImg(options){ //fn的内部this指向img的object对象,可以控制各种信息 /* options的参数 { src:"", //表示图片的服务器地址 success:function, //图片从服务器加载成功之后,执行的成功回调 error:function //图片加载失败时,执行的回调 } */ var src = "", success = null, error = null, loadTime = 0; try{ src = options.src || ""; }catch(e){ src = ""; } if(!src){ throw new TypeError("load imgae need src!"); } success = options.success; error = options.error; load(); function load(){ var imgObj = new Image(); imgObj.type = "success"; imgObj.onload = success; imgObj.onerror = _error; imgObj.src = src; loadTime++; } function _error(p1,p2,p3){ if(loadTime < 5 ){ //如果图下载失败,则尝试最多五次 load(); }else{ //如果下载图片失败,则也执行回调,并把this传入 this.type = "error"; if(typeof error == "function"){ error.call(this); } } } } xmsCore.xmsLoadImg = _xmsLoadImg; //更改url的一个函数, //支持两个参数,第一个参数为url,可以为绝对和相对地址 //第二个参数为string或者fn(),string或者返回值为"name1=value1&name2=value2" //格式的字符串。 //第二个参数的同名数据,会覆盖url中的同名数据 function _xmsQueryUrl(options){ //更改url的链接,需要 /* options支持两个参数 { url:"",//原有的url值 fn:"",额外需要添加或者更新到url上的数据值 } */ var url = "", arr = null, hostStr = "", searchObj = null; try{ url = options.url || ""; }catch(e){ url = ""; } if(!url){ throw new TypeError("在使用xmsQueryUrl方法时,传入的对象必须包含url的属性值!"); } //前面的判断,会验证options为一个对象, //那么如果没有定义fn,则直接返回url if(!options.fn){ return url; } // http://www.xiaomishu.com?key1=1&key2=2 // 以?作为分割将字符串分为两部分 arr = url.split("?"); hostStr = arr[0] || ""; searchObj = xmsCore.xmsStrToObj(arr[1] || ""); //把新的数据,覆盖同名原有的数据 $.extend(searchObj,_xmsQueryUrl.getData(options.fn)); return hostStr+"?"+xmsCore.xmsObjToStr(searchObj); } _xmsQueryUrl.getData = function(fn){ //根据传入的fn的值 var fnType = typeof fn, str = "", obj = null; if(fnType == "function"){ str = fn(); if(typeof str == "object"){ return str; } }else if(fnType == "string"){ str = fn; }else if(fnType == "object" && fn){ return fn; } return xmsCore.xmsStrToObj(str); }; xmsCore.xmsQueryUrl = _xmsQueryUrl; //防止多次提交,有做提交信息的频率限制 function xmsFormSubmit(obj,options){ /* //obj为需要绑定该方法的Form的jQuery/Zepto对象。 //options可以为一个函数,也可以是一个对象 //如果options为一个对象,那么它支持以下三个参数 //callback:function,当成功之后执行的回调, // 其内部this指向obj // 传入一个参数,为提交返回的JSON对象。 //error:function,当执行失败时的处理, // 如果设置了该方法,那么错误时,按照该方法处理 // 如果没有设置该方法,那么执行一个默认的错误提示。 //beforeFn:function,在提交数据之前的处理的验证 // 内部this指向obj,做一些特殊的验证,或者处理 // 如果该方法返回的是false,那么会停止AJAX的提交 //className:"xms-form-submit-waiting", // 当form处于正在提交状态时,会给form添加该样式。 */ if(!(this instanceof xmsFormSubmit)){ return new xmsFormSubmit(obj,options,className); } try{ obj.size(); }catch(e){ throw new TypeError("xmsFormSubmit初始化时传入的对象不合法。"); } this.obj = obj.eq(0); this.options = options; this.initEvent(); } xmsFormSubmit.prototype.initEvent = function(){ var options = this.options, obj = this.obj, className = "xms-form-submit-waiting", success = null, error = null, beforeFn = null, method = obj.attr("method") || "post", url = obj.attr("action"), submitTimer = false, reqOptions = {sep:","}; this.initEvent = null; if(typeof options == "function"){ success = options; }else{ success = options.success || options.callback || ""; error = options.error || ""; beforeFn = options.beforeFn || ""; className = options.className || className; errorMsgBox = $(className); errorMsgDetail = errorMsgBox.find('span.error-cont-detail').eq(0); } if(!url || obj.prop("xmsFormSubmit") === "true"){ return false; } //如果能找到对应的元素,则处理 obj.on("submit",_submitCb); obj.find("[type=submit]").on("click",_triggerSubmitCb); obj.find("button").on("click",_triggerSubmitCb); obj.prop("xmsFormSubmit","true"); function _triggerSubmitCb(){ if(errorMsgBox && errorMsgBox.hasClass('show-msg')){ errorMsgBox.removeClass('show-msg'); } if(submitTimer == true){ return false; } submitTimer = true; obj.trigger("submit",this); setTimeout(function(){ submitTimer = false; },500); return false; } function _submitCb(e){ if(errorMsgBox && errorMsgBox.hasClass('show-msg')){ errorMsgBox.removeClass('show-msg'); } var reqStr = ""; if(obj.hasClass(className)){ alert("正在提交数据,请稍后!"); return false; } if(!obj.xmsAllpass()){ return false; } // 自定义表单提交前操作 if(typeof beforeFn == "function" && !beforeFn.call(obj)){ return false; } reqStr = obj.serialize(); if("xmsQueryParam" in xmsCore){ reqOptions.data = reqStr; reqStr = xmsCore.xmsQueryParam(reqOptions); } $.ajax({ url:url, type:method, data:reqStr, dataType:"json", success:function(data){ obj.removeClass(className); //之所以把该代码放在最前面,是防止后面的代码, //抛出异常时,不会影响整个form表单的后续动作 data = ( typeof data == "object" ) ? data : JSON.stringify(data); if(typeof success == "function"){ success.call(obj,data); } }, error:function(){ obj.removeClass(className); if(typeof error == "function"){ error.call(obj,arguments); }else{ alert("由于网络的原因,您刚才的操作没有成功。"); } } }); //放在这里提交,也是为了防止一些不确定的异常,导致无法提交。 obj.addClass(className); return false; } } xmsCore.xmsFormSubmit = xmsFormSubmit; /* //str的格式为:“按时间段卢卡斯爱上大声地dajsjdk{{name}}阿斯顿静安寺,{{age}}阿斯顿就卡死了都看见啊” //str中,只有“{{name}}”中的值,会被obj[name]的属性值替换 //所以,请注意格式。 */ function _xmsTmplete(str,obj){ if(!str || ( typeof str != "string") || !obj || (typeof obj != "object")){ return ""; } var reg = /\{\{([^\s]+?)\}\}/g; str = str.replace(reg,_replace); function _replace(p1,p2){ var i = 0, key = p2.split("."), len = key.length, value = obj, type = ""; for( i ; i < len ;i += 1){ value = value[key[i]]; type = typeof value; if( type == "string" || type == "number" || type == "boolean"){ if(i == (len-1)){ return value; }else{ return p2; } } if(type == "undefined" || value === null){ if( i == (len-1) ){ return ""; }else{ return p2; } } } return p2; }; return str; } xmsCore.xmsTmplete = _xmsTmplete; /* options是一个对象,支持以下参数 date:日期值,如果没有,那么作为当天, 请输入有效的可以转换为时间对象的数组 length:获取的长度。 lineFirst:0, //表示一行,以周几开始,默认为0,表示一周以周日开始 //该数据,只有在获取整月时有效。 */ function _xmsCustomDate(){ function _getDateObject(time){ var date = null, year = 0, month = 0, day = 0, week = 0; if(time){ date = new Date(time); }else{ date = new Date(); } year = date.getFullYear(); month = date.getMonth() + 1; day = date.getDate(); week = date.getDay(); if(month < 10){ month = "0" + month; } if(day < 10){ day = "0" + day; } return { year:year, month:month, day:day, week:week }; } function _toDate(date){ var type = typeof date; if(!date || type == "undefined"){ return new Date(); }else if(date instanceof Date){ return isNaN(date.getDate()) ? false : date; }else if((type == "string" || type == "number") && !isNaN(date)){ date = date - 0; }else if(type == "string"){ date = date.replace(/[^\d\s\:]+/g,"/"); } date = new Date(date); return isNaN(date.getDate()) ? false : date; } //按照时间长度,获取规定日期的时间数组 function _getLatestDate(date,len){ var i = 0, arr = [], one = null, secs = 86400000; for(i;i<len;i+=1){ arr.push(_getDateObject(date)); date += secs; } return arr; } //按照月份,获取时间数组 function _getMonthDate(date,lineFirst){ var curDay = _getDateObject(date), fristDay = (new Date(curDay.year+"/"+curDay.month+"/01")).getTime(), monthDay = _getDateObject(fristDay), arr = [], month = monthDay.month, one = monthDay, i = 1, secs = 86400000; //添加上月末尾的信息 while(one.week !== lineFirst){ one = _getDateObject(fristDay - secs*i); i++; arr.push(one); } if(arr.length){ arr.reverse(); } //添加本月的信息 while(monthDay.month == month){ arr.push(monthDay); fristDay += secs; monthDay = _getDateObject(fristDay); } //当月最后一天,正好是周六,属于最后一天 //直接返回 if(monthDay.week == lineFirst){ return arr; } //添加下一月开头的一些信息 while(monthDay.week != lineFirst){ arr.push(monthDay); fristDay += secs; monthDay = _getDateObject(fristDay); } return arr; } function xmsCustomDate(options){ if(!options || (typeof options == "function")){ throw new TypeError("在调用xmsGetLatestDate时,传入的参数有误!"); } var len = options.length || 0, date = _toDate(options.date), lineFirst = options.lineFirst || 0, dateArr = null; if(date === false){ throw new TypeError("调用xmsGetLatestDate时,传入对象的date属性不能转换为合法的时间对象!"); } date = date.getTime(); if(len){ //获取固定的天数 dateArr = _getLatestDate(date,len); }else{ //获取传入时间所在的月,按“周”获取(会有上月和下月的几天) dateArr = _getMonthDate(date,lineFirst); } return dateArr; } return xmsCustomDate; } xmsCore.xmsCustomDate = _xmsCustomDate(); //使用闭包了。 //模拟radio的样式 function _xmsRadio(options){ /* obj为container */ var obj = null, input = null, items = null; try{ obj = options.obj; if(!obj.size()){ throw new Error("error"); } }catch(e){ throw new TypeError("在初始化xmsRadio时,传入的参数有误!"); } obj = obj.eq(0); input = obj.find(".xms-radio-input"); items = obj.find(".xms-radio-item"); items.on("click",_clickCb); function _clickCb(){ var _obj = $(this), value = _obj.attr("data-value"); if(_obj.hasClass("active")){ return false; } input.val(value); items.removeClass("active"); _obj.addClass("active"); input.trigger("change"); } _init(); function _init(){ var v = input.val() || ""; if(!v){ return ""; } $.each(items,function(){ var _obj = $(this); if(_obj.attr("data-value") == v){ _clickCb.call(this); return false; } }); } } xmsCore.xmsRadio = _xmsRadio; //模拟checkbox的样式 function _xmsCheckBox(options){ /* obj为container */ var obj = null, input = null; try{ obj = options.obj; if(!obj.size()){ throw new Error("error"); } }catch(e){ throw new TypeError("在初始化xmsCheckBox时,传入的参数有误!"); } input = obj.find(".xms-checkbox-input"); obj.on("click",_clickCb); function _clickCb(){ if(obj.hasClass("active")){ input.prop("checked",false); }else{ input.prop("checked",true); } obj.toggleClass("active"); input.trigger("change"); } _init(); function _init(){ if(input.prop("checked") === true){ obj.addClass("active"); }else{ obj.removeClass("active"); } } } xmsCore.xmsCheckBox = _xmsCheckBox; })(window);
7b756303297683b794c2c58ce8a4ed6774c4b625
[ "JavaScript" ]
1
JavaScript
KeepStudyOn/paymentWap_V1.0
2fbaa8a850398e77ee7b4128b764011fc9795d5c
eb62d92a9770bdb3b30a0314d10a9f60f5ca4fcb
refs/heads/master
<repo_name>ML-DKC-Training/Session1-Day2<file_sep>/mongo_connect.py """ An example of how to connect to MongoDB """ import sys from pymongo import MongoClient from random import randint from pymongo.errors import ConnectionFailure # step 1: Connect to MongoDb server try: c = MongoClient(host="localhost", port=27017) print ("Connected successfully") except ConnectionFailure: sys.stderr.write("Could not connect to MongoDB") db = c.trial # step 2: create sample data names = ['Kitchen','Animal','State', 'Tastey', 'Big','City','Fish', 'Pizza','Goat', 'Salty','Sandwich','Lazy', 'Fun'] company_type = ['LLC','Inc','Company','Corporation'] company_cuisine = ['Pizza', 'Bar Food', 'Fast Food', 'Italian', 'Mexican', 'American', 'Sushi Bar', 'Vegetarian'] for x in range(1, 501): trial = { 'name' : names[randint(0, (len(names)-1))] + ' ' + names[randint(0, (len(names)-1))] + ' ' + company_type[randint(0, (len(company_type)-1))], 'rating' : randint(1, 5), 'cuisine' : company_cuisine[randint(0, (len(company_cuisine)-1))] } #Step 3: Insert trial object directly into MongoDB via isnert_one result=db.reviews.insert_one(trial) # insert_one will insert one document into MongoDb #Step 4: Print to the console the ObjectID of the new document print('Created {0} of 100 as {1}'.format(x,result.inserted_id)) #Step 5: Tell us that you are done print('finished creating 100 business reviews')<file_sep>/mongo_update.py from pymongo import MongoClient #include pprint for readabillity of the from pprint import pprint #change the MongoClient connection string to your MongoDB database instance c = MongoClient() db=c.trial ASingleReview = db.reviews.find_one({}) print('A sample document:') pprint(ASingleReview) result = db.reviews.update_one({'_id' : ASingleReview.get('_id') }, {'$inc': {'likes': 1}}) print('Number of documents modified : ' + str(result.modified_count)) UpdatedDocument = db.reviews.find_one({'_id':ASingleReview.get('_id')}) print('The updated document:') pprint(UpdatedDocument) """If you wanted to update all the fields of the document and keep the same ObjectID you will want to use the replace_one function."""<file_sep>/README.md # Session1-Day2 Intermediate Python and MongoDb <file_sep>/mongo_delete.py year_lst=[1980, 1988, 1990, 1992, 1993, 1998, 2002] Leap_Years=list(filter(lambda leap_yrs:(leap_yrs%4==0),year_lst)) print("Leap years after applying filter: ", Leap_Years) #from pymongo import MongoClient #change the MongoClient connection string to your MongoDB database instance c = MongoClient() db=c.trial result = db.restaurants.delete_many({"category": "Bar Food"}) bar_food = db.reviews.find({'category': 'Bar Food'}).count() print(bar_food)
d5e420b84efac21148ef4ee3e9e491e5ad3e508f
[ "Markdown", "Python" ]
4
Python
ML-DKC-Training/Session1-Day2
a9144b4c9666b667568c4f87944ff114e723ca57
350a578e961f23f58c2e5659dde369360d8a43cb
refs/heads/master
<repo_name>Woodu/taiko.tk<file_sep>/Lib/Action/IndexAction.class.php <?php // By:Woodu ver 3.2 // 2012 02 11 class IndexAction extends Action { public function Index() { //echo 'aaa'; $Demo = new Model('youxijiting');//创建查询对象 $condition['deleted'] = 0; $list = $Demo->where($condition)->order('id desc')->limit('1')->select();//赋予条件 //dump($list); $this->assign('list',$list); $this->display(); // 输出模板 } } ?><file_sep>/README.md # taiko.tk 2012年的太鼓太鼓!源码 <file_sep>/Lib/Action/CityAction.class.php <?php // 本文档自动生成,仅供测试运行 //require("./test.php"); class CityAction extends Action { /** +---------------------------------------------------------- * 默认操作 +---------------------------------------------------------- */ // 数据写入操作 Public function _empty() { // 把所有城市癿操作都览枂刡city方法 $cityName = ACTION_NAME; if($cityName == "index") $cityName=htmlspecialchars($_POST['cityName']); $this->city($cityName); } Public function fankui() { $Demo12 = new Model('jiting'); $Demo12->text = htmlspecialchars($_POST['text']); $Demo12->securecode = Cookie::get('secureid'); $Demo12->username = htmlspecialchars(Cookie::get('username')); $Demo12->url = urlencode(htmlspecialchars($_POST['url'])); $Demo12->create(); //var_dump($Demo12); //$Demo12->create(); //$Demo23['text'] = htmlspecialchars($_POST['text']); //$Demo23['securecode'] = Cookie::get('secureid'); //$Demo23['username'] = htmlspecialchars(Cookie::get('username')); //Demo23['url'] = urlencode(htmlspecialchars($_POST['url'])); $result = $Demo12->add(); //echo $result; if ($result) {//echo $result; $this->assign('informationtext', '提交成功哦!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', 'Javascript:window.history.go(-1)');//模板变量赋值 $this->display('Public:information');//如果模板为空 } else { $this->assign('informationtext', '提交失败,不过还是谢谢你。请登录后再提交哦');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', 'Javascript:window.history.go(-1)');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } Public function city($name) { // 和$name 返个城市相关癿处理 //确认没提交基厅id if($_GET['ViewJiting']<>'') //如果提交了 { $linshibianliang=htmlspecialchars($_GET['ViewJiting']); //echo $linshibianliang; $this->getjiting($linshibianliang); } else { //$py=new py_class(); //$name = iconv('GBK', 'UTF-8',strtolower($py->str2py($name)));//输出城市名 $Demo = new Model('youxijiting');//创建查询对象 $condition['yxt_area'] = $name; //地区名 魔都-上海 妖都-广州 古都-西安 帝都-北京 if($condition['yxt_area'] == "魔都") $condition['yxt_area'] = "上海"; if($condition['yxt_area'] == "妖都") $condition['yxt_area'] = "广州"; if($condition['yxt_area'] == "古都") $condition['yxt_area'] = "西安"; if($condition['yxt_area'] == "帝都") $condition['yxt_area'] = "北京"; $condition['deleted'] = 0; $list = $Demo->where($condition)->select();//赋予条件 //echo 'asdfasdfasdf'; //echo $name; //$this->assign('CityName',$name); if($list == NULL) { if($name == NULL){ $this->assign('informationtext','直接访问什么的可不好哟,年轻人'); // 模板发量赋值 $this->assign('informationtitle','太鼓太鼓提示'); // 模板发量赋值 $this->assign('informationurl','__APP__');//模板变量赋值 $this->display('Index:index'); //如果模板为空 } else{ $this->assign('informationtext','抱歉,暂时没有'.$name.'的信息哦。要不要帮我们加一下?'); // 模板发量赋值 $this->assign('informationtitle','太鼓太鼓提示'); // 模板发量赋值 $this->assign('informationurl','__APP__/New');//模板变量赋值 $this->display('Public:information'); //如果模板为空 } } else { $this->assign('CityName',$name); // 模板发量赋值 $this->assign('list',$list); // 模板发量赋值 $this->display('index'); // 输出模板 } } } /** +---------------------------------------------------------- * 探针模式 +---------------------------------------------------------- */ Public function getjiting($id) { // 和$name 返个城市相关癿处理 //确认没提交基厅id //$py=new py_class(); //$name = iconv('GBK', 'UTF-8',strtolower($py->str2py($name)));//输出城市名 //echo '当前城市: '.$id; $Demo1 = new Model('youxijiting');//创建查询对象 $Demo2 = new Model('youxijitai');//创建查询对象 $Demo3 = new Model('youxijiting');//创建查询对象 $condition1['id'] = $id; //地区名 $condition2['yxtid'] = $id; //地区名 $condition2['deleted'] = 0; $list1 = $Demo1->where($condition1)->select();//赋予条件 $list2=$Demo2->where($condition2)->select(); $list22 = $Demo3->getField('yxt_area','id = '.$condition1['id']);//赋予条件 //$list2 = $Demo1->where($condition1)->select(); //echo 'asdfasdfasdf'; //print_r($list1); //echo $list1['yxt_name']; //$this->assign('CityName',$name); $this->assign('CityName',$list22); // 模板发量赋值 $this->assign('jitingmingzi',$list1); // 模板发量赋值 $this->assign('jitai',$list2); // 模板发量赋值 $this->display('room'); // 输出模板 } } ?><file_sep>/Conf/config.php <?php return array( //'配置项'=>'配置值' 'APP_DEBUG' => false, // 开启调试模式 'DB_TYPE'=> 'mysql', // 数据库类型 'DB_HOST'=> 'localhost', // 数据库朋务器地址 'DB_NAME'=>'', // 数据库名称 'DB_USER'=>'', // 数据库用户名 'DB_PWD'=>'', // 数据库密码 'DB_PORT'=>'', // 数据库端口 'DB_PREFIX'=>'', // 数据表前缀 ); ?><file_sep>/Lib/Action/EditAction.class.php <?php // 本文档自动生成,仅供测试运行 //require("./test.php"); class EditAction extends Action{ /** +---------------------------------------------------------- * 默认操作 +---------------------------------------------------------- */ // 数据写入操作 public function submiteditjt() { $test=checklogin(); $secureid = Cookie::get('secureid'); //echo md5($secureid).'<br>'.$_POST['verify']; $test2= md5($secureid)==htmlspecialchars($_POST['verify'], ENT_QUOTES);//摆设 if ($test and $test2) { $Demo = new Model('youxijiting');// 实例化模型类 $condition['id'] = htmlspecialchars($_POST['yxt_id'], ENT_QUOTES);//地区名 $list = $Demo->getField('username','id = '.$condition['id']);//赋予条件 //->getField('username') //echo $list; $username = Cookie::get('username'); $secureusername = Cookie::get('secureusrname'); $secureusername_chk = securecode($secureid, $username); //$condition['username'] = md5($username);//以用户名为md5值查询 if(($list == md5($username)) and ($secureusername == $secureusername_chk))//验证是不是此用户 { //处理数据 $Demo3 = new Model('youxijiting');// 实例化模型类 //$Demo2 = new Model('youxijiting');// 实例化模型类 $Demo2['id'] = $condition['id']; $Demo2['yxt_name'] = htmlspecialchars($_POST['yxt_name'], ENT_QUOTES); $Demo2['yxt_address'] = htmlspecialchars($_POST['yxt_address'], ENT_QUOTES); $Demo2['yxt_hyjg'] = htmlspecialchars($_POST['yxt_hyjg'], ENT_QUOTES); $Demo2['yxt_csqk'] = htmlspecialchars($_POST['yxt_csqk'], ENT_QUOTES); $Demo2['yxt_jtqk'] = htmlspecialchars($_POST['yxt_jtqk'], ENT_QUOTES); $Demo2['deleted'] = htmlspecialchars($_GET['delete'], ENT_QUOTES); //检查是否删除 //$Demo2['yxt_area'] = htmlspecialchars($_POST['location'], ENT_QUOTES); //$Demo2->Create();// 创建数据对象 // 写入数据库 if($Demo2['deleted'] == 'yes') {$Demo2['deleted'] = '1';} else {$Demo2['deleted'] = '0';} $result = $Demo3->save($Demo2); //echo $result; if ($result) {//写入成功了 $this->assign('informationtext', '修改成功!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } else { $this->assign('informationtext', '数据写入失败!如果操作正常而多次出现本错误可能是协作者锁定了本数据!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } else{ //不是用户 $this->assign('informationtext', '权限失败,请使用录入人帐号请登录后再试!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } //$this->redirect('/Index/index', array('redirect'=>1), 3,'请稍等'); else { $this->assign('informationtext', '用户鉴权失败。请重新登陆后再试。');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/New/'.$_POST['location']);//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function delete() { $test=checklogin(); //echo $test; $secureid = Cookie::get('secureid'); //echo md5($secureid).'<br>'.$_POST['verify']; $test2= 1; if ($test and $test2) { $Demo = new Model('youxijiting');// 实例化模型类 $condasdfasdf = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 $condasdfasdf; $list = $Demo->getField('username','id = '.$condasdfasdf);//赋予条件 //->getField('username') //echo $list; $username = Cookie::get('username'); $secureusername = Cookie::get('secureusrname'); $secureusername_chk = securecode($secureid, $username); //$condition['username'] = md5($username);//以用户名为md5值查询 if(($list == md5($username)) and ($secureusername == $secureusername_chk))//验证是不是此用户 { //处理数据 $Demo3 = new Model('youxijiting');// 实例化模型类 //$Demo2 = new Model('youxijiting');// 实例化模型类 $Demo2['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES); $Demo2['deleted'] = '1'; //检查是否删除 //$Demo2['yxt_area'] = htmlspecialchars($_POST['location'], ENT_QUOTES); //$Demo2->Create();// 创建数据对象 // 写入数据库 $result = $Demo3->save($Demo2); //echo $result; if ($result) {//写入成功了 $this->assign('informationtext', '已经删除。');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } else { $this->assign('informationtext', '删除失败。抱歉。');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } else{ //不是用户 $this->assign('informationtext', '权限失败,请使用录入人帐号请登录后再试!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } //$this->redirect('/Index/index', array('redirect'=>1), 3,'请稍等'); else { $this->assign('informationtext', '用户鉴权失败。请重新登陆后再试。');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/New/'.$_POST['location']);//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function editjt() {//确认用户是否登录 $test=checklogin(); $Demo = new Model('youxijiting');// 实例化模型类 $condition['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 $list = $Demo->getField('username','id = '.$condition['id']);//赋予条件 $username = Cookie::get('username'); $secureid = Cookie::get('secureid'); $secureusername = Cookie::get('secureusrname'); $secureusername_chk = securecode($secureid, $username); //$condition['username'] = md5($username);//以用户名为md5值查询 $test2 = ($list == md5($username)) and ($secureusername == $secureusername_chk);//验证是不是此用户 if (($test) and ($test2)) { $showjiting = new Model('youxijiting'); $condition['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 $condition['deleted'] = 0;//是否删了? $list = $showjiting->where($condition)->select();//赋予条件 //echo $list; //$this->assign('yxt_name',$yxt_name); // 模板发量赋值 $this->assign('list', $list);// 模板发量赋值 //$this->assign('yxt_address',$yxt_address); // 模板发量赋值 //$this->assign('yxt_hyjg',$yxt_hyjg); // 模板发量赋值 //$this->assign('yxt_csqk',$yxt_csqk); // 模板发量赋值 //$this->assign('yxt_jtqk',$yxt_jtqk); // 模板发量赋值 $username = Cookie::get('username'); $this->assign('CityName', $username.'添加的机厅');// 模板发量赋值 $this->assign('verify', md5($secureid));// 模板发量赋值 $this->display('editjt');// 输出模板 } else { $this->assign('informationtext', '鉴权失败。请使用该机厅添加者帐号登录!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit/');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function viewgd() {//确认用户是否登录 $test=checklogin(); $Demo = new Model('youxijiting');// 实例化模型类 $condition['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 $condition['deleted'] = 0;//是否删了? $list = $Demo->getField('username','id = '.$condition['id']);//赋予条件 $username = Cookie::get('username'); $secureid = Cookie::get('secureid'); $secureusername = Cookie::get('secureusrname'); $secureusername_chk = securecode($secureid, $username); //$condition['username'] = md5($username);//以用户名为md5值查询 $test2 = ($list == md5($username)) and ($secureusername == $secureusername_chk);//验证是不是此用户 if (($test) and ($test2)) { $showgudian = new Model('youxijitai'); $condition3['yxtid'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 $condition3['deleted'] = 0;//地区名 $list2 = $showgudian->where($condition3)->select();//赋予条件 //echo $list; //$this->assign('yxt_name',$yxt_name); // 模板发量赋值 $this->assign('list', $list2);// 模板发量赋值 //$this->assign('yxt_address',$yxt_address); // 模板发量赋值 //$this->assign('yxt_hyjg',$yxt_hyjg); // 模板发量赋值 //$this->assign('yxt_csqk',$yxt_csqk); // 模板发量赋值 //$this->assign('yxt_jtqk',$yxt_jtqk); // 模板发量赋值 $username = Cookie::get('username'); $this->assign('CityName', $username.'添加的机厅');// 模板发量赋值 $this->assign('yxtid', $condition3['yxtid']);// 模板发量赋值 $this->display('gudian');// 输出模板 } else { $this->assign('informationtext', '鉴权失败。请使用该机厅添加者帐号登录!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit/');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function submiteditac() { $test=checklogin(); $secureid = Cookie::get('secureid'); $test2= 1;//摆设 if ($test and $test2) { //Demo = new Model('youxijitai');// 实例化模型类 //$condition['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 //$list = $Demo->getField('username','yxtid = '.$condition['id']);//赋予条件 //->getField('username') //echo $list; $username = Cookie::get('username'); $ididid = htmlspecialchars($_POST['id'], ENT_QUOTES); $list = checkyyz($ididid); //echo md5($username).'<br>'.$username.'<br>'.$list; $secureusername = Cookie::get('secureusrname'); $secureusername_chk = securecode($secureid, $username); //$condition['username'] = md5($username);//以用户名为md5值查询 if(($list == md5($username)) and ($secureusername == $secureusername_chk))//验证是不是此用户 { //处理数据 $Demo4 = new Model('youxijitai');// 实例化模型类 //$Demo2 = new Array('youxijitai');// 实例化模型类 $Demo3['id'] = (int)htmlspecialchars($_POST['id'], ENT_QUOTES); //$Demo4->find($Demo5['id']); $Demo5['yxtid'] = htmlspecialchars($_POST['yxtid'], ENT_QUOTES); $Demo5['jt_dm'] = htmlspecialchars($_POST['jt_dm'], ENT_QUOTES); $Demo5['jt_jg'] = htmlspecialchars($_POST['jt_jg'], ENT_QUOTES); $Demo5['jt_gk'] = htmlspecialchars($_POST['jt_gk'], ENT_QUOTES); $Demo5['id'] = htmlspecialchars($_POST['id'], ENT_QUOTES); $Demo5['deleted'] = htmlspecialchars($_POST['deleted'], ENT_QUOTES); //$Demo2->Create();// 创建数据对象 //echo $Demo5['deleted']; if($Demo5['deleted'] == 'no') {$Demo5['deleted'] = '1';} else {$Demo5['deleted'] = '0';} //echo $Demo5['deleted']; $result = $Demo4->where($Demo3)->save($Demo5); //$this->error($Form->getError()); //echo $Demo3->getLastSql(); //echo $result; if ($result !== false) {//写入成功了 $this->assign('informationtext', '修改成功!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } else { $this->assign('informationtext', '数据写入失败!如果操作正常而多次出现本错误可能是协作者锁定了本数据!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } else{ //不是用户 $this->assign('informationtext', '权限失败,请使用录入人帐号请登录后再试!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } //$this->redirect('/Index/index', array('redirect'=>1), 3,'请稍等'); else { $this->assign('informationtext', '暂未登录。请登录后再试。');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit'.$_POST['location']);//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function editac() {//确认用户是否登录 $test=checklogin(); $Demo = new Model('youxijiting');// 实例化模型类 $condition['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 $list = $Demo->getField('username','id = '.$condition['id']);//赋予条件 $username = Cookie::get('username'); $secureid = Cookie::get('secureid'); $secureusername = Cookie::get('secureusrname'); $secureusername_chk = securecode($secureid, $username); //$condition['username'] = md5($username);//以用户名为md5值查询 $test2 = (1 == 1) and ($secureusername == $secureusername_chk);//验证是不是此用户 if (($test) and ($test2)) { $showjitai = new Model('youxijitai'); $condition2['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 $condition2['deleted'] = 0;//地区名 $list = $showjitai->where($condition2)->select();//赋予条件 //echo $condition2['yxtid']; //var_dump($list); //$this->assign('yxt_name',$yxt_name); // 模板发量赋值 $this->assign('list', $list);// 模板发量赋值 //$this->assign('yxt_address',$yxt_address); // 模板发量赋值 //$this->assign('yxt_hyjg',$yxt_hyjg); // 模板发量赋值 //$this->assign('yxt_csqk',$yxt_csqk); // 模板发量赋值 //$this->assign('yxt_jtqk',$yxt_jtqk); // 模板发量赋值 $username = Cookie::get('username'); $this->assign('CityName', $username.'添加的机厅');// 模板发量赋值 //$this->assign('verify', md5($secureid));// 模板发量赋值 $this->display('editac');// 输出模板 } else { $this->assign('informationtext', '鉴权失败。请使用该机厅添加者帐号登录!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit/');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function insertnewac() { $test=checklogin(); $secureid = Cookie::get('secureid'); $test2= 1;//摆设 if ($test and $test2) { //Demo = new Model('youxijitai');// 实例化模型类 //$condition['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 //$list = $Demo->getField('username','yxtid = '.$condition['id']);//赋予条件 //->getField('username') //echo $list; $username = Cookie::get('username'); $ididid = htmlspecialchars($_POST['yxtid'], ENT_QUOTES); $Demo233 = new Model('youxijiting');// 实例化模型类 $list = $Demo233->getField('username','id = '.$ididid);//赋予条件 //echo md5($username).'<br>'.$username.'<br>'.$list; $secureusername = Cookie::get('secureusrname'); $secureusername_chk = securecode($secureid, $username); //$condition['username'] = md5($username);//以用户名为md5值查询 if(($list == md5($username)) and ($secureusername == $secureusername_chk))//验证是不是此用户 { //处理数据 $youxijitai = new Model('youxijitai'); // 实例化模型类 $youxijitai->yxtid = htmlspecialchars($_POST['yxtid'], ENT_QUOTES); $youxijitai->jt_dm = htmlspecialchars($_POST['jt_dm'], ENT_QUOTES); $youxijitai->jt_jg = htmlspecialchars($_POST['jt_jg'], ENT_QUOTES); $youxijitai->jt_gk = htmlspecialchars($_POST['jt_gk'], ENT_QUOTES); $youxijitai->Create(); // 创建数据对象 // 写入数据库 if($result = $youxijitai->add()){ $this->assign('yxtid',htmlspecialchars($_POST['yxtid'], ENT_QUOTES)); $condition['yxtid'] = htmlspecialchars($_POST['yxtid'], ENT_QUOTES); //地区名 $list = $youxijitai->where($condition)->select();//赋予条件 //$Demo->closeConnect(); $this->assign('list',$list); // 模板发量赋值 $this->assign('informationtext', '添加成功哦。');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit/viewgd/?jitingid='.htmlspecialchars($_POST['yxtid'], ENT_QUOTES));//模板变量赋值 $this->display('Public:information');//如果模板为空 } else { $this->redirect('/Index/index', array(''), 5,'数据写入错误!返回首页中'); } //$this->redirect('/Index/index', array('redirect'=>1), 3,'请稍等'); } else{ //不是用户 $this->assign('informationtext', '权限失败,请使用录入人帐号请登录后再试!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } //$this->redirect('/Index/index', array('redirect'=>1), 3,'请稍等'); else { $this->assign('informationtext', '暂未登录。请登录后再试。');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit'.$_POST['location']);//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function addgd() {//确认用户是否登录 $test=checklogin(); $Demo = new Model('youxijiting');// 实例化模型类 $condition['id'] = htmlspecialchars($_GET['jitingid'], ENT_QUOTES);//地区名 $list = $Demo->getField('username','id = '.$condition['id']);//赋予条件 $username = Cookie::get('username'); $secureid = Cookie::get('secureid'); $secureusername = Cookie::get('secureusrname'); $secureusername_chk = securecode($secureid, $username); //$condition['username'] = md5($username);//以用户名为md5值查询 $test2 = (1 == 1) and ($secureusername == $secureusername_chk);//验证是不是此用户 if (($test) and ($test2)) { //$jitingid = $this->assign('yxtid', $condition['id']);// 模板发量赋值 //$this->assign('yxt_address',$yxt_address); // 模板发量赋值 //$this->assign('yxt_hyjg',$yxt_hyjg); // 模板发量赋值 //$this->assign('yxt_csqk',$yxt_csqk); // 模板发量赋值 //$this->assign('yxt_jtqk',$yxt_jtqk); // 模板发量赋值 $username = Cookie::get('username'); $this->assign('CityName', $username.'添加的机厅');// 模板发量赋值 //$this->assign('verify', md5($secureid));// 模板发量赋值 $this->display('addgd');// 输出模板 } else { $this->assign('informationtext', '鉴权失败。请使用该机厅添加者帐号登录!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit/');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } // 数据查诟操作 Public function _empty() {// 把所有城市癿操作都览枂刡city方法 $name = ACTION_NAME; if ($name == 'index') { $cityName=htmlspecialchars($_POST['location']); } $this->index(); } public function index() { $this->checklogin(1); } public function returnlogin() { $redirect_uri = 'http://taiko.52yinyou.net/Edit/returnlogin'; $authorization_code = $_REQUEST['code'];//echo $authorization_code; $token_uri = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code='. htmlspecialchars($_REQUEST['code'], ENT_QUOTES). '&client_id=zQcuDz31BKDeA6GHLjgOeYWl&client_secret=<KEY>&redirect_uri='. urlencode($redirect_uri); $retval = request($token_uri, NULL); if ($retval != NULL) { $Arr = json_decode($retval); } else { $this->assign('informationtext', '服务器过载,与百度通信错误!请刷新重试');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', 'Javascript:window.history.go(-1)');//模板变量赋值 $this->display('Public:information');//如果模板为空 } $useruri = 'https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?access_token='.$Arr->access_token.'&format=json'; $retvaluser = request($useruri, NULL);//echo $useruri; //echo $retvaluser; if ($retvaluser != NULL) { $Arr2 = json_decode($retvaluser); } else { $this->assign('informationtext', '用户信息获取失败,可能是服务器与百度通信错误!请刷新重试');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', 'Javascript:window.history.go(-1)');//模板变量赋值 $this->display('Public:information');//如果模板为空 } //此时用户名$Arr2->uname。uid是$Arr2->uid。 $newusername = $Arr2->uname; if ($newusername != NULL) { $newuid = $Arr2->uid; Cookie::set('username', $newusername, time()+3600*24); $secureid = securecode($newusername, $newuid); Cookie::set('secureid', $secureid, time()+3600*24); Cookie::set('uid', $newuid, time()+3600*24); $secureusrname = securecode($secureid, $newusername); Cookie::set('secureusrname', $secureusrname, time()+3600*24); $this->checklogin(1); } else { $this->assign('informationtext', '数据错误,请不要返回刷新本页!请重新点击登录按钮');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } //this->redirect('/Edit/index', array(''), 1,'数据写入错误!返回首页中'); //if(Cookie::get('secureid') != securecode(Cookie::get('username'),Cookie::get('uid'))){ //如果说你的验证是不通过的 //echo $Arr2->uname.'<br />'.$Arr2->uid; } public function logout() {// 导入Image类库 Cookie::delete('username'); Cookie::delete('secureid'); Cookie::delete('uid'); $this->assign('informationtext', '退出成功!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } /** +---------------------------------------------------------- * 探针模式 +---------------------------------------------------------- */ public function verify(){// 导入Image类库 import('ORG.Util.Image'); Image::buildImageVerify(); } public function checklogin($integer){//$py=new py_class(); //die("Cannot Run!"); //$name = htmlspecialchars($_POST['location']); //if($name == NULL) $name = ACTION_NAME; //$name = iconv('GBK', 'UTF-8',strtolower($py->str2py($name)));//输出城市名 ///$Demo = new Model('Demo'); // 实例化模型类 //$list = $Demo->select(); // 查诟数据 //if($name == 'index') //{ //在开始之前先检查Cookies //echo $is_username ; //////////FORTEST //$secureid = Cookie::get('secureid'); //$username = Cookie::get('secureusrname'); //$uid = Cookie::get('uid'); //echo $secureid .' '.$username.' '.$uid ; /////////////FORTEST $is_username = Cookie::is_set('username'); //Cookie::delete('username'); if($is_username != NULL)//如果设置了 { $secureid = Cookie::get('secureid'); $username = Cookie::get('username'); //echo $username; $secureusrname = Cookie::get('secureusrname'); $uid = Cookie::get('uid');//echo $secureid .' '.$username.' '.$uid ; //$secureusrname = securecode($secureid, $newusername); //echo $secureusrname; //$username = Cookie::delete('username'); if ($secureid != securecode($username, $uid)) {//如果说你的验证是不通过的 $redirect_uri = 'http://taiko.52yinyou.net/Edit/returnlogin'; $authorize_uri = 'https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=zQcuDz31BKDeA6GHLjgOeYWl&redirect_uri=' . urlencode($redirect_uri); $this->assign('loginurl', $authorize_uri); $this->display('index'); } else {//验证过了直接Pass掉 $getlist = new Model('youxijiting');//创建查询对象 $condition['username'] = md5($username);//以用户名为md5值查询 $condition['deleted'] = 0;//以用户名为md5值查询 $list = $getlist->where($condition)->select();//赋予条件 $this->assign('CityName', $username.'添加的机厅');// 模板发量赋值 $this->assign('list', $list);// 模板发量赋值 $this->display('mycity');// 输出模板 } } else {//或者说根本就木有 $redirect_uri = 'http://taiko.52yinyou.net/Edit/returnlogin'; $authorize_uri = 'https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=zQcuDz31BKDeA6GHLjgOeYWl&redirect_uri=' . urlencode($redirect_uri); $this->assign('loginurl', $authorize_uri); $this->display('index');//}else{ //$this->assign('cityname',htmlspecialchars($name, ENT_QUOTES)); //$this->display('New:index'); // 输出模板 } } } function request($url, $posts) { if (is_array($posts) && !empty($posts)) { foreach ($posts as $key=>$value) { $post[] = $key.'='.urlencode($value); } $posts = implode('&', $post); } $curl = curl_init(); $options = array(CURLOPT_URL=>$url, CURLOPT_CONNECTTIMEOUT => 20, CURLOPT_TIMEOUT => 20, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => 1, CURLOPT_POSTFIELDS=>$posts,//CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0', //CURLOPT_SSL_VERIFYPEER => FALSE, //CURLOPT_FOLLOWLOCATION => 1, //CURLOPT_SSL_VERIFYHOST => false ); curl_setopt_array($curl, $options);//echo $url; // echo '<br />'; $retval = curl_exec($curl);//echo '<br />'; //echo $retval; return $retval; } function securecode($username, $uid) { $restore = md5(md5('*_(taiko)_*|'.$username.'|Taiko.tk|'.$uid.'|taigu.us|taiko.52yinyou.net')); return $restore; } function checklogin() { $is_username = Cookie::is_set('username'); if($is_username != NULL)//如果设置了 { $secureid = Cookie::get('secureid'); $username = Cookie::get('username'); $uid = Cookie::get('uid');//echo $secureid .' '.$username.' '.$uid ; if ($secureid != securecode($username, $uid)) {//如果说你的验证是不通过的 return false; } else {//验证过了直接Pass掉 return true; } } else {//或者说根本就木有 return false; } } function checkyyz($id) //检查该鼓是否属于该人录入的机厅 { $Demo = new Model('youxijitai');// 实例化模型类 $Demo2 = new Model('youxijiting');// 实例化模型类 $id32323 = $id;//机台id //echo $id32323; $list = $Demo->getField('yxtid','id = '.$id32323);//获得机厅id //echo $list; $list2 = $Demo2->getField('username','id = '.$list);//获得用户id //echo $list2; return $list2; } ?><file_sep>/Lib/Action/NewAction.class.php <?php class NewAction extends Action{ /** +---------------------------------------------------------- * 默认操作 +---------------------------------------------------------- */ // 数据写入操作 public function insert() { if ($_SESSION['verify'] == md5($_POST['verify'])) { $youxijiting = new Model('youxijiting');// 实例化模型类 $youxijiting->yxt_name = htmlspecialchars($_POST['yxt_name'], ENT_QUOTES); $youxijiting->yxt_address = htmlspecialchars($_POST['yxt_address'], ENT_QUOTES); $youxijiting->yxt_hyjg = htmlspecialchars($_POST['yxt_hyjg'], ENT_QUOTES); $youxijiting->yxt_csqk = htmlspecialchars($_POST['yxt_csqk'], ENT_QUOTES); $youxijiting->yxt_jtqk = htmlspecialchars($_POST['yxt_jtqk'], ENT_QUOTES); $youxijiting->yxt_area = htmlspecialchars($_POST['location'], ENT_QUOTES); $youxijiting->securecode = htmlspecialchars($_POST['securecode'], ENT_QUOTES); $youxijiting->username = htmlspecialchars($_POST['username'], ENT_QUOTES); $_POST['yxt_area'] = htmlspecialchars($_POST['yxt_area'], ENT_QUOTES);//$youxijiting->test = 'test'; $youxijiting->Create();// 创建数据对象 // 写入数据库 if ($result = $youxijiting->add()) {//echo $result; $this->assign('yxtid', htmlspecialchars($result, ENT_QUOTES)); $this->assign('yxtname', htmlspecialchars($_POST['yxt_name'], ENT_QUOTES));//$Demo = new Model('Demo');//创建查询对象 $condition['yxtid'] = $result;//地区名 $list = $youxijiting->where($youxijiting)->select();//赋予条件 e //echo $list->yxt_area; //$Demo->closeConnect(); //echo $_POST['yxt_address']; $this->display('step2');// 输出模板 } else { $this->redirect('/Index/index', array(''), 5, '数据写入错误!返回首页中'); } //$this->redirect('/Index/index', array('redirect'=>1), 3,'请稍等'); } else { $this->assign('informationtext', '验证码提交不正确。四个数字YOOO!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/New/'.$_POST['location']);//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function insertnew() { if ($_SESSION['verify'] == md5($_POST['verify'])) { $youxijitai = new Model('youxijitai');// 实例化模型类 $youxijitai->yxtid = htmlspecialchars($_POST['yxtid'], ENT_QUOTES); $youxijitai->jt_dm = htmlspecialchars($_POST['jt_dm'], ENT_QUOTES); $youxijitai->jt_jg = htmlspecialchars($_POST['jt_jg'], ENT_QUOTES); $youxijitai->jt_gk = htmlspecialchars($_POST['jt_gk'], ENT_QUOTES); $youxijitai->Create();// 创建数据对象 // 写入数据库 if ($result = $youxijitai->add()) { $this->assign('yxtid', htmlspecialchars($_POST['yxtid'], ENT_QUOTES)); $condition['yxtid'] = htmlspecialchars($_POST['yxtid'], ENT_QUOTES);//地区名 $list = $youxijitai->where($condition)->select();//赋予条件 //$Demo->closeConnect(); $this->assign('list', $list);// 模板发量赋值 $this->display('step2');// 输出模板 } else { $this->redirect('/Index/index', array(''), 5, '数据写入错误!返回首页中'); } //$this->redirect('/Index/index', array('redirect'=>1), 3,'请稍等'); } else { $this->assign('informationtext', '验证码提交不正确。四个数字YOOO!');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/New/'.$_POST['location']);//模板变量赋值 $this->display('Public:information');//如果模板为空 } } public function index() {//$py=new py_class(); $name = htmlspecialchars($_POST['location']); $haslogin = checklogin(); if($haslogin) { $username123 = md5(cookie('username')); $secureid123 = cookie::get('secureid'); //$secureusername = cookie::get('secureusrname'); $secureusername_chk123 = securecode($secureid, $username); $this->assign('securecode', $secureusername_chk123 );//模板变量赋值 $this->assign('username', $username123);//模板变量赋值 $this->display('city');//如果模板为空 } else { if ($name == NULL) { $name = ACTION_NAME; } //$name = iconv('GBK', 'UTF-8',strtolower($py->str2py($name)));//输出城市名 $Demo = new Model('Demo');// 实例化模型类 $list = $Demo->select();// 查诟数据 if ($name == 'index') { $redirect_uri = 'http://taiko.52yinyou.net/New/returnlogin/'; $authorize_uri = 'https://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=zQcuDz31BKDeA6GHLjgOeYWl&redirect_uri=' . urlencode($redirect_uri); $this->assign('loginurl', $authorize_uri);//if($name == "index") $cityName=htmlspecialchars($_POST['location']); $this->display('New:index'); } else { $this->assign('cityname', htmlspecialchars($name, ENT_QUOTES)); $this->display('New:index');// 输出模板 } } } public function Old() { $this->display('choosecity'); } public function City($securecode, $username) { $taiguus_cityname=htmlspecialchars($_POST['location'], ENT_QUOTES); $securecode_32=htmlspecialchars($_POST['securecode'], ENT_QUOTES); $username_32=htmlspecialchars($_POST['username'], ENT_QUOTES); //WW$this->assign('cityname', htmlspecialchars($name, ENT_QUOTES)); $this->assign('hash1', htmlspecialchars($securecode_32, ENT_QUOTES)); $this->assign('hash2', htmlspecialchars($username_32, ENT_QUOTES)); $this->assign('location', htmlspecialchars($taiguus_cityname, ENT_QUOTES)); $this->display('newgd'); } /** +---------------------------------------------------------- * 探针模式 +---------------------------------------------------------- */ public function verify(){// 导入Image类库 import('ORG.Util.Image'); Image::buildImageVerify(); } function returnlogin() { $redirect_uri = 'http://taiko.52yinyou.net/New/returnlogin/'; $authorization_code = 'aa'; $authorization_code = $_GET['code']; //$authorization_code = ACTION_NAME; //echo $_SERVER['self']; //print_r($_GET); //foreach ($_GET as $key=>$value) //{ //echo "Key: $key; Value: $value <br/>\n "; //} //echo $authorization_code; $token_uri = 'https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code='. $authorization_code . '&client_id=zQcuDz31BKDeA6GHLjgOeYWl&client_secret=<KEY>&redirect_uri='. urlencode($redirect_uri); $retval = request($token_uri, NULL); //echo $token_uri; if ($retval != NULL) { $Arr = json_decode($retval); } else { $this->assign('informationtext', '服务器过载,与百度通信错误!请刷新重试');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', 'Javascript:window.history.go(-1)');//模板变量赋值 $this->display('Public:information');//如果模板为空 } $useruri = 'https://openapi.baidu.com/rest/2.0/passport/users/getLoggedInUser?access_token='.$Arr->access_token.'&format=json'; $retvaluser = request($useruri, NULL); //echo $useruri; //echo $retvaluser; if ($retvaluser != NULL) { $Arr2 = json_decode($retvaluser); } else { $this->assign('informationtext', '用户信息获取失败,可能是服务器与百度通信错误!请刷新重试');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', 'Javascript:window.history.go(-1)');//模板变量赋值 $this->display('Public:information');//如果模板为空 } //此时用户名$Arr2->uname。uid是$Arr2->uid。 $newusername = $Arr2->uname; //echo $newusername; if ($newusername != NULL) { $newuid = $Arr2->uid; //echo $newuid ; cookie('username', $newusername, time()+3600*24); $secureid = securecode($newusername, $newuid); //echo $secureid; cookie('secureid', $secureid, time()+3600*24); cookie('uid', $newuid, time()+3600*24); $secureusrname = securecode($secureid, $newusername); cookie('secureusrname', $secureusrname, time()+3600*24);//登录成功 $secureusername_md5 = securecode($secureid, $username); $username_md5 = md5($newusername); //<input type="hidden" name="securecode" value="{$securecode}" /> //<input type="hidden" name="username" value="{$username}" /> $this->assign('securecode', $secureusername_md5 );//模板变量赋值 $this->assign('username', $username_md5);//模板变量赋值 $this->display('city');//如果模板为空 //echo $secureid,$secureusrname; } else { $this->assign('informationtext', '数据错误,请不要返回刷新本页!请重新点击登录按钮');// 模板发量赋值 $this->assign('informationtitle', '太鼓太鼓提示');// 模板发量赋值 $this->assign('informationurl', '/Edit');//模板变量赋值 $this->display('Public:information');//如果模板为空 } } } function securecode($username, $uid) { $restore = md5(md5('*_(taiko)_*|'.$username.'|Taiko.tk|'.$uid.'|taigu.us|taiko.52yinyou.net')); return $restore; } function request($url, $posts) { if (is_array($posts) && !empty($posts)) { foreach ($posts as $key=>$value) { $post[] = $key.'='.urlencode($value); } $posts = implode('&', $post); } $curl = curl_init(); $options = array(CURLOPT_URL=>$url, CURLOPT_CONNECTTIMEOUT => 20, CURLOPT_TIMEOUT => 20, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => 1, CURLOPT_POSTFIELDS=>$posts,//CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0', //CURLOPT_SSL_VERIFYPEER => FALSE, //CURLOPT_FOLLOWLOCATION => 1, //CURLOPT_SSL_VERIFYHOST => false ); curl_setopt_array($curl, $options);//echo $url; // echo '<br />'; $retval = curl_exec($curl);//echo '<br />'; //echo $retval; return $retval; } function checklogin() { $is_username = cookie('username'); if($is_username != NULL)//如果设置了 { $secureid = cookie::get('secureid'); $username = cookie::get('username'); $uid = cookie::get('uid');//echo $secureid .' '.$username.' '.$uid ; if ($secureid != securecode($username, $uid)) {//如果说你的验证是不通过的 return false; } else {//验证过了直接Pass掉 return true; } } else {//或者说根本就木有 return false; } } ?><file_sep>/Tpl/Edit/addgd.html <layout name="Public:header" cache="60" /> <tr> <td colspan="3" style="font-size:12px;text-align:center;"> <table width="544px" height="30px" border="0" cellpadding="0" cellspacing="0" bordercolor="#DDDDDD"> </table> <table width="544px" border="0" cellpadding="0" cellspacing="0" bordercolor="#DDDDDD" align="center"> <tbody> <tr> <td width=544px height=59px background='/img/new_top.jpg'> </td> </tr> </tbody> <tbody> <tr> <td width=544px background='/img/new_bg.jpg'> <table width=500px align=center> <tr> <td> <p> <b> 给id为{$yxtid}的基厅<font color=orange><u>{$yxtname}</u></font>添加一台鼓 </b> </p> <form method="post" action="/Edit/insertnewac" style="font-size:12px;"> <input type="hidden" name="yxtid" value="{$yxtid}" /> 代目(请直接输入数字,12增请输入12m,亚洲版请输入11a或12a): <input type="text" name="jt_dm" maxlength=3 style="width:25px" /><br /> &nbsp; 价格(几币几曲什么的,双人有送么?): <input type="text" name="jt_jg" maxlength=30 style="width:150px" /><br/> 鼓况(其实不光是感应器鼓皮,音箱好么,有没有黑屏?): <INPUT TYPE=TEXTBOX NAME="jt_gk" maxlength=200 style="width:150px" /> <hr> <p align=right><input type="submit" value="下一步"></p> </form> </td> </tr> </table> </td> </tr> </tbody> <tbody> <tr> <td width=544px height=15px background='/img/new_down.jpg'> </td> </tr> </tbody> </table> </td> </tr> </table> <table width="544px" height="20px" border="0" cellpadding="0" cellspacing="0" bordercolor="#DDDDDD"> </table> </td> <td background="/img/bg2.png"> </td> </tr> <layout name="Public:footer" cache="60" />
01e17ebe4a80e9a94280ae64d32a5a30dc46a874
[ "Markdown", "HTML", "PHP" ]
7
PHP
Woodu/taiko.tk
cfe06f0bb7cfc63072ff4ea99874a9179d5efc60
f97428efa0c1f54fbf352eb1fba664f682134dab
refs/heads/master
<file_sep>package coreSelenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Util { WebDriver driver; /** * creating constructor to add the driver and to avoid hard coding over and over just call class and its gonna come all together * @param driver */ public Util(WebDriver driver) { this.driver = driver; } /** * in selenium most important method is to get web element because we are testing automating everythng on basis of the * web elements because of that im creating one generic method like getwebelemet method on my utility class * then everytime when i need to get and test any elment i m just calling that method and passing the web element * this time im just using page object with By class * * This method is used to create the webElement on the basis of By locator. * * how to handle exception handling in selenium let me explain * here below method telling me hey jeyhun im handlinig any kind web element and any kind exception * lets say my locator is perfectly fine then it will return my element if some exception comes it will print below message * but if some error or some web elemenet not there it will return null * * @param locator * @return */ public WebElement getElement(By locator) { WebElement element = null; try { element = driver.findElement(locator); } catch (Exception e) { System.out.println("some exception occurred while creating the webelement...."); System.out.println(e.getMessage()); } return element; } //generic method for explicitly wait element public void waitForElementPresent(By locator, int timeOut) { WebDriverWait wait = new WebDriverWait(driver, timeOut); wait.until(ExpectedConditions.presenceOfElementLocated(locator)); } ////generic method for explicitly wait for title public String waitForTitlePresent(String title, int timeOut) { WebDriverWait wait = new WebDriverWait(driver, timeOut); wait.until(ExpectedConditions.titleContains(title)); return driver.getTitle(); } /** * This method is used to click on element * * @param locator */ public void doClick(By locator) { try { getElement(locator).click(); } catch (Exception e) { System.out.println("some exception occurred while clicking on the webelement...."); System.out.println(e.getMessage()); } } /** * This method is used to pass the values in a webelement * * @param locator * @param value */ public void doSendKeys(By locator, String value) { try { getElement(locator).sendKeys(value); } catch (Exception e) { System.out.println("some exception occurred while passing value to the webelement...."); System.out.println(e.getMessage()); } } }<file_sep> /** * while working on web page where there is some web table for that need to create xpath with tr and td * in dom document object model html tag tr means number of rows td means number of coulmns * in selenium we dont have any direct method to handle webtable we have to use xpath concept * td most of the time is constant tr is dynamic * * * * in web table handling based on rows and columns breaking xpath into two part and creating before and after xpath * and getting the value from the xpath * */ package coreSelenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class WebTableHandle { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://www.w3schools.com/html/html_tables.asp"); int rowCount = driver.findElements(By.xpath("//table[@id='customers']//tr")).size() - 1;//here minus one means exclude unwanted row //here i store in int beacuse return type .size is int System.out.println(rowCount); // *[@id="customers"]/tbody/tr[2]/td[1] // *[@id="customers"]/tbody/tr[3]/td[1] // *[@id="customers"]/tbody/tr[7]/td[1] String beforeXpath = "//*[@id='customers']/tbody/tr["; //here breaking xpath into two part String afterXpath = "]/td[1]"; for (int rowNum = 2; rowNum <= rowCount + 1; rowNum++) { //starting from 2 beacuse in web page strart from 2 String actualXpath = beforeXpath + rowNum + afterXpath; //System.out.println(actualXpath); here i will get all the xpath how? //actualxpath is ref name ----> beforexpath +rowcount+afterxpath al; together its gonna give me all the table xpath String value = driver.findElement(By.xpath(actualXpath)).getText();//here getting actual xpath System.out.println(value); } } }<file_sep> /** * ScreenShot concept in selenium * for that two things is more important one is TAke screenShot interface and getscreenshotas method is there * now days selenium version 4 alfa 3 is came to the market with this new updates we can take screen * shot for specific elements as well */ package coreSelenium; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.openqa.selenium.By; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class ScreenshotConcept { public static void main(String[] args) throws InterruptedException, IOException { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://app.hubspot.com/login"); Thread.sleep(5000); takePageScreenshot(driver, "loginpage"); WebElement emailId = driver.findElement(By.id("username")); WebElement password = driver.findElement(By.id("password")); WebElement loginButton = driver.findElement(By.id("loginBtn")); emailId.sendKeys("<EMAIL>"); password.sendKeys("<PASSWORD>"); //loginButton.click(); takeElementScreenshot(emailId, "emailId"); takeElementScreenshot(password, "password"); takeElementScreenshot(loginButton, "loginButton"); takePageScreenshot(driver, "loginpageError"); driver.quit(); } public static void takePageScreenshot(WebDriver driver, String fileName){ //---this line takes the screenshot File SrcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);//--this line copy and store the screenshot in file try { FileUtils.copyFile(SrcFile, new File("./target/screenshots/"+fileName+".png")); } catch (IOException e) { e.printStackTrace(); } } public static void takeElementScreenshot(WebElement element, String fileName){ File SrcFile = ((TakesScreenshot)element).getScreenshotAs(OutputType.FILE); try { FileUtils.copyFile(SrcFile, new File("./target/screenshots/"+fileName+".png")); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/** * Autentication popUp in selenium and how to handle it * to handle it eaither u pass the right credentials to the url right after http for example * driver.get("http://admin:admin@the-internet.herokuapp.com/basic_auth"); * * or i can create the string usernmae or password then i can congat the string to the url for example * driver.get("http://"+username+":"+password+"@the-internet.herokuapp.com/basic_auth"); */ // package coreSelenium; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class AuthPopUp { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "./Drivers/chromedriver.exe"); WebDriver driver = new ChromeDriver(); String username = "admin"; String password = "<PASSWORD>"; driver.get("http://"+username+":"+password+"@the-internet.herokuapp.com/basic_auth"); } } <file_sep> /** * * diffreneces between normal send keys and action class send keys * normally we use normal sendkesys in any adding credentials but lets say sometimes some text boxes not working at time * i use action class send keys * here differences is normal send keys it works just adding all the particular credentials * but action class send keys theres internal move to element method it moves the element then passing the credentials * * */ package coreSelenium; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import io.github.bonigarcia.wdm.WebDriverManager; public class ActionsEvents { public static void main(String[] args) throws InterruptedException { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://app.hubspot.com/login"); Thread.sleep(5000); WebElement emailId = driver.findElement(By.id("username")); WebElement password = driver.findElement(By.id("password")); WebElement loginButton = driver.findElement(By.id("loginBtn")); Actions action = new Actions(driver); action.sendKeys(emailId, "<EMAIL>").build().perform(); action.sendKeys(password, "<PASSWORD>").build().perform(); action.click(loginButton).build().perform(); } }<file_sep>package coreSelenium; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.wdm.WebDriverManager; public class DropDownWithoutSelect { public static void main(String[] args) { WebDriverManager.chromedriver().setup(); WebDriver driver = new ChromeDriver(); driver.get("https://www.facebook.com/"); String day = "//select[@id='day']/option"; String month = "//select[@id='month']/option"; String year = "//select[@id='year']/option"; DropDownUtil.selectDropDownValueWithoutSelect(driver, day, "13"); DropDownUtil.selectDropDownValueWithoutSelect(driver, month, "Jun"); DropDownUtil.selectDropDownValueWithoutSelect(driver, year, "1987"); /** * here in this class im trying to select values from webPages without using select class * for that two things need to remember * 1st for loop to get all the size * 2nd after getting size need to choose one of the value without select class so how to do that * in this case java comes to the picture for that i m gonna use if else candition * to see all the codes how i chooese without select class check the dropdownutill class * * 1st we have to find xpath of the drop down driver.findelement then click that particular element * 2nd finding xpath of the first option of dropdwon menu after finding xpath stroring in list of web elmenet then getting * size text printing all the value on the console * but lets say my target to select multiple value from drop down how to that * for that im making my method as generic passing parameters web driver then string with three dot String ... value like this * then starting my for loop concept under driver.find element then if else statement selecting one then break * return type of three dot in java is Array * after adding three dot as paramater for that another inner for loop then if else and break * if i want to select all the values from drop down simple pass after method name driver and "All" inside called method * and covering it with try catch block if any exception comes it will handle it * * * while doing the select drop down if in html dom i can see the tag of the select then select class is compulsory * other vise no * * in select class there another method is isMultiple this method is returning boolean value true or false * its used to whenever i have more selection just to verification * * * there three method under select class select by visible text * select by index , select by value * select by index is not recommended if the position of the index changed then need to maintain it again * * there isMultiple method inside select class return type is boolean true or false direct sop and get to know all the values selected or no * * * */ } }
d4254ba09b5831fa37fb69e33a932a2cc6405b2e
[ "Java" ]
6
Java
JeyhunAli/SeleniumSessionFromNVN
18711f7bb3e27cb0a61ae505842fbf09890ebdd6
7e8b29d43864151ba10ca724b787cf12b208ab04
refs/heads/master
<file_sep>import React, { Component } from 'react'; import { Text, View, ScrollView, Image, TouchableOpacity, Dimensions } from 'react-native'; var { width } = Dimensions.get('window') import AsyncStorage from '@react-native-community/async-storage'; export default class Cart extends Component { constructor(props) { super(props); this.state = { dataCart:[], }; } componentDidMount() { AsyncStorage.getItem('key').then((cart)=>{ if (cart !== null) { const cartfood = JSON.parse(cart) this.setState({dataCart:cartfood}) } }) .catch((err)=>{ alert(err) }) } render() { return ( <View style={{flex:1}}> <View style={{backgroundColor:'orange'}}> <View style={{height:10}} /> <Text style={{fontSize:32,fontWeight:'bold',color:'black'}}> Cart food</Text> <View style={{height:10}} /> </View> <View style={{flex:1}}> <ScrollView> { this.state.dataCart.map((item,i)=>{ return( <View style={{width:width-20,margin:10,backgroundColor:'flycolor',flexDirection:'row',borderBottomWidth:2,borderColor:'silver',paddingBottom:10}}> <Image resizeMode={'contain'} style={{width:width/3,height:width/3}} source={{uri: item.food.image}}/> <View style={{flex:1,backgroundColor:'flycolor',padding:10,justifyContent:'space-between'}}> <View style={{flexDirection:'row',justifyContent:'space-between'}}> <Text style={{fontWeight:'bold',fontSize:20}}>{item.food.name}</Text> <View style={{flexDirection:'row',alignItems:'center'}}> <TouchableOpacity style={{backgroundColor:'red',padding:8,borderRadius:1000}} onPress={()=>this.onClickDeleteCart(i)}> <Text style={{fontWeight:'bold',fontSize:10,color:'white'}}>x</Text> </TouchableOpacity> </View> </View> <View> <Text>Describe the product</Text> </View> <View style={{flexDirection:'row',justifyContent:'space-between'}}> <Text style={{fontWeight:'bold',color:'black',fontSize:20}}>${item.price*item.quantity}</Text> <View style={{flexDirection:'row', alignItems:'center'}}> <TouchableOpacity style={{backgroundColor:'orange',padding:8,borderRadius:1000}} onPress={()=>this.onChangeQual(i,false)}> <Text>-</Text> </TouchableOpacity> <Text style={{paddingHorizontal:8, fontWeight:'bold', fontSize:18}}>{item.quantity}</Text> <TouchableOpacity style={{backgroundColor:'orange',padding:8,borderRadius:1000}} onPress={()=>this.onChangeQual(i,true)}> <Text>+</Text> </TouchableOpacity> </View> </View> </View> </View> ) }) } <View style={{height:20}} /> <View style={{flexDirection:'row',justifyContent:'space-around'}}> <Text style={{paddingHorizontal:8, fontWeight:'bold', fontSize:18}}>Total</Text> <View style={{flexDirection:'row', alignItems:'center'}}> <Text style={{fontWeight:'bold',color:"#33c37d",fontSize:20 }}>${this.onLoadTotal()}</Text> </View> </View> <TouchableOpacity style={{ backgroundColor:'orange', width:width-40, alignItems:'center', padding:10, borderRadius:5, margin:20 }}onPress={()=>this.Checkout()}> <Text style={{ fontSize:24, fontWeight:'bold', color:'white' }}> CHECKOUT </Text> </TouchableOpacity> <View style={{height:20}} /> </ScrollView> </View> </View> ); } onChangeQual(i,type) { const dataCar = this.state.dataCart let cantd = dataCar[i].quantity; if (type) { cantd = cantd + 1 dataCar[i].quantity = cantd this.setState({dataCart:dataCar}) } else if (type==false&&cantd>=2){ cantd = cantd - 1 dataCar[i].quantity = cantd this.setState({dataCart:dataCar}) } } onLoadTotal() { var total = 0 const cart = this.state.dataCart for (var i = 0; i < cart.length; i++){ total = total + (cart[i].price*cart[i].quantity) } return total } onClickDeleteCart(i) { const dataCar = this.state.dataCart dataCar.splice(i,1) this.setState({dataCart:dataCar}) alert('Delete Cart') AsyncStorage.setItem('key',JSON.stringify(dataCar)); } Checkout() { AsyncStorage.getItem('key').then((Cart)=>{ if (Cart == null) { alert('Your cart is empty!') } else if(Cart.length == 2){ alert('Your cart is empty!') } else{ AsyncStorage.removeItem('key') const cartfood = [] this.setState({dataCart:cartfood}) alert('Buy Successfully!') } }) .catch((err)=>{ alert(err) }) } } <file_sep>import React, { Component } from 'react'; import { Text, View, TouchableOpacity, StyleSheet, Dimensions, LogBox } from 'react-native'; var { width } = Dimensions.get("window") import Food from './src/Food'; import Cart from './src/Cart'; LogBox.ignoreAllLogs(); export default class Example extends Component { constructor(props) { super(props); this.state = { module:1, }; } render() { return ( <View style={{flex:1}}> { this.state.module==1? <Food /> :<Cart /> } <View style={styles.bottomTab}> <TouchableOpacity style={styles.itemTab} onPress={()=>this.setState({module:1})}> <Text>Food</Text> </TouchableOpacity> <TouchableOpacity style={styles.itemTab} onPress={()=>this.setState({module:2})}> <Text>Cart</Text> </TouchableOpacity> </View> </View> ); } } const styles = StyleSheet.create({ bottomTab:{ height:60, width:width, backgroundColor:'orange', flexDirection:'row', justifyContent:'space-between', elevation:8, shadowOpacity:0.3, shadowRadius:50, }, itemTab:{ width:width/2, backgroundColor:'white', alignItems:'center', justifyContent:'center' } })
6fa6b79f38ec61df20026f1978f5fbf481bae56f
[ "JavaScript" ]
2
JavaScript
TinhMong/FoodCart
f3594c1ac1d10ea84b1092298ab6acbb8f44652f
df62a89c6e259312c9f9894e671930c9932fca0c
refs/heads/master
<repo_name>cattommy/BigDataGraph<file_sep>/GraphVis.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Fusion; using Fusion.Mathematics; using Fusion.Graphics; using Fusion.Audio; using Fusion.Input; using Fusion.Content; using Fusion.Development; using System.IO; namespace GraphVis { public class GraphVis : Game { /// <summary> /// GraphVis constructor /// /// </summary> public GraphVis() : base() { // enable object tracking : Parameters.TrackObjects = true; // uncomment to enable debug graphics device: // (MS Platform SDK must be installed) // Parameters.UseDebugDevice = true; // add services : AddService(new SpriteBatch(this), false, false, 0, 0); AddService(new DebugStrings(this), true, true, 9999, 9999); AddService(new DebugRender(this), true, true, 9998, 9998); AddService(new GeoCamera(this), true, false, 9997, 9997); // add here additional services : AddService(new ParticleSystem(this), true, true, 9996, 9996); AddService(new Directory(this), true, false, 9997, 9997); // load configuration for each service : LoadConfiguration(); // make configuration saved on exit : Exiting += Game_Exiting; } int timer; bool play; int counter; int fCount; int speed; /// <summary>q /// Initializes game : /// </summary> protected override void Initialize() { // initialize services : base.Initialize(); InputDevice.MouseScroll += InputDevice_MouseScroll; var cam = GetService<GeoCamera>(); InputDevice.IsMouseHidden = true; timer = -1000500; play = false; counter = 0; //fileNames = Directory.GetFiles("stabNormEdges_03/edgeLists"); //filecolorNames = Directory.GetFiles("stabNormEdges_03/stab"); // fCount = fileNames.Length; speed = 10; //var h1 = font1.LineHeight; //var h2 = font2.LineHeight; //cam.Config.FreeCamEnabled = false; cam.Config.FreeCamEnabled = true; // add keyboard handler : InputDevice.KeyDown += InputDevice_KeyDown; // load content & create graphics and audio resources here: } void InputDevice_MouseScroll(object sender, InputDevice.MouseScrollEventArgs e) { Log.Message("...mouse scroll event : {0}", e.WheelDelta); //scrollValue += e.WheelDelta; } /// <summary> /// Disposes game /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { if (disposing) { // dispose disposable stuff here // Do NOT dispose objects loaded using ContentManager. } base.Dispose(disposing); } /// <summary> /// Handle keys /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void InputDevice_KeyDown(object sender, Fusion.Input.InputDevice.KeyEventArgs e) { if (e.Key == Keys.F1) { DevCon.Show(this); } if (e.Key == Keys.F5) { Reload(); } if (e.Key == Keys.F12) { GraphicsDevice.Screenshot(); } if (e.Key == Keys.Escape) { Exit(); } if (InputDevice.IsKeyDown(Keys.K)) { if (speed < 100) { speed = speed + 5; } timer = 0; } if (InputDevice.IsKeyDown(Keys.L)) { if (speed > 10) { speed = speed - 5; } timer = 0; } } /// <summary> /// Saves configuration on exit. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Game_Exiting(object sender, EventArgs e) { SaveConfiguration(); } /// <summary> /// Updates game /// </summary> /// <param name="gameTime"></param> protected override void Update(GameTime gameTime) { var ds = GetService<DebugStrings>(); ds.Add(Color.Orange, "FPS {0}", gameTime.Fps); //ds.Add("F1 - show developer console"); //ds.Add("F5 - build content and reload textures"); //ds.Add("F12 - make screenshot"); //ds.Add("ESC - exit"); var cam = GetService<GeoCamera>(); var debRen = GetService<DebugRender>(); int w = GraphicsDevice.DisplayBounds.Width; int h = GraphicsDevice.DisplayBounds.Height; var partSys = GetService<ParticleSystem>(); timer++; if (play == true && counter <= fCount && timer == speed && partSys.state == ParticleSystem.State.RUN) { partSys.readData(); partSys.SetCitations(); //Console.WriteLine(fileNames[counter] + " " + counter); partSys.setBuffers(); timer = 0; } if (InputDevice.IsKeyDown(Keys.I)) { partSys.AddMaxParticles(); timer = 0; play = true; } if (InputDevice.IsKeyDown(Keys.Q)) { timer = 0; } if (InputDevice.IsKeyDown(Keys.LeftButton)) { //Capital = partSys.Capital; //Assets = partSys.Assets; //Liquidity = partSys.Liquidity; //Yield = partSys.Yield; } base.Update(gameTime); // Update stuff here : } /// <summary> /// Draws game /// </summary> /// <param name="gameTime"></param> /// <param name="stereoEye"></param> protected override void Draw(GameTime gameTime, StereoEye stereoEye) { base.Draw(gameTime, stereoEye); // Draw stuff here : } } }
7d74072254c982e73a447fdfe28a456992c54602
[ "C#" ]
1
C#
cattommy/BigDataGraph
61f075d67f1092a1195a51e82a170d26561809fe
8bf3fad82665ae6916db9a3f790bfd3f59f4a999
refs/heads/main
<repo_name>AndryFin/SampleAutomationTest-Protractor-<file_sep>/formAuthenticationTest.js describe('Form Authentication Test', function () { browser.ignoreSynchronization = true; var userName = element(by.id('username')); var password = element(by.id('password')); var message = element(by.id('flash')); var loginBtn = element(by.xpath('//button[@type="submit"]')); var logoutBtn = element(by.xpath('//a[@href="/logout"]')); it('go to test page', function () { browser.get('http://the-internet.herokuapp.com/login'); return browser.wait(function () { return browser.executeScript('return document.readyState==="complete"').then(function (text) { return text === true; //wait for page to download, should be moved to the helper }); }, 6000); }); it('logging in with correct credentials', function () { userName.sendKeys('tomsmith'); password.sendKeys('<PASSWORD>!'); loginBtn.click(); expect(message.getText()).toContain('You logged into a secure area!'); expect(logoutBtn.isPresent()).toBe(true); expect(loginBtn.isPresent()).toBe(false); }); it('logging out', function () { logoutBtn.click(); expect(message.getText()).toContain('You logged out of the secure area!'); expect(loginBtn.isPresent()).toBe(true); expect(logoutBtn.isPresent()).toBe(false); }); it('trying to log in with incorrect credentials', function () { userName.sendKeys('ksjdhfks'); password.sendKeys('<PASSWORD>!'); loginBtn.click(); expect(message.getText()).toContain('Your username is invalid!'); expect(loginBtn.isPresent()).toBe(true); expect(logoutBtn.isPresent()).toBe(false); }); it('trying to log in with no credentials', function () { userName.clear(); password.clear(); loginBtn.click(); expect(message.getText()).toContain('Your username is invalid!'); expect(loginBtn.isPresent()).toBe(true); expect(logoutBtn.isPresent()).toBe(false); }); it('trying to log in without password', function () { userName.sendKeys('tomsmith'); password.clear(); loginBtn.click(); expect(message.getText()).toContain('Your password is invalid!'); expect(loginBtn.isPresent()).toBe(true); expect(logoutBtn.isPresent()).toBe(false); }); it('trying to log in without usernme', function () { userName.clear(); password.sendKeys('<PASSWORD>!'); loginBtn.click(); expect(message.getText()).toContain('Your username is invalid!'); expect(loginBtn.isPresent()).toBe(true); expect(logoutBtn.isPresent()).toBe(false); }); }); <file_sep>/dynamicControlsTest.js describe('Dynamic Controls test', function () { browser.ignoreSynchronization = true; var addRemoveBtn = element(by.xpath('//button[@onclick="swapCheckbox()"]')); var enableDisableBtn = element(by.xpath('//button[@onclick="swapInput()"]')); var checkbox = element(by.xpath('//input[@type="checkbox"]')); var inputTextField = element(by.xpath('//input[@type="text"]')); it('go to test page', function () { browser.get('http://the-internet.herokuapp.com/dynamic_controls'); return browser.wait(function () { return browser.executeScript('return document.readyState==="complete"').then(function (text) { return text === true; //wait for page to download, should be moved to the helper }); }, 6000); }); it('checking that checkbox is present and select it', function () { expect(checkbox.isPresent()).toBe(true); checkbox.click().then(function(){ expect(checkbox.isSelected()).toBe(true); }); }); it('removing checkbox element and waiting for it to be removed from the DOM', function () { addRemoveBtn.click().then(function(){ return browser.wait(function () { return checkbox.isPresent().then( function (present) { return !present; }, // "wait" function should be moved to the separate helper in real project function (error) { return false }); }, 7000); }); }); it('adding checkbox element back and waiting for it to be present', function () { addRemoveBtn.click().then(function(){ return browser.wait(function () { return checkbox.isPresent().then( function (present) { return present; }, // "wait" function should be moved to the separate helper in real project function (error) { return false }); }, 7000); }); }); it('expecting checkbox not to be selected', function () { expect(checkbox.isSelected()).toBe(false); }); it('expecting input field to be disabled', function () { expect(inputTextField.isEnabled()).toBe(false); }); it('enabling input text field', function () { enableDisableBtn.click().then(function(){ return browser.wait(function () { return inputTextField.isEnabled().then( function (enabled) { return enabled; }, // "wait" function should be moved to the separate helper in real project function (error) { return false }); }, 7000); }); }); it('entering some text', function () { inputTextField.sendKeys("test input text"); }); it('disabling input text field', function () { enableDisableBtn.click().then(function(){ return browser.wait(function () { return inputTextField.isEnabled().then( function (enabled) { return !enabled; }, // "wait" function should be moved to the separate helper in real project function (error) { return false }); }, 7000); }); }); it('expecting input field to be disabled and to have entered text', function () { expect(inputTextField.isEnabled()).toBe(false); expect(inputTextField.getAttribute('value')).toEqual('test input text'); }); }); <file_sep>/notificationMessagesTest.js describe('Notification Message Test', function () { browser.ignoreSynchronization = true; var mesgBtn = element(by.xpath('//a[@href="/notification_message"]')); var retryCount = 1; var passCount = 0; var failCount = 0; it('go to test page', function () { browser.get('http://the-internet.herokuapp.com/notification_message_rendered'); return browser.wait(function () { return browser.executeScript('return document.readyState==="complete"').then(function (text) { return text === true; //wait for page to download, should be moved to the helper }); }, 6000); }); it('clicking until the action is successful', function () { mesgBtn.click().then(function(){ return browser.wait(function () { return element(by.cssContainingText('.flash.notice', 'Action successful')).isPresent().then( function (present) { if (present){ console.log('action took '+retryCount+' retries to succeed'); return present; } retryCount++; mesgBtn.click(); }, function (error) { return false }); }, 8000); }); }); for (var i=0; i<20; i++){ (function (j) { it('testing pass/fail rate on the action', function () { mesgBtn.click().then(function(){ element(by.cssContainingText('.flash.notice', 'Action successful')).isPresent().then( function (present) { if (present){ passCount++; } }); element(by.cssContainingText('.flash.notice', 'Action unsuccesful, please try again')).isPresent().then( function (present) { if (present){ failCount++; } }); }); }); })(i); } it('pass/fail rate output', function () { console.log('Number of times action passed = '+passCount, 'Number of times action failed = '+failCount); }); });
ec2d7098c8ff208db933c9c700e3b215358bdd30
[ "JavaScript" ]
3
JavaScript
AndryFin/SampleAutomationTest-Protractor-
4b1be8d7761674aca892cba4df36cbef2d4f757c
641334f13fd6aefe9f4020d6aaff5da64db675ec
refs/heads/master
<repo_name>LJjn66786396/helloTest<file_sep>/src/main/java/com/example/hello/controller/Hello2.java package com.example.hello.controller; public class Hello2 { } <file_sep>/src/main/java/com/example/hello/controller/HelloTest2.java package com.example.hello.controller; public class HelloTest2 { }
09cca3e7ddcd5f13c92afbb49156ed167010cffe
[ "Java" ]
2
Java
LJjn66786396/helloTest
deed35f31f529c025841d7511cf2e2e8f267a979
35fa084aae31f861864c93ec4b42e6638d4db2ab
refs/heads/main
<file_sep>import fs from 'fs'; import path from 'path'; import { Publisher, PublishContext, UploadTask } from 'electron-publish'; import { log } from 'builder-util'; import untildify from 'untildify'; import OSS from 'ali-oss'; import YAML from 'yaml'; export interface OSSOptions { readonly provider: "oss" readonly credentials?: string readonly bucket: string readonly base: string readonly region?: string readonly endpoint?: string readonly secure: boolean } interface Credentials { readonly accessKeyId: string readonly accessKeySecret: string readonly region?: string readonly endpoint?: string } export default class OSSPublisher extends Publisher { public readonly providerName = "OSS"; protected client: OSS; constructor(context: PublishContext, private options: OSSOptions) { super(context); const credentialsFile: string = untildify(this.options.credentials || "~/.fcli/config.yaml"); const credentials = this.parseCredentials(credentialsFile); const clientOpts: OSS.Options = { accessKeyId: credentials.accessKeyId, accessKeySecret: credentials.accessKeySecret, bucket: this.options.bucket, region: this.options.region || credentials.region, endpoint: this.options.endpoint || credentials.endpoint, secure: this.options.secure } this.client = new OSS(clientOpts); } parseCredentials(file: string): Credentials { const content = fs.readFileSync(file, 'utf8'); const doc = YAML.parse(content); return { accessKeyId: doc.access_key_id, accessKeySecret: doc.access_key_secret }; } async upload(task: UploadTask): Promise<any> { // TODO: safeArtifactName? const fileName = path.basename(task.file); const fileStat = await fs.promises.stat(task.file); const progressBar = this.createProgressBar(fileName, fileStat.size); const name = this.options.base + "/" + fileName; const stream = this.createReadStreamAndProgressBar(task.file, fileStat, progressBar, err => { log.error(err); }); return await this.client.putStream(name, stream); } toString() { return `${this.providerName} (bucket: ${this.options.bucket})`; } } <file_sep># electron-publisher-oss Format of credentials file ```yaml access_key_id: "key id" access_key_secret: "key secret" endpoint: "" region: "" ``` `endpoint` and `region` will be overrided by options of `OSSPublisher`.
641f67f5381e28904d26844e6983cd8a6ec738a1
[ "Markdown", "TypeScript" ]
2
TypeScript
wsw0108/electron-publisher-oss
895b21bf9e7b4be632e88381f1bb53e33796f21d
14e67a3792d6877ea610398bb11a9ede918f3c91
refs/heads/master
<file_sep> What is this project about ? ------------ This web app is written in python and contains NoSQLi vulnerabilities. What types of vulnerabilities are there and how can I expose them ? -------------------------- First vulnerability is authentication bypass and to simulate it to you need to modify network traffic. A suitable tool to modify traffic is burp broxy and I suggest you install it. Simulating authentication bypass ------------- 1. First you have to setup burp proxy to intercept the network traffic. 2. Go to login page and for username enter 'admin' and for password enter any value you want. We are trying to simulate how a hacker can access the system without knowing the password. 3. Once request for authentication is intercepted, Modify post body as follows [{"name":"username","value":"admin"},{"name":"<PASSWORD>","value":{"$ne": null}}] 4. You should be redirected to profile page now <file_sep>FROM python:3.6-alpine RUN pip install pipenv COPY . /vulnapp WORKDIR /vulnapp RUN pipenv install --deploy --ignore-pipfile CMD ["pipenv", "run", "python", "main.py"]<file_sep>import json from flask import Flask, render_template, request, jsonify, session, redirect, url_for from database import Database app = Flask(__name__) app.secret_key = '<KEY>' db = Database() @app.route('/') def index(): return render_template('index.html') @app.route('/login', methods=['POST']) def login(): data = request.get_json() for field in data: if field['name'] == 'username': username = field['value'] if field['name'] == 'password': password = field['value'] user = db.login(username, password) if user is not None : session['loggedin'] = True session['username'] = user['username'] resp = jsonify(success=True) else : resp = jsonify(success=False) return resp @app.route('/profile', methods=['GET']) def profile(): if 'loggedin' in session: users = db.get_users_by_admin(session['username']) return render_template('profile.html', users= users, username=session['username']) else: return redirect(url_for('index')) @app.route('/logout') def logout(): # Remove session data, this will log the user out session.pop('loggedin', None) session.pop('username', None) # Redirect to login page return redirect(url_for('index')) @app.route('/search', methods=['POST']) def search(): data = request.get_json() for field in data: if field['name'] == 'search': username = field['value'] if field['name'] == 'managed_by': managed_by = field['value'] user = db.get_users_by_admin(managed_by, username) if user is not None : resp = jsonify(user) else : resp = jsonify(success=False) return resp <file_sep>import pymongo from pymongo import MongoClient class Database: client = pymongo.MongoClient("mongodb://localhost:27017/") def login(self, username, password): collection = self.client.users.collection result = collection.find( {"username": username, "password": <PASSWORD>} ) users = list(result) if not users : return None else : return users[0] def get_users_by_admin(self, admin_username, search_criteria=None): collection = self.client.users.collection if not search_criteria : result = collection.find( {"managed_by": admin_username}, {"_id": 0 } ) else: result = collection.find( {"managed_by": admin_username, "username": search_criteria}, {"_id": 0 } ) users = list(result) if not users : return None else : return users
14f70830845d83acf59487491df3f9657b36cbd6
[ "Markdown", "Python", "Dockerfile" ]
4
Markdown
akilaweerat/mongodbvuln-python
2c8f4c2c440e5ee17c759ab45a926b6c338f92c1
7ab498bb0c090caa58fac3ca8c8061c4ed4700b7
refs/heads/master
<repo_name>GabrielSartori/treinamento-bootcamp<file_sep>/readme.Md # Engenharia de Dados Bootcamp<file_sep>/aula2/jinja/jinja_template.py import jinja2 template_string = """ Olá {{nome}} Sua senha {{link }} """ template = jinja2.Template(template_string) rendered_template = template.render({"nome": "Gabriel", "link": "htttptppt"})
cbf6da68c5f1ffd08bb0c6c544bb46b68d040936
[ "Markdown", "Python" ]
2
Markdown
GabrielSartori/treinamento-bootcamp
75540bba868b78e77b231d427ab1c9df5b4b1cc3
58677095059c2684f14ef477e0cdcdffe82cf048
refs/heads/master
<file_sep>#!/usr/bin/env python # coding: utf-8 # In[ ]: # import import os import sys import time import copy import h5py import numpy as np import tensorflow as tf # from scipy.misc import imread, imresize from PIL import Image from tf_cnnvis import * # In[ ]: # download alexnet model weights if not os.path.exists("alexnet_weights.h5"): os.system("python -m wget -o alexnet_weights.h5 http://files.heuritech.com/weights/alexnet_weights.h5") # In[ ]: # loading parameters and mean image for pretrained alexnet model mean = np.load("./img_mean.npy").transpose((1, 2, 0)) # load mean image of imagenet dataset f = h5py.File('./alexnet_weights.h5','r') conv_1 = [f["conv_1"]["conv_1_W"], f["conv_1"]["conv_1_b"]] conv_2_1 = [f["conv_2_1"]["conv_2_1_W"], f["conv_2_1"]["conv_2_1_b"]] conv_2_2 = [f["conv_2_2"]["conv_2_2_W"], f["conv_2_2"]["conv_2_2_b"]] conv_3 = [f["conv_3"]["conv_3_W"], f["conv_3"]["conv_3_b"]] conv_4_1 = [f["conv_4_1"]["conv_4_1_W"], f["conv_4_1"]["conv_4_1_b"]] conv_4_2 = [f["conv_4_2"]["conv_4_2_W"], f["conv_4_2"]["conv_4_2_b"]] conv_5_1 = [f["conv_5_1"]["conv_5_1_W"], f["conv_5_1"]["conv_5_1_b"]] conv_5_2 = [f["conv_5_2"]["conv_5_2_W"], f["conv_5_2"]["conv_5_2_b"]] fc_6 = [f["dense_1"]["dense_1_W"], f["dense_1"]["dense_1_b"]] fc_7 = [f["dense_2"]["dense_2_W"], f["dense_2"]["dense_2_b"]] fc_8 = [f["dense_3"]["dense_3_W"], f["dense_3"]["dense_3_b"]] # In[ ]: # tensorflow model implementation (Alexnet convolution) tf.reset_default_graph() X = tf.placeholder(tf.float32, shape = [None, 224, 224, 3]) # placeholder for input images y_ = tf.placeholder(tf.float32, shape = [None, 1000]) # placeholder for true labels for input images radius = 5; alpha = 1e-4; beta = 0.75; bias = 2.0 # hyper parametes for lrn # Layer - 1 conv1 W_conv_1 = tf.Variable(np.transpose(conv_1[0], (2, 3, 1, 0))) b_conv_1 = tf.Variable(np.reshape(conv_1[1], (96, ))) y_conv_1 = tf.nn.conv2d(X, filter=W_conv_1, strides=[1, 4, 4, 1], padding="SAME") + b_conv_1 h_conv_1 = tf.nn.relu(y_conv_1, name = "conv1") h_conv_1 = tf.nn.local_response_normalization(h_conv_1, depth_radius=radius, alpha=alpha, beta=beta, bias=bias) h_pool_1 = tf.nn.max_pool(h_conv_1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding="VALID") h_pool_1_1, h_pool_1_2 = tf.split(axis = 3, value = h_pool_1, num_or_size_splits = 2) # Layer - 2 conv2 W_conv_2_1 = tf.Variable(np.transpose(conv_2_1[0], (2, 3, 1, 0))) b_conv_2_1 = tf.Variable(np.reshape(conv_2_1[1], (128, ))) y_conv_2_1 = tf.nn.conv2d(h_pool_1_1, filter=W_conv_2_1, strides=[1, 1, 1, 1], padding="SAME") + b_conv_2_1 h_conv_2_1 = tf.nn.relu(y_conv_2_1, name = "conv2_1") h_conv_2_1 = tf.nn.local_response_normalization(h_conv_2_1, depth_radius=radius, alpha=alpha, beta=beta, bias=bias) h_pool_2_1 = tf.nn.max_pool(h_conv_2_1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding="VALID") W_conv_2_2 = tf.Variable(np.transpose(conv_2_2[0], (2, 3, 1, 0))) b_conv_2_2 = tf.Variable(np.reshape(conv_2_2[1], (128, ))) y_conv_2_2 = tf.nn.conv2d(h_pool_1_2, filter=W_conv_2_2, strides=[1, 1, 1, 1], padding="SAME") + b_conv_2_2 h_conv_2_2 = tf.nn.relu(y_conv_2_2, name = "conv2_2") h_conv_2_2 = tf.nn.local_response_normalization(h_conv_2_2, depth_radius=radius, alpha=alpha, beta=beta, bias=bias) h_pool_2_2 = tf.nn.max_pool(h_conv_2_2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding="VALID") h_pool_2 = tf.concat(axis = 3, values = [h_pool_2_1, h_pool_2_2]) # Layer - 3 conv3 W_conv_3 = tf.Variable(np.transpose(conv_3[0], (2, 3, 1, 0))) b_conv_3 = tf.Variable(np.reshape(conv_3[1], (384, ))) y_conv_3 = tf.nn.conv2d(h_pool_2, filter=W_conv_3, strides=[1, 1, 1, 1], padding="SAME") + b_conv_3 h_conv_3 = tf.nn.relu(y_conv_3, name = "conv3") h_conv_3_1, h_conv_3_2 = tf.split(axis = 3, value = h_conv_3, num_or_size_splits = 2) # h_conv_4_1 = h_conv_3_1 # h_conv_4_2 = h_conv_3_2 # Layer - 4 conv4 W_conv_4_1 = tf.Variable(np.transpose(conv_4_1[0], (2, 3, 1, 0))) b_conv_4_1 = tf.Variable(np.reshape(conv_4_1[1], (192, ))) y_conv_4_1 = tf.nn.conv2d(h_conv_3_1, filter=W_conv_4_1, strides=[1, 1, 1, 1], padding="SAME") + b_conv_4_1 h_conv_4_1 = tf.nn.relu(y_conv_4_1, name = "conv4_1") W_conv_4_2 = tf.Variable(np.transpose(conv_4_2[0], (2, 3, 1, 0))) b_conv_4_2 = tf.Variable(np.reshape(conv_4_2[1], (192, ))) y_conv_4_2 = tf.nn.conv2d(h_conv_3_2, filter=W_conv_4_2, strides=[1, 1, 1, 1], padding="SAME") + b_conv_4_2 h_conv_4_2 = tf.nn.relu(y_conv_4_2, name = "conv4_2") h_conv_4 = tf.concat(axis = 3, values = [h_conv_4_1, h_conv_4_2]) # Layer - 5 conv5 W_conv_5_1 = tf.Variable(np.transpose(conv_5_1[0], (2, 3, 1, 0))) b_conv_5_1 = tf.Variable(np.reshape(conv_5_1[1], (128, ))) y_conv_5_1 = tf.nn.conv2d(h_conv_4_1, filter=W_conv_5_1, strides=[1, 1, 1, 1], padding="SAME") + b_conv_5_1 h_conv_5_1 = tf.nn.relu(y_conv_5_1, name = "conv5_1") h_conv_5_1 = tf.nn.local_response_normalization(h_conv_5_1, depth_radius=radius, alpha=alpha, beta=beta, bias=bias) h_pool_5_1 = tf.nn.max_pool(h_conv_5_1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding="VALID") W_conv_5_2 = tf.Variable(np.transpose(conv_5_2[0], (2, 3, 1, 0))) b_conv_5_2 = tf.Variable(np.reshape(conv_5_2[1], (128, ))) y_conv_5_2 = tf.nn.conv2d(h_conv_4_2, filter=W_conv_5_2, strides=[1, 1, 1, 1], padding="SAME") + b_conv_5_2 h_conv_5_2 = tf.nn.relu(y_conv_5_2, name = "conv5_2") h_conv_5_2 = tf.nn.local_response_normalization(h_conv_5_2, depth_radius=radius, alpha=alpha, beta=beta, bias=bias) h_pool_5_2 = tf.nn.max_pool(h_conv_5_2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding="VALID") h_pool_5 = tf.concat(axis = 3, values = [h_pool_5_1, h_pool_5_2]) dimensions = h_pool_5.get_shape().as_list() dim = dimensions[1] * dimensions[2] * dimensions[3] # # Part of Alexnet model which is not required for deconvolution h_flatten = tf.reshape(h_pool_5, shape=[-1, dim]) # Layer - 6 fc6 W_full_6 = tf.Variable(np.array(fc_6[0])) b_full_6 = tf.Variable(np.array(fc_6[1])) y_full_6 = tf.add(tf.matmul(h_flatten, W_full_6), b_full_6) h_full_6 = tf.nn.relu(y_full_6, name = "fc6") h_dropout_6 = tf.nn.dropout(h_full_6, 0.5) # Layer - 7 fc7 W_full_7 = tf.Variable(np.array(fc_7[0])) b_full_7 = tf.Variable(np.array(fc_7[1])) y_full_7 = tf.add(tf.matmul(h_dropout_6, W_full_7), b_full_7) h_full_7 = tf.nn.relu(y_full_7, name = "fc7") h_dropout_7 = tf.nn.dropout(h_full_7, 0.5) # Layer - 8 fc8 W_full_8 = tf.Variable(np.array(fc_8[0])) b_full_8 = tf.Variable(np.array(fc_8[1])) y_full_8 = tf.add(tf.matmul(h_dropout_7, W_full_8), b_full_8, name = "fc8") # In[ ]: # reading sample image im = np.asarray(Image.open(os.path.join("sample_images", "images.jpg")).resize((256, 256))) - mean im = np.asarray(Image.fromarray(np.uint8(im)).resize((224, 224))) im = np.expand_dims(im, axis = 0) # In[ ]: # open a session and initialize graph variables # CAVEAT: trained alexnet weights have been set as initialization values in the graph nodes. # For this reason visualization can be performed just after initialization sess = tf.Session(graph=tf.get_default_graph()) sess.run(tf.global_variables_initializer()) # In[ ]: # activation visualization layers = ['r', 'p', 'c'] start = time.time() with sess.as_default(): # with sess_graph_path = None, the default Session will be used for visualization. is_success = activation_visualization(sess_graph_path = None, value_feed_dict = {X : im}, layers=layers, path_logdir=os.path.join("Log","AlexNet"), path_outdir=os.path.join("Output","AlexNet")) start = time.time() - start print("Total Time = %f" % (start)) # In[ ]: # deconv visualization layers = ['r', 'p', 'c'] start = time.time() with sess.as_default(): is_success = deconv_visualization(sess_graph_path = None, value_feed_dict = {X : im}, layers=layers, path_logdir=os.path.join("Log","AlexNet"), path_outdir=os.path.join("Output","AlexNet")) start = time.time() - start print("Total Time = %f" % (start)) # In[ ]: #close the session and release variables sess.close() # In[ ]: <file_sep>from .tf_cnnvis import activation_visualization from .tf_cnnvis import deconv_visualization from .tf_cnnvis import deepdream_visualization from .utils import convert_into_grid from .utils import image_normalization __all__ = ["activation_visualization", "deconv_visualization", "deepdream_visualization", "convert_into_grid", "image_normalization"] <file_sep># Setup script for tf_cnnvis import os import sys import six import pkgutil import shutil import glob # required pkgs dependencies = ['numpy', 'scipy', 'h5py', 'wget', 'Pillow', 'six','scikit-image'] try: from setuptools import setup except ImportError: from distutils.core import setup print("Please install if not installed:", dependencies) from distutils.command.clean import clean def read(fname): if six.PY2: return open(os.path.join(os.path.dirname(__file__), fname)).read() else: return open(os.path.join(os.path.dirname(__file__), fname), encoding='latin1').read() class CleanCommand(clean): """Custom clean command to tidy up the project root.""" def deleteFileOrDir(self, f): try: if os.path.isdir(f): shutil.rmtree(f, ignore_errors=True) else: os.remove(f) except Exception as e: print(e) def run(self): for p in './build ./dist ./*.pyc ./*.tgz ./*.egg-info'.split(' '): if '*' in p: for f in glob.glob(p): self.deleteFileOrDir(f) else: self.deleteFileOrDir(p) setup( name = "tf_cnnvis", version = "1.0.0", author = "<NAME> & <NAME>", author_email = "<EMAIL> & <EMAIL>", description = ("tf_cnnvis is a CNN visualization library based on the paper 'Visualizing and Understanding Convolutional Networks' by <NAME> and <NAME>. We use the 'TensorFlow' library to reconstruct the input images from different layers of the convolutional neural network. The generated images are displayed in [TensorBoard](https://www.tensorflow.org/get_started/summaries_and_tensorboard)."), license = "MIT", keywords = "tensorflow tensorboard convolutional-neural-networks cnn visualization", url = "https://github.com/InFoCusp/tf_cnnvis", packages=['tf_cnnvis'], long_description=read('ReadMe.md'), classifiers=[ "Development Status :: 3 - Alpha", "Intended Audience :: Science/Research", "Topic :: Utilities", "License :: OSI Approved :: MIT License", "Natural Language :: English", "Operating System :: Unix", "Programming Language :: Python", "Topic :: Scientific/Engineering :: Visualization", ], install_requires=dependencies, cmdclass={ 'clean': CleanCommand, } ) # Check TF version as it requires > 1.8 try: import tensorflow if (int(tensorflow.__version__.split(".")[0]) + 0.1 * int(tensorflow.__version__.split(".")[1])) < 1.8: print("Please upgrade to TensorFlow >= 1.8.0") except: print("Please install TenSorflow with 'pip install tensorflow'") <file_sep># tf_cnnvis [![DOI](https://zenodo.org/badge/85802370.svg)](https://zenodo.org/badge/latestdoi/85802370) A blog post describing the library: https://medium.com/@falaktheoptimist/want-to-look-inside-your-cnn-we-have-just-the-right-tool-for-you-ad1e25b30d90 tf_cnnvis is a CNN visualization library which you can use to better understand your own CNNs. We use the [TensorFlow](https://www.tensorflow.org/) library at the backend and the generated images are displayed in [TensorBoard](https://www.tensorflow.org/get_started/summaries_and_tensorboard). We have implemented 2 CNN visualization techniques so far: 1) Based on the paper [Visualizing and Understanding Convolutional Networks](https://www.cs.nyu.edu/~fergus/papers/zeilerECCV2014.pdf) by <NAME> and <NAME>. The goal here is to reconstruct the input image from the information contained in any given layers of the convolutional neural network. Here are a few examples | | | | | | :-----------: | :-----------: | :-----------: | :-----------: | | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/1.jpg" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/2.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/3.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/4.png" width="196" height="196"> | | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/5.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/6.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/7.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/8.png" width="196" height="196"> | | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/9.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/10.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/11.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/12.png" width="196" height="196"> | Figure 1: Original image and the reconstructed versions from maxpool layer 1,2 and 3 of Alexnet generated using tf_cnnvis. 2) CNN visualization based on [Deep dream](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/tutorials/deepdream/deepdream.ipynb) by Google. Here's the relevant [blog post](https://research.googleblog.com/2015/06/inceptionism-going-deeper-into-neural.html) explaining the technique. In essence, it attempts to construct an input image that maximizes the activation for a given output. We present some samples below: | | | | | | :-----------: | :-----------: | :-----------: | :-----------: | | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Carbonara.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Ibex.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Elephant.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Ostrich.png" width="196" height="196"> | | Carbonara | Ibex | Elephant | Ostrich | | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Cheese burger.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Tennis ball.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Fountain pen.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Clock tower.png" width="196" height="196"> | | Cheese burger | Tennis ball | Fountain pen | Clock tower | | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Cauliflower.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Baby Milk bottle.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Sea lion.png" width="196" height="196"> | <img src="https://github.com/InFoCusp/ui_resources/blob/master/cnnvis_images/Dolphin.png" width="196" height="196"> | | Cauliflower | Baby Milk bottle | Sea lion | Dolphin | ## Requirements: * Tensorflow (>= 1.8) * numpy * scipy * h5py * wget * Pillow * six * scikit-image If you are using pip you can install these with ```pip install tensorflow numpy scipy h5py wget Pillow six scikit-image``` ## Setup script Clone the repository ``` #!bash git clone https://github.com/InFoCusp/tf_cnnvis.git ``` And run ``` #!bash sudo pip install setuptools sudo pip install six sudo python setup.py install sudo python setup.py clean ``` ### Citation If you use this library in your work, please cite ``` @misc{tf_cnnvis, author = {<NAME>, <NAME>}, title = {CNN Visualization}, year = {2017}, howpublished = {\url{https://github.com/InFoCusp/tf_cnnvis/}}, doi = {10.5281/zenodo.2594491} } ``` ## API **tf_cnnvis.activation_visualization(graph_or_path, value_feed_dict, input_tensor=None, layers='r', path_logdir='./Log', path_outdir='./Output')** The function to generate the activation visualizations of the input image at the given layer. #### Parameters * graph_or_path (tf.Graph object or String) – TF graph or [Path-to-saved-graph] as String containing the CNN. * value_feed_dict (dict) – Values of placeholders to feed while evaluating the graph * dict : {placeholder1 : value1, ...} * input_tensor (tf.tensor object (Default = None)) – tf.tensor (input tensor to the model - where images enter into the models) Note: This is not a standalone tensor/placeholder separate from the model * layers (list or String (Default = 'r')) – * layerName : Reconstruction from a layer specified by name * ‘r’ : Reconstruction from all the relu layers * ‘p’ : Reconstruction from all the pooling layers * ‘c’ : Reconstruction from all the convolutional layers * path_outdir (String (Default = "./Output")) – [path-to-dir] to save results into disk as images * path_logdir (String (Default = "./Log")) – [path-to-log-dir] to make log file for TensorBoard visualization #### Returns * is_success (boolean) – True if the function ran successfully. False otherwise **tf_cnnvis.deconv_visualization(graph_or_path, value_feed_dict, input_tensor=None, layers='r', path_logdir='./Log', path_outdir='./Output')** The function to generate the visualizations of the input image reconstructed from the feature maps of a given layer. #### Parameters * graph_or_path (tf.Graph object or String) – TF graph or [Path-to-saved-graph] as String containing the CNN. * value_feed_dict (dict) – Values of placeholders to feed while evaluating the graph * dict : {placeholder1 : value1, ...} * input_tensor (tf.tensor object (Default = None)) – tf.tensor (input tensor to the model - where images enter into the models) Note: This is not a standalone tensor/placeholder separate from the model * layers (list or String (Default = 'r')) – * layerName : Reconstruction from a layer specified by name * ‘r’ : Reconstruction from all the relu layers * ‘p’ : Reconstruction from all the pooling layers * ‘c’ : Reconstruction from all the convolutional layers * path_outdir (String (Default = "./Output")) – [path-to-dir] to save results into disk as images * path_logdir (String (Default = "./Log")) – [path-to-log-dir] to make log file for TensorBoard visualization #### Returns * is_success (boolean) – True if the function ran successfully. False otherwise **tf_cnnvis.deepdream_visualization(graph_or_path, value_feed_dict, layer, classes, input_tensor=None, path_logdir='./Log', path_outdir='./Output')** The function to generate the visualizations of the input image reconstructed from the feature maps of a given layer. #### Parameters * graph_or_path (tf.Graph object or String) – TF graph or [Path-to-saved-graph] as String containing the CNN. * value_feed_dict (dict) – Values of placeholders to feed while evaluating the graph * dict : {placeholder1 : value1, ...} * layer (String) - name of a layer in TF graph * classes (List) - list featuremap index for the class classification layer * input_tensor (tf.tensor object (Default = None)) – tf.tensor (input tensor to the model - where images enter into the models) Note: This is not a standalone tensor/placeholder separate from the model * path_outdir (String (Default = "./Output")) – [path-to-dir] to save results into disk as images * path_logdir (String (Default = "./Log")) – [path-to-log-dir] to make log file for TensorBoard visualization #### Returns * is_success (boolean) – True if the function ran successfully. False otherwise ## To visualize in TensorBoard To start Tensorflow, run the following command on the console ``` #!bash tensorboard --logdir=./Log ``` and on the TensorBoard homepage look under the *Images* tab ## Additional helper functions ### tf_cnnvis.utils.image_normalization(image, ubound=255.0, epsilon=1e-07) Performs Min-Max image normalization. Transforms the pixel intensity values to range [0, ubound] #### Parameters * image (3-D numpy array) – A numpy array to normalize * ubound (float (Default = 255.0)) – upperbound for a image pixel value #### Returns * norm_image (3-D numpy array) – The normalized image ### tf_cnnvis.utils.convert_into_grid(Xs, padding=1, ubound=255.0) Convert 4-D numpy array into a grid of images for display #### Parameters * Xs (4-D numpy array (first axis contations an image)) – The 4D array of images to put onto grid * padding (int (Default = 1)) – Spacing between grid cells * ubound (float (Default = 255.0)) – upperbound for a image pixel value #### Returns * (3-D numpy array) – A grid of input images
0630804218dcdb9e48b98ba11dae13b358559b01
[ "Markdown", "Python" ]
4
Python
ziqizh/tf_cnnvis
c743841774d6281e53b32f51342d034a24641d34
0745aba44674bf492d95539def2f16ddf1d9831c
refs/heads/main
<repo_name>fjord-framework/producer<file_sep>/README.md <p align="center"> <img src="./readme_materials/fjord.svg" width="500" height="200" /> </p> # Test Producer This repository contains three `.js` scripts that can be used to test the production of records into a Kafka cluster. 1. `producer.js` is the simplest script. Run it to test the production of one record into a cluster. Sample usage: `node producer.js stocks ko 125`. The arguments passed represent the Kafka topic, the record key, and the record value. 2. `batch.js` produces a one-time batch of records into a cluster. Sample usage: `node batch.js stocks 1000`. Here, the arguments represent the topic and the number of records. The key will be a random number between 1 and 10, and the value will be a combination of the topic, time in milliseconds, and record number as it's created in the program. 3. `interval.js` produces a specified number of records per second into the cluster. Sample usage: `node interval.js stocks 10`. The arguments here represent the Kafka topic and the number of records you want to producer per second. Be sure to include a `.env` file with the following environmental variables: ``` CLIENT= BROKERS= KAFKA_USERNAME= KAFKA_PASSWORD= SECURITY= ``` <file_sep>/lib/interval.js const { Kafka } = require('kafkajs'); require('dotenv').config(); const { BROKERS, CLIENT, SECURITY, KAFKA_USERNAME, KAFKA_PASSWORD } = process.env const myArgs = process.argv.slice(2); let [topic, numPerSecond, batch] = myArgs; // node interval.js stocks 10 const config = { clientId: CLIENT, brokers: BROKERS.split(" ") }; if (SECURITY === 'SASL-plain') { config.sasl = { mechanism: 'plain', username: KAFKA_USERNAME, password: <PASSWORD> }; } const kafka = new Kafka(config); // create a producer to produce a message const producer = kafka.producer(); const BATCH_ID = batch ? batch : Date.now(); function populate(num) { const m = []; let i = 0; let key, value; while (i < num) { key = String(1 + Math.floor(Math.random() * 10)); value = topic + "-" + BATCH_ID + "-" + (i + 1); m.push({ key, value}); i++; } return m; } const producerStart = async() => { await producer.connect(); await producer.send({ topic, messages: [{key: "start", value: "start"}], }); setInterval( () => { const MESSAGES = populate(numPerSecond); producer.send({ topic, messages: MESSAGES, }); }, 1000); }; producerStart();<file_sep>/lib/producer.js const { Kafka } = require('kafkajs'); require('dotenv').config(); const { BROKERS, CLIENT, SECURITY, KAFKA_USERNAME, KAFKA_PASSWORD } = process.env const myArgs = process.argv.slice(2); // node producer.js stocks ko 125 const [TOPIC, KEY, VALUE] = myArgs; // instantiating the KafkaJS client by pointing it towards at least one broker: const config = { clientId: CLIENT, brokers: BROKERS.split(" ") }; if (SECURITY === 'SASL-plain') { config.sasl = { mechanism: 'plain', username: KAFKA_USERNAME, password: <PASSWORD> }; } const kafka = new Kafka(config); // create a producer to produce a message const producer = kafka.producer(); const producerStart = async() => { await producer.connect(); await producer.send({ topic: TOPIC, messages: [ { key: KEY, value: VALUE }, ], }); await producer.disconnect(); }; producerStart();
a1097f646a52bb4ba951052eef54a451019ceaaf
[ "Markdown", "JavaScript" ]
3
Markdown
fjord-framework/producer
efbc8b82b30b0e0da39b16c4b488e8ff8dfe5c61
e51b910d94539ebeb144bfa9c6ac99d7bb211c45
refs/heads/master
<file_sep>package com.example.flash; import android.content.Intent; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { MediaPlayer am; Thread thread; Thread timer; Intent intent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); am=MediaPlayer.create(MainActivity.this,R.raw.hello); am.start(); timer = new Thread() { public void run() { try { sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } finally { Intent intent = new Intent(getApplicationContext(),MainActivity.class); startActivity(intent); } } }; timer.start(); } }
222e6c530bf8684e1ba698ccfcc521d58dd88f56
[ "Java" ]
1
Java
mayurichintalwar2998/Flash
1005e08b6ce135f072474e4b187f8ac7c25bac17
3b25f5a0ec5a7c71bb9431d27413b4ac1fdc74a9
refs/heads/master
<file_sep>import { NgModuleRef, Compiler, NgModule, Type, NgZone } from "@angular/core"; import { NgModuleResolver } from "@angular/compiler"; import { environment } from "../../environments/environment"; import { DynamicComponentsService } from "../dynamic-components.service"; /** * This class contains common functionality that allows component modules to hot-reload in the app without reloading the whole app. * * ### Example * * export class MyModule { * constructor(moduleRef: NgModuleRef<MyModule>) { * HmrModuleHelper.enableHmrNgModule(module, moduleRef); * } * } * * HmrModuleHelper.enableHmrNodeModule(module); * * ### Remarks * * The source code for the webpack Hot Module Replacement is available at * https://github.com/webpack/webpack/blob/v4.9.2/lib/HotModuleReplacement.runtime.js **/ export class HmrModuleHelper { /** * Call this method from your module file (but outside your module class) to enable hot-module-reload. * @param nodeModuleRef The module to enable HMR on. Just pass the "module" reference from the module you're calling from. */ public static enableHmrNodeModule(nodeModuleRef: NodeModule): void { if (environment.hmr) { (<any>nodeModuleRef).hot.accept(); } } /** * Call this method from your module's constructor to make it available for hot-reload. * @param nodeModuleRef The module to enable HMR on. Just pass the "module" reference from the module you're calling from. * @param moduleRef An NgModuleRef that points to the Angular module to enable HMR on. */ public static enableHmrNgModule<T>(nodeModuleRef: NodeModule, moduleRef: NgModuleRef<T>): void { //only add a Dispose handler if this environment supports hmr and we haven't already created a disposeHandler if (environment.hmr && (<any>nodeModuleRef).hot._disposeHandlers.length == 0) { let compiler = moduleRef.injector.get(Compiler); let dynamicComponentSvc = moduleRef.injector.get(DynamicComponentsService); let zone = moduleRef.injector.get(NgZone); (<any>nodeModuleRef).hot.addDisposeHandler(() => { try { zone.run(() => { //get the metadata for this module let metaData: NgModule = ((compiler as any)._metadataResolver._ngModuleResolver as NgModuleResolver).resolve((<any>moduleRef)._moduleType); //get a list of all component types that are part of this module (they should all be listed as entryComponents) let componentTypes = <Array<Type<any>>>metaData.entryComponents; //ask all components of all affected types to reload dynamicComponentSvc.reloadComponents(componentTypes); //clear the Angular cache that knows about this component, so its reloaded for (let declarations of metaData.declarations) { let dec = <Type<any>>declarations; compiler.clearCacheFor(dec); } compiler.clearCacheFor((<any>moduleRef)._moduleType); }); } catch (error) { console.error(error); throw error; } }); } } }
8239ce1f83b762ced5d2531bafb0c1c635f8533a
[ "TypeScript" ]
1
TypeScript
pppdns/angular-hmr-lazy-components
92e17d3b28a0583ac46f107932140dad30037078
9ffe62b1149fea11736740f639d7f0cacb42b964
refs/heads/main
<repo_name>asl-epfl/sl-partial-icassp2020<file_sep>/codefig3.py """ This code can be used to generate simulations similar to Fig. 3 in the following paper: <NAME>, <NAME>, and <NAME>, ``Social learning with partial information sharing,'' Proc. IEEE ICASSP, Barcelona, Spain, May 2020. Please note that the code is not generally perfected for performance, but is rather meant to illustrate certain results from the paper. The code is provided as-is without guarantees. July 2020 (Author: <NAME>) """ import matplotlib as mpl import matplotlib.gridspec as gridspec import random import os import networkx as nx from functions import * #%% mpl.style.use('seaborn-deep') plt.rcParams.update({'text.usetex': True}) mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.serif'] = 'Computer Modern Roman' getcontext().prec = 200 #%% FIG_PATH = 'figs/' if not os.path.isdir(FIG_PATH): os.makedirs(FIG_PATH) #%% N=10 M=3 N_ITER = 200 N_MC = 1 np.random.seed(2) #%% ################################ Build Network Topology ################################ G = np.random.choice([0.0,1.0],size=(N,N), p=[0.5,0.5]) G = G+G.T+np.eye(N) G=(G>0)*1.0 #%% lamb = .03 A = np.zeros((N,N)) for i in range(N): A[G[i]>0, i]=(1-lamb)/(np.sum(G[i])-1) A[i,i]=lamb A_dec = np.array([[Decimal(x) for x in y] for y in A]) #%% np.random.seed(0) getcontext().prec = 100 #%% L = np.array([np.array([Decimal(.1), Decimal(.7), Decimal(.2)]), np.array([Decimal(.15), Decimal(.65), Decimal(.2)]), np.array([Decimal(.4), Decimal(.2), Decimal(.4)])]) Lf = np.array([[float(x) for x in y] for y in L]) #%% mu_0 = np.random.rand(N,M) mu_0 = mu_0/np.sum(mu_0, axis = 1)[:, None] mu_0 = np.array([[Decimal(x) for x in y] for y in mu_0]) #%% csi = [] for l in range(N): csi.append(np.random.choice([0,1,2],size=N_ITER, p=Lf[0])) csi=np.array(csi) #%% MU_sa_0 = partial_info_d(mu_0, csi, A_dec, L, N_ITER, M, N, tx=0, self_aware = True) vec_0sa= np.array([MU_sa_0[k][0] for k in range(len(MU_sa_0))]) MU_sa_1 = partial_info_d(mu_0, csi, A_dec, L, N_ITER, M, N, tx=1, self_aware = True) vec_1sa= np.array([MU_sa_1[k][0] for k in range(len(MU_sa_1))]) MU_sa_2 = partial_info_d(mu_0, csi, A_dec, L, N_ITER, M, N, tx=2, self_aware = True) vec_2sa= np.array([MU_sa_2[k][0] for k in range(len(MU_sa_2))]) #%% import matplotlib.gridspec as gridspec plt.figure(figsize=(12,2.5)) gs = gridspec.GridSpec(1, 4, width_ratios=[1.5,1,1,1]) plt.subplot(gs[0]) plt.grid(True, axis='y') h1=plt.bar(np.arange(3)-.1,L[0], width=.1) h2=plt.bar(np.arange(3),L[1], width=.1) h3=plt.bar(np.arange(3)+.1,L[2], width=.1) plt.ylabel(r'$L(\xi|\theta)$', fontsize = 15) plt.xlabel(r'$\xi$', fontsize = 15) plt.tight_layout() plt.title('Discrete Likelihoods', fontsize=15) plt.xticks(np.arange(3)) plt.subplot(gs[1]) plt.plot(vec_0sa[:,0], linewidth='1.5', color = 'C0') plt.plot(vec_0sa[:,1], linewidth='1.5', color = 'C1') plt.plot(vec_0sa[:,2], linewidth='1.5', color = 'C2') plt.annotate('%0.2f' % vec_0sa[-1,0], (1.01, vec_0sa[-1,0]),xycoords=('axes fraction', 'data'), color = 'C0') plt.annotate('%0.2f' % vec_0sa[-1,1], (1.01, vec_0sa[-1,1]),xycoords=('axes fraction', 'data'), color = 'C1') plt.annotate('%0.2f' % vec_0sa[-1,2], (1.01, vec_0sa[-1,2]-Decimal(.1)),xycoords=('axes fraction', 'data'), color = 'C2') plt.xlim([0,200]) plt.ylim([-0.1,1.1]) plt.title(r'$\theta_{\sf TX}=1$', fontsize = 15) plt.xlabel(r'$i$', fontsize = 15) plt.ylabel(r'$\mu_{{{l},i}}(\theta)$'.format(l=1), fontsize = 15) plt.tight_layout() plt.subplot(gs[2]) plt.plot(vec_1sa[:,0], linewidth='1.5', color = 'C0') plt.plot(vec_1sa[:,1], linewidth='1.5', color = 'C1') plt.plot(vec_1sa[:,2], linewidth='1.5', color = 'C2') plt.annotate('%0.2f' % vec_1sa[-1,0], (1.01, vec_1sa[-1,0]),xycoords=('axes fraction', 'data'), color = 'C0') plt.annotate('%0.2f' % vec_1sa[-1,1], (1.01, vec_1sa[-1,1]),xycoords=('axes fraction', 'data'), color = 'C1') plt.annotate('%0.2f' % vec_1sa[-1,2], (1.01, vec_1sa[-1,2]-Decimal(.1)),xycoords=('axes fraction', 'data'), color = 'C2') plt.xlim([0,200]) plt.ylim([-0.1,1.1]) plt.title(r'$\theta_{\sf TX}=2$', fontsize = 15) plt.xlabel(r'$i$', fontsize = 15) plt.ylabel(r'$\mu_{{{l},i}}(\theta)$'.format(l=1), fontsize = 15) plt.tight_layout() a=plt.subplot(gs[3]) a.plot(vec_2sa[:,0], linewidth='1.5', color = 'C0', label=r'$\theta=1$') a.plot(vec_2sa[:,1], linewidth='1.5', color = 'C1', label = r'$\theta=2$') a.plot(vec_2sa[:,2], linewidth='1.5', color = 'C2', label = r'$\theta=3$') a.annotate('%0.2f' % vec_2sa[-1,0], (1.005, vec_2sa[-1,0]),xycoords=('axes fraction', 'data'), color = 'C0') a.annotate('%0.2f' % vec_2sa[-1,1], (1.005, vec_2sa[-1,1]-Decimal(.1)),xycoords=('axes fraction', 'data'), color = 'C1') a.annotate('%0.2f' % vec_2sa[-1,2], (1.005, vec_2sa[-1,2]),xycoords=('axes fraction', 'data'), color = 'C2') a.set_xlim([0,100]) a.set_ylim([-0.1,1.1]) rect = [0.5,0.7,0.3,0.25] ax1 = add_subplot_axes(a,rect) ax1.plot(vec_2sa[:,0], linewidth='1.5', color = 'C0') ax1.plot(vec_2sa[:,1], linewidth='1.5', color = 'C1') ax1.set_ylim([0.499, 0.501]) ax1.set_xlim([80, 90]) ax1.set_xticklabels('') ax1.set_yticks([0.499, 0.501]) ax1.set_yticklabels([0.499, 0.501]) a.set_title(r'$\theta_{\sf TX}=3$', fontsize = 15) a.set_xlabel(r'$i$', fontsize = 15) a.set_ylabel(r'$\mu_{{{l},i}}(\theta)$'.format(l=1), fontsize = 15) a.add_line(mpl.lines.Line2D([80,55],[.5, 0.7], color='black', linestyle='dashed' ,linewidth=.8)) a.add_line(mpl.lines.Line2D([90,85],[.5, 0.7], color='black', linestyle='dashed',linewidth=.8)) plt.tight_layout() plt.subplots_adjust(bottom=0.32) plt.figlegend(ncol=M,fontsize = 14, bbox_to_anchor=(0.13,-0.31, 0.5, 0.5), handlelength=1) plt.savefig(FIG_PATH + 'fig3.pdf', bbox_inches='tight') <file_sep>/README.md ## Release v1.0.0. [![DOI](https://zenodo.org/badge/303961575.svg)](https://zenodo.org/badge/latestdoi/303961575) This code can be used to generate simulations similar to Figs. 1, 2, 3, 4 and 5 in the following paper: <NAME>, <NAME>, and <NAME>, ``Social learning with partial information sharing,'' Proc. IEEE ICASSP, Barcelona, Spain, May 2020. [![DOI:10.1109/ICASSP40776.2020.9052947](https://zenodo.org/badge/DOI/10.1109/ICASSP40776.2020.9052947.svg)](https://doi.org/10.1109/ICASSP40776.2020.9052947) Figs. 1 and 2 are generated executing file 'codefig12.py'. Fig. 3 is generated executing file 'codefig3.py'. Fig. 4 is generated executing file 'codefig4.py'. Fig. 5 is generated executing file 'codefig5.py'. Please note that the code is not generally perfected for performance, but is rather meant to illustrate certain results from the paper. The code is provided as-is without guarantees. July 2020 (Author: <NAME>) <file_sep>/codefig12.py """ This code can be used to generate simulations similar to Figs. 1 and 2 in the following paper: <NAME>, <NAME>, and <NAME>, ``Social learning with partial information sharing,'' Proc. IEEE ICASSP, Barcelona, Spain, May 2020. Please note that the code is not generally perfected for performance, but is rather meant to illustrate certain results from the paper. The code is provided as-is without guarantees. July 2020 (Author: <NAME>) """ import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import random import os import networkx as nx from functions import * #%% mpl.style.use('seaborn-deep') plt.rcParams.update({'text.usetex': True}) mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.serif'] = 'Computer Modern Roman' getcontext().prec = 200 #%% FIG_PATH = 'figs/' if not os.path.isdir(FIG_PATH): os.makedirs(FIG_PATH) #%% N=10 M=3 N_ITER = 200 N_MC = 1 np.random.seed(2) #%% ################################ Build Network Topology ################################ G = np.random.choice([0.0,1.0],size=(N,N), p=[0.5,0.5]) G = G+G.T+np.eye(N) G=(G>0)*1.0 #%% lamb = .5 A = np.zeros((N,N)) for i in range(N): A[G[i]>0, i]=(1-lamb)/(np.sum(G[i])-1) A[i,i]=lamb A_dec = np.array([[Decimal(x) for x in y] for y in A]) #%% Gr= nx.from_numpy_array(A) pos = nx.spring_layout(Gr) #%% f,ax=plt.subplots(1,1, figsize=(4,2)) plt.axis('off') plt.xlim([-1.2,1.2]) plt.ylim([-1.15,1.1]) nx.draw_networkx_nodes(Gr, pos=pos, node_color= 'C4',nodelist=[0],node_size=700, edgecolors='k', linewidths=.5) nx.draw_networkx_nodes(Gr, pos=pos, node_color= 'C2',nodelist=range(1,N),node_size=700, edgecolors='k', linewidths=.5) nx.draw_networkx_labels(Gr,pos,{i: i+1 for i in range(N)},font_size=16, font_color='black', alpha = 1) nx.draw_networkx_edges(Gr, pos = pos, node_size=500, alpha=1, arrowsize=6, width=1); plt.tight_layout() plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.savefig(FIG_PATH + 'fig1.pdf', format='pdf', bbox_inches='tight', pad_inches=0) #%% ################################ Run Social Learning ################################ theta = np.array([Decimal(0), Decimal(0.2), Decimal(1)]) var = Decimal(1) x = np.linspace(-4, 6, 1000) x = decimal_array(x) dt = (max(x)-min(x))/len(x) #%% mu_0 = np.random.rand(N,M) mu_0 = mu_0/np.sum(mu_0, axis = 1)[:, None] mu_0 = decimal_array(mu_0) #%% csi=[] for l in range(N): csi.append(theta[0]+np.sqrt(var)*decimal_array(np.random.randn(N_ITER))) csi=np.array(csi) #%% MU_ob_0 = partial_info(mu_0, csi, A_dec, N_ITER, theta, var, M, N) vec_0 = np.array([MU_ob_0[k][0] for k in range(len(MU_ob_0))]) MU_ob_1 = partial_info(mu_0, csi, A_dec, N_ITER, theta, var, M, N, tx=1) vec_1 = np.array([MU_ob_1[k][0] for k in range(len(MU_ob_1))]) MU_ob_2 = partial_info(mu_0, csi, A_dec, N_ITER, theta, var, M, N, tx=2) vec_2 = np.array([MU_ob_2[k][0] for k in range(len(MU_ob_2))]) #%% plt.figure(figsize=(12,2.5)) gs = gridspec.GridSpec(1, 4, width_ratios=[1.5,1,1,1]) plt.subplot(gs[0]) L0 = gaussian(x, theta[0], var,) L1 = gaussian(x, theta[1], var) L2 = gaussian(x, theta[2], var) plt.plot(x, L0) plt.plot(x, L1) plt.plot(x, L2) plt.ylabel(r'$L(\xi|\theta)$', fontsize = 15) plt.xlabel(r'$\xi$', fontsize = 15) plt.tight_layout() plt.xlim(-4,6) plt.title('Gaussian Likelihoods', fontsize=15) plt.tight_layout() plt.subplot(gs[1]) plt.plot(vec_0[:,0], linewidth='1.5', color = 'C0') plt.plot(vec_0[:,1], linewidth='1.5', color = 'C1') plt.plot(vec_0[:,2], linewidth='1.5', color = 'C2') plt.annotate('%0.2f' % vec_0[-1,0], (1.01, vec_0[-1,0]),xycoords=('axes fraction', 'data'), color = 'C0') plt.annotate('%0.2f' % vec_0[-1,1], (1.01, vec_0[-1,1]),xycoords=('axes fraction', 'data'), color = 'C1') plt.annotate('%0.2f' % vec_0[-1,2], (1.01, vec_0[-1,2]-Decimal(.1)),xycoords=('axes fraction', 'data'), color = 'C2') plt.xlim([0,200]) plt.ylim([-0.1,1.1]) plt.title(r'$\theta_{\sf TX}=1$', fontsize = 15) plt.xlabel(r'$i$', fontsize = 15) plt.ylabel(r'$\mu_{{{l},i}}(\theta)$'.format(l=1), fontsize = 15) plt.tight_layout() plt.subplot(gs[2]) plt.plot(vec_1[:,0], linewidth='1.5', color = 'C0') plt.plot(vec_1[:,1], linewidth='1.5', color = 'C1') plt.plot(vec_1[:,2], linewidth='1.5', color = 'C2') plt.annotate('%0.2f' % vec_1[-1,0], (1.01, vec_1[-1,0]),xycoords=('axes fraction', 'data'), color = 'C0') plt.annotate('%0.2f' % vec_1[-1,1], (1.01, vec_1[-1,1]),xycoords=('axes fraction', 'data'), color = 'C1') plt.annotate('%0.2f' % vec_1[-1,2], (1.01, vec_1[-1,2]-Decimal(.1)),xycoords=('axes fraction', 'data'), color = 'C2') plt.xlim([0,200]) plt.ylim([-0.1,1.1]) plt.title(r'$\theta_{\sf TX}=2$', fontsize = 15) plt.xlabel(r'$i$', fontsize = 15) plt.ylabel(r'$\mu_{{{l},i}}(\theta)$'.format(l=1), fontsize = 15) plt.tight_layout() plt.subplot(gs[3]) plt.plot(vec_2[:,0], linewidth='1.5', color = 'C0', label=r'$\theta=1$') plt.plot(vec_2[:,1], linewidth='1.5', color = 'C1', label = r'$\theta=2$') plt.plot(vec_2[:,2], linewidth='1.5', color = 'C2', label = r'$\theta=3$') plt.annotate('%0.2f' % vec_2[-1,0], (1.01, vec_2[-1,0]),xycoords=('axes fraction', 'data'), color = 'C0') plt.annotate('%0.2f' % vec_2[-1,1], (1.01, vec_2[-1,1]-Decimal(.1)),xycoords=('axes fraction', 'data'), color = 'C1') plt.annotate('%0.2f' % vec_2[-1,2], (1.01, vec_2[-1,2]),xycoords=('axes fraction', 'data'), color = 'C2') plt.xlim([0,200]) plt.ylim([-0.1,1.1]) plt.title(r'$\theta_{\sf TX}=3$', fontsize = 15) plt.xlabel(r'$i$', fontsize = 15) plt.ylabel(r'$\mu_{{{l},i}}(\theta)$'.format(l=1), fontsize = 15) plt.tight_layout() plt.subplots_adjust(bottom=0.32) plt.figlegend(ncol=M,fontsize = 14, bbox_to_anchor=(0.13,-0.31, 0.5, 0.5), handlelength=1) plt.savefig(FIG_PATH + 'fig2.pdf', bbox_inches='tight') <file_sep>/codefig4.py """ This code can be used to generate simulations similar to Fig. 3 in the following paper: <NAME>, <NAME>, and <NAME>, ``Social learning with partial information sharing,'' Proc. IEEE ICASSP, Barcelona, Spain, May 2020. Please note that the code is not generally perfected for performance, but is rather meant to illustrate certain results from the paper. The code is provided as-is without guarantees. July 2020 (Author: <NAME>) """ import matplotlib as mpl import matplotlib.gridspec as gridspec import random import os import networkx as nx from functions import * #%% mpl.style.use('seaborn-deep') plt.rcParams.update({'text.usetex': True}) mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.serif'] = 'Computer Modern Roman' getcontext().prec = 200 #%% FIG_PATH = 'figs/' if not os.path.isdir(FIG_PATH): os.makedirs(FIG_PATH) #%% N=10 M=3 N_ITER = 200 N_MC = 1 np.random.seed(2) #%% ################################ Build Network Topology ################################ G = np.random.choice([0.0,1.0],size=(N,N), p=[0.5,0.5]) G = G+G.T+np.eye(N) G=(G>0)*1.0 #%% np.random.seed(0) getcontext().prec = 100 #%% L = np.array([np.array([Decimal(.1), Decimal(.7), Decimal(.2)]), np.array([Decimal(.15), Decimal(.65), Decimal(.2)]), np.array([Decimal(.4), Decimal(.2), Decimal(.4)])]) Lf = np.array([[float(x) for x in y] for y in L]) #%% ################################ Run Social Learning ################################ mu_0 = np.random.rand(N,M) mu_0 = mu_0/np.sum(mu_0, axis = 1)[:, None] mu_0 = np.array([[Decimal(x) for x in y] for y in mu_0]) #%% np.random.seed(0) N_ITER=500 #%% csi = [] for l in range(N): csi.append(np.random.choice([0,1,2],size=N_ITER, p=Lf[0])) csi=np.array(csi) #%% lamb = .9 A = np.zeros((N,N)) for i in range(N): A[G[i]>0, i]=(1-lamb)/(np.sum(G[i])-1) A[i,i]=lamb A_dec = np.array([[Decimal(x) for x in y] for y in A]) #%% MU_sa_29 = partial_info_d(mu_0, csi, A_dec, L, N_ITER, M, N, tx=2, self_aware = True) vec_2sa_9=np.array([MU_sa_29[k][0] for k in range(len(MU_sa_29))]) #%% lamb = .99 A = np.zeros((N,N)) for i in range(N): A[G[i]>0, i]=(1-lamb)/(np.sum(G[i])-1) A[i,i]=lamb A_dec = np.array([[Decimal(x) for x in y] for y in A]) #%% MU_sa_299 = partial_info_d(mu_0, csi, A_dec, L, N_ITER, M, N, tx=2, self_aware = True) vec_2sa_99=np.array([MU_sa_299[k][0] for k in range(len(MU_sa_299))]) #%% plt.figure(figsize=(5,2.2)) gs = gridspec.GridSpec(1, 2, width_ratios=[1,1]) plt.subplot(gs[0]) plt.plot(vec_2sa_9[:,0], linewidth='1.5', color = 'C0', label=r'$\theta=1$') plt.plot(vec_2sa_9[:,1], linewidth='1.5', color = 'C1', label = r'$\theta=2$') plt.plot(vec_2sa_9[:,2], linewidth='1.5', color = 'C2', label = r'$\theta=3$') plt.annotate('%0.2f' % vec_2sa_9[-1,0], (1.01, vec_2sa_9[-1,0]),xycoords=('axes fraction', 'data'), color = 'C0') plt.annotate('%0.2f' % vec_2sa_9[-1,1], (1.01, vec_2sa_9[-1,1]+Decimal(.07)),xycoords=('axes fraction', 'data'), color = 'C1') plt.annotate('%0.2f' % vec_2sa_9[-1,2], (1.01, vec_2sa_9[-1,2]),xycoords=('axes fraction', 'data'), color = 'C2') plt.xlim([0,200]) plt.ylim([-0.1,1.1]) plt.title(r'$\lambda = 0.9$', fontsize = 13) plt.xlabel(r'$i$', fontsize = 15) plt.ylabel(r'$\mu_{{{l},i}}(\theta)$'.format(l=1), fontsize = 16) plt.figlegend(ncol=3,fontsize=12, handlelength=1, bbox_to_anchor=[.32,-.31,.5,.5]) plt.tight_layout() plt.subplot(gs[1]) plt.plot(vec_2sa_99[:,0], linewidth='1.5', color = 'C0', label=r'$\theta=1$') plt.plot(vec_2sa_99[:,1], linewidth='1.5', color = 'C1', label = r'$\theta=2$') plt.plot(vec_2sa_99[:,2], linewidth='1.5', color = 'C2', label = r'$\theta=3$') plt.annotate('%0.2f' % vec_2sa_99[-1,0], (1.01, vec_2sa_99[-1,0]),xycoords=('axes fraction', 'data'), color = 'C0') plt.annotate('%0.2f' % vec_2sa_99[-1,1], (1.01, vec_2sa_99[-1,1]+Decimal(.07)),xycoords=('axes fraction', 'data'), color = 'C1') plt.annotate('%0.2f' % vec_2sa_99[-1,2], (1.01, vec_2sa_99[-1,2]),xycoords=('axes fraction', 'data'), color = 'C2') plt.xlim([0,200]) plt.ylim([-0.1,1.1]) plt.title(r'$\lambda = 0.99$', fontsize = 13) plt.xlabel(r'$i$', fontsize = 15) plt.ylabel(r'$\mu_{{{l},i}}(\theta)$'.format(l=1), fontsize = 16) plt.tight_layout() plt.subplots_adjust(bottom=.35, wspace=.55) plt.savefig(FIG_PATH+'fig4.pdf', bbox_inches='tight') <file_sep>/functions.py import numpy as np from decimal import * import matplotlib.pyplot as plt def gaussian(x, m, var): ''' Computes the Gaussian pdf value at x. x: value at which the pdf is computed (Decimal type) m: mean (Decimal type) var: variance ''' p = np.exp(-(x-m)**Decimal(2)/(Decimal(2)*Decimal(var)))/(np.sqrt(Decimal(2)*Decimal(np.pi)*Decimal(var))) return p def bayesian_update(L, mu): ''' Computes the Bayesian update. L: likelihoods matrix mu: beliefs matrix ''' aux = L*mu bu = aux/aux.sum(axis = 1)[:, None] return bu def DKL(m,n,dx): ''' Computes the KL divergence between m and n. m: true distribution in vector form n: second distribution in vector form dx : sample size ''' mn=m/n mnlog= np.log(mn) return np.sum(m*dx*mnlog) def decimal_array(arr): ''' Converts an array to an array of Decimal objects. arr: array to be converted ''' if len(arr.shape)==1: return np.array([Decimal(y) for y in arr]) else: return np.array([[Decimal(x) for x in y] for y in arr]) def partial_info(mu_0, csi, A_dec, N_ITER, theta, var, M, N, tx = 0, self_aware = False, partial=True): ''' Executes the social learning algorithm. mu_0: initial beliefs csi: observations A_dec: Combination matrix (Decimal type) N_ITER: number of iterations theta: vector of means for the Gaussian likelihoods var: variance of Gaussian likelihoods M: number of hypothese N: number of agents tx: transmitted hypothesis (can be a numerical value or 'max') self_aware: self-awareness flag partial: partial information flag ''' mu = mu_0.copy() MU = [mu] for i in range(N_ITER): L_i = np.array([gaussian(csi[:,i], t, var) for t in theta]).T psi = bayesian_update(L_i, mu) decpsi = np.array([[x.ln() for x in y] for y in psi]) if partial: if tx=='max': # share theta max aux = np.array([[Decimal(1) for x in y] for y in mu])*(1-np.max(psi,axis=1))[:,None]/(M-1) aux[np.arange(N), np.argmax(psi,axis=1)]=np.max(psi,axis=1) else: # share tx aux = np.array([[Decimal(1) for x in y] for y in mu])*(1-psi[:,tx])[:, None]/(M-1) aux[np.arange(N), np.ones(N, dtype=int)*tx]=psi[:,tx] decaux = np.array([[x.ln() for x in y] for y in aux]) if partial: if not self_aware: # Without non-cooperative term: mu = np.exp((A_dec.T).dot(decaux))/np.sum(np.exp((A_dec.T).dot(decaux)),axis =1)[:,None] else: # With non-cooperative term: mu = np.exp(np.diag(np.diag(A_dec)).dot(decpsi)+(A_dec.T-np.diag(np.diag(A_dec))).dot(decaux))/np.sum(np.exp(np.diag(np.diag(A_dec)).dot(decpsi)+(A_dec.T-np.diag(np.diag(A_dec))).dot(decaux)),axis =1)[:,None] else: mu = np.exp((A_dec.T).dot(decpsi))/np.sum(np.exp((A_dec.T).dot(decpsi)),axis =1)[:,None] MU.append(mu) return MU def mc_partial_info(N_MC, A_dec, N_ITER, theta, var, M, N, tx=0, self_aware = False, partial=True): ''' Executes N_MC Monte Carlo runs of the social learning algorithm. N_MC: number of Monte Carlo runs A_dec: combination matrix (Decimal type) N_ITER: number of iterations theta: vector of means for the Gaussian likelihoods var: variance of Gaussian likelihoods M: number of hypotheses N: number of agents tx: transmitted hypothesis (can be a numerical value or 'max') self_aware: self-awareness flag partial: partial information flag ''' ALL_MU = [ for i in range(N_MC): mu_0 = np.random.rand(N,M) mu_0 = mu_0/np.sum(mu_0, axis = 1)[:, None] mu_0 = decimal_array(mu_0) csi=[] for l in range(N): csi.append(theta[0]+np.sqrt(var)*decimal_array(np.random.randn(N_ITER))) csi=np.array(csi) MU = partial_info(mu_0, csi, A_dec, N_ITER, theta, var, M, N, tx, self_aware = False, partial=partial) ALL_MU.append(MU) return ALL_MU def partial_info_d(mu_0, csi, A_dec, L, N_ITER, M, N, tx=0, self_aware = False): ''' Executes the social learning algorithm for a discrete family of likelihoods. mu_0: initial beliefs csi: observations A_dec: combination matrix (Decimal type) L: likelihoods matrix N_ITER: number of iterations M: number of hypotheses N: number of agents tx: transmitted hypothesis (can be a numerical value or 'max') self_aware: self-awareness flag ''' mu = mu_0.copy() MU = [mu] for i in range(N_ITER): L_i = L[:,csi[:,i]].T psi = bayesian_update(L_i, mu) if tx=='max': # share theta max aux = np.array([[Decimal(1) for x in y] for y in mu])*(1-np.max(psi,axis=1))[:,None]/(M-1) aux[np.arange(N), np.argmax(psi,axis=1)]=np.max(psi,axis=1) else: # share tx aux = np.array([[Decimal(1) for x in y] for y in mu])*(1-psi[:,tx])[:, None]/(M-1) aux[np.arange(N), np.ones(N, dtype=int)*tx]=psi[:,tx] decpsi = np.array([[x.ln() for x in y] for y in psi]) decaux = np.array([[x.ln() for x in y] for y in aux]) if not self_aware: # Without non-cooperative term: mu = np.exp((A_dec.T).dot(decaux))/np.sum(np.exp((A_dec.T).dot(decaux)),axis =1)[:,None] else: # With non-cooperative term: mu = np.exp(np.diag(np.diag(A_dec)).dot(decpsi)+(A_dec.T-np.diag(np.diag(A_dec))).dot(decaux))/np.sum(np.exp(np.diag(np.diag(A_dec)).dot(decpsi)+(A_dec.T-np.diag(np.diag(A_dec))).dot(decaux)),axis =1)[:,None] MU.append(mu) return MU def add_subplot_axes(ax, rect, axisbg='w'): ''' Adds an axis within a graph. ''' fig = plt.gcf() box = ax.get_position() width = box.width height = box.height inax_position = ax.transAxes.transform(rect[0:2]) transFigure = fig.transFigure.inverted() infig_position = transFigure.transform(inax_position) x = infig_position[0] y = infig_position[1] width *= rect[2] height *= rect[3] # <= Typo was here subax = fig.add_axes([x,y,width,height]) return subax <file_sep>/codefig5.py """ This code can be used to generate simulations similar to Fig. 5 in the following paper: <NAME>, <NAME>, and <NAME>, ``Social learning with partial information sharing,'' Proc. IEEE ICASSP, Barcelona, Spain, May 2020. Please note that the code is not generally perfected for performance, but is rather meant to illustrate certain results from the paper. The code is provided as-is without guarantees. July 2020 (Author: <NAME>) """ import matplotlib as mpl import matplotlib.gridspec as gridspec import random import os import networkx as nx from functions import * #%% mpl.style.use('seaborn-deep') plt.rcParams.update({'text.usetex': True}) mpl.rcParams['font.family'] = 'serif' mpl.rcParams['font.serif'] = 'Computer Modern Roman' getcontext().prec = 200 #%% FIG_PATH = 'figs/' if not os.path.isdir(FIG_PATH): os.makedirs(FIG_PATH) #%% N=10 M=3 N_ITER = 200 N_MC = 1 np.random.seed(2) #%% ################################ Build Network Topology ################################ G = np.random.choice([0.0,1.0],size=(N,N), p=[0.5,0.5]) G = G+G.T+np.eye(N) G=(G>0)*1.0 #%% lamb = .5 A = np.zeros((N,N)) for i in range(N): A[G[i]>0, i]=(1-lamb)/(np.sum(G[i])-1) A[i,i]=lamb A_dec = np.array([[Decimal(x) for x in y] for y in A]) #%% ################################ Run Social Learning ################################ theta = np.array([Decimal(0), Decimal(0.2), Decimal(1)]) var = Decimal(1) x = np.linspace(-4, 6, 1000) x = decimal_array(x) dt = (max(x)-min(x))/len(x) #%% np.random.seed(0) mu_0 = np.ones((N,M)) mu_0 = mu_0/np.sum(mu_0, axis = 1)[:, None] mu_0 = decimal_array(mu_0) #%% csi=[] for l in range(N): csi.append(theta[0]+np.sqrt(var)*decimal_array(np.random.randn(N_ITER))) csi=np.array(csi) #%% MU_max_uni= partial_info(mu_0, csi, A_dec, N_ITER, theta, var, M, N, tx='max', self_aware = False) mu_uni=[MU_max_uni[k][0] for k in range(len(MU_max_uni))] #%% N_MC=100 #%% getcontext().prec = 20 ALL_MU = mc_partial_info(N_MC, A_dec, N_ITER, theta, var, M, N, tx='max', self_aware = False) #%% plt.figure(figsize=(5,2.2)) gs = gridspec.GridSpec(1, 2, width_ratios=[ 1, 1]) plt.subplot(gs[:,0]) plt.plot(np.array(mu_uni)[:,0], linewidth='1.5', alpha=1,color = 'C0',label=r'$\theta=1$') plt.plot(np.array(mu_uni)[:,1], linewidth='1.5', alpha=1,color = 'C1',label=r'$\theta=2$') plt.plot(np.array(mu_uni)[:,2], linewidth='1.5', alpha=1,color = 'C2',label=r'$\theta=3$') plt.annotate('%0.2f' % np.array(mu_uni)[:,0][-1], (1.02, np.array(mu_uni)[:,0][-1]),xycoords=('axes fraction', 'data'), color = 'C0') plt.annotate('%0.2f' % np.array(mu_uni)[:,1][-1], (1.02, np.array(mu_uni)[:,1][-1]),xycoords=('axes fraction', 'data'), color = 'C1') plt.annotate('%0.2f' % np.array(mu_uni)[:,2][-1], (1.02, np.array(mu_uni)[:,2][-1]-Decimal(.12)),xycoords=('axes fraction', 'data'), color = 'C2') plt.xlim([0,N_ITER]) plt.ylim([-0.1,1.1]) plt.xlabel(r'$i$', fontsize = 15) plt.ylabel(r'$\mu_{1,i}(\theta)$',fontsize=16) plt.figlegend(ncol=3,fontsize=12, handlelength=1, bbox_to_anchor=[.32,-.31,.5,.5]) plt.tight_layout() plt.title('Uniform initialization', fontsize=13) plt.subplot(gs[:,1]) for j in range(len(ALL_MU)): h0=plt.plot([ALL_MU[j][k][0,0] for k in range(len(ALL_MU[j]))], linewidth='.2', alpha=.7,color = 'C0') plt.xlim([0,N_ITER]) plt.ylim([-0.1,1.1]) plt.ylabel(r'$\mu_{1,i}(\theta)$',fontsize=16) plt.xlabel(r'$i$', fontsize = 15) plt.title('Random initialization', fontsize=13) plt.tight_layout() plt.subplots_adjust(bottom=.35, wspace=.55) plt.savefig(FIG_PATH+'fig5.pdf', bbox_inches='tight')
79aafedae73ecb1d565f55d8e931895847c10430
[ "Markdown", "Python" ]
6
Python
asl-epfl/sl-partial-icassp2020
32fb4d61226724ebc92279219fc82e087fb3f8aa
acae28a75d0bd38aa146a26139b53feb36528df2
refs/heads/master
<repo_name>mukezhz/DataStructureandAlgorithms<file_sep>/README.md # DataStructureandAlgorithms I've tried to solve most of the DSA problems using algorithms that consumes less time and with efficient memory management. Most of the contents are taken from my college curriculum and are programmed accordingly. You can create a pull and contribute to the project and grow this project more. Programming Language : C/C++ IDE used : I've compiled and tested using VS Code but you can try in any IDE like DevC++, Codeblocks,etc. Also don't forget to visit my website (blogs section) where I will be posting the full explannation of codes published here. Wesite : http://adarshaacharya.com.np Happy Coding!<file_sep>/Array/InsertionofArray.c #include<stdio.h> #include<stdlib.h> void insert(int,int,int,int a[]); int main(){ int a[10], len, i,pos,num; printf("Enter the size of array: "); scanf("%d",&len); printf("Enter numbers one by one :\n"); for(i=0;i<len;i++){ scanf("%d",&a[i]); } printf("Enter position to be inserted: "); scanf("%d",&pos); printf("Enter value to be inserted: "); scanf("%d",&num); insert(num,pos,len,a); printf("Array after insertion\n"); for(i=0;i<len;i++) printf("a[%d] = %d\n ",i,a[i]); } void insert(int num, int pos, int len, int a[]){ int i; if(pos>len){ printf("\n\nPosition is more than length of array\n\n"); } else { for(i=len+1;i>=pos;i--) { a[i+1]=a[i]; } a[pos]=num; } }
6b03c5dfe82461f900cd84ce580f95f2bd2a750f
[ "Markdown", "C" ]
2
Markdown
mukezhz/DataStructureandAlgorithms
516a17d4e44256839379105924239a6d3de26342
2a1a7981c7c398e792c96e3b3ee712413a3b8eda
refs/heads/master
<repo_name>nowStackOverflow/allcode_test<file_sep>/_htmlCss/A017 이미지 이용 메뉴.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>navig-apple</title> <style type="text/css"> * { margin:0; padding:0;} ul,ol,li { list-style:none} #header{ width:980px; margin:20px auto 0 auto} .gnb{} .gnb li{ float:left;} .gnb li a{ display:block; width:102px; height:36px; background:url(img/globalnav.png) -102px 0;text-indent:-9999px; overflow:hidden} .gnb li.m1 a{ background-position:0 0} .gnb li a:hover{ background-position:-102px -72px} .gnb li.m1 a:hover{ background-position:0 -72px} .gnb li a:focus{ outline:none;} .gnb li a span{ display:block; height:100%; background:url(img/globalnav_text.png) center 3px; } .gnb li.m1 a span{ background-position:center 3px} .gnb li.m2 a span{ background-position:center -27px} .gnb li.m3 a span{ background-position:center -57px} .gnb li.m4 a span{ background-position:center -87px} .gnb li.m5 a span{ background-position:center -117px} .gnb li.m6 a span{ background-position:center -147px} .gnb li.m7 a span{ background-position:center -177px} .gnb li.m8 a span{ background-position:center -207px} </style> </head> <body> <div id="header"> <div id="nav"> <ul class="gnb"> <li class="m1"><a href="#"><span>home</span></a></li> <li class="m2"><a href="#"><span>store</span></a></li> <li class="m3"><a href="#"><span>mac</span></a></li> <li class="m4"><a href="#"><span>ipod</span></a></li> <li class="m5"><a href="#"><span>iphone</span></a></li> <li class="m6"><a href="#"><span>ipad</span></a></li> <li class="m7"><a href="#"><span>itunes</span></a></li> <li class="m8"><a href="#"><span>support</span></a></li> </ul> </div> </div> </body> </html> ``` <file_sep>/KNOU.java.test/src/knou/first/grade/ArrayTest.java package knou.first.grade; public class ArrayTest { public static void main(String[] args) { int anArray1[] = new int[5]; for(int i = 0; i<anArray1.length; i++) { anArray1[i] = i; } int anArray2[][] = new int[3][2]; System.out.println(anArray2.length); System.out.println(anArray2[0].length); System.out.println(anArray2[1].length); System.out.println(anArray2[2].length); System.out.println(anArray2[3].length); for(int i = 0; i<anArray2.length; i++) { for(int j = 0; j<anArray2[i].length; j++) { anArray2[i][j] = i; } } } } <file_sep>/_java/OOPS - Inheritance Example - Child.md ``` class Parent { String name = "Class A"; public String getName() { return name; } } class Child extends Parent { String address = "Thane, Mumbai"; public String getAddress() { return address; } public static void main(String[] args) { Child obj = new Child(); System.out.println(obj.getName()); System.out.println(obj.getAddress()); } } ``` ##OUTPUT ``` Class A <NAME> ```<file_sep>/_htmlCss/A016 이미지 파일 이용 메뉴.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>nav4</title> <link href='http://fonts.googleapis.com/css?family=Josefin+Sans:400,700' rel='stylesheet' type='text/css'> <style type="text/css"> * { margin:0; padding:0} #wrap{} ul,ol,li { list-style:none} .tab { margin:50px; width:400px;} .tab li{ float:left; background:url(img/tab_right.png) right top no-repeat} .tab li a{ font-size:12px; display:block;/* padding:0 2em;*/ line-height:40px; background:url(img/tab_left.png) no-repeat; text-decoration:none;color:#FFFFFF; text-align:center; font-family:"Josefin Sans", arial,sans-serif} .tab li a.select{ color:#333333 !important;} .tab li.t1 a{ width:80px;} .tab li.t2 a{ width:100px;} .tab li.t3 a{ width:100px;} .tab li a:hover{ color:red; font-weight:bold } .tab li a:active{ color:#FFFF33} .tab li a:focus{ color:#99CC00; outline:none} </style> </head> <body> <ul class="tab"> <li class="t1"><a href="#" class="select" >Event</a></li> <li class="t2"><a href="#" >Products</a></li> <li class="t3"><a href="#" >Notice</a></li> </ul> </body> </html> ``` <file_sep>/KNOU.java.test/src/knou/test/applet/ImageApplet.java package knou.test.applet; import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.ScrollPane; class MyCanvas extends Canvas { Image image; MediaTracker mt; public MyCanvas(Applet a, String f) { mt = new MediaTracker(this); try { image = a.getImage(a.getCodeBase(), f); } catch(Exception e) { } mt.addImage(image, 0); try { mt.waitForAll(); } catch(InterruptedException e) {} setSize(image.getWidth(this), image.getHeight(this)); } public void paint(Graphics g) { if(image != null) { g.drawImage(image, 0, 0, this); } } } public class ImageApplet extends Applet { Canvas canvas; ScrollPane sp; @Override public void init() { setLayout(new BorderLayout()); canvas = new MyCanvas(this, "githubkr.jpg"); sp = new ScrollPane(); sp.add(canvas); add(sp); } } <file_sep>/_jspServlet/A002 understanding-WAS.md ## WAS의 이해 클라이언트 서버 시스템 구조에서 서버 쪽 애플리케이션의 생성과 실행, 소멸을 관리하는 프로그램을 '**애플리케이션 서버(Application Server)**'라 한다. 특히 Java에서 말하는 WAS란, Java EE 기술 사양을 준수하여 만든 서버를 가리킨다. 다른 말로 **Java EE 구현체(Implementation)** 라고도 말한다. 상용되고 있는 제품은 * 티맥스소프트의 [제우스(JEUS)][1] * 오라클의 [웹로직(WebLogic)][2] * IBM의 [웹스피어(WebSphere)][3] * 레드햇의 제이보스 [엔터프라이즈(JBoss Enterprise)][4] 등이 있다. ## 서블릿 컨테이너 Java EE 기술 중에서 서블릿, JSP 등 웹 관련 부분만 구현한 서버도 있는데 이런 서버를 '**서블릿 컨테이너**' 또는 '**웹 컨테이너**'라고 부른다. 아파치 재단의 톰캣, Caucho의 Resin, 오픈 프로젝트 Jetty 등이 있다. 서블릿이나 JSP 프로그래밍을 할 때는 사용하는 제품의 버전에 맞추어 API를 사용해야 한다. 즉, 사용하는 WAS가 어떤 버전의 Java EE 구현체인지 또는 서블릿의 컨테이너인지 확인하여 그 버전에 맞는 API를 사용한다. ## Java EE와 Servlet/JSP 버전, 그리고 구현체 버전 JavaEE | Servlet/JSP | Tomcat | JBoss | WebLogic | JEUS --- | --- | --- | --- | --- | --- JavaEE 6 | Servlet 3.0 JSP 2.2 | 7.0.x | 7.x(all) 6.x(almost) | 12.x | 7.x JavaEE 5 | Servlet 2.5 JSP 2.1 | 6.0.x | 5.x | 10.x | 6.x J2EE 1.4 | Servlet 2.4 JSP 2.0 | 5.5.x | 4.x | 9.x | 5.x J2EE 1.3 | Servlet 2.3 JSP 1.2 | 4.1.x | - | 7.x, 8.x | 4.x J2EE 1.2 | Servlet 2.2 JSP 1.1 | 3.3.x | - | 6.x | 3.x **NOTE:** all(모든 기술 구현함). almost(일부 기술 미구현) 이렇게, 실행되고 있는 서버의 Java EE 버전을 확인한 다음, 섭르릿/JSP 프로그래밍을 하면 된다. 예를 들어 고객사에서 사용하는 WAS가 WebLogic 10.x라면, 서블릿/JSP를 만들 때 Java EE 5 버전에 맞추어 프로그래밍을 한다. 즉 서블릿은 2.5, JSP는 2.1 버전의 API를 사용해서 만들면 된다. [1]: http://kr.tmaxsoft.com/product/productView.do?prod_cd=jeus [2]: https://www.oracle.com/middleware/weblogic/suite.html [3]: ftp://public.dhe.ibm.com/software/kr/resource/websphere_vs_weblogic.pdf [4]: http://www.redhat.com/ko <file_sep>/_java/A005 상속, 인터페이스 사용.md ``` package com.me.interfacetest; // 아무런 내용도 없는 인터페이스를 표시 인터페이스라 한다. // 표시 인터페이스를 구현해 특정 메소드의 실행 가능/불가능 여부를 지정할 경우 사용한다. interface Repairble { } // Repairble 인터페이스가 구현되면 수리가능 그렇치 않으면 불가능 // 모든 유닛의 조상 클래스 Unit을 만든다. class Unit { // final 변수는 반드시 생성시 또는 생성자 메소드를 통해서 초기화를 해줘야 한다. final int MAX_HP; // 최대 HP int hitpoint; // 현재 HP public Unit(int hp) { MAX_HP = hp; } } // Unit 클래스를 상속받아 육상 유닛의 조상 클래스 GroundUnit 클래스를 만든다. class GroundUnit extends Unit { public GroundUnit(int hp) { super(hp); // 부모(Unit) 클래스의 생성자 Unit(int hp)을 호출한다. } } // Unit 클래스를 상속받아 공중 유닛의 조상 클래스 AirUnit 클래스를 만든다. class AirUnit extends Unit { public AirUnit(int hp) { super(hp); // 부모(Unit) 클래스의 생성자 Unit(int hp)을 호출한다. } } // GroundUnit 클래스를 상속받아 Tank, Marine, SCV 클래스를 만든다. class Tank extends GroundUnit implements Repairble { // 수리 가능 public Tank() { super(200); // 부모(Unit) 클래스의 생성자 GroundUnit(int hp)을 호출한다. hitpoint = MAX_HP; } @Override public String toString() { return "Tank [MAX_HP=" + MAX_HP + ", hitpoint=" + hitpoint + "]"; } } class Marine extends GroundUnit { public Marine() { super(100); hitpoint = MAX_HP; } @Override public String toString() { return "Marine [MAX_HP=" + MAX_HP + ", hitpoint=" + hitpoint + "]"; } } class SCV extends GroundUnit implements Repairble { // 수리 가능 public SCV() { super(130); hitpoint = MAX_HP; } // 수리하는 메소드는 유닛별로 따로 만들지 않고 수리 기능을 하는 유닛의 객체인 이곳에만 만든다. // Repairble 표시 인터페이스를 구현한 유닛만 수리가 가능하게 수리 메소드를 만든다. // ★★★★★ 메소드의 인수로 인터페이스 변수를 사용한다. ★★★★★ void repair(Repairble r) { // 수리 기능 구현 // Repairble 인터페이스는 아무런 내용이 없으므로 구현될 내용이 있는 클래스로 형변환 해야한다. if(r instanceof Unit) { // 안전하게 형변환 가능한가? Unit u = (Unit)r; // 형변환 while(u.hitpoint != u.MAX_HP) { u.hitpoint++; } System.out.println(u + "를(을) 수리합니다."); } } @Override public String toString() { return "SCV [MAX_HP=" + MAX_HP + ", hitpoint=" + hitpoint + "]"; } } // AirUnit 클래스를 상속받아 Dropship 클래스를 만든다. class Dropship extends AirUnit implements Repairble { // 수리 가능 public Dropship() { super(150); hitpoint = MAX_HP; } @Override public String toString() { return "Dropship [MAX_HP=" + MAX_HP + ", hitpoint=" + hitpoint + "]"; } } public class InterfaceTest2 { public static void main(String[] args) { Tank tank = new Tank(); System.out.println(tank); Marine marine = new Marine(); System.out.println(marine); SCV scv = new SCV(); System.out.println(scv); Dropship dropship = new Dropship(); System.out.println(dropship); scv.repair(tank); scv.repair(scv); scv.repair(dropship); // scv.repair(marine); // 에러,Marine 클래스는 Repairble 인터페이스를 구현하지 않아서 } } ``` <file_sep>/_java/EXCEPTION HANDLING - Create Your Own Exception.md ``` public class MyOwnException { public static void main(String[] a) { try { MyOwnException.myTest(null); } catch (MyAppException mae) { System.out.println("Inside catch block: " + mae.getMessage()); } } static void myTest(String str) throws MyAppException { if (str == null) { throw new MyAppException("String val is null"); } } } class MyAppException extends Exception { private String message = null; public MyAppException() { super(); } public MyAppException(String message) { super(message); this.message = message; } public MyAppException(Throwable cause) { super(cause); } @Override public String toString() { return message; } @Override public String getMessage() { return message; } } ``` ##OUTPUT ``` Inside catch block: String val is null ```<file_sep>/_java/COLLECTION - TreeMap Class.md ``` import java.util.Map; import java.util.TreeMap; public class TreeMapTest { public static void main(String[] args) { //TreeMap is sorted TreeMap<Integer,String> hm=new TreeMap<Integer,String>(); hm.put(100,"java"); hm.put(102,"android"); hm.put(101,"php"); hm.put(103,"c++"); hm.put(104, "html"); System.out.println(hm); } } ``` ##OUTPUT ``` {100=java, 101=php, 102=android, 103=c++, 104=html} ```<file_sep>/_htmlCss/A019 이미지 배열, 영화 페이지.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>imgList-position</title> <style type="text/css"> * { margin:0; padding:0 } body { background-color:#666666} ul,ol,li { list-style:none } img{ border:none;} .img_list { width:580px; margin:20px auto} .img_list li{ float:left; margin:10px; position:relative;} .img_list li a{ display:block; height:179px; width:123px;} .img_list li a:hover { outline:3px solid #99C} .img_list li .span_ab{ display:block; position:absolute; left:0; top:0; z-index:1; width:123px; height:179px; text-indent:-9999px; overflow:hidden;} .img_list li .rank{ width:50px; height:70px; text-indent:0} .img_list li .hot{left:70px; top:-3px; width:56px; height:56px;background:url(img/ico_hot.png);} .img_list li .over{text-align:center; line-height:179px; color:#FFFFFF; z-index:2} .img_list li .over:hover{ background:url(img/over.png) } .img_list li .btn{ background:url(img/img_video_play.png) center center no-repeat; } </style> </head> <body> <ul class="img_list"> <li><a href="#"><img src="img/m1.jpg" alt="인사이드아웃" /> <span class="rank span_ab"><img src="img/ico_rank1.png" alt="1" /></span></a></li> <li><a href="#"><img src="img/m2.jpg" alt="" /> <span class="rank span_ab "><img src="img/ico_rank2.png" alt="2" /></span></a></li> <li><a href="#"><img src="img/m3.jpg" alt="" /> <span class="rank span_ab"><img src="img/ico_rank3.png" alt="3" /></span></a></li> <li><a href="#"><img src="img/m4.jpg" alt="" /> <span class="rank span_ab"><img src="img/ico_rank4.png" alt="4" /></span></a></li> <li><a href="#"><img src="img/m5.jpg" alt="" /><span class="hot span_ab">hot</span></a></li> <li><a href="#"><img src="img/m6.jpg" alt="" /><span class="hot span_ab">hot</span></a></li> <li><a href="#"><img src="img/m7.jpg" alt="" /><span class="hot span_ab">hot</span></a></li> <li><a href="#"><img src="img/m8.jpg" alt="" /><span class="hot span_ab">hot</span></a></li> <li><a href="#"><img src="img/m5.jpg" alt="" /><span class="over span_ab"></span><span class="btn span_ab">play</span></a></li> <li><a href="#"><img src="img/m6.jpg" alt="" /><span class="over span_ab"></span><span class="btn span_ab">play</span></a></li> <li><a href="#"><img src="img/m7.jpg" alt="" /><span class="over span_ab"></span><span class="btn span_ab">play</span></a></li> <li><a href="#"><img src="img/m8.jpg" alt="" /><span class="over span_ab"></span><span class="btn span_ab">play</span></a></li> </ul> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>imgList-position</title> <style type="text/css"> * { margin:0; padding:0 } body { background-color:#666666} ul,ol,li { list-style:none } img{ border:none;} .img_list { width:580px; margin:20px auto} .img_list li{ float:left; margin:10px; position:relative;} .img_list li a{ display:block; height:179px; width:123px;} .img_list li a:hover { outline:3px solid #99C} .img_list li .span_ab{ display:block; position:absolute; left:0; top:0; z-index:1; width:123px; height:179px; text-indent:-9999px; overflow:hidden;} .img_list li .rank{ width:50px; height:70px; text-indent:0} .img_list li .hot{left:70px; top:-3px; width:56px; height:56px;background:url(img/ico_hot.png);} .img_list li .over{text-align:center; line-height:179px; color:#FFFFFF; z-index:2} .img_list li .over:hover{ background:url(img/over.png) } .img_list li .btn{ background:url(img/img_video_play.png) center center no-repeat; } </style> </head> <body> <ul class="img_list"> <li><a href="#"><img src="img/m1.jpg" alt="인사이드아웃" /> <span class="rank span_ab"><img src="img/ico_rank1.png" alt="1" /></span></a></li> <li><a href="#"><img src="img/m2.jpg" alt="" /> <span class="rank span_ab "><img src="img/ico_rank2.png" alt="2" /></span></a></li> <li><a href="#"><img src="img/m3.jpg" alt="" /> <span class="rank span_ab"><img src="img/ico_rank3.png" alt="3" /></span></a></li> <li><a href="#"><img src="img/m4.jpg" alt="" /> <span class="rank span_ab"><img src="img/ico_rank4.png" alt="4" /></span></a></li> <li><a href="#"><img src="img/m5.jpg" alt="" /><span class="hot span_ab">hot</span></a></li> <li><a href="#"><img src="img/m6.jpg" alt="" /><span class="hot span_ab">hot</span></a></li> <li><a href="#"><img src="img/m7.jpg" alt="" /><span class="hot span_ab">hot</span></a></li> <li><a href="#"><img src="img/m8.jpg" alt="" /><span class="hot span_ab">hot</span></a></li> <li><a href="#"><img src="img/m5.jpg" alt="" /><span class="over span_ab"></span><span class="btn span_ab">play</span></a></li> <li><a href="#"><img src="img/m6.jpg" alt="" /><span class="over span_ab"></span><span class="btn span_ab">play</span></a></li> <li><a href="#"><img src="img/m7.jpg" alt="" /><span class="over span_ab"></span><span class="btn span_ab">play</span></a></li> <li><a href="#"><img src="img/m8.jpg" alt="" /><span class="over span_ab"></span><span class="btn span_ab">play</span></a></li> </ul> </body> </html> ``` <file_sep>/_java/PATTERN - Number Pattern 10.md ``` import java.util.*; class Pattern { public static void main(String[] args) { int i, j, k=1, l, n; Scanner sc = new Scanner(System.in); System.out.println("Enter the number of levels of pattern"); n = sc.nextInt(); System.out.println("\nPattern is : \n"); for(i = 1; i <= n; i++) { l = i; for (j = 1; j <= k ; j++ ) { if(j >= i + 1) { System.out.print(--l); } else { System.out.print(j); } } k = k + 2; System.out.println(" "); } } } ``` ##OUTPUT ``` Enter the number of levels of pattern 7 Pattern is : 1 121 12321 1234321 123454321 12345654321 1234567654321 ```<file_sep>/_htmlCss/A012 기본 레이아웃-float이해.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>layout2</title> </head> <body> <div id="headerWrap"> <div id="header"> <h1 class="logo">LOGO</h1> <ul class="t_menu"> <li><a href="#">LOGIN</a></li> <li><a href="#">회원가입</a></li> <li><a href="#">SITE MAP</a></li> <li><a href="#">고객지원</a></li> </ul> </div><!--//header--> <div id="nav"> <h2>메뉴목록</h2> <ul class="gnb"> <li><a href="#">MENU1</a></li> <li><a href="#">MENU2</a></li> <li><a href="#">MENU3</a></li> <li><a href="#">MENU4</a></li> <li><a href="#">MENU5</a></li> </ul><!--//gnb--> </div><!--//nav--> </div><!--//headerWrap--> <div id="mainContents"> <div class="slider"> slide </div><!--//slider--> <div class="con_box"> <div class="box">box1</div> <div class="box">box2</div> <div class="box">box3</div> </div><!--//con_box--> </div><!--//mainContents--> <div id="footerWrap"> <div id="footer"> <address>주소</address> <p>copyright</p> </div> </div><!--//footerWrap--> </body> </html> ``` <file_sep>/_htmlCss/A003 웹 무료호스팅, 접속기(알드라이브).md ``` 블록 안에 블록 넣기 2. 글자속성 (외우기★) (1) 글자 폰트 ( font-family:"맑은 고딕"; ) <!-- font-family:"맑은 고딕", "arial", "돋움"; (첫번째 폰트 없으면 뒤에 폰트 여러개 가능, 하나만 표기하는게 좋은방식, 영어는 더블 쿼테이션 생략가능(특수기호 포함은 안됨))--> (2) 글자 크기 ( font-size:11px; ) (3) 글자 굵기 ( font-weight:bold;, font-weight:normal; ) <!-- 안쓰면 normal 상태 --> (4) 줄간 ( line-height:30px; ) <!-- 글자사이즈 포함 밑에 간격인데 font-size:20px 일때 줄간 15px은 적용이 안됨. 글 위, 아래 간격까지 포함해서 글 밑 5px 간격 주고 싶다면 30px 줘야함. --> (5) 자간 ( letter-spacing:2px; ) <!-- 마이너스 간격도 있어서 겹치기 가능 --> (6) 글자 색 ( color:blue; ) - blue, red, white, gray, silver, black, orange, olive, navy, lime, fuchsia, green, yellow (7) 정렬 ( text-align:left/center/right; ) <!-- default값 : left --> (8) 글자 들여쓰기 ( text-indent:30px; ) <!-- 많이 쓰진 않음, padding 쓰는게 더 나음 --> (9) 글자 꾸미기(밑줄 등등) ( text-decoration:underline/none ) <!-- 밑줄이 쓸대없이 들어 갈 경우 normal로 지움 --> <body> <div id="box"><a href="http://www.naver.com" target="_black">안녕하세요</a></div> </body> <!-- a href="링크 주소" --> <!-- target="_blank" 새창으로 띄우기 --> <div id="box"> <a href="test.html">테스트</a> </div> <!-- 이렇게 html문서도 링크 가능 --> <a href="http://외부홈페이지주소"> 외부 홈페이지 연결시 http:// 까지 써줌. <a href="sub.html"> 내부 홈페이지 파일(html) 연결시 파일명만 써주면됨. 같은 폴더일 경우. 다른 폴더일 경우 <a href="폴더명/sub.html"> href="폴더명/html파일명.html" href="../html파일명.html" 현재 폴더를 한번 나가서 링크 ("../../../html파일명.html" 여러번 나갈 수 있지만 보기안좋음) 위치만 연결 시켜 준 것, 옮길 때 이미지나 파일들의 루트 생각해서 가져가야 함 홈페이지 제작시 무조건 폴더를 하나 만들어 놓고 시작...-> root 폴더 (링크 꼬이면 복잡해짐, 한글x, 특문x, 숫자시작x, 띄어쓰기x) href = Hyperlink Reference html 기본 셋팅 1. a 링크를 걸면 자동으로 글자 색이 파란색 처리하고 밑줄 처리한다. 기본 세팅정보 없애기 -> 코딩의 초기화 <!-- a 스타일을 바꿔 줄 수 있음. <style> a { color:orange; text-decoration:none; } #box { ~~~ } </style> --> 웹호스팅(홈페이지를 인터넷에 유지하는 것) 인터넷 공간 확보(웹호스팅 -> N드라이브라 생각하면됨) www.dothome.co.kr -> 회원가입 -> 웹호스팅 -> 무료 호스팅 신청(무료로 할당) 굳이 dothome이 아니여도 좋습니다. 웹호스팅 업체는 많아요~ -사진생략 ``` <file_sep>/_java/A035 서적관리, 점수관리.md ``` package com.me.book; import java.util.Date; public class BookTest2 { public static void main(String[] args) { // 책을 저장할 수 있는 책꽃이 객체 생성 BookList2 booklist = new BookList2(); // 책꽃이에 넣을 책 객체를 만든다. BookVO book1 = new BookVO("JAVA", "홍길동", "SBS", new Date(2012,5,21), 35000); BookVO book2 = new BookVO("JSP", "홍길자", "MBC", new Date(2013,11,4), 32500); BookVO book3 = new BookVO("SPRING", "홍길숙", "KBS", new Date(2010,7,15), 43000); BookVO book4 = new BookVO("HTML", "홍길용", "OBS", new Date(2011,3,9), 25000); BookVO book5 = new BookVO("jQUERY", "홍길녀", "CNN", new Date(2012,7,8), 31000); BookVO book6 = new BookVO("JAVASCRIPT", "홍길도", "NBC", new Date(2008,1,20), 28000); // 책꽃이에 책을 넣는다. booklist.setBooklist(book1); booklist.setBooklist(book2); booklist.setBooklist(book3); booklist.setBooklist(book4); booklist.setBooklist(book5); booklist.setBooklist(book6); System.out.println(booklist); } } package com.me.book; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Arrays; // 여러권의 책(BookVO class) 정보를 기억할 클래스 public class BookList2 { // 멤버 변수 정의 private static int sum; // 책 가격의 합계를 계산할 변수 // 여러권의 책 정보(BookVO 클래스)를 저장할 ArrayList를 선언한다. ArrayList<BookVO> booklist = new ArrayList<BookVO>(); // getter & setter 메소드 정의 public ArrayList<BookVO> getBooklist() { return booklist; } public void setBooklist(BookVO book) { this.booklist.add(book); sum += book.getPrice(); } // toString() 메소드 override @Override public String toString() { DecimalFormat df = new DecimalFormat("#,##0원"); String str = ""; if(booklist.size() != 0) { str += "===============================================\n"; str += " 도서명 저자 출판사 출판일 가격\n"; str += "===============================================\n"; int total = 0; for(BookVO book : booklist) { if(book == null) { break; } str += book + "\n"; total += book.getPrice(); } str += "===============================================\n"; str += " 가격합계 : " + df.format(sum) + "\n"; str += " 가격합계 : " + df.format(total) + "\n"; str += "===============================================\n"; } else { str += "책 엄거덩"; } return str; } } package com.me.book; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; // 책 1권의 정보를 기억할 클래스 public class BookVO { // 멤버 변수 정의 private String title; // 도서명 private String author; // 저자 private String publisher; // 출판사 private Date date; // 출판일 private int price; // 가격 // 생성자 메소드 정의 public BookVO() { } public BookVO(String title, String author, String publisher, Date date, int price) { this.title = title; this.author = author; this.publisher = publisher; // 넘겨받은 날짜(date)의 년도에서 1900을 빼서 다시 날짜(date)에 넣어준다. date.setYear(date.getYear() - 1900); // 넘겨받은 날짜(date)의 월에서 1을 빼서 다시 날짜(date)에 넣어준다. date.setMonth(date.getMonth() - 1); this.date = date; this.price = price; } // getter & setter 메소드 정의 public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } // toString() 메소드 override @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd."); NumberFormat nf = NumberFormat.getCurrencyInstance(); // 화폐기호, 천단위 "," // NumberFormat nf = NumberFormat.getPercentInstance(); // 백분율, 천단위 "," DecimalFormat df = new DecimalFormat("#,##0'EA'"); return String.format("%-10s %s %s %s %s %s", title, author, publisher, sdf.format(date), nf.format(price), df.format(price)); } } ``` ``` package com.me.score; import java.util.ArrayList; public class ScoreList { // 멤버 변수 ArrayList<ScoreVO> scorelist = new ArrayList<ScoreVO>(); // getter & setter 메소드 public ArrayList<ScoreVO> getScorelist() { return scorelist; } public void setScorelist(ScoreVO score) { this.scorelist.add(score); } // toString() 메소드 override @Override public String toString() { String str = ""; str += "==============================================\n"; str += " 번호 이름 java jsp spring 총점 평균 석차\n"; str += "==============================================\n"; int javatot, jsptot, springtot; javatot = jsptot = springtot = 0; if(scorelist.size() != 0) { // 석차를 계산한다. for(int i=0 ; i<scorelist.size()-1 ; i++) { for(int j=i+1 ; j<scorelist.size() ; j++) { if(scorelist.get(i).getTotal() < scorelist.get(j).getTotal()) { scorelist.get(i).setRank(scorelist.get(i).getRank() + 1); } else if(scorelist.get(i).getTotal() > scorelist.get(j).getTotal()) { scorelist.get(j).setRank(scorelist.get(j).getRank() + 1); } } } for(ScoreVO score : scorelist) { str += score + "\n"; javatot += score.getJava(); jsptot += score.getJsp(); springtot += score.getSpring(); } } else { str += "학생 정보 없음\n"; } str += "==============================================\n"; if(scorelist.size() != 0) { str += String.format(" %3d %3d %3d", javatot, jsptot, springtot); } return str; } } package com.me.score; public class ScoreTest { public static void main(String[] args) { ScoreList scoreList = new ScoreList(); ScoreVO score1 = new ScoreVO("홍길동", 100, 100, 100); ScoreVO score2 = new ScoreVO("임꺽정", 70, 60, 81); ScoreVO score3 = new ScoreVO("장길산", 81, 77, 55); scoreList.setScorelist(score1); scoreList.setScorelist(score2); scoreList.setScorelist(score3); System.out.println(scoreList); } } package com.me.score; public class ScoreVO { // 멤버 변수 private static int count; // 번호를 자동으로 증가 할 정적 변수 private int no; // 번호(자동증가) private String name; // 이름 private int java; // java 점수 private int jsp; // jsp 점수 private int spring; // spring 점수 private int total; // 총점 private double average; // 평균 private int rank; // 석차 // 생성자 메소드 public ScoreVO() { } // 기본 생성자 메소드 // 이름과 각 과목의 점수를 넘겨받아 총점, 평균을 계산하는 생성자 메소드 public ScoreVO(String name, int java, int jsp, int spring) { no = ++count; // 번호 자동 증가 this.name = name; this.java = java; this.jsp = jsp; this.spring = spring; total = java + jsp + spring; // 총점 average = total / 3.; // 평균 rank = 1; // 석차를 기억할 변수는 초기치가 무조건 1이다. } // getter & setter 메소드 public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getJava() { return java; } public void setJava(int java) { this.java = java; } public int getJsp() { return jsp; } public void setJsp(int jsp) { this.jsp = jsp; } public int getSpring() { return spring; } public void setSpring(int spring) { this.spring = spring; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public double getAverage() { return average; } public void setAverage(double average) { this.average = average; } public int getRank() { return rank; } public void setRank(int rank) { this.rank = rank; } // toString() 메소드 override @Override public String toString() { return String.format("%d %s %3d %3d %3d %3d %5.1f %d", no, name, java, jsp, spring, total, average, rank); } } ``` <file_sep>/_java/PATTERN - Number Pattern 2.md ``` ------------------ 54321 5432 543 54 5 ------------------- public class NumberPat2 { public static void main(String arg[]) { for (int i = 1; i <= 5; i++) { for (int j = 5; j >= i; j--) { System.out.print(j); } System.out.println(); } } } ``` ##OUTPUT ``` 54321 5432 543 54 5 ```<file_sep>/_java/COLLECTION - Basics Of TreeSet.md ``` import java.util.TreeSet; public class TreeSetBasics { public static void main(String[] args) { TreeSet<Integer> ts=new TreeSet<Integer>(); ts.add(12); ts.add(11); ts.add(14); ts.add(15); ts.add(10); ts.add(16); ts.add(17); System.out.println(ts); // getting the ceiling value for 13 System.out.println("ceiling value :"+ts.ceiling(13)); //getting the floor value for 13 System.out.println("floor value :"+ts.floor(13)); //first element System.out.println("first element :"+ts.first()); //last element System.out.println("last element :"+ts.last()); System.out.println("poll first element :"+ts.pollFirst()); System.out.println("poll last element :"+ts.pollLast()); System.out.println("TreeSet after polling :"+ts); //the greatest element less than 12 System.out.println("lower element of 12 :"+ts.lower(12)); //the least element greater than 12 System.out.println("higher element of 12 :"+ts.higher(12)); System.out.println("Is 12 is present "+ts.contains(12)); //TreeSet to Array Object [] a=ts.toArray(); System.out.print("Array :"); for (Object object : a) { System.out.print(object+" "); } System.out.println(); // descending Set System.out.print("descending Set"+ts.descendingSet()); System.out.println(); //remove from TreeSet ts.remove(11); //Size of TreeSet System.out.println("size of TreeSet after removal of 11 :"+ts.size()); //clear whole TreeSet ts.clear(); System.out.println(ts+" "+"Is TreeSet is empty :"+ts.isEmpty()); } } ``` ##OUTPUT ``` [10, 11, 12, 14, 15, 16, 17] ceiling value :14 floor value :12 first element :10 last element :17 poll first element :10 poll last element :17 TreeSet after polling :[11, 12, 14, 15, 16] lower element of 12 :11 higher element of 12 :14 Is 12 is present true Array :11 12 14 15 16 descending Set[16, 15, 14, 12, 11] size of TreeSet after removal of 11 :4 [] Is TreeSet is empty :true ```<file_sep>/_cpp/구조체(사용자 정의 자료형, struct) 선언과 사용.md ``` #include <cstdio> #include <iostream> #include <iomanip> #include <string> using namespace std; // 구조체(사용자 정의 자료형) 형식 // struct 구조체이름 { // 구조체 멤버 변수 정의; // ...; // }; struct Sungjuk { // 구조체 선언 // 구조체 멤버의 기본 접근 권한은 public 이다. int no; // char name[20]; char *name; // string name; int java, jsp, spring, total; double average; }; // ";" 빼먹지 말자 int main() { // 구조체 변수 선언 // [struct] 구조체이름 구조체변수명; struct Sungjuk s; // 구조체 변수 선언 // 구조체 변수를 통해 구조체 멤버에 접근려면 구조체 변수명에 "."을 찍어서 접근한다. s.no = 100; // s.name = "홍길동"; // 문자 배열로 만든 멤버는 그냥 넣으면 에러가 난다. // strcpy(a, b) : b의 문자열을 a로 복사한다. 보안상의 이유로 경고가 뜨면 strcpy_s(a, b)로 바꿔 사용한다. // strcpy_s(s.name, "홍길동"); // 문자 배열로 만든 멤버에는 strcpy(a, b) 함수를 사용해 값을 넣어야 했었다. s.name = "홍길동"; // 포인터나 string 클래스를 이용해 만든 멤버는 그냥 넣으면 에러 안난다. s.java = 100; s.jsp = 95; s.spring = 74; s.total = s.java + s.jsp + s.spring; s.average = s.total / 3.; cout << "번호 : " << s.no << endl; cout << "이름 : " << s.name << endl; cout << "java 점수 : " << s.java << endl; cout << "jsp 점수 : " << s.jsp << endl; cout << "spring 점수 : " << s.spring << endl; // 구조체 포인터 변수를 통해 구조체 멤버에 접근려면 구조체 포인터 변수명에 "->"을 찍어서 접근한다. struct Sungjuk *p; // 구조체 포인터 변수 선언 p = &s; cout << "총점 : " << p->total << endl; cout << "평균 : " << p->average << endl; } ``` ``` #include <cstdio> #include <iostream> #include <iomanip> #include <string> using namespace std; // 클래스(사용자 정의 자료형) 형식, 클래스는 구조체(데이터)에 데이터를 처리할 수 있는 함수가 추가된 형태이다. // class 클래스이름 { // 접근 권한 지정자: // 클래스 멤버 변수 정의; // ...; // 클래스 멤버 함수 정의; // ...; // }; // 접근 권한 지정자 // private : 현재 클래스 내부에서만 사용 가능하고 외부에서는 접근이 불가능하다. // protected : 현재 클래스와 현재 클래스를 상속받은 자식 클래스에서만 접근이 가능하고 다른 클래스에서는 접근이 불가능하다. // public : 언제 어디서나 자유롭게 접근이 가능하다. // 일반적으로 멤버 변수는 private으로 멤버 함수는 public으로 선언한다. class Sungjuk { // 클래스 선언 // 클래스 멤버의 기본 접근 권한은 private 이다. private: int no; string name; int java, jsp, spring, total; double average; // 생성자 함수 : 클래스 객체가 생성되는 순간 자동으로 실행되는 함수를 말한다. // 생성자 함수는 리턴 타입을 가지지 않고 생성자 함수의 이름은 클래스 이름과 같게 만든다. // 클래스의 멤버 변수에 초기값을 할당하려 할 경우 사용하고 만들지 않으면 컴파일러가 아무일도 하지 않는 기본 생성자 함수를 만든다. // C++은 같은 이름의 함수가 여러개 나올수 있다 이 경우 괄호 안의 인수의 개수, 개수도 같다면 인수의 형태로 구분한다. => 함수 오버로딩 public: // 기본 생성자 함수 Sungjuk() { cout << "객체가 생성되었습니다." << endl; } // 멤버에 값을 전달하는 생성자 함수 Sungjuk(int no, string name, int java, int jsp, int spring) { // 멤버 변수와 지역 변수의 이름이 같을 경우 지역 변수에 더 높은 우선순위가 부여된다. 따라서 생성자 함수 내부에서 멤버 변수에 접근을 해야 할 // 경우 현재 클래스 자신을 의미하는 this 포인터를 사용해 접근해야 한다. this->no = no; this->name = name; this->java = java; this->jsp = jsp; this->spring = spring; // 연산이 필요하면 필요한 연산을 한다. total = java + jsp + spring; average = total / 3.; cout << "총점 : " << total << endl; cout << "평균 : " << average << endl; } // 소멸자(파괴자) 함수 // ~Sungjuk() { // cout << "객체가 소멸되었습니다." << endl; // } }; // ";" 빼먹지 말자 int main() { class Sungjuk s1; // 클래스 변수(인스턴스, 객체) 선언, 기본 생성자 함수(Sungjuk())가 실행된다. // Sungjuk(int no, string name, int java, int jsp, int spring) 생성자 함수를 이용해 객체가 생성된다. class Sungjuk s2(1, "홍길동", 100, 95, 77); } ``` <file_sep>/_java/PATTERN - Spiral Number Pattern.md ``` import java.io.*; class SpiralNumberPattern { public static void main(String args[]) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter no. for spiral pattern : "); int INPUT = Integer.parseInt(br.readLine()); final int LEFT = 1; final int DOWN = 2; final int RIGHT = 3; final int UP = 4; int[][] patt = new int[INPUT][INPUT]; //initial position int x = 0; int y = 0; //initial direction int Direction = LEFT; //Master Loop for (int i = 0; i < INPUT * INPUT; i++) { int temp = i + 1; //Checking boundaries if (y > INPUT - 1) { Direction = DOWN; x++; y--; i--; continue; } else if (x > INPUT - 1) { Direction = RIGHT; x--; y--; i--; continue; } else if (y < 0) { Direction = UP; y++; x--; i--; continue; }else if (x < 0) { Direction = LEFT; y++; x++; i--; continue; } if (patt[x][y] == 0) { patt[x][y] = temp; } else { if (Direction == LEFT) { Direction = DOWN; y--; } else if (Direction == DOWN) { Direction = RIGHT; x--; } else if (Direction == RIGHT) { Direction = UP; y++; } else { Direction = LEFT; x++; } i--; } switch (Direction) { case LEFT: y++; break; case DOWN: x++; break; case RIGHT: y--; break; case UP: x--; break; } } // Print Grid Array for (int i = 0; i < INPUT; i++) { for (int k = 0; k < INPUT; k++) if (patt[i][k] <= 9) System.out.print(" "+patt[i][k] + " "); else System.out.print(patt[i][k] + " "); System.out.println(); } } } ``` ##OUTPUT ``` Enter no. for spiral pattern : 7 1 2 3 4 5 6 7 24 25 26 27 28 29 8 23 40 41 42 43 30 9 22 39 48 49 44 31 10 21 38 47 46 45 32 11 20 37 36 35 34 33 12 19 18 17 16 15 14 13 ```<file_sep>/_java/PATTERN - Number Pattern 6.md ``` public class NumberPat6 { public static void main(String arg[]) { for(int i=1;i<=5;i++) { for(int j=1;j<=i;j++) { System.out.print(i); } System.out.println(); } } } ``` ##OUTPUT ``` 1 22 333 4444 55555 ```<file_sep>/_java/A007 Thread, AWT, SWING 윈도우창.md ``` package com.me.threadtest3; // PrintThread 클래스와 CalcThread 에서 공유 영역으로 사용할 클래스 public class ShareArea { double result; // 연산 결과 boolean ready; // 연산 완료 여부 } ------------------ package com.me.threadtest3; public class ThreadTest3 { public static void main(String[] args) { // 공유 영역으로 사용할 클래스(ShareArea)의 객체를 만든다. ShareArea shareArea = new ShareArea(); // ======================================= // 공유 영역을 공유할 클래스(PrintThread, CalcThread)의 객체를 만든다. // PrintThread printThread = new PrintThread(); // CalcThread calcThread = new CalcThread(); // 공유 영역을 사용할 객체의 멤버에 공유 영역의 주소를 직접 넣어준다. // 아래의 두 줄의 식은 같은 객체의 주소를 기억한다. // printThread.shareArea = shareArea; // calcThread.shareArea = shareArea; // 이 방식은 멤버가 private 으로 선언되어 있으면 사용할 수 없다. // ======================================= // 공유 영역의 주소를 생성자 메소드를 통해 전달해 넣어준다. // PrintThread printThread = new PrintThread(shareArea); // CalcThread calcThread = new CalcThread(shareArea); // 이 방식은 공유 영역의 주소를 전달받는 생성자 메소드가 있어야 한다. // ======================================= // 공유 영역의 주소를 setter 메소드를 통해 넣어준다. PrintThread printThread = new PrintThread(); CalcThread calcThread = new CalcThread(); printThread.setShareArea(shareArea); calcThread.setShareArea(shareArea); // ======================================= // 공유 영역 확인 테스트 // printThread.shareArea.result = 100; // System.out.println(calcThread.shareArea.result); calcThread.start(); printThread.start(); } } ------------------ package com.me.threadtest3; // 무한 급수를 이용한 원주율을 계산하는 스레드, 시간이 많이 걸리는 스레드 public class CalcThread extends Thread{ // 공유 영역으로 사용할 클래스 변수를 멤버로 선언한다. ShareArea shareArea; public CalcThread() { } // shareArea에 초기화 하는 생성자 메소드를 만든다. public CalcThread(ShareArea shareArea) { this.shareArea = shareArea; } public ShareArea getShareArea() { return shareArea; } // shareArea를 초기화 하는 setter 메소드를 만든다. public void setShareArea(ShareArea shareArea) { this.shareArea = shareArea; } @Override public void run() { double total = 0.0; long start = System.currentTimeMillis(); // 시작시간 ( 1/1000초 단위 ) for(int i=1; i<1000000000; i+=2){ if(i / 2 % 2 == 0){ total += 1.0 / i; } else { total += -1.0 / i; } } long end = System.currentTimeMillis(); // 종료시간 System.out.println(); System.out.println(end - start); // 경과시간 // System.out.println("원주율 : " + total * 4); shareArea.result = total * 4; // 계산 결과를 공유 영역에 넣는다. // shareArea.ready = true; // 계산 완료를 공유 영역에 넣는다. synchronized (shareArea) { // 동기화 블록 shareArea.notify(); // wait()로 잠시 멈춘 스레드 1개를 깨운다. // shareArea.notifyAll(); // wait()로 잠시 멈춘 스레드를 모두 깨운다. } } } ------------------- package com.me.threadtest3; // 결과를 출력하는 클래스, 시간이 적게 걸리는 스레드 public class PrintThread extends Thread{ // 공유 영역으로 사용할 클래스 변수를 멤버로 선언한다. ShareArea shareArea; public PrintThread() { } // shareArea에 초기화 하는 생성자 메소드를 만든다. public PrintThread(ShareArea shareArea) { this.shareArea = shareArea; } public ShareArea getShareArea() { return shareArea; } // shareArea를 초기화 하는 setter 메소드를 만든다. public void setShareArea(ShareArea shareArea) { this.shareArea = shareArea; } // Thread를 상속받을 경우 run메소드를 상속받는다. @Override public void run() { System.out.print("계산중."); // CalcThread 클래스에서 계산이 완료되지 않았으면 "."을 출력한다. // 여기부터 // while(!shareArea.ready){ // System.out.print("."); // try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } // } // 여기까지 쓸데없이 작업 전환이 많이 이루어진다. synchronized (shareArea) { // 동기화 블록 // 동기화 블록의 괄호 안에는 공유 영역의 이름을 적어준다. // 동기화라는 의미는 순서를 정한다는 의미로 동기화 블록은 블록 내부의 스레드가 실행 중 일때 // 다른 스레드가 실행되는 것을 막아준다. try { // 스레드를 깨우기 전까지 잠시 멈춘다. shareArea.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("PrintThread에서 원주율 출력 : " + shareArea.result); } } ``` ``` package com.me.window; import java.awt.Color; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; // Frame 또는 JFrame 클래스의 객체를 생성해 윈도우 만들기 public class WindowTest1 { public static void main(String[] args) { // Frame win = new Frame(); // 제목 없는 윈도우 생성 Frame win = new Frame("윈도우 제목"); // 제목 있는 윈도우 생성 win.setTitle("setTitle"); // 윈도우 제목 변경 // win.setSize(300, 500); // 윈도우 크기 변경 // win.setLocation(800, 200); // 윈도우 위치 변경 win.setBounds(800, 200, 300, 500); // 윈도우 위치와 크기 변경 // win.setBackground(Color.BLUE); // 윈도우 배경색 변경 // 웹에서 사용하는 #A566FF 은 2자리씩 끊어서 16진수 -> 10진수로 변환해서 사용한다. // Color 클래스를 이용해 색상 지정, 생성자에 RGB 순서로 0~255 사이의 숫자로 색을 만든다. // Color color = new Color(165,102,255); // win.setBackground(color); win.setBackground(new Color(165,102,255)); win.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); // 프로그램 강제종료 } }); win.setVisible(true); // 윈도우를 화면에 표시한다. } // main() } // class ``` ``` package com.me.window; import java.awt.Color; import java.awt.Container; import javax.swing.JFrame; // JFrame 클래스의 객체를 생성해 윈도우 만들기 public class WindowTest2 { public static void main(String[] args) { JFrame win = new JFrame("윈도우 제목"); win.setTitle("setTitle"); win.setBounds(800, 200, 300, 500); // JFrame으로 만든 윈도우에 배경색을 넣으려면 아래의 방식으로 넣어준다. Container con = win.getContentPane(); con.setBackground(new Color(165,102,255)); // 만약에 JFrame 창이 닫히지 않으면 아래와 같은 코드를 넣어준다. // 아래 코드를 넣지않고 창이 닫히면 메모리에 상주하여 메모리를 잡아먹는다. (콘솔에서 직접 꺼줘야 함.) win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); win.setVisible(true); // 윈도우를 화면에 표시한다. } // main() } // class ``` <file_sep>/Eclipse_Java_Project/src/MobilePhone.java public class MobilePhone { public void callYou() { System.out.println("전화걸기"); } public void callMe() { System.out.println("전화받기"); } } <file_sep>/_java/PATTERN - Christmas Tree.md ``` class ChristmasTree { public static final int segments = 4; public static final int height = 4; public static void main(String[] args) { makeTree(); } public static void makeTree() { int maxStars = 2 * height + 2 * segments - 3; String maxStr = ""; for (int l = 0; l < maxStars; l++) { maxStr += " "; } for (int i = 1; i <= segments; i++) { for (int line = 1; line <= height; line++) { String starStr = ""; for (int j = 1; j <= 2 * line + 2 * i - 3; j++) { starStr += "*"; } for (int space = 0; space <= maxStars - (height + line + i); space++) { starStr = " " + starStr; } System.out.println(starStr); } } for (int i = 0; i <= maxStars / 2; i++) { System.out.print(" "); } System.out.println(" " + "*" + " "); for (int i = 0; i <= maxStars / 2; i++) { System.out.print(" "); } System.out.println(" " + "*" + " "); for (int i = 0; i <= maxStars / 2 - 3; i++) { System.out.print(" "); } System.out.println(" " + "*******"); } } ``` ###OUTPUT ``` * *** ***** ******* *** ***** ******* ********* ***** ******* ********* *********** ******* ********* *********** ************* * * ******* ```<file_sep>/_htmlCss/A000 웹표준이란.md ``` 웹표준이란? - 크로스 브라우징; 모든 브라우저에서 호환, - 크로스 플랫폼; 다양한 플랫폼에서 호환(냉장고, 폰, 태블릿, pc...) - 웹 접근성 : 시각장애인, 노인, 시력감퇴를 고려함 moon_and_james-41 틀을 먼저 짠다 - 사각형의 틀들로 구성 웹표준 + 추가기능 : HTML5 IE11 버전 이상에서 HTML5 가능(크로스 브라우징의 부재) , 스마트폰웹 -> html5가능 드림위버 File ; new ; DocType : HTML5 <!DOCTYPE HTML> <!-- HTML 문서종류 --> <html> <head> <meta charset="utf-8"> <!-- 한글 코드 값(안깨지게 해주는) --> <title>20150512 demo01</title> <!-- 브라우저 내에서의 탭 제목 --> <style> div { width:1000px; height:100px; background-color:red; } <!-- 사각형 그리기 --> </style> </head> <body> <div></div> <!-- 실제 그려지는 부분 --> <div></div> <!-- 두개 그려짐, 간격을 줘야 보임 --> </body> </html> 사각형 그리기 (block(사각형) 속성) 외우기★ 1.가로 ( width:1000px; ) 2.높이 ( height:700px; ) 3.배경색 ( background-color:black; ) 13개정도의 색 값 4.배경그림 ( background-image:... ) 5.바깥간격 ( margin:100px; ) 6.안쪽간격 ( padding:100px; ) 사각형 안에 사각형 ( div p 사용함) 7.정렬 ( float:left; ) 기본 세로정렬, 가로 정렬할것인지 정의함 8.테두리 ( border:3px solid green; ) 선 종류 다양함 solid는 실선, dotted 점선, (:굵기 선종류 색, 순서상관없음) + background-postion:가로px 세로px 사각형 속성 추가 <style> div { width:50px; height:50px; background-color:red; margin-right:50px; float:left; border:3px solid green; } </style> html 기본구조 <!doctype html> <html> <head> <meta charset="UTF-8"> <title></title> <style> div { width:100px; ... } </style> </head> <body> <div></div> </body> </html> ``` <file_sep>/_java/OOPS - Interface Example - Multiple Inheritance.md ``` /* @author: CreativeCub */ //Java doesn't support Multiple Inheritance //To achieve multiple inheritance Java has Interface interface MyInterface { public String hello = "Hello"; public void sayHello(); } interface MyOtherInterface { public void sayGoodbye(); } public class MyInterfaceImpl implements MyInterface, MyOtherInterface { public void sayHello() { System.out.println("Hello"); } public void sayGoodbye() { System.out.println("Goodbye"); } public static void main(String args[]) { MyInterfaceImpl obj = new MyInterfaceImpl(); obj.sayHello(); obj.sayGoodbye(); } } ``` ##OUTPUT ``` Hello Goodbye ```<file_sep>/_java/A036 PrintWriter,Scanner,try,catch,finally.md ``` package com.me.printwritertest; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Scanner; public class PrintWriterTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 출력에 사용할 PrintWriter 선언 PrintWriter pw = null; try { // 파일로 출력할 PrintWriter 객체 생성(출력 파일 열기) // 파일로 출력할 경우에 파일이 존재하지 않으면 새로 만들고 출력한다. pw = new PrintWriter("./src/out.txt"); String str = ""; // "QUIT"가 입력되기 전 까지 키보드로 입력받은 내용을 파일로 출력한다. while(true) { System.out.print("저장할 내용 입력 > "); str = sc.nextLine(); if(str.toLowerCase().trim().equals("quit")) { // trim() : 문자열 앞/뒤의 불필요한 빈칸을 제거한다. // "QUIT"가 입력도면 반복을 탈출한다. break; } // 입력받은 내용을 파일에 출력한다. pw.write(str + "\r\n"); // \n : New Line, 줄을 바꾼다. // \r : Carriage Return, 커서를 줄의 맨 앞으로 보낸다. } System.out.println("파일로 출력 완료"); } catch(FileNotFoundException e) { e.printStackTrace(); } finally { // 파일로 출력시 작업 완료 후 파일을 닫지 않으면 정상적으로 저장되지 않는다. try { if(pw != null) pw.close(); } catch(Exception e) { } } } } ------ 다른 패키지 유의* package com.me.scannertest; import java.util.Scanner; public class ScannerTest2 { public static void main(String[] args) { String str1 = "123 true 12.34 홍길동"; String str2 = "true 123 임꺽정 12.34"; String str3 = "12.34 이몽룡 true 123"; String str4 = "성춘향 12.34 123 false"; // str1 String 변수에서 읽어 들이는 스캐너 생성 Scanner sc = new Scanner(str1); int i = sc.nextInt(); boolean b = sc.nextBoolean(); double d = sc.nextDouble(); String s = sc.next(); System.out.println("i = " + i); System.out.println("b = " + b); System.out.println("d = " + d); System.out.println("s = " + s); System.out.println("================================"); Scanner scan = new Scanner(str4); // 읽어들일 데이터가 있는 동안 반복한다. // scan.hasNext() : 스캐너로 읽어들일 다음 데이터가 있는가? // 다음 데이터가 있으면 true, 없으면 false를 리턴한다. while(scan.hasNext()) { if(scan.hasNextInt()) { // 다음 데이터가 정수인가? i = scan.nextInt(); } else if(scan.hasNextBoolean()) { // 다음 데이터가 불린인가? b = scan.nextBoolean(); } else if(scan.hasNextDouble()) { // 다음 데이터가 더블인가? d = scan.nextDouble(); } else { s = scan.next(); } } System.out.println("i = " + i); System.out.println("b = " + b); System.out.println("d = " + d); System.out.println("s = " + s); System.out.println("================================"); } } ------ 다른 패키지 유의* package com.me.textfileread; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class TextFileRead { public static void main(String[] args) { // 파일에서 읽어들이는 스캐너 선언 Scanner sc = null; try { // 현재 프로젝트 이름의 폴더(0803)에 읽어들일 파일이 위치하고 있으면 파일의 이름만 // 적으면 되고 그렇치 않으면 파일의 경로까지 같이 적어야 한다. // 절대경로 : root 폴더(디렉토리) 부터 파일이 위치한 곳 까지의 경로를 말한다. // "C:\\workspace0930\\0803\\src\\data.txt" ==> 절대경로 // "C:/workspace0930/0803/src/data.txt" ==> 절대경로 // 폴더와 폴더를 구분하는 [\]는 연달아 2번을 적어야하고 귀찮으면 [\\]를 [/]로 대체하면 된다. // 상대경로 : 현재 프로젝트 이름의 폴더 부터 파일이 위치한 곳 까지의 경로를 말한다. // . : 현재 프로젝트 이름의 폴더(C:/workspace0930/0803)를 의미한다. // .. : 현재 프로젝트 이름의 상위 폴더(C:/workspace0930)를 의미한다. // "./src/data.txt" ==> 상대경로 // 파일에서 읽어들이는 스캐너 객체 생성(입력 파일 열기) sc = new Scanner(new File("./src/data.txt")); // System.out.println("파일 있당~~~"); // 읽어들일 줄이 있는 동안 반복한다. // scan.hasNextLine() : 스캐너로 읽어들일 파일에서 다음 줄이 있는가? // 다음 줄이 있으면 true, 없으면 false를 리턴한다. while(sc.hasNextLine()) { // 텍스트 파일에서 한 줄을 읽어 문자열 변수 str에 넣는다. String str = sc.nextLine(); // System.out.println(str); // 문자열 변수 str에서 읽어들이는 스캐너 생성 Scanner scan = new Scanner(str); int i = 0; double d = 0; boolean b = false; String s = null; while(scan.hasNext()) { if(scan.hasNextInt()) { i = scan.nextInt(); } else if(scan.hasNextDouble()) { d = scan.nextDouble(); } else if(scan.hasNextBoolean()) { b = scan.nextBoolean(); } else { s = scan.next(); } } System.out.println("i = " + i); System.out.println("b = " + b); System.out.println("d = " + d); System.out.println("s = " + s); System.out.println("================================"); } } catch(FileNotFoundException e) { System.out.println("data.txt 파일이 존재하지 않습니다."); // e.printStackTrace(); } finally { try { if(sc != null) sc.close(); } catch(Exception e) { } } } } ``` <file_sep>/_java/PATTERN - Floyd Triangle.md ``` import java.util.Scanner; class FloydTriangle { public static void main(String args[]) { int n, num = 1, c, d; Scanner in = new Scanner(System.in); System.out.print("Enter the number of rows of floyd's triangle : "); n = in.nextInt(); System.out.println("Floyd's triangle :-"); for ( c = 1 ; c <= n ; c++ ) { for ( d = 1 ; d <= c ; d++ ) { System.out.print(num+" "); num++; } System.out.println(); } } } ``` ##OUTPUT ``` Enter the number of rows of floyd's triangle : 5 Floyd's triangle :- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ```<file_sep>/_java/PATTERN - Diamond Pattern.md ``` /* Enter no of characters:7 Enter String:PROGRAM P P R P R O P R O G P R O G R P R O G R A P R O G R A M P R O G R A P R O G R P R O G P R O P R P */ import java.io.*; class DiamondPattern { public static void main(String s[]) throws Exception { int i,j,k,n; String s1; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter no of characters:"); n=Integer.parseInt(br.readLine()); System.out.print("Enter String:"); s1=br.readLine(); for(i=0;i<n;i++) { for(j=0;j<(n-i);j++) { System.out.print(" "); } for(k=0;k<=i;k++) { System.out.print(s1.charAt(k)); System.out.print(" "); } System.out.print("\n"); } for(i=(n-2);i>=0;i--) { for(j=0;j<(n-i);j++) { System.out.print(" "); } for(k=0;k<=i;k++) { System.out.print(s1.charAt(k)); System.out.print(" "); } System.out.print("\n"); } } } ``` ##OUTPUT ``` Enter no of characters:7 Enter String:PROGRAM P P R P R O P R O G P R O G R P R O G R A P R O G R A M P R O G R A P R O G R P R O G P R O P R P ```<file_sep>/_java/COLLECTION - Basics Of ArrayList.md ``` import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class ArrayListBasics{ public static void main(String[] args){ ArrayList<String> al = new ArrayList<>(); // adding object in arraylist al.add("java"); al.add("C"); al.add("C++"); al.add("php"); al.add("python"); al.add("css"); // add al.add("html"); //add at specific index al.add(1, "Android"); System.out.print("ArrayList : " + al); System.out.println(); // remove from arraylist al.remove("php"); // Size of ArrayList System.out.print("Size of ArrayList after removing php : "+al.size()); System.out.println(); System.out.println("Is java is in list : " + al.contains("Java")); // get specific element System.out.print("I want "+alget(0)); System.out.println(); // list to array Object[] a = al.toArray(); System.out.print("Array : "); for (Object object : a){ System.out.print(object + " "); } System.out.println(); // change element al.set(6, "Javascript"); System.out.print("ArrayList after replace : "+al); System.out.println(); // sort list using Collections Class Collections.sort(al); System.out.print("ArrayList after sort : " + al); System.out.println(); // Index System.out.println("Index of Android : " + al.indexOf("Android")); // clear whole list al.clear(); System.out.print(al+" "+"Is list empty after clear : " + al.isEmpty()); } } ``` ### OUTPUT ``` ArrayList : [Java, Android, C, C++, php, python, css, html] Size of ArrayList after removing php : 7 Is java is in list : true I want Java Array : Java Android C C++ python css html ArrayList after replace : [Java, Android, C, C++, python, css, Javascript] ArrayList after sort : [Android, C, C++, Java, Javascript, css, python] Index of Android : 0 [] is list empty after clear : true ``` <file_sep>/_javascript/A008 if조건문, 아코디언 메뉴.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>if조건문</title> <script> test=prompt('숫자를 입력하시오','0') if(test=='0'){ alert('다시입력하시오') }else{ alert(test+'를 입력하셨습니다.') } </script> </head> <body> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>if조건문</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ $('button').click(function(){ if($('#uid').val()==''){ alert('id를 입력하시오') $('#uid').focus() }else if($('#upw').val()==''){ alert('비밀번호를 입력하시오') $('#upw').focus() }else { document.write('로그인 되었습니다.') document.write('<a href="#">home</a>') } }) }) </script> </head> <body> <input id="uid" type="text" /> <input id="upw" type="text" /> <button>확인</button> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>if조건문</title> <script> avg = parseInt(prompt('평균입력하시오','0')) if(avg>=0 && avg<=100){ if(avg >= 90){ alert('수') }else if(avg >= 80){ alert('우') }else if(avg >= 70){ alert('미') }else if(avg >= 60){ alert('양') }else{ alert('가') } }else{ alert('평균을 다시 입력하시오') } </script> </head> <body> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>if응용- 아코디언패널</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ $('dd:not(:first)').css('display','none') $('dt:first').addClass('selected') $('dt').click(function(){ if($('+dd',this).css('display')=='none'){ $('dd').slideUp() $('+dd',this).slideDown('slow') $('dt').removeClass('selected') $(this).addClass('selected') }else{ $('+dd',this).slideUp('fast') $(this).removeClass('selected') } }).mouseover(function(){ $(this).addClass('over') }).mouseout(function(){ $(this).removeClass('over') }) }) </script> <style> * { margin:0; padding:0} dl{ margin:50px; width:500px;} dt{ line-height:40px; background-color:#666; color:#FFFFFF; padding-left:20px; cursor:pointer; border-bottom:1px solid #333} dd{ height:160px; background-color:#F2F2F2; padding:20px;} .selected{ background-color:#333} .over{ background-color:#000} </style> </head> <body> <dl> <dt>제목영역1</dt> <dd>내용영역1</dd> <dt>제목영역2</dt> <dd>내용영역2</dd> <dt>제목영역3</dt> <dd>내용영역3</dd> </dl> </body> </html> ``` <file_sep>/_jspServlet/A004 Refresh-Redirect.md ## 리프래시 ``` 일정 시간이 지나고 나서 자동으로 서버에 요청을 보내는 방법. '리프래시' 또는 '새로 고침'이라 한다. 자동으로 회원 목록을 출력하는 순서 1. 웹 브라우저에서 '회원 등록 입력폼'을 요청. 2. MemberAddServlet은 회원 등록폼을 클라이언트로 보낸다. 3. 웹 브라우저는 회원 등록폼을 화면에 출력한다. 사용자가 회원 정보를 입력하고 나서 '추가'버튼을 누르면 서버에 등록 요청. 4. MemberAddServlet은 회원 등록 결과를 클라이언트로 보낸다. 5. 웹 브라우저는 회원 등록 결과를 출력. 그리고 1초 후에 서버에 '회원 목록'을 요청한다. 6. MemberListServlet은 회원 목록을 클라이언트로 보낸다. ``` >리프래시의 방법. ``` MemberAddServlet 클래스의 doPost() 메서드에서 response.addHeader("Refresh", "1;url=list");를 추가한다. ``` HttpServletResponse의 AddHeader()는 HTTP 응답 정보에 헤더를 추가하는 메서드이다. ``` HTML 본문에 리프래시 정보를 추가한다. ``` HTML의 `<head>`태그 안에 리프래시를 설정하는 <meta> 태그를 추가한다. out.println("`<meta http-equiv='Refresh' content='1; url=list'>`"); 를 `<head>` 태그안에 삽입. ## 리다이렉트 ``` 작업 결과를 출력한 후 다른 페이지로 이동할때는 리프래시를 사용하지만 작업 결과를 출력하지 않고 다른 페이지로 이동할 때는 '리다이렉트'로 처리한다. ``` >리다이렉트의 방법. ``` HttpServletResponse의 sendRedirect() 호출 코드를 추가한다. response.sendRedirect("list") ``` ``` 리다이렉트는 클라이언트로 본문을 출력하지 않기 때문에 HTML을 출력하는 코드를 모두 제거한다. sendRedirct()에 넘기는 URL이 '/'로 시작하지 않기 때문에 상대 주소로 계산된다. 리다이렉트의 HTTP 응답 정보를 살펴 보면, 응답 상태 코드가 200이 아닌 302로 되어있다. '요청한 자원이 다른 URL로 이동되었으니 Location 헤더에 있는 주소로 다시 요청하라' 라는 뜻이다. 웹 브라우저가 이런 응답을 받으면 즉시 Location 헤더의 주소로 다시 요청한다. 이런 이유로 sendRedirect()를 호출할 때는 HTML 출력 코드를 작성할 필요가 없다. 설사 작성한다 하더라도 클라이언트로 보내지 않기 대문에 아무런 소용이 없다. ``` >작업 결과를 출력하지 않고 즉시 다른 페이지로 이동하기를 원한다면 '리다이렉트'를 사용하고 잠깐이나마 작업 결과를 출력하고 다른 페이지로 이동하기를 원한다면 '리프래시'를 사용하면 된다. <file_sep>/_jspServlet/A012 useInterface.md ### 실생활의 예 요즘 대부분의 스마트폰은 마이크로 USB 포트가 있는데, 이 포트를 통해 데이터를 주고 받거나 충전을 합니다. 마이크로 USB는 제품의 이름이 아니라 직렬 방식으로 데이터를 주고 받기 위해 고안된 입출력 규격입니다. 자바 문법으로 보자면 `Interface`라 할 수 있습니다. 이렇게 규격 을 정의해 두면, 제조 회사에 상관없이 이 규격을 준수하는 어떤 충전기라도 사용할 수 있어 제품 선택의 폭이 넓어집니다. ### 프로그래밍에서의 활용 사용할 의존 객체에 대해 선택 폭을 넓히고 싶고 향후 확장을 고려하여 교체하기 쉽게 만들고 싶다면, 인터페이스 문법을 통해 사용 규칙을 정의하세요. 그리고 그 규칙에 따라 호출하도록 코드를 작성하면 됩니다. 여기에다가 `Dependency Injection` 방식을 적용한다면 금상첨화일 것입니다. <file_sep>/_java/COLLECTION - TreeSet Class.md ``` import java.util.Iterator; import java.util.TreeSet; public class TreeSetTest { public static void main(String[] args) { TreeSet<String> ts=new TreeSet<String>(); ts.add("java"); ts.add("php"); ts.add("android"); ts.add("css"); System.out.println(ts); //using Iterator Iterator<String> itr=ts.iterator(); while(itr.hasNext()) { System.out.print(itr.next()+" "); } System.out.println(); //Using enhanced for-loop for (String string : ts) { System.out.print(string+" "); } } } ``` ##OUTPUT ``` [android, css, java, php] android css java php android css java php ```<file_sep>/_cpp/숫자 랜덤으로 섞기.md ``` #include <cstdio> #include <iostream> using namespace std; //난수를 사용(rand(), srand())하려면 Visual C++ 6.0은 반드시 stdlib.h를 포함시킨다. #include <stdlib.h> #include <ctime> // time() 함수를 사용하기 위한 헤더 파일 int main() { //난수를 그냥 발생시키면 항상 똑같은 값이 나오므로 반드시 초기화 작업을 해줘야한다. srand((unsigned int)time(NULL)); //for(int i=0 ; i<6 ; i++) { // cout << rand() % 45 + 1 << endl; //} //1. 추첨기를 준비한다. int lotto[45]; //2. 추첨기에 공을 넣는다. for(int i=0 ; i<45 ; i++) { lotto[i] = i + 1; } cout << "섞기전" << endl; for(int i=0 ; i<45 ; i++) { printf("%02d ", lotto[i]); if(i % 10 == 9) { cout << endl; // 1줄에 숫자 10개를 출력했으면 줄을 바꾼다. } } cout << endl; //3. 섞는다. //lotto[0]와 lotto[1]~[44] 중에서 랜덤한 위치와 값을 교환한다. for(int i=0 ; i<1000000 ; i++) { int r = rand() % 44 + 1; int temp = lotto[0]; lotto[0] = lotto[r]; lotto[r] = temp; } cout << "섞은후" << endl; for(int i=0 ; i<45 ; i++) { printf("%02d ", lotto[i]); if(i % 10 == 9) { cout << endl; // 1줄에 숫자 10개를 출력했으면 줄을 바꾼다. } } cout << endl; //4. 앞의 6개가 1등 번호, 7번째는 뽀나스 cout << "1등번호 : "; for(int i=0 ; i<6 ; i++) { cout << lotto[i] << " "; } cout << "뽀나스 : " << lotto[6] << endl; } ``` <file_sep>/_java/A025 소문자를 대문자로.md ``` public class StringTest1 { public static void main(String[] args) { String str1 = "AAA";// 메모리에 없어서 새로 만든다. //클래스를 사용해서 만든 변수(객체, 인스턴스)는 참조형 변수로 주소값을 기억한다. String str2 = "AAA";// 메모리에 있으므로 재활용한다. System.out.println(str1 == str2 ? "같다" : "다르다"); String str3 = str1; System.out.println(str1 == str3 ? "같다" : "다르다"); String str4 = new String("AAA"); //new를 사용해 문자열을 생성하면 메모리에 있던 없던 무조건 새로 만든다. System.out.println(str1 == str4 ? "같다" : "다르다"); //문자열을 "=="을 사용해 비교하면 문자열의 내용을 비교하는 것이 아니고 문자열이 생성된 메모리의 //주소값(hashcode)를 비교하므로 같은 내용의 문자열이라 해도 다르다라고 나올 수 있다. System.out.println(str1.equals(str4) ? "같다" : "다르다"); //★★★★★ 문자열의 내용 자체를 비교하려면 equals() 메소드를 사용한다. } } ``` ``` import java.util.Scanner; public class StringTest2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("영문자 입력 : "); String str = sc.nextLine(); // 소문자를 대문자로 바꾸 출력하기 // for(int i=0 ; i<str.length() ; i++) { // if(str.charAt(i) >= 'a' && str.charAt(i) <= 'z') { // System.out.print((char)(str.charAt(i) - 32)); // } else { // System.out.print(str.charAt(i) - 32); // } // } System.out.println(str.toUpperCase()); // toUpperCase() : 무조건 대문자로 출력 // toLowerCase() : 무조건 소문자로 출력 } } ``` <file_sep>/_javascript/A010 animate, Interval, resize.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>animate</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ var win_width =$(window).width() var box1_width = $('.box1').width() $('.box1').animate({ marginLeft:win_width-box1_width},1000,'linear') $('button:first').click(function(){ clearInterval(box2move) }) $('button:eq(1)').click(function(){ box2move = setInterval(function(){ $('.box2').animate({ marginLeft:500},500,'swing', function(){ $(this).animate({marginLeft:0},500) }) },2000) }).click() }) </script> <style> * { margin:0; padding:0} .box{ width:200px; height:100px; margin:10px 0;} .box1{ background-color:red} .box2{ background-color:blue} </style> </head> <body> <button>clearInterval</button> <button>setInterval</button> <div class="box box1">box1</div> <div class="box box2">box2</div> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>resize()</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ boxWidth() $(window).resize(function(){ boxWidth() }) //function() function boxWidth(){ win_w = $(window).width() $('#box').css({width:win_w-20, maxWidth:1000, minWidth:300}) } }) </script> <style> #box{ width:100px; height:100px; background-color:red;} </style> </head> <body> <div id="box">box</div> </body> </html> ``` <file_sep>/_javascript/A009 로그인 ID, PASSWORD.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>login</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ var uid_txt = 'ID' var upw_txt = '<PASSWORD>' $('#uid').val(uid_txt) $('#upw').val(upw_txt) $('#uid, #upw').addClass('input_txt') $('input').one('focus',function(){ $(this).val('').removeClass('input_txt') }).blur(function(){ // uid if($('#uid').val()==''){ $('#uid').val(uid_txt).addClass('input_txt') $('#uid').one('focus',function(){ $(this).val('').removeClass('input_txt') }) } //upw if($('#upw').val()==''){ $('#upw').val(upw_txt).addClass('input_txt') $('#upw').one('focus',function(){ $(this).val('') .removeClass('input_txt') }) } }) }) </script> <style> .input_txt{ color:#999999;} </style> </head> <body> <p> <label for="uid">아이디</label> <input type="text" id="uid" /> </p> <p> <label for="upw" >비밀번호</label> <input type="text" id="upw" /> </p> </body> </html> ``` <file_sep>/_javascript/A002 filter 응용.md ``` 제이쿼리는 필터기능을 제공합니다. 밑에 코드를 보면 li:first 라는게 보이실겁니다. 콜론(:)으로 연결된 것이 제이쿼리에서 제공하는 필터 기능입니다. 생각보다 다양한 기능이 있기 때문에 경우에 따라 css를 이용하는 것보다 편합니다. <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery filter</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { //css3 $('li:nth-child(2)').css('color','red') //jquery filter $('li:first').css('color','green') $('li:last').css('color','yellow') $('li:eq(2)').css('color','#39F') $('li:odd').css('background-color','#CCC') $('li:even').css('background-color','#FCF') $('li:gt(4)').css('border','3px solid #000') $('li:lt(4)').css('border','3px solid #000') $(':header').css('font','16px "돋움"') $('li:has(em)').css('background-color','red') $('li:contains("네번째")').css('background-color','#9C0') $('li:empty').css('height','100px') $('li:parent').css('height','40px') }) </script> </head> <body> <h1>jquery Filter</h1> <h2>filter를 이용해서 원하는 영역에 스타일주기</h2> <ul> <li><em>첫번째</em>입니다</li> <li>두번째 목록</li> <li>세번째 목록</li> <li>네번째 목록</li> <li>다섯번째 목록</li> <li></li> </ul> <ul> <li>첫번째 목록</li> <li><em>두번째 목록</em></li> <li>세번째 목록</li> <li>네번째 목록</li> <li>다섯번째 목록</li> </ul> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery filter응용1</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('.gnb li').css('background-color','#eee') $('.gnb li:first').css({ backgroundColor:'#333', color:'#fff', borderRadius:'5px 0 0 5px' }) $('.gnb li:last').css({ color:'#F60', borderRadius:'0 5px 5px 0' }) $('.gnb li:odd').css({backgroundColor:'#F5F5F5'}) }) </script> <style type="text/css"> * { margin:0; padding:0} ul,ol,li { list-style:none} .gnb{ margin:50px auto; width:700px;height:40px; border-radius:5px; box-shadow:0px 1px 2px rgba(0,0,0,0.2);} .gnb li{ float:left; width:100px; line-height:40px; text-align:center;} </style> </head> <body> <ul class="gnb"> <li>HOME</li> <li>PROFILE</li> <li>PORTFOLIO</li> <li>GALLERY</li> <li>BOARD</li> <li>QnA</li> <li>고객센터</li> </ul> </body> </html> ``` <file_sep>/_htmlCss/A014 메뉴(navigation) 만들기.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>navigation1</title> <style type="text/css"> * { margin:0; padding:0} ul,ol,li { list-style:none;} .gnb { margin:50px; width:200px;} .gnb li{ display:block; line-height:27px; border-bottom:1px solid #666} .gnb li a{ color:#06C; text-decoration:none; display:block; background:url(img/arr1.png) no-repeat 0 9px; padding-left:20px; } .gnb li a:hover { color:#FF6600; background-color:#FFFF99; /*padding-left:30px;*/ background-position:0 -10px;} </style> </head> <body> <ul class="gnb"> <li><a href="#">HOME</a></li> <li><a href="#">PROFILE</a></li> <li><a href="#">PORTFOLIO</a></li> <li><a href="#">GALLERY</a></li> <li><a href="#">BOARD</a></li> </ul> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>navigation1</title> <style type="text/css"> * { margin:0; padding:0} ul,ol,li { list-style:none;} .gnb { margin:50px; width:750px;} .gnb li{ display:block; line-height:40px; float:left;} .gnb li a{color:#666; text-decoration:none; display:block; width:150px; text-align:center; border-bottom:1px solid #ddd; border-top:1px solid #F0F0F0} .gnb li a:hover { background:url(img/arr2.png) no-repeat center bottom; background-color:#F2F2F2; border-bottom-color: #bfbdbd; color:#333; font-weight:bold} </style> </head> <body> <ul class="gnb"> <li><a href="#">HOME</a></li> <li><a href="#">PROFILE</a></li> <li><a href="#">PORTFOLIO</a></li> <li><a href="#">GALLERY</a></li> <li><a href="#">BOARD</a></li> </ul> </body> </html> ``` <file_sep>/_javascript/A000 버튼 alert.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js" > </script> <script type="text/javascript"> $(document).ready(function(){ //alert('jquery시작합니다.') $('.btn').click(function(){ alert('버튼을 클릭하셨습니다.') }) }) </script> <style type="text/css"> .btn{ width:50px; height:30px;} /* css3 */ .btn:first-child{ background-color:#099} .btn:last-child{ background-color:#600} .btn:nth-child(2){ background-color:#00CC99;} </style> </head> <body> <p> <button class="btn">b1</button> <button class="btn">b2</button> <button class="btn">b3</button> <button class="btn">b4</button> <button class="btn">b5</button> <button class="btn">b6</button> </p> <p> <button class="btn">b1</button> <button class="btn">b2</button> <button class="btn">b3</button> <button class="btn">b4</button> <button class="btn">b5</button> <button class="btn">b6</button> </p> </body> </html> ``` <file_sep>/_java/OOPS - Address Details using 'this' keyword.md ``` class AddressDetails { int flatno; String blgd; String city; AddressDetails(int flatno, String blgd) { this.flatno = flatno; this.blgd = blgd; } AddressDetails(int flatno, String blgd, String city) { //now no need to initialize id and name this(flatno, blgd); this.city = city; } void display() { System.out.println(flatno + " " + blgd + " " + city); } public static void main(String args[]) { AddressDetails e1 = new AddressDetails(01, "abc"); AddressDetails e2 = new AddressDetails(02, "def", "mumbai"); e1.display(); e2.display(); } } ``` ## OUTPUT ``` 1 WTC null 2 Twin Tower mumbai ```<file_sep>/_htmlCss/A011 2단 레이아웃, float이해.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>기본2단 레이아웃-float이해하기</title> <style type="text/css"> body{ margin:0} #wrap { width:960px; margin:0 auto} #header { height:100px; background-color:#9C3; } #nav{ height:40px; background-color:#333;} #aside{ float:left; width:150px; height:400px; background-color:#FFCCFF} #contents{ float:left;width:810px; background-color:#FF9900;} .sbox{ float:left; width:100px; height:100px; background-color:#FFF; margin:10px 10px 10px 10px; } .bbox{ background-color:red; float:left; clear:both} #footer{ height:100px; background-color:#CCC; clear:both} </style> </head> <body> <div id="wrap"> <div id="header"> </div><!--//header--> <div id="nav"> </div><!--//nav--> <div id="aside"> </div><!--//aside--> <div id="contents"> <div class="bbox"> <div class="sbox">box1</div> <div class="sbox">box2</div> </div> <div class="bbox"> <div class="sbox">box1</div> <div class="sbox">box2</div> <div class="sbox">box3</div> <div class="sbox">box4</div> </div> </div><!--//contents--> <div id="footer"> </div><!--//footer--> </div> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>기본2단 레이아웃-float이해하기</title> <style type="text/css"> body{ margin:0} #wrap { width:960px; margin:0 auto} #header { height:100px; background-color:#9C3; } #nav{ height:40px; background-color:#333;} #aside{ float:left; width:150px; height:400px; background-color:#FFCCFF} #contents{ float:left;width:810px; background-color:#FF9900;} #footer{ height:100px; background-color:#CCC; clear:both} </style> </head> <body> <div id="wrap"> <div id="header"> </div><!--//header--> <div id="nav"> </div><!--//nav--> <div id="aside"> </div><!--//aside--> <div id="contents"> <div class="bbox"> <div class="sbox">box1</div> <div class="sbox">box2</div> </div> <div class="bbox"> <div class="sbox">box1</div> <div class="sbox">box2</div> <div class="sbox">box3</div> <div class="sbox">box4</div> </div> </div><!--//contents--> <div id="footer"> </div><!--//footer--> </div> </body> </html> ``` <file_sep>/_java/A013 JPanel, Runnable 구현.md ``` package com.me.animationtest; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JPanel; public class AnimationTest4 extends JPanel implements Runnable{ Image [] img = new Image[15]; // 변화되는 이미지를 저장할 배열 선언 int w = 88, h = 146; // 이미지의 크기를 저장 int count = 0; // 이미지 출력 순서 변경에 사용할 변수 int x = 50, y = 50; // 이미지가 출력될 x, y좌표 public AnimationTest4(){ for(int i = 0 ; i<img.length ; i++){ String filename = String.format("./src/images/princess_walk_%02d.png", i); // 2칸만큼 0을 채움 // System.out.println(filename); img[i] = Toolkit.getDefaultToolkit().getImage(filename); } } public static void main(String[] args) { JFrame win = new JFrame("앞으로 걸어가는 애니메이션"); win.setBounds(300, 300, 720, 320); // win.addWindowListener(new WindowAdapter() { // @Override // public void windowClosing(WindowEvent e){ // System.exit(0); // } // }); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 닫히지 않으면 이거 추가한다. AnimationTest4 g = new AnimationTest4(); win.add(g); win.setVisible(true); // win.setVisible 뒤로하는게 좋음 (캔버스 사용시 문제가 발생할 수 있음) // Thread thread = new Thread(g); // thread.start(); new Thread(g).start(); } @Override public void paint(Graphics g) { // 그래픽 구현 g.setColor(Color.WHITE); g.fillRect(0, 0, 720, 320); // 위 두 줄 안써주면 잔상이 남음 g.drawImage(img[count], x, y, this); } @Override public void run() { // 스레드(움직임) 구현 while(true){ x += 7; if(x > 700) x = 0; if(++count == 15){ count = 0; } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } repaint(); } } } // class ``` ``` package com.me.animationtest; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JFrame; import javax.swing.JPanel; public class AnimationTest5 extends JPanel implements Runnable{ Image [] img = new Image[15]; // 변화되는 이미지를 저장할 배열 선언 int w = 88, h = 146; // 이미지의 크기를 저장 int count = 14; // 이미지 출력 순서 변경에 사용할 변수 int x = 550, y = 50; // 이미지가 출력될 x, y좌표 public AnimationTest5(){ for(int i = 0 ; i<img.length ; i++){ String filename = String.format("./src/images/princess_walk_%02d.png", i); // 2칸만큼 0을 채움 // System.out.println(filename); img[i] = Toolkit.getDefaultToolkit().getImage(filename); } } public static void main(String[] args) { JFrame win = new JFrame("뒤로 걸어가는 애니메이션"); win.setBounds(300, 300, 720, 320); // win.addWindowListener(new WindowAdapter() { // @Override // public void windowClosing(WindowEvent e){ // System.exit(0); // } // }); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 닫히지 않으면 이거 추가한다. AnimationTest5 g = new AnimationTest5(); win.add(g); win.setVisible(true); // win.setVisible 뒤로하는게 좋음 (캔버스 사용시 문제가 발생할 수 있음) // Thread thread = new Thread(g); // thread.start(); new Thread(g).start(); } @Override public void paint(Graphics g) { // 그래픽 구현 g.setColor(Color.WHITE); g.fillRect(0, 0, 720, 320); // 위 두 줄 안써주면 잔상이 남음 g.drawImage(img[count], x, y, this); } @Override public void run() { // 스레드(움직임) 구현 while(true){ x-=7; if(x<=-90) x=550; if(--count == -1){ count = 14; } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } repaint(); } } } // class ``` <file_sep>/_cpp/부호없는 int형, 주민번호 체크.md ``` #include <cstdio> #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { // char *check = "234567892345"; // string check = "234567892345"; // int check[] = {2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5}; // char jumin[14]; // char *jumin = new char[14]; string jumin; cout << "주민등록번호 13자리를 '-'없이 입력하세요 : "; cin >> jumin; // string 클래스가 제공되지 않던 시절의 문자 배열로 문자열을 처리할 경우 문자열의 끝까지 반복시킬 경우 반복문 // for(int i=0 ; jumin[i] != '\0' ; i++) { // cout << jumin[i] << endl; // } // 주민등록번호의 각 자리와 자리별 가중치의 곱한 결과의 합계를 구한다. int sum = 0; for(unsigned int i=0 ; i<jumin.size()-1 ; i++) { // sum += (jumin.at(i)-48) * (check.at(i)-'0'); // string check를 사용할 경우 // sum += (jumin.at(i)-48) * (i<8 ? i+2 : i-6); sum += (jumin.at(i)-48) * (i % 8 + 2); } // sum = sum % 11; // 합계를 11로 나눈 나머지를 구한다. // sum = 11 - sum; // 나머지를 11에서 뺀다. // sum = sum % 10; // 나머지에서 뺀 결과가 10 이상이면 10자리를 버리고 1자리만 취한다. // 위의 3줄을 1줄로 줄이면 아래와 같다. sum = (11 - sum % 11) % 10; if(sum == jumin.at(12)-48) { cout << "정상" << endl; } else { cout << "오류" << endl; } cout << (sum == jumin.at(12)-48 ? "정상" : "오류") << endl; } ``` ``` #include <cstdio> #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { string jumin; cout << "주민등록번호 13자리를 '-'없이 입력하세요 : "; cin >> jumin; int sum = 0; for(unsigned int i=0 ; i<jumin.size()-1 ; i++) { sum += (jumin.at(i)-48) * (i % 8 + 2); } sum = (11 - sum % 11) % 10; cout << (sum == jumin.at(12)-48 ? "정상" : "오류") << endl; } ``` <file_sep>/_java/A030 Date, SimpleDateFormat.md ``` import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class DateTest { public static void main(String[] args) { // 컴퓨터 시스템의 현재 날짜와 시간을 포함하는 객체가 생성된다. Date date1 = new Date(); System.out.println(date1); // 날짜 및 시간의 출력 서식 지정하기 SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd(E) HH:mm:ss"); System.out.println(sdf1.format(date1)); SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy년 MM월 dd일"); System.out.println(sdf2.format(date1)); // 주민등록번호를 입력받아 생일 만들기 Scanner sc = new Scanner(System.in); System.out.print("주민등록번호 : "); String jumin = sc.nextLine(); // substring(a) : a번째 문자부터 끝까지 얻어온다. // substring(a, b) : a번째 문자부터 b-1번째 문자까지 얻어온다. // System.out.println(jumin.substring(6)); // System.out.println(jumin.substring(0, 2)); // Integer.parseInt() : () 안의 문자열을 정수로 변환한다. int yy = Integer.parseInt(jumin.substring(0, 2)); int mm = Integer.parseInt(jumin.substring(2, 4)); int dd = Integer.parseInt(jumin.substring(4, 6)); // 년, 월, 일을 입력해서 날짜 데이터 만들기 // Date 클래스는 1900년 1월 1일을 기준으로 날짜 데이터를 처리한다. // 년도를 입력할 때는 1900을 빼서 입력하고 얻어올 때는 1900을 더해서 얻어온다. // 월을 입력할 때는 1을 빼서 입력하고 얻어올 때는 1을 더해서 얻어온다. Date date2 = new Date(yy, mm-1, dd); System.out.println(sdf2.format(date2)); // 날짜 및 시간에서 필요한 요소만 얻어오기 System.out.println(date1.getYear() + 1900); // getYear() 년도를 얻어온다. System.out.println(date1.getMonth() + 1); // getMonth() 월를 얻어온다. System.out.println(date1.getDate()); // getDate() 일을 얻어온다. System.out.println(date1.getDay()); // getDay() 요일을 얻어온다. System.out.println(date1.getHours()); // getHours() 시간을 얻어온다. System.out.println(date1.getMinutes()); // getMinutes() 분을 얻어온다. System.out.println(date1.getSeconds()); // getSeconds() 초를 얻어온다. // 날짜 및 시간에서 필요한 요소만 수정하려면 get을 set으로 변경하면 된다. date1.setYear(200); System.out.println(sdf2.format(date1)); } } ``` <file_sep>/_java/A029 달력.md ``` import java.util.Scanner; // 달력을 출력하는 클래스 public class Calen { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("달력을 출력할 년, 월을 입력하세요 : "); int year = sc.nextInt(); int month = sc.nextInt(); // int day = sc.nextInt(); // MyCal myCal = new MyCal(); // System.out.println(myCal.isYoun(year)); // System.out.println(MyCal.isYoun(year)); // System.out.println(MyCal.lastday(year, month)); // System.out.println(MyCal.totalday(year, month, day)); // System.out.println(MyCal.weekday(year, month, day)); System.out.println("============================"); System.out.printf(" %4d년 %2d월\n", year, month); System.out.println("============================"); System.out.println(" 일 월 화 수 목 금 토 "); System.out.println("============================"); // 1일의 요일을 맞추기 위해 빈 칸을 출력한다. for(int i=1 ; i<=MyCal.weekday(year, month, 1) ; i++) { System.out.print(" "); } // 1일 부터 그 달의 마지막 날짜까지 출력한다. for(int i=1 ; i<=MyCal.lastday(year, month) ; i++) { System.out.printf(" %2d ", i); // 출력한 날짜가 토요일이고 마지막 날짜가 아니면 줄을 바꾼다. if(MyCal.weekday(year, month, i) == 6 && i != MyCal.lastday(year, month)) { System.out.println(); } } System.out.println("\n============================"); } } ``` ``` import java.util.Date; import java.util.Scanner; // 달력을 출력하는 클래스 public class Calen1 { public static void main(String[] args) { Date date = new Date(); int year = date.getYear() + 1900; int month = date.getMonth() + 1; System.out.println("============================"); System.out.printf(" %4d년 %2d월\n", year, month); System.out.println("============================"); System.out.println(" 일 월 화 수 목 금 토 "); System.out.println("============================"); for(int i=1 ; i<=MyCal.weekday(year, month, 1) ; i++) { System.out.print(" "); } for(int i=1 ; i<=MyCal.lastday(year, month) ; i++) { System.out.printf(" %2d ", i); if(MyCal.weekday(year, month, i) == 6 && i != MyCal.lastday(year, month)) { System.out.println(); } } System.out.println("\n============================"); } } * 위 소스는 아래의 메소드를 사용합니다. // 달력 출력에 사용할 메소드가 모여있는 클래스 public class MyCal { // 메소드의 형식 // [접근권한지정자] [static] 메소드의리턴타입 메소드이름(인수) { // 메소드 내용; // ...; // [return 값;] // } // 접근 권한 지정자 // private : 현재 클래스 외부에서 접근 불가능, 정보은폐, 상속 불가능 // protected : 현재 클래스와 자식 클래스에서만 접근 가능, 상속 가능 // default(생략시, package) : 같은 패키지 안에서만 접근 가능, 상속 가능 // public : 모든 클래스에서 접근 가능, 상속 가능 // 일반적으로 멤버 변수는 private으로 멤버 메소드는 public으로 선언한다. // 정적(static) 메소드 // 클래스의 객체를 생성하지 않고 클래스 이름에 "."을 찍어 바로 실행이 가능한 메소드 // 자주 사용하는 메소드를 static 메소드로 만들어 사용하면 편리하다. // 년을 넘겨받아 윤년, 평년을 판단해서 윤년은 true, 평년은 false를 리턴하는 메소드 public static boolean isYoun(int year) { return year%4 == 0 && year%100 != 0 year%400 == 0; } // 년, 월을 넘겨받아 해당 월의 마지막 날짜를 리턴하는 메소드 public static int lastday(int year, int month) { int m[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; m[1] = isYoun(year) ? 29 : 28; return m[month-1]; } // 년, 월, 일을 넘겨받아 1년 1월 1일 부터 지나온 날짜수를 리턴하는 메소드 public static int totalday(int year, int month, int day) { int sum = (year-1) * 365 + (year-1) / 4 - (year-1) / 100 + (year-1) / 400; for(int i=1 ; i<month ; i++) { sum += lastday(year, i); } return sum + day; } // 년, 월, 일을 넘겨받아 해당 날짜의 요일을 숫자로 리턴하는 메소드 // 일요일(0), 월요일(1), 화요일(2), ..., 토요일(6) public static int weekday(int year, int month, int day) { return totalday(year, month, day) % 7; } } ``` <file_sep>/_htmlCss/A001 간격 속성, 네이밍.md ``` HTML/CSS에서 간격 속성 바깥 간격 : margin margin-top margin-right margin-left margin-bottom 안쪽 간격 : padding padding-top padding-right padding-left padding-bottom body태그 안에 사용하는 div(사각형 속성) div id="NAME" 이름표를 붙일 때 주의점 1. 한글 사용 금지 2. 특수 기호 금지 ( 하이픈-, 언더바_ 사용 가능) 3. 숫자로 시작 금지 4. 띄어쓰기는 금지 / 알고 사용(용도가 다름) <style> <!-- div 생략가능(생략이 편함) --> div#box01 { width:300px; height:300px; background-color:red; margin-top:300px; margin-left:50px; } div#box02 {width:400px; height:400px; background-color:blue;} </style> <body> <!-- id는 이름표 --> <div id="box01"></div> <div id="box02"></div> </body> 용어 정리 , (콤마) . (닷) ; (세미콜론) : (콜론) {} (브레이스 브라켓) () (라운드 브라켓) [] (스퀘어 브라켓) " (더블 쿼테이션) ' (쿼테이션) css ( 선택해서 꾸며준다 ) <style> 선택자 { 속성:속성값; 속성:속성값; } <!-- #box { } // id선택자 --> </style> <body> <div></div> </body> 코딩 원칙 1. 가독성 <div></div> <div> <div></div> </div> <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>demo03</title> <style> #wrap { width:1000px; height:700px; background-color:red; } #header { width:900px; height:100px; background-color:blue; margin-left:50px; } #article { width:900px; height:400px; background-color:orange; margin-left:50px; margin-top:50px; } #footer { width:900px; height:70px; background-color:lime; margin-left:50px; margin-top:50px; } #leftsection { width:300px; height:300px; background-color:red; margin-top:50px; margin-left:50px; float:left; } #rightsection { width:300px; height:300px; background-color:black; margin-top:50px; margin-left:50px; float:left; } <!-- leftsection, rightsection 첫번째 것 부터 둘 다 float:left로 처리해줘야 같이 처리됨 --> </style> </head> <body> <div id="wrap"> <div id="header"></div> <div id="article"> <div id="leftsection"></div> <!-- margin 겹침현상 생길수 있음 --> <div id="rightsection"></div> </div> <div id="footer"></div> </div> </body> </html> 도형 한개 밑에 여러개 도형 있을 때 밑에 도형에 margin-top 여러번 넣는 것 보다 위에 도형에 margin-bottom 쓰는게 나음 margin 축약형 margin:위 오른 아래 왼; <!-- 값이 없으면 0px , 시계방향 --> margin:100px 200px 200px 100px; margin:100px 0px 0px 100px; <!-- 0일 때는 단위 생략 가능 --> margin:10px 50px 100px; <!-- 무조건 4번은 채워야함, 위(10px) 오른(50px) 아래(100px) 왼(50px) 순으로 앞 값을 참조 --> 4자리. margin : 위 오른쪽 아래쪽 왼쪽; 3자리. margin:위 오른쪽/왼쪽 아래쪽; 10px 50px 100px 50px 2자리. margin: 위/아래쪽 오른쪽/왼쪽(같이있는것); 10px 50px 10px 50px 브라우저의 중앙 값으로 알아서 맞춰짐 #box { width:700px; height:600px; background-color:red; margin-left: auto; margin-right:auto; } margin-left: auto; margin-right:auto =같음= margin:0 auto margin:100px auto 0 (위 오른 아래 왼) ``` <file_sep>/_htmlCss/A022 애플 페이지.md ``` @charset "utf-8"; /*reset */ body,div,p,h1,h2,h3,h4,ul,ol,li,dl,dt,dd,form,fieldset,input,button { margin:0; padding:0;} body,h1,h2,h3,h4,th,td,input,button{ font:12px/1.5 "맑은 고딕","돋움",dotum,sans-serif} ul,ol,li { list-style:none} img, fieldset{border:none; vertical-align:middle;} /* layout */ #wrap{ width:980px; margin:20px auto 0 auto} #header{ } #nav{} #mainContents{} #footer{} /* header */ /* nav */ .gnb{ width:816px; height:36px; float:left;} .gnb li{ float:left;} .gnb li a{ display:block; width:102px; height:36px; background:url(../img/globalnav.png) -102px 0;text-indent:-9999px; overflow:hidden} .gnb li.m1 a{ background-position:0 0} .gnb li a:hover{ background-position:-102px -72px} .gnb li.m1 a:hover{ background-position:0 -72px} .gnb li a:focus{ outline:none;} .gnb li a span{ display:block; height:100%; background:url(../img/globalnav_text.png) center 3px; } .gnb li.m1 a span{ background-position:center 3px} .gnb li.m2 a span{ background-position:center -27px} .gnb li.m3 a span{ background-position:center -57px} .gnb li.m4 a span{ background-position:center -87px} .gnb li.m5 a span{ background-position:center -117px} .gnb li.m6 a span{ background-position:center -147px} .gnb li.m7 a span{ background-position:center -177px} .gnb li.m8 a span{ background-position:center -207px} .search{ width:164px; height:36px; float:left; background:url(../img/globalsearch_bg.png) right top no-repeat;} .search #inputSch{ background:url(../img/globalsearch_field.png) no-repeat; width:110px; height:20px; border:none; padding:0 10px 0 20px; margin:8px 12px} .search #inputSch:focus { background-position:0 -20px; outline:none} 위 코딩은 외부 css 파일입니다. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=euc-kr" /> <title>navig-apple</title> <link href="css/common.css" type="text/css" rel="stylesheet" /> <link href="css/main.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="wrap"> <div id="header"> <div id="nav"> <ul class="gnb"> <li class="m1"><a href="#"><span>home</span></a></li> <li class="m2"><a href="#"><span>store</span></a></li> <li class="m3"><a href="#"><span>mac</span></a></li> <li class="m4"><a href="#"><span>ipod</span></a></li> <li class="m5"><a href="#"><span>iphone</span></a></li> <li class="m6"><a href="#"><span>ipad</span></a></li> <li class="m7"><a href="#"><span>itunes</span></a></li> <li class="m8"><a href="#"><span>support</span></a></li> </ul> <div class="search"> <form ation="#"> <input type="text" id="inputSch" /> </form> </div><!--// search --> </div><!--//nav--> </div><!--// header --> <div id="mainContents"> <div class="slide"> <div class="txt_box"> <h1 class="logo"><img src="img/ios_title_small.png" alt="IOS7-The mobile OS from a whole new perspective." /></h1> <p class="link"> <a href="#" class="l1">Watch the keynote</a> <a href="#" class="l2">Learn more</a> </p> </div><!--//txt_box--> <div class="view_img"> <img src="img/mainimg.jpg" alt="아이폰측면사진" /> </div><!--//view_img--> </div><!--//slide--> <div class="m_box"> <ul class="news"> <li><a href="#"><img src="img/news1.gif" alt="MacPro" /></a></li> <li><a href="#"><img src="img/news2.gif" alt="The new MacBook Air" /></a></li> <li><a href="#"><img src="img/news3.gif" alt="Designed by Apple in California" /></a></li> <li><a href="#"><img src="img/news4.gif" alt="Our college offer ends soon." /></a></li> </ul> <p class="privacy"><a href="#">Apple's Commitment to customer Privacy</a></p> </div><!--//m_box--> </div><!--//mainContents--> <div id="footer"> <p class="store">Shop the Apple Online Store (1-800-MY-APPLE), visit an Apple Retail Store, or find a reseller</p> <ul class="f_menu"> <li><a href="#">Site Map</a></li> <li><a href="#">Hot News</a></li> <li><a href="#">Media Info</a></li> <li><a href="#">Environment</a></li> <li><a href="#">Job Opportunities</a></li> <li><a href="#">Contact Us</a></li> </ul> <p class="copyright"> Copyright 2014 Apple Inc. All rights reserved. </p> <ul class="policy"> <li><a href="#">Terms of Use</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div><!--//footer--> </div><!--//wrap --> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>apple</title> <link href="css/common.css" type="text/css" rel="stylesheet" /> <link href="css/main.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="wrap"> <div id="header"> <div id="nav"> <ul class="gnb"> <li class="m1"><a href="#"><span>home</span></a></li> <li class="m2"><a href="#"><span>store</span></a></li> <li class="m3"><a href="#"><span>mac</span></a></li> <li class="m4"><a href="#"><span>ipod</span></a></li> <li class="m5"><a href="#"><span>iphone</span></a></li> <li class="m6"><a href="#"><span>ipad</span></a></li> <li class="m7"><a href="#"><span>itunes</span></a></li> <li class="m8"><a href="#"><span>support</span></a></li> </ul> <div class="search"> <form action="#"> <input type="text" id="inputSch" /> </form> </div><!--// search --> </div><!--//nav--> </div><!--// header --> <div id="mainContents" class="clearfix"> <div class="slide"> <div class="txt_box"> <h1 class="logo"><img src="img/ios_title_small.png" alt="IOS7-The mobile OS from a whole new perspective." width="286" height="167" /></h1> <p class="link"> <a href="#" class="l1">Watch the keynote</a> <a href="#" class="l2">Learn more</a> </p> </div><!--//txt_box--> <div class="view_img"> <img src="img/mainimg.jpg" alt="아이폰측면사진" width="666" height="454" /> </div><!--//view_img--> </div><!--//slide--> <div class="m_box"> <ul class="news"> <li><a href="#"><img src="img/news1.gif" alt="MacPro" width="244" height="174" /></a></li> <li><a href="#"><img src="img/news2.gif" alt="The new MacBook Air" /></a></li> <li><a href="#"><img src="img/news3.gif" alt="Designed by Apple in California" /></a></li> <li><a href="#"><img src="img/news4.gif" alt="Our college offer ends soon." /></a></li> </ul> <p class="privacy"><a href="#">Apple's Commitment to customer Privacy</a></p> </div><!--//m_box--> </div><!--//mainContents--> <div id="footer"> <p class="store">Shop the Apple Online Store (1-800-MY-APPLE), visit an Apple Retail Store, or find a reseller</p> <ul class="f_menu"> <li><a href="#">Site Map</a></li> <li><a href="#">Hot News</a></li> <li><a href="#">Media Info</a></li> <li><a href="#">Environment</a></li> <li><a href="#">Job Opportunities</a></li> <li><a href="#">Contact Us</a></li> </ul> <p class="copyright"> Copyright 2014 Apple Inc. All rights reserved. </p> <ul class="policy"> <li><a href="#">Terms of Use</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div><!--//footer--> </div><!--//wrap --> </body> </html> ``` ### 앱스토어 페이지, 로그인을 위한 페이지 만들기 ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>apple</title> <link href="css/common.css" type="text/css" rel="stylesheet" /> <link href="css/main.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="wrap"> <div id="header"> <div id="nav"> <ul class="gnb"> <li class="m1"><a href="#"><span>home</span></a></li> <li class="m2"><a href="#"><span>store</span></a></li> <li class="m3"><a href="#"><span>mac</span></a></li> <li class="m4"><a href="#"><span>ipod</span></a></li> <li class="m5"><a href="#"><span>iphone</span></a></li> <li class="m6"><a href="#"><span>ipad</span></a></li> <li class="m7"><a href="#"><span>itunes</span></a></li> <li class="m8"><a href="#"><span>support</span></a></li> </ul> <div class="search"> <form action="#"> <input type="text" id="inputSch" /> </form> </div><!--// search --> </div><!--//nav--> </div><!--// header --> <div id="mainContents" class="clearfix"> <div class="slide"> <div class="txt_box"> <h1 class="logo"><img src="img/ios_title_small.png" alt="IOS7-The mobile OS from a whole new perspective." width="286" height="167" /></h1> <p class="link"> <a href="#" class="l1">Watch the keynote</a> <a href="#" class="l2">Learn more</a> </p> </div><!--//txt_box--> <div class="view_img"> <img src="img/mainimg.jpg" alt="아이폰측면사진" width="666" height="454" /> </div><!--//view_img--> </div><!--//slide--> <div class="m_box"> <ul class="news"> <li><a href="#"><img src="img/news1.gif" alt="MacPro" width="244" height="174" /></a></li> <li><a href="#"><img src="img/news2.gif" alt="The new MacBook Air" /></a></li> <li><a href="#"><img src="img/news3.gif" alt="Designed by Apple in California" /></a></li> <li><a href="#"><img src="img/news4.gif" alt="Our college offer ends soon." /></a></li> </ul> <p class="privacy"><a href="#">Apple's Commitment to customer Privacy</a></p> </div><!--//m_box--> </div><!--//mainContents--> <div id="footer"> <p class="store">Shop the <a href="#">Apple Online Store</a> (1-800-MY-APPLE), visit an <a href="#">Apple Retail Store</a>, or find a <a href="#">reseller</a></p> <ul class="f_menu"> <li><a href="#">Site Map</a></li> <li><a href="#">Hot News</a></li> <li><a href="#">Media Info</a></li> <li><a href="#">Environment</a></li> <li><a href="#">Job Opportunities</a></li> <li><a href="#">Contact Us</a></li> </ul> <p class="copyright"> Copyright 2014 Apple Inc. All rights reserved. </p> <ul class="policy"> <li><a href="#">Terms of Use</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div><!--//footer--> </div><!--//wrap --> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>apple</title> <link href="css/common.css" type="text/css" rel="stylesheet" /> <link href="css/main.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="wrap"> <div id="header"> <div id="nav"> <ul class="gnb"> <li class="m1"><a href="#"><span>home</span></a></li> <li class="m2"><a href="#"><span>store</span></a></li> <li class="m3"><a href="#"><span>mac</span></a></li> <li class="m4"><a href="#"><span>ipod</span></a></li> <li class="m5"><a href="#"><span>iphone</span></a></li> <li class="m6"><a href="#"><span>ipad</span></a></li> <li class="m7"><a href="#"><span>itunes</span></a></li> <li class="m8"><a href="#"><span>support</span></a></li> </ul> <div class="search"> <form action="#"> <input type="text" id="inputSch" /> </form> </div><!--// search --> </div><!--//nav--> </div><!--// header --> <div id="contents"> login </div><!--//Contents--> <div id="footer"> <p class="store">Shop the <a href="#">Apple Online Store</a> (1-800-MY-APPLE), visit an <a href="#">Apple Retail Store</a>, or find a <a href="#">reseller</a></p> <ul class="f_menu"> <li><a href="#">Site Map</a></li> <li><a href="#">Hot News</a></li> <li><a href="#">Media Info</a></li> <li><a href="#">Environment</a></li> <li><a href="#">Job Opportunities</a></li> <li><a href="#">Contact Us</a></li> </ul> <p class="copyright"> Copyright 2014 Apple Inc. All rights reserved. </p> <ul class="policy"> <li><a href="#">Terms of Use</a></li> <li><a href="#">Privacy Policy</a></li> </ul> </div><!--//footer--> </div><!--//wrap --> </body> </html> ``` <file_sep>/KNOU.java.test/src/knou/test/awt/PulldownMenu3.java package knou.test.awt; import java.awt.Color; import java.awt.Frame; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; public class PulldownMenu3 { public static void main(String[] args) { Frame f = new Frame("Pulldown Menu"); MenuBar mb = new MenuBar(); Menu m = new Menu("Menu1"); m.add(new MenuItem("MenuItem1")); Menu sm = new Menu("SubMenu1"); sm.add(new MenuItem("SubMenuItem1")); sm.add(new MenuItem("SubMenuItem2")); m.add(sm); m.add(new MenuItem("MenuItem2")); mb.add(m); f.setMenuBar(mb); f.setSize(200, 200); f.setBackground(Color.white); f.setVisible(true); } } <file_sep>/_htmlCss/A020 form태그, fieldset, legend, label, input, button.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> *{ margin:0; padding:0} ul,ol,li { list-style:none} body,button,inputy { font:12px Arial, Helvetica, sans-serif} img, fieldset { border:none; vertical-align:top;} #searchBox{ margin:50px} legend{ display:none;} label, input, button{ float:left;} label {} input{ padding:5px; border:1px solid #999; width:150px; height:14px} button{ border:1px solid #999; height:26px; margin-left:-1px; width:40px} </style> </head> <body> <div id="searchBox"> <form action="#"> <fieldset> <legend>검색</legend> <label for="inputSch">search</label> <input type="text" id="inputSch" /> <button>찾기</button> </fieldset> </form> </div> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> *{ margin:0; padding:0} ul,ol,li { list-style:none} body,button,inputy { font:12px Arial, Helvetica, sans-serif} img, fieldset { border:none; vertical-align:top;} #searchBox{ margin:50px; width:270px;} .sch_line{ float:left; width:218px; border:1px solid} legend{ display:none;} label, input, button{ float:left;} label { display:block; width:50px; padding-top:14px; } .hidden { width:0; height:0; overflow:hidden; text-indent:-9999px; position:absolute; z-index:-1} input{ padding:5px;margin:5px 5px; border:none; width:150px; height:14px; background:none} button{ float:right; border:none; height:38px; margin-left:-1px; width:40px; outline:1px solid #666} </style> </head> <body> <div id="searchBox"> <form action="#"> <fieldset> <legend>검색</legend> <label for="inputSch" class="hidden">search</label> <div class="sch_line"> <input type="text" id="inputSch" /> <button>찾기</button> </div> </fieldset> </form> </div> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>navig-apple</title> <style type="text/css"> * { margin:0; padding:0;} ul,ol,li { list-style:none} #header{ width:980px; margin:20px auto 0 auto} .gnb{ width:816px; height:36px; float:left;} .gnb li{ float:left;} .gnb li a{ display:block; width:102px; height:36px; background:url(img/globalnav.png) -102px 0;text-indent:-9999px; overflow:hidden} .gnb li.m1 a{ background-position:0 0} .gnb li a:hover{ background-position:-102px -72px} .gnb li.m1 a:hover{ background-position:0 -72px} .gnb li a:focus{ outline:none;} .gnb li a span{ display:block; height:100%; background:url(img/globalnav_text.png) center 3px; } .gnb li.m1 a span{ background-position:center 3px} .gnb li.m2 a span{ background-position:center -27px} .gnb li.m3 a span{ background-position:center -57px} .gnb li.m4 a span{ background-position:center -87px} .gnb li.m5 a span{ background-position:center -117px} .gnb li.m6 a span{ background-position:center -147px} .gnb li.m7 a span{ background-position:center -177px} .gnb li.m8 a span{ background-position:center -207px} .search{ width:164px; height:36px; float:left; background:url(img/globalsearch_bg.png) right top no-repeat;} .search #inputSch{ background:url(img/globalsearch_field.png) no-repeat; width:110px; height:20px; border:none; padding:0 10px 0 20px; margin:8px 12px} .search #inputSch:focus { background-position:0 -20px; outline:none} </style> </head> <body> <div id="header"> <div id="nav"> <ul class="gnb"> <li class="m1"><a href="#"><span>home</span></a></li> <li class="m2"><a href="#"><span>store</span></a></li> <li class="m3"><a href="#"><span>mac</span></a></li> <li class="m4"><a href="#"><span>ipod</span></a></li> <li class="m5"><a href="#"><span>iphone</span></a></li> <li class="m6"><a href="#"><span>ipad</span></a></li> <li class="m7"><a href="#"><span>itunes</span></a></li> <li class="m8"><a href="#"><span>support</span></a></li> </ul> <div class="search"> <form ation="#"> <input type="text" id="inputSch" /> </form> </div> </div> </div> </body> </html> ``` <file_sep>/_jspServlet/A003 MemberUpdateServlet.md ## 서블릿 초기화 매개변수 ``` 서블릿 초기화 매개변수란 서블릿을 생성하고 초기화할 때 즉, init()를 호출할 때 서블릿 컨테이너가 전달하는 데이터이다. 보통 데이터베이스 연결 정보와 같은 정적인 데이터를 서블릿에 전달할 때 사용한다. 서블릿 초기화 매개변수는 DD파일(Web.xml)의 섭르릿 배치정보에 설정할 수 있고, 애노테이션을 사용하여 서블릿 소스 코드에 설정할 수 있다. 가능한 소스 코드에서 분리하여 외부 파일에 두는 것을 추천하는데 이는 외부 파일에 두면 변경하기 쉽기 때문이다. 실무에서도 데이터베이스 정보와 같은 시스템 환경과 관련된 정보는 외부 파일에 두어 관리한다. ``` ##회원 정보 조회와 변경## ``` 1. 웹 브라우저가 회원 목록을 요청(/member/list, GET 요청)한다. 2. MemberListServlet은 회원 목록을 웹 브라우저에 보낸다. 웹 브라우저는 회원목록을 출력한다. 3. 사용자가 회원 목록에서 이름을 클릭하면 회원 상세 정보를 요청 (/member/update, GET 요청) 한다. 4. MemberUpdateServlet은 회원 상세 정보를 웹 브라우저에 보낸다. 웹 브라우저는 회원 상세 정보를 출력. 5. 사용자가 회원 정보를 변경하고 저장을 클릭하면 회원 정보 변경을 요청(/member/update, POST 요청)한다. 6. MemberUpdateServlet은 회원 정보 변경 결과를 웹 브라우저에 보낸다. 웹 브라우저는 그 결과를 출력. ``` ##회원 목록 페이지에 상세 정보 링크 추가## ``` MemberListServlet 클래스에서 회원 이름 앞뒤로 <a> 태그를 추가한다. "<a href='update?no=" + rs.getInt("MNO") + "'>" + rs.getString("MNAME") + "</a>," 회원 상세 정보를 출력하는 서블릿의 URL은 '/member/update'로 할 것. 상세 정보를 조회하려면 회원 번호가 필요하므로 이 링크에 'no' 매개변수를 포함시킨다. ``` ##DD파일에 서블릿 초기화 매개변수 설정## ``` web.xml 파일에 MemberUpdateServlet의 서블릿 배치 정보를 작성한다. <servlet> <servlet-name>MemberUpdateServet</servlet-name> ... </servlet> ... 서블릿 초기화 매개변수를 설정하는 엘리먼트 <init-param> <param-name>매개변수 이름</param-name> <param-value>매개변수 값</param-value> </init-param> 매개변수의 값을 여러 개 설정하고 싶으면 <init-param> 엘리먼트를 여러개 작성하면 된다. 서블릿 초기화 매개변수들은 오직 그 매개변수를 선언한 서블릿에서만 사용할 수 있으며 다른 서블릿은 사용할 수 없다. DB 정보가 나중에 바뀌더라도 web.xml만 편집하면 되기 때문에 유지보수가 쉬워진다. ``` ``` 클래스 로딩 이전 방식 - DriverManager.registerDriver(new com.mysql.jdbc.Driver()); 유지보수가 쉬운 방식 - Class.forName( /* JDBC 드라이버 클래스의 이름 */ ) 서블릿 초기화 매개변수의 값 꺼내기 this.getInitParameter( /* 매개변수 이름 */ ) ``` <file_sep>/_java/A023 주민번호 유효성 검사.md ``` import java.util.Scanner; public class JuminCheck { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String check = "234567892345"; // 주민등록번호 검사 가중치 System.out.print("주민등록번호 13자리를 '-'없이 입력하세요 : "); String jumin = sc.nextLine(); // for(변수 = 초기치 ; 조건 ; 증감치) { // 실행할 문장; // ...; // } // 초기치를 조건과 비교해 조건을 만족하면 "{}" 블록의 내용을 실행한다. // 초기치를 받은 변수 값을 증감치 만큼 변경후 조건을 만족하면 "{}" 블록의 내용을 실행한다. // int j = jumin.charAt(0) - 48; // 야메 1호 // int c = check.charAt(0) - '0'; // 야메 2호 // System.out.println(j * c); int sum = 0; for(int i = 0 ; i<jumin.length()-1 ; i++) { // 자기 자신이 연산에 참여하는 변수는 반드시 초기화를 해야 한다. sum = sum + (jumin.charAt(i) - 48) * (check.charAt(i) - '0'); } // System.out.println(sum); // sum = sum % 11; // 11로 나눈 나머지를 구한다. // sum = 11 - sum; // 나머지를 11에서 뺀다. // sum = sum % 10; // 일의 자리만 취한다. // 위의 3줄을 1줄로 합치면 아래와 같다. sum = (11 - sum % 11) % 10; if(sum == jumin.charAt(12) - '0') { System.out.println("정상"); } else { System.out.println("오류"); } System.out.println(sum == jumin.charAt(12) - '0' ? "정상" : "오류"); } } ``` ``` import java.util.Scanner; public class JuminCheck1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("주민등록번호 13자리를 '-'없이 입력하세요 : "); String jumin = sc.nextLine(); int sum = 0; for(int i = 0 ; i<jumin.length()-1 ; i++) { // sum = sum + (jumin.charAt(i) - 48) * (i<8 ? i+2 : i-6); sum = sum + (jumin.charAt(i) - 48) * (i % 8 + 2); } sum = (11 - sum % 11) % 10; System.out.println(sum == jumin.charAt(12) - '0' ? "정상" : "오류"); } } ``` <file_sep>/_javascript/A007 click, mouseover 이벤트, 변수 연산.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>animation</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(function(){ $('#hide').click(function(){ $('img').hide(500,'linear') }) $('#show').click(function(){ $('img').show('slow') }) $('#slideDown').click(function(){ $('img').slideDown(1000,'linear') }) $('#slideUp').click(function(){ $('img').slideUp(1000,'linear') }) $('#fadeIn').click(function(){ $('img').fadeIn(1000) }) $('#fadeOut').click(function(){ $('img').fadeOut(1000) }) $('#fadeTo').click(function(){ $('img').fadeTo(1000,0) }) }) </script> </head> <body> <button id="show">show()</button> <button id="hide">hide()</button> <button id="slideDown">slideDown()</button> <button id="slideUp">slideUp()</button> <button id="fadeIn">fadeIn()</button> <button id="fadeOut">fadeOut()</button> <button id="fadeTo">fadeTo()</button> <p><img src="img/m2.jpg" width="123" height="179" /></p> 영화이미지 </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>show()-tabmenu</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ $('.panel li:not("#tab1")').hide() //$('.panel li:not(:first)').hide() $('.tab li a').mouseover(function(){ //$('#tab2').show() $('.panel li').hide() $($(this).attr('href')).show() $('.tab li a').removeClass('selected') $(this).addClass('selected') }) }) </script> <style> * { margin:0; padding:0} ul,ol,li { list-style:none} #nav{ margin:50px;width:300px;} .tab{ } .tab li{ float:left; width:100px; } .tab li a{ display:block; background-color:#666; color:#FFFFFF; font:12px/40px Arial, Helvetica, sans-serif; padding-left:16px; text-decoration:none;} .tab li a.selected{ background-color:#C00 !important} .tab li a:hover{ background-color:#333} .panel{ clear:both; display:block; background-color:#F5F5F5; height:150px} .panel li{ padding:10px;} </style> </head> <body> <div id="nav"> <ul class="tab"> <li><a href="#tab1" class="selected">tab1</a></li> <li><a href="#tab2">tab2</a></li> <li><a href="#tab3">tab3</a></li> </ul> <ul class="panel"> <li id="tab1"><a href="#">첫번째 내용</a></li> <li id="tab2"><a href="#">두번째 내용</a></li> <li id="tab3"><a href="#">세번째 내용</a></li> </ul> </div> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>변수1</title> <script> i = 100 j = parseInt('2') c = i + j document.write(c) </script> </head> <body> </body> </html> ``` <file_sep>/KNOU.java.test/src/knou/first/grade/JDBCTest.java package knou.first.grade; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCTest { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://locahlost/my_db", "root", "admin"); stmt = conn.createStatement(); rs = stmt.executeQuery("SELECT * FROM book"); System.out.println("제목\t\t저자\t가격"); while(rs.next()) { System.out.println(rs.getString("title")+"\t"); System.out.println(rs.getString("author")+"\t"); System.out.println(rs.getInt("price")+"\t"); } } catch(Exception ex) { System.out.println(ex); } finally { try { if(rs != null) rs.close(); if(stmt != null) stmt.close(); if(conn != null) conn.close(); } catch(SQLException ex) {} } } } <file_sep>/_java/A020 HelloJava.md ``` public class HelloJava { public static void main(String[] args) { System.out.print("안녕 \n자바"); System.out.println("안녕 자바"); System.out.println("5 + 3 = " + (5 + 3)); // "+"는 양쪽에 모두 숫자가 있을때는 덧셈, 그렇치 않으면 붙이기 System.out.println("5 - 3 = " + (5 - 3)); System.out.println("5 * 3 = " + 5 * 3); System.out.println("5 / 3 = " + 5 / 3); // 자바는 정수와 정수의 연산은 결과 값이 정수다. System.out.println("5 / 3 = " + (double)5 / 3); System.out.println("5 % 3 = " + 5 % 3); System.out.println("A + 32 = " + ('A' + 32)); System.out.println("A + 32 = " + (char)('A' + 32)); System.out.println("'0' * 2 = " + '0' * 2); } } ``` <file_sep>/_javascript/A011 animate 응용.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>animate</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ $('#left').click(function(){ var win_w = $(window).width()-10 if($('#left').css('width')=='150px'){ $('#left').stop().animate({width:win_w},1000) }else{ $('#left').stop().animate({width:150},1000) } }) }) </script> <style> * { margin:0; padding:0} html,body { height:100%} #left{ width:150px; background-color:red; height:100%} </style> </head> <body> <div id="left"></div> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>animate</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ var li_height = 40 var timeset = 100 $('#nav, #nav ul').css({height:li_height}) $('#nav ul li').css({lineHeight:li_height+'px'}) $('#nav ul').mouseover(function(){ slowtime= timeset*$('li',this).size() $(this).stop().animate({height: li_height* $('li',this).size()},slowtime) }).mouseout(function(){ $(this).stop().animate({height:li_height},'fast') }) }) </script> <style> * { margin:0; padding:0} ul,ol,li { list-style:none} #nav{ margin:50px; width:450px; } #nav ul{ float:left; width:150px; overflow:hidden; background-color:red} #nav ul li{ cursor:pointer; background-color:#CCC; padding-left:14px;} #nav ul li:hover { background-color:#999999} #nav ul li:first-child { background-color:#333333; color:#FFF} #nav ul li:first-child:hover { background-color:#F3F3F3; color:#333} </style> </head> <body> <div id="nav"> <ul> <li>menu1</li> <li>menu1-sub</li> <li>menu1-sub</li> <li>menu1-sub</li> <li>menu1-sub</li> </ul> <ul> <li>menu2</li> <li>menu2-sub</li> <li>menu2-sub</li> </ul> <ul> <li>menu3</li> <li>menu3-sub</li> <li>menu3-sub</li> <li>menu3-sub</li> <li>menu3-sub</li> <li>menu3-sub</li> <li>menu3-sub</li> </ul> </div> </body> </html> ``` <file_sep>/_java/A008 awt,swing의 이벤트(Dimension)와 layout.md ``` package com.me.window; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; // Frame 클래스를 상속받아 윈도우 만들기 public class WindowTest3 extends Frame { public WindowTest3() { this("이름이 없는 윈도우"); } public WindowTest3(String title) { this.setTitle(title); this.setBounds(800, 200, 300, 500); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { // System.exit(0); // 프로그램 강제 종료, 모든 창이 같이 닫힌다. dispose(); // 자원을 시스템에 반납한다. 현재 창만 닫힌다. 상속받아 사용할 때만 이용가능. } }); this.setVisible(true); } public static void main(String[] args) { // Frame 클래스나 JFrame 클래스를 상속받아 윈도우를 만들 경우는 자기 자신의 객체를 만들고 // 윈도우에 관련된 세부 설정은 생성자 메소드에서 한다. WindowTest3 win = new WindowTest3("이름이 있는 윈도우"); new WindowTest3(); } } ``` ``` package com.me.window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; // JFrame 클래스를 상속받아 윈도우 만들기 public class WindowTest4 extends JFrame { public WindowTest4() { this("이름이 없는 윈도우"); } public WindowTest4(String title) { this.setTitle(title); this.setBounds(800, 200, 300, 500); // setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 모든 윈도우가 닫힌다. // this.addWindowListener(new WindowAdapter() { // // @Override // public void windowClosing(WindowEvent arg0) { //// System.exit(0); // 프로그램 강제 종료, 모든 창이 같이 닫힌다. // dispose(); // 자원을 시스템에 반납한다. 현재 창만 닫힌다. 상속받아 사용할 때만 이용가능. // } // // }); this.setVisible(true); } public static void main(String[] args) { // Frame 클래스나 JFrame 클래스를 상속받아 윈도우를 만들 경우는 자기 자신의 객체를 만들고 // 윈도우에 관련된 세부 설정은 생성자 메소드에서 한다. WindowTest3 win = new WindowTest3("이름이 있는 윈도우"); new WindowTest3(); } } ``` ``` package com.me.window; import java.awt.Dimension; import java.awt.Frame; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class WindowTest5 extends Frame { // Dimension 클래스는 윈도우 또는 모니터의 크기를 기억하는 클래스이다. Dimension dimen1, dimen2; // dimen1 : 모니터 크기, dimen2 : 윈도우 크기 int xpos, ypos; // 윈도우의 시작 좌표 public WindowTest5() { this("이름이 없는 윈도우"); } public WindowTest5(String title) { this.setTitle(title); this.setSize(300, 500); // 모니터 크기(해상도)를 얻어 dimen1 변수에 저장한다. dimen1 = Toolkit.getDefaultToolkit().getScreenSize(); // getDefaultToolkit()은 static 메소드 System.out.println("모니터의 크기 : " + dimen1.width + " * " + dimen1.height); System.out.println("모니터의 크기 : " + dimen1.getWidth() + " * " + dimen1.getHeight()); setSize(new Dimension(350, 300)); // 프로그램 중간에서 윈도우 크기 변경 // 윈도우 크기를 얻어 dimen2 변수에 저장한다. dimen2 = this.getSize(); System.out.println("윈도우 크기 : " + dimen2.width + " * " + dimen2.height); System.out.println("윈도우 크기 : " + dimen2.getWidth() + " * " + dimen2.getHeight()); xpos = (dimen1.width/2) - (dimen2.width/2); ypos = (dimen1.height/2) - (dimen2.height/2); this.setLocation(xpos, ypos); // 모니터 중앙에 위치하게 만듬. this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent arg0) { // System.exit(0); dispose(); } }); this.setVisible(true); } public static void main(String[] args) { WindowTest5 win = new WindowTest5("이름이 있는 윈도우"); } } ``` ``` package com.me.layout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Frame; import java.awt.Label; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JLabel; import javax.swing.plaf.FontUIResource; public class FlowLayoutTest extends Frame{ Label lb1 = new Label("test1"); Label lb2 = new Label("test2"); Label lb3 = new Label("test3"); JLabel jl = new JLabel("테스트4"); public FlowLayoutTest(String title) { setTitle(title); setSize(400, 400); setLocation(800, 200); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); // FlowLayout은 컴포넌트(컨테이너 위에 올라가는 것)들을 프레임(윈도우)에 원래의 크기대로 차례차례 배치하는 레이아웃 매니저이다. FlowLayout flow = new FlowLayout(); // FlowLayout 객체를 생성한다. setLayout(flow); // FlowLayout을 프레임(컨테이너)에 적용한다. // 위의 2줄을 익명클래스로 setLayout(new FlowLayout()); 사용 가능 // FlowLayout의 컴포넌트 정렬방법, 기본 값은 가운데 정렬 // 왼쪽 : new FlowLayout(FlowLayout.LEFT); // 오른쪽 : new FlowLayout(FlowLayout.RIGHT); // 중앙 : new FlowLayout(FlowLayout.CENTER); - 기본값, 생략시 // 레이블 배경색 변경 lb1.setBackground(Color.RED); lb2.setBackground(Color.GREEN); lb3.setBackground(Color.BLUE); // JLabel 속성 변경 jl.setOpaque(true); // JLabel에 배경색을 넣으려면 이것을 먼저 해야함. jl.setBackground(Color.GRAY); // JLabel 배경색 변경 jl.setPreferredSize(new Dimension(300, 100)); // JLabel 크기 변경 jl.setForeground(Color.MAGENTA); // JLabel 글자색 변경 jl.setFont(new FontUIResource("궁서체", Font.BOLD, 50)); // JLabel 글꼴 변경, 한글 글꼴 가능 jl.setHorizontalAlignment(JLabel.CENTER); // JLabel 글자 수평 맞춤 // JLabel.LEFT(왼쪽) - 기본값, JLabel.CENTER(가운데), JLabel.RIGHT(오른쪽) jl.setVerticalAlignment(JLabel.TOP); // JLabel 글자 수직 맞춤 // JLabel.TOP(위쪽), JLabel.CENTER(중간) - 기본값, JLabel.BOTTOM(아래쪽) // 레이블 글자색(전경색) 변경 lb1.setForeground(Color.YELLOW); lb2.setForeground(Color.RED); lb3.setForeground(Color.GREEN); // 레이블 글꼴 변경 Font font = new Font("SansSerif", Font.BOLD, 30); // name : 글꼴이름, style : 글꼴모양, size : 글자크기 // 글꼴 이름 : Serif, SansSerif, Monospaced, Dialog, DialogInput 중에서 1개만 가능하다. // 글꼴 모양 : font.BOLD(굵게), font.ITALIC(기울임), font.PLAIN lb1.setFont(font); lb2.setFont(new Font("Dialog", Font.ITALIC, 45)); lb3.setFont(new Font("Monospaced", Font.PLAIN, 30)); // 레이블 글자 정렬 lb1.setAlignment(Label.LEFT); lb2.setAlignment(Label.CENTER); lb3.setAlignment(Label.RIGHT); // 프레임에 레이블(컴포넌트)을 추가한다. add(lb1); add(lb2); add(lb3); add(jl); // remove(lb2); // 프레임에서 컴포넌트를 제거한다. setVisible(true); } public static void main(String[] args){ new FlowLayoutTest("FlowLayoutTest"); } } ``` <file_sep>/_java/OOPS - Passing Argument, Parameter In Constructor.md ``` class Demo { // constructor with parameters Demo(int num1, int num2) { int addition; addition = num1 + num2; System.out.println("Addition of Numbers : "+addition); } public static void main(String args[]) { Demo p = new Demo(30, 40); } } ``` ##OUTPUT ``` Addition of Numbers : 70 ```<file_sep>/_javascript/BASIC - Writing to the Document.md ``` <!DOCTYPE html> <html> <body> <h1>JavaScript Example</h1> <script> document.write("<p>This is a paragraph</p>"); </script> </body> </html> ``` ##OUTPUT ``` JavaScript Example This is a paragraph ``` <!DOCTYPE html> <html> <body> <h1>JavaScript Example</h1> <script> document.write("<p>This is a paragraph</p>"); </script> </body> </html> <file_sep>/_javascript/BASIC - Using a Variable.md ``` <!DOCTYPE html> <html> <body> <script> var firstname; firstname = "Goku"; document.write(firstname); document.write("<br>"); firstname = "Krillin"; document.write(firstname); </script> <p>The script above declares a variable, assigns a value to it, displays the value, changes the value, and displays the value again.</p> </body> </html> ``` ##OUTPUT ``` Goku Krillin The script above declares a variable, assigns a value to it, displays the value, changes the value, and displays the value again. ```<file_sep>/_cpp/rand함수와 srand함수 활용해서 카드 섞기.md ``` #include <cstdio> #include <iostream> using namespace std; //난수를 사용(rand(), srand())하려면 Visual C++ 6.0은 반드시 stdlib.h를 포함시킨다. #include <stdlib.h> #include <ctime> // time() 함수를 사용하기 위한 헤더 파일 int main() { //난수를 그냥 발생시키면 항상 똑같은 값이 나오므로 반드시 초기화 작업을 해줘야한다. srand((unsigned int)time(NULL)); //for(int i=0 ; i<6 ; i++) { // cout << rand() % 45 + 1 << endl; //} //1. 추첨기를 준비한다. int lotto[45]; //2. 추첨기에 공을 넣는다. for(int i=0 ; i<45 ; i++) { lotto[i] = i + 1; } cout << "섞기전" << endl; for(int i=0 ; i<45 ; i++) { printf("%02d ", lotto[i]); if(i % 10 == 9) { cout << endl; // 1줄에 숫자 10개를 출력했으면 줄을 바꾼다. } } cout << endl; //3. 섞는다. //lotto[0]와 lotto[1]~[44] 중에서 랜덤한 위치와 값을 교환한다. for(int i=0 ; i<1000000 ; i++) { int r = rand() % 44 + 1; int temp = lotto[0]; lotto[0] = lotto[r]; lotto[r] = temp; } cout << "섞은후" << endl; for(int i=0 ; i<45 ; i++) { printf("%02d ", lotto[i]); if(i % 10 == 9) { cout << endl; // 1줄에 숫자 10개를 출력했으면 줄을 바꾼다. } } cout << endl; //4. 앞의 6개가 1등 번호, 7번째는 뽀나스 cout << "1등번호 : "; for(int i=0 ; i<6 ; i++) { cout << lotto[i] << " "; } cout << "뽀나스 : " << lotto[6] << endl; } ``` ``` #include <cstdio> #include <iostream> using namespace std; #include <stdlib.h> #include <ctime> int main() { srand((unsigned int)time(NULL)); //문자열 배열은 배열명 앞에 "*"를 붙여서 만든다. char *number[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; //for(int i=0 ; i<13 ; i++) { // cout << number[i] << endl; //} char *symbol[] = {"♠","◇","♥","♧"}; //for(int i=0 ; i<4 ; i++) { // cout << symbol[i] << endl; //} int card[52]; for(int i=0 ; i<52 ; i++) { card[i] = i; } cout << "섞기전" << endl; for(int i=0 ; i<52 ; i++) { printf("%s%2s ", symbol[card[i]/13], number[card[i]%13]); //if(i % 13 == 12) { if((i+1) % 13 == 0) { cout << endl; } } for(int i=0 ; i<1000000 ; i++) { int r = rand() % 51 + 1; int temp = card[0]; card[0] = card[r]; card[r] = temp; } cout << "섞은후" << endl; for(int i=0 ; i<52 ; i++) { printf("%s%2s ", symbol[card[i]/13], number[card[i]%13]); //if(i % 13 == 12) { if((i+1) % 13 == 0) { cout << endl; } } } ``` <file_sep>/_java/OOPS - Constructor.md ``` class Student { String student_name; public Student(String student_name) { this.student_name = student_name; } public String getName() { return student_name; } } public class ConstructorTest { public static void main(String args[]) { Student t = new Student("<NAME>"); System.out.println(t.student_name); System.out.println(t.getName()); } } ``` ## OUTPUT ``` <NAME> <NAME> ```<file_sep>/_java/A002 tip.md ``` ★자바, JSP, 서블릿, SPRING 등등의 동강 http://wiz.center/ 카테고리 -> software_development (161)에 있습니다. 안드로이드 원하시면 자바 -> 안드로이드 순으로 공부하시고, 웹 원하시면 자바 -> HTML5&CSS3 -> JSP 순으로 공부하는 것을 추천합니다! 유튜브에서 다운로드하는 기능. http://www.youtube.com/wizcenterseoul 에 목록 쫙 나옴 유튜브 들어가면 https://www.youtube.com/watch?v=6KoBEYBjki4 동영상 주소에서 https://www.ssyoutube.com/watch?v=6KoBEYBjki4 ssyoutube 으로 바꿔주면 다운로드 가능 320p 로 받으면 27Gb 나옴 (컴퓨터로 보는게 나을듯) ``` <file_sep>/_jspServlet/A013 javabean-returnTHIS-returnINSTANCE.md 셋터 메서드의 리턴 타입이 void가 아니라 인스턴스를 반환하면, 셋터 메서드를 연속으로 호출하여 값을 설정할 수 있다. ``` ex) public class Ex { protected String title; protected int no; public Ex setTitle(String title) { this.title = title; // 단순 셋터 return this; // Ex를 반환(연결고리) } public Ex setNo(int no) { this.no = no; // 단순 셋터 return this; // Ex를 반환(연결고리) } } ``` 이렇게 있다고 가정하고 두개 셋터를 호출할 때, ``` 보통의 경우) ~~~ Ex.setTitle ~~~ ; ~~~ Ex.setNo ~~~ ; 연결고리의 경우) ~~~ Ex.setTitle.setNo ~~~ ; 라인수를 줄일 수 있다. ``` <file_sep>/_java/PATTERN - Number Pattern 8.md ``` import java.util.Scanner; public class Pattern { public static void main(String args[]) { int n,i,j; Scanner sc=new Scanner(System.in); System.out.println("Enter the number of rows "); n = sc.nextInt(); for(i=1;i<=n;i++) { for(j=i;j<=n;j++) { if(i%2==0) System.out.print("0"); else System.out.print("1"); } System.out.println(); } } } ``` ##OUTPUT ``` Enter the number of rows 5 11111 0000 111 00 1 ```<file_sep>/_java/A012 카드 섞기, 경주 애니메이션.md ``` package com.me.animationtest; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Panel; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Random; public class AnimationTest2 extends Panel implements Runnable{ Image img; // 카드 이미지를 저장할 변수 int w = 1027 / 13, h = 615 / 5; // 카드 1장의 크기를 변수에 저장 int[] card = new int[52]; // 카드를 섞는 기능을 할 배열 Random ran = new Random(); // 카드 섞기에 사용할 랜덤 객체 생성 public AnimationTest2(){ // 카드 이미지를 읽어서 img 변수에 저장 String filename = "./src/images/cards.png"; img = Toolkit.getDefaultToolkit().getImage(filename); // 카드 넣기, card[0]~card[51]에 0~51의 숫자를 넣는다. for(int i=0; i<=51; i++){ card[i] = i; } // alt + shift + t 눌러서 Extract Method로 카드섞는 부분을 메소드로 만들어줌(alt + shift + M) swap(); // 카드를 섞어주는 메소드 호출 } private void swap() { // 카드 섞기, card[0]와 card[1]~[51] 번째 중 랜덤한 위치와 값을 교환한다. for(int i=0; i<=1000; i++){ int r = ran.nextInt(51) + 1; // 랜덤으로 섞을 위치 결정 int temp = card[0]; // 카드 섞기 card[0] = card[r]; card[r] = temp;; } } public static void main(String[] args) { Frame win = new Frame("카드 섞기"); win.setSize(1045, 530); win.setLocation(500, 200); win.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e){ System.exit(0); } }); AnimationTest2 g = new AnimationTest2(); Thread thread = new Thread(g); thread.start(); win.add(g); win.setVisible(true); } @Override public void paint(Graphics g) { // 그래픽 구현 for(int i=0; i<52 ; i++){ g.drawImage(img, (i%13)*w, (i/13)*h, (i%13+1)*w, (i/13+1)*h, (card[i]%13)*w, (card[i]/13)*h, (card[i]%13+1)*w, (card[i]/13+1)*h, this); } } @Override public void run() { // 스레드(움직임) 구현 while(true){ try { Thread.sleep(1000); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } swap(); repaint(); } } } /* 이해를 돕기 위한 쉬운 버전 import java.util.Random; public class CardNumber { public static void main(String[] args) { int card[] = new int[52]; String number[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; String symbol[] = {"♠","◇","♥","♧"}; System.out.println("섞기전 ======================================"); for(int i=0 ; i<52 ; i++) { card[i] = i; } for(int i=0 ; i<52 ; i++) { System.out.printf("%s%2s ", symbol[card[i]/13], number[card[i]%13]); if((i+1) % 13 == 0) { System.out.println(); } } System.out.println("섞은후 ======================================"); Random ran = new Random(); for(int i=0 ; i<1000 ; i++) { int r = ran.nextInt(51) + 1; int temp = card[0]; card[0] = card[r]; card[r] = temp; } for(int i=0 ; i<52 ; i++) { System.out.printf("%s%2s ", symbol[card[i]/13], number[card[i]%13]); if((i+1) % 13 == 0) { System.out.println(); } } } } */ ``` ``` package com.me.animationtest; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Panel; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.Random; public class AnimationTest3 extends Panel implements Runnable{ Image img1; // 배경 이미지를 저장할 변수 Image img2; // 우주선 이미지를 저장할 변수 int w = 488 / 4, h = 65; // 우주선 이미지 크기를 설정 int count = 0; // 우주선 이미지의 출력 순서 변경에 사용 int x1 = 50; // 우주선의 x좌표 int x2 = 50, x3 = 50; // Random ran = new Random(); // ran.nextInt(10) + 1; 로 사용가능 public AnimationTest3(){ // 별도의 이미지는 생성자에서 바로 하는게 좋음 // img1에 배경 이미지를 img2에 우주선 이미지를 읽어 저장한다. String filename = "./src/images/bg.png"; img1 = Toolkit.getDefaultToolkit().getImage(filename); filename = "./src/images/ship.png"; img2 = Toolkit.getDefaultToolkit().getImage(filename); } public static void main(String[] args) { Frame win = new Frame("우주선 애니메이션"); win.setBounds(300, 300, 736, 358); win.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e){ System.exit(0); } }); AnimationTest3 g = new AnimationTest3(); Thread thread = new Thread(g); thread.start(); win.add(g); win.setVisible(true); } @Override public void paint(Graphics g) { // 그래픽 구현 // 나중에 넣은 이미지가 위로 올라온다. g.drawImage(img1, 0, 0, this); // 프레임에 배경 이미지 표시 g.drawImage(img2, x1, 20, w+x1, h+20, count*w, 0, (count+1)*w, h, this); // 프레임에 우주선 표시 g.drawImage(img2, x2, 120, w+x2, h+120, count*w, 0, (count+1)*w, h, this); // 프레임에 우주선 표시 g.drawImage(img2, x3, 220, w+x3, h+220, count*w, 0, (count+1)*w, h, this); // 프레임에 우주선 표시 } @Override public void run() { // 스레드(움직임) 구현 // count를 이용해서 제자리 애니메이션 구현 while(true){ x1 = x1 + (int)(Math.random()*25)+3; x2 = x2 + (int)(Math.random()*40)+3; x3 = x3 + (int)(Math.random()*30)+3; if(x1 > 700) x1 = -200; if(x2 > 700) x2 = -200; if(x3 > 700) x3 = -200; if(++count==4) count=0; try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } repaint(); } } } ``` <file_sep>/_java/A000 상속관계 이해.md ``` package com.me.inheritancetest; public class InheritanceTest1 { public static void main(String[] args) { Parent parent1 = new Parent("홍길동", true); System.out.println(parent1); Parent parent2 = new Parent("홍길동", false); System.out.println(parent2); // Child 클래스에 toString 없지만 Parent에서 상속받음 Child child1 = new Child("임꺽정", true); System.out.println(child1); Child child2 = new Child("임꺽숙", false, 20, "꺽숙이"); System.out.println(child2); } } package com.me.inheritancetest; // 부모(상위, 슈퍼, 기반) 클래스 (ctrl + T 누르면 상속관계 나옴) public class Parent { // private String name; // private boolean gender; // protected : 부모(현재) 클래스와 부모 클래스를 상속받은 자식 클래스에서만 접근이 가능하다. // 상속 관계가 있는 클래스는 private 대신 protected로 멤버 변수의 접근 권한을 지정한다. protected String name; protected boolean gender; // super(); 를 적지않아도 자바에서 자동으로 처리 (Object의 경우) // alt+shift+s(우클릭+Source)에서 Construction에서 자동생성 가능 public Parent() { } public Parent(String name, boolean gender) { this.name = name; this.gender = gender; } // alt+shift+s(우클릭+Source)에서 getters and setters에서 자동생성 가능 public String getName() { return name; } public void setName(String name) { this.name = name; } // boolean의 경우 is를 붙힘 public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } // System.out.println(parent); 를 처리하기 위한 toString 오버라이드 @Override public String toString() { return "부모(Parent) 클래스의 toString() : " + name + "(" + (gender ? "남" : "여") + ")"; } } package com.me.inheritancetest; // 자식(하위, 서브, 파생) 클래스 public class Child extends Parent{ // 부모(Parent) 클래스의 멤버 변수 name, gender, getter & setter 메소드 // 생성자 메소드, toString() 메소드를 상속받았다. // 부모 클래스의 private 멤버인 name, gender에 초기치를 전달하기 위해 부모 클래스의 생성자 메소드 // 개수 만큼 자식 클래스의 생성자 메소드를 만든다. private int age; private String neckName; public Child() { // 부모 클래스의 Parent() 생성자 메소드를 호출한다. // 지워도 상관없음. (Child의 Object 상속을 처리) super(); } public Child(String name, boolean gender) { // 부모 클래스의 Parent(String name, boolean gender) 생성자 메소드를 호출한다. // 부모 클래스의 private 멤버에 부모 클래스의 생성자 메소드를 통해 초기치를 입력한다. super(name, gender); // super대신 아래처럼 써도 됨. // 부모 클래스의 private 멤버에 부모 클래스의 setter 메소드를 통해 초기치를 입력한다. // setName(name); // setGender(gender); } // 부모 클래스와 자식 클래스의 모든 멤버 변수에 초기치를 전달하는 생성자 메소드를 만든다. public Child(String name, boolean gender, int age, String neckName) { // super(name, gender); // setName(name); // setGender(gender); // 위 super와 setter (private 일 때 사용)가 this 사용한 것과 같음 (protected이기 때문에 가능) this.name = name; this.gender = gender; this.age = age; this.neckName = neckName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getNeckName() { return neckName; } public void setNeckName(String neckName) { this.neckName = neckName; } // 부모 클래스의 name과 gender는 private 멤버이기 때문에 getter와 setter를 이용 // super.getName() 으로 사용해도 가능(public의 getName을 상속받았기 때문에 super 안써도됨) // protected로 바꿀경우 getter 쓸 필요없이 name으로 사용가능 @Override public String toString() { if(age == 0) { // 나이가 넘어오지 않으면 부모 클래스의 toString() 메소드를 실행한다. return super.toString(); } else { // 나이가 넘어왔으면 자식 클래스의 toString() 메소드를 실행한다. return "자식(Child) 클래스의 toString() : " + getName() + "(" + (isGender() ? "남" : "여") + ") -" + age + ", " + neckName; // return super.toString() + " - " + age + ", " + neckName; } } } ``` <file_sep>/_java/COLLECTION - PriorityQueue Class.md ``` import java.util.Iterator; import java.util.PriorityQueue; public class PriorityQueueTest { public static void main(String[] args) { PriorityQueue<String> queue=new PriorityQueue<String>(); queue.add("java"); queue.add("android"); queue.add("php"); queue.add("c++"); queue.add("css"); queue.add("javascript"); queue.add("python"); queue.add("ajax"); queue.offer("jquery"); //using iterator Iterator itr=queue.iterator(); while(itr.hasNext()) { System.out.print(itr.next()+" "); } System.out.println(); //Retrieves, but does not remove, the head of this queue //throws Exception if Queue is empty System.out.println("head:"+queue.element()); //Retrieves, but does not remove, the head of this queue System.out.println("head:"+queue.peek()); //Retrieves and removes the head of this queue //throws Exception if Queue is empty queue.remove(); //Retrieves and removes the head of this queue queue.poll(); //remove specific value queue.remove("css"); System.out.println("Queue After remove and poll operation:"+queue); System.out.println("Is python is present :"+queue.contains("python")); Object a[]=queue.toArray(); for (Object object : a) { System.out.print(object+" "); } System.out.println(); queue.clear(); System.out.println(queue+" queue size :"+queue.size()); } } ``` ##OUTPUT ``` ajax android javascript c++ css php python java jquery head:ajax head:ajax Queue After remove and poll operation:[c++, java, javascript, python, jquery, php] Is python is present :true c++ java javascript python jquery php [] queue size :0 ```<file_sep>/KNOU.java.test/src/knou/test/awt/Test02.java package knou.test.awt; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; class MyFrame2 extends Frame { public MyFrame2(String title) { super(title); this.setSize(400, 300); this.setVisible(true); // 이벤트 리스너 구현 WindowListener xListener = new WindowAdapter() { public void windowClosing(WindowEvent ev) { System.exit(0); } }; // 이벤트 리스너 등록 this.addWindowListener(xListener); } public void paint(Graphics g) { g.drawString("Hello AWT", 150, 150); } } public class Test02 { public static void main(String[] args) { MyFrame2 myFrame = new MyFrame2("Hello AWT"); } } <file_sep>/_java/OOPS - Polymorphism Method Overriding.md ``` class SuperClass { void display() { System.out.println("Hello Superclass "); } } class Polymorphism extends SuperClass { void display() { System.out.println("Hello Subclass "); } public static void main(String args[]) { //This is called upcasting SuperClass s = new Polymorphism(); s.display(); } } ``` ##OUTPUT ``` Hello Subclass ```<file_sep>/_cpp/외부 함수 오버로딩.md ``` #include <cstdio> #include <iostream> using namespace std; // 외부 함수의 형식 // 함수의리턴타입 함수명([인수, ...]) { // 함수의 머리 // 함수가 실행할 명령; // 함수의 몸체 // ...; // [return 값;] // return이 생략되면 함수의 리턴 타입은 void가 된다. // } // 같은 이름을 가지는 함수가 여러 개 나올수 있다. 이 경우에는 인수의 개수 개수도 같다면 인수의 형태로 // 함수를 구분한다. ==> 함수의 오버로딩 // 컴파일러에게 total은 리턴 타입이 정수형이고 인수가 없는 함수임을 알려준다. int total(); // total() 함수의 원형 정의 // 컴파일러에게 total은 리턴 타입이 정수형이고 인수가 정수형 1개인 함수임을 알려준다. int total(int); // int total(int n) 함수의 원형 정의 int main() { cout << total() << endl; // total() 함수를 호출한다. int n; cout << "합계를 계산할 숫자 : "; cin >> n; cout << total(n) << endl; // total(int n) 함수를 호출한다. cout << "main() 함수의 n : " << n << endl; } // main() 함수보다 아래에서 함수를 정의할 경우 오류가 발생된다. 이를 해결하려면 main() 함수 앞에 함수의 원형을 // 정의해 줘야 한다. int total() { // 1 에서 100 까지의 합계를 계산하는 함수 int sum = 0; for(int i=1 ; i<=100 ; i++) { sum += i; } return sum; // 리턴 값을 가지고 함수를 호출한 곳으로 돌아간다. } // call by value(값에 의한 호출) // 함수는 함수를 호출하는 곳에서 실인수의 값을 복사해서 가인수에 넣어준다. // 실인수와 가인수는 이름은 같던 다르던 상관 없지만 데이터 타입은 반드시 같아야 한다. // 리턴은 생략하거나 리턴되는 값을 무조건 1개만 가능하다. int total(int n) { // 1 에서 n 까지의 합계를 계산하는 함수 int sum = 0; for(int i=1 ; i<=n ; i++) { sum += i; } n = 12345; cout << "total() 함수의 n : " << n << endl; return sum; // 리턴 값을 가지고 함수를 호출한 곳으로 돌아간다. } ``` ``` #include <cstdio> #include <iostream> using namespace std; int total() { int sum = 0; for(int i=1 ; i<=100 ; i++) { sum += i; } return sum; } int total(int n) { int sum = 0; for(int i=1 ; i<=n ; i++) { sum += i; } n = 12345; cout << "total() 함수의 n : " << n << endl; return sum; } int main() { cout << total() << endl; int n; cout << "합계를 계산할 숫자 : "; cin >> n; cout << total(n) << endl; cout << "main() 함수의 n : " << n << endl; } ``` <file_sep>/_java/A037 ArrayList,StringTokenizer(메모만들기).md ``` import java.util.Scanner; public class MemoProject { // ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ // ★ static 메소드는 static 메소드나 static 변수만 참조할 수 있다. 접근이 가능하다. ★ // ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ // ★★★ 여러 메소드에서 사용해야 할 변수는 반드시 멤버로 만들어 줘야한다. ★★★ static MemoList list = new MemoList(); public static void main(String[] args) { Scanner sc = new Scanner(System.in); int menu = 0; while(menu != 7) { // 1, 2, 3, 4, 5, 6, 7 이외의 메뉴가 선택되면 재입력을 받는다. do { System.out.println("==============================================================="); System.out.println(" 1.쓰기 2.목록보기 3.수정 4.삭제 5. 저장 6.열기 7.종료 "); System.out.println("==============================================================="); System.out.print("원하는 작업을 선택하세요 : "); menu = sc.nextInt(); } while(menu < 1 || menu > 7); // 여기 ";"쫌 빼먹지 말자 // 입력받은 메뉴에 해당되는 메소드를 실행한다. switch(menu) { case 1: write(); break; case 2: view(); break; case 3: update(); break; case 4: delete(); break; case 5: fileWrite(); break; case 6: fileRead(); break; } } // while(menu != 5) 반복 범위 System.out.println("프로그램을 종료합니다. 바이바이~~~~"); } // 텍스트 파일의 내용일 읽어서 ArrayList로 저장하는 메소드 private static void fileRead() { // 읽어들일 텍스트 파일의 이름을 입력받는다. Scanner sc = new Scanner(System.in); System.out.print("입력 파일명 : "); String fileName = sc.nextLine(); // 입력받은 파일명의 파일을 읽어서 ArrayList로 저장하는 메소드를 실행한다. list.fileRead(fileName); } // ArrayList의 내용을 텍스트 파일로 저장하는 메소드 private static void fileWrite() { // ArrayList의 내용을 출력할 텍스트 파일의 이름을 입력받는다. Scanner sc = new Scanner(System.in); System.out.print("출력 파일명 : "); String fileName = sc.nextLine(); // 입력받은 파일명으로 ArrayList에 저장된 메모를 텍스트 파일에 저장하는 메소드를 실행한다. list.fileWrite(fileName); } // 수정할 글 번호를 입력받아 수정할 글을 화면에 보여주고 비밀번호와 메모를 입력받아 메모를 수정하는 메소드 private static void update() { Scanner sc = new Scanner(System.in); System.out.println("메모 수정"); System.out.print("수정할 글 번호 : "); int no = sc.nextInt(); // 수정할 글 번호 입력 // MemoList 클래스의 ArrayList에서 수정할 글을 꺼내서 화면에 보여준다. MemoVO original = list.getMemo(no-1); if(original == null) { System.out.println(no + "번 글은 존재하지 않습니다."); } else { System.out.println("수정할 글 확인"); System.out.println(original); System.out.print("비밀번호 : "); sc.nextLine(); // 키보드 버퍼를 비운다. String password = sc.nextLine().trim(); System.out.print("메모 : "); String memo = sc.nextLine().trim(); // 입력받은 비밀번호(password)와 ArrayList에 저장된 원본 글의 비밀번호를 비교해 같으면 글을 // 수정하는 메소드를 실행한다. // MemoVO m = new MemoVO(original.getName(), password, memo); // list.updateMemo(no-1, m); list.updateMemo(no-1, new MemoVO(original.getName(), password, memo)); } } // 삭제할 글 번호를 입력받아 삭제할 글을 화면에 보여주고 비밀번호를 입력받아 메모를 삭제하는 메소드 private static void delete() { Scanner sc = new Scanner(System.in); System.out.println("메모 삭제"); System.out.print("삭제할 글 번호 : "); int no = sc.nextInt(); // 삭제할 글 번호 입력 // MemoList 클래스의 ArrayList에서 삭제할 글을 꺼내서 화면에 보여준다. MemoVO original = list.getMemo(no-1); if(original == null) { System.out.println(no + "번 글은 존재하지 않습니다."); } else { System.out.println("삭제할 글 확인"); System.out.println(original); System.out.print("비밀번호 : "); sc.nextLine(); // 키보드 버퍼를 비운다. String password = sc.nextLine().trim(); // 입력받은 비밀번호(password)와 ArrayList에 저장된 원본 글의 비밀번호를 비교해 같으면 글을 // 삭제하는 메소드를 실행한다. list.deleteMemo(no-1, password); } } // ArrayList에 저장된 메모를 화면에 출력하는 메소드 private static void view() { System.out.println(list); } // 키보드로 이름, 비밀번호, 메모를 입력받아 MemoList 클래스의 ArrayList에 저장하는 메소드 private static void write() { Scanner sc = new Scanner(System.in); System.out.println("메모 입력"); System.out.print("이름 : "); String name = sc.nextLine().trim(); // 이름 입력 System.out.print("비밀번호 : "); String password = sc.nextLine().trim(); // 비밀번호 입력 System.out.print("메모 : "); String memo = sc.nextLine().trim(); // 메모 입력 // 입력받은 내용으로 MemoVO 클래스의 객체를 만들고 ArrayList에 저장한다. // MemoVO m = new MemoVO(name, password, memo); // list.appendMemo(m); // 위의 2줄을 1줄로 사용하면 아래와 같다. list.appendMemo(new MemoVO(name, password, memo)); System.out.println("저장 완료"); } } import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Scanner; // 여러건의 메모(MemoVO 클래스)를 기억할 클래스 public class MemoList { // 멤버 변수 ArrayList<MemoVO> list = new ArrayList<MemoVO>(); // getter & setter 메소드 // 수정 또는 삭제할 글 1개를 얻어오는 메소드 public MemoVO getMemo(int no) { try { return list.get(no); } catch(IndexOutOfBoundsException e) { return null; } } // ArrayList에 메모를 저장하는 메소드 public void appendMemo(MemoVO memo) { list.add(memo); } // toString() 메소드 override @Override public String toString() { String str = ""; str += "================================================\n"; str += " 번호 이름 비밀번호 메모 작성일\n"; str += "================================================\n"; if(list.size() != 0) { // for(MemoVO memo : list) { // str += memo + "\n"; // } for(int i=list.size()-1 ; i>=0 ; i--) { // ArrayList는 중간의 데이터가 삭제되면 삭제된 데이터 이후의 데이터를 한 칸씩 앞으로 당긴다. // 삭제 작업이 실행된 경우 ArrayList의 index와 글번호를 맞춰준다. list.get(i).setNo(i + 1); str += list.get(i) + "\n"; } } else { str += "메모가 없습니다.\n"; } str += "================================================"; return str; } // ArrayList에 메모를 삭제하는 메소드 public void deleteMemo(int no, String password) { // 넘겨받은 비밀번호(password)와 삭제할 글의 비밀번호(list.get(no).getPassword())를 비교해 같으면 // 메모를 삭제하고 다르면 비밀번호가 일치하지 않는다는 메시지를 출력한다. if(password.equals(list.get(no).getPassword())) { list.remove(no); System.out.println("삭제 완료"); } else { System.out.println("비밀번호가 올바르지 않습니다."); } } // ArrayList에 메모를 수정하는 메소드 public void updateMemo(int no, MemoVO m) { // 넘겨받은 비밀번호(m.getPassword())와 삭제할 글의 비밀번호(list.get(no).getPassword())를 비교해 // 같으면 메모를 삭제하고 다르면 비밀번호가 일치하지 않는다는 메시지를 출력한다. if(m.getPassword().equals(list.get(no).getPassword())) { list.set(no, m); System.out.println("수정 완료"); } else { System.out.println("비밀번호가 올바르지 않습니다."); } } // ArrayList의 내용을 파일로 저장하는 메소드 public void fileWrite(String fileName) { // 텍스트 파일로 출력하는 PrintWriter를 만든다. PrintWriter pw = null; SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); // String file = "./src/com/me/memoproject/" + fileName + ".txt"; String file = String.format("./src/com/me/memoproject/%s.txt", fileName); try { pw = new PrintWriter(file); // 출력 파일 열기 for(MemoVO m : list) { String str = ""; str += m.getNo() + " "; str += m.getName() + " "; str += m.getPassword() + " "; str += m.getMemo() + " "; str += sdf.format(m.getWriteDate()) + "\r\n"; pw.write(str); } System.out.println("파일로 출력 완료"); } catch(FileNotFoundException e) { System.out.println("파일 없다."); } finally { // 출력 파일 닫기 try { if(pw != null) pw.close(); } catch(Exception e) { } } } // 텍스트 파일의 내용을 ArrayList에 저장하는 메소드 public void fileRead(String fileName) { // 텍스트 파일에서 읽어들이는 스캐너를 만든다. Scanner sc = null; String file = String.format("./src/com/me/memoproject/%s.txt", fileName); try { sc = new Scanner(new File(file)); // 입력 파일 열기 // 텍스트 파일에 읽어들일 줄이 있는 동안 반복한다. while(sc.hasNextLine()) { // 텍스트 파일에서 한 줄을 읽어들인다. String str = sc.nextLine(); // 문자열 변수(str)의 내용을 읽어들이는 스캐너를 만든다. Scanner scan = new Scanner(str); int no = scan.nextInt(); // 번호를 읽어들인다. String name = scan.next(); // 이름을 읽어들인다. String password = scan.next(); // 비밀번호를 읽어들인다. String memo = scan.next(); // 메모를 읽어들인다. String writeDate = scan.next(); // 작성일을 읽어들인다. // 읽어들인 내용으로 메모 1건(MemoVO 클래스)의 객체를 만들어 ArrayList에 넣어준다. // MemoVO m = new MemoVO(no, name, password, memo, writeDate); // list.add(m); list.add(new MemoVO(no, name, password, memo, writeDate)); } System.out.println(fileName + ".txt에서 읽기 완료"); } catch(FileNotFoundException e) { System.out.println("입력 파일이 없습니다."); } finally { try { if(sc != null) sc.close(); } catch(Exception e) { } } } } import java.text.SimpleDateFormat; import java.util.Date; // 1건의 메모를 기억할 클래스 public class MemoVO { // 멤버 변수 private static int count; // 글번호 자동증가 private int no; // 글번호 private String name; // 이름 private String password; // 비밀번호 private String memo; // 메모 private Date writeDate; // 작성일(자동입력) // 생성자 메소드 public MemoVO() { } // 키보드로 이름, 비밀번호, 메모를 입력받아 객체를 생성하는 생성자 메소드 public MemoVO(String name, String password, String memo) { no = ++count; // 글번호 자동증가 this.name = name; this.password = <PASSWORD>; this.memo = memo; writeDate = new Date(); // 작성일 자동입력 } // 텍스트 파일에서 읽어들인 번호, 이름, 비밀번호, 메모, 작성일 입력받아 객체를 생성하는 생성자 메소드 // 텍스트 파일에는 날짜 형태의 데이터를 저장시킬 수 없으므로 텍스트 파일에 저장된 날짜를 일단 문자열로 // 읽어오기 위해서 writeDate의 데이터 타입을 String으로 변경한다. public MemoVO(int no, String name, String password, String memo, String writeDate) { this.no = no; this.name = name; this.password = <PASSWORD>; this.memo = memo; // 넘겨받은 문자열에서 필요한 부분을 얻어내 날짜 데이터로 만들어 넣어준다. // substring(a, b) : 문자열에서 a번째 문자부터 b-1번째 문자까지 얻어온다. int yy = Integer.parseInt(writeDate.substring(0, 4)) - 1900; int mm = Integer.parseInt(writeDate.substring(5, 7)) - 1; int dd = Integer.parseInt(writeDate.substring(8, 10)); this.writeDate = new Date(yy, mm, dd); } // getter & setter 메소드 public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public Date getWriteDate() { return writeDate; } public void setWriteDate(Date writeDate) { this.writeDate = writeDate; } // toString() 메소드 override @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd"); return String.format("%d %s %s %s %s", no, name, password, memo, sdf.format(writeDate)); } } ``` ``` /* --- 다른 내용의 클래스 --- */ import java.util.StringTokenizer; public class StringTokenTest { public static void main(String[] args) { // 문자열이 spacebar, tab키로 구분 String str1 = "사과 배 복숭아 밤 대추"; // StringTokenizer는 특정 구분자를 이용해 문자열을 분리한다. // 별도로 구분자를 지정하지 않으면 spacebar, tab키가 기본 구분자가 된다. StringTokenizer st1 = new StringTokenizer(str1); // 다음 토큰이 있는 동안 반복하며 토큰으로 분리한다. // st1.hasMoreTokens() : 다음 토큰이 있는가? // 다음 토큰이 있으면 true, 없으면 false를 리턴한다. while(st1.hasMoreTokens()) { // nextToken() : 다음 토큰을 얻어온다. System.out.println(st1.nextToken()); } System.out.println("============================================"); // 문자열이 ","로 구분 String str2 = "사과,배,복숭아,밤,대추"; // StringTokenizer 생성자의 2번째 인수로 구분자를 지정할 수 있다. StringTokenizer st2 = new StringTokenizer(str2, ","); while(st2.hasMoreTokens()) { System.out.println(st2.nextToken()); } System.out.println("============================================"); // 문자열이 ","와 "."로 구분 String str3 = "사과,배.복숭아,밤.대추"; // StringTokenizer 생성자의 2번째 인수로 구분자를 여러개 지정할 수 있다. StringTokenizer st3 = new StringTokenizer(str3, ",."); while(st3.hasMoreTokens()) { System.out.println(st3.nextToken()); } System.out.println("============================================"); // 문자열이 "="와 ","로 구분 String str4 = "사과=100,배=200,복숭아=300,밤=400,대추=500"; // StringTokenizer 생성자의 3번째 인수로 구분자를 토큰에 포함 여부를 지정할 수 있다. // 생략시(false) 구분자를 토큰에 포함시키지 않고 true를 적으면 토큰에 포함시킨다. StringTokenizer st4 = new StringTokenizer(str4, "=,", true); while(st4.hasMoreTokens()) { String str = st4.nextToken(); if(str.equals("=")) { System.out.print("("); } else if(str.equals(",")) { System.out.println("원)"); } else { System.out.print(str); } } System.out.println("원)"); } } ``` <file_sep>/_java/A014 WindowListener 더블 버퍼링.md ``` package com.me.animationtest; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Panel; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class AnimationTest6 extends Panel implements Runnable { Image img[] = new Image[10]; // 이미지를 저장할 배열 int w = 55, h = 68; // 이미지의 크기 int count = 0; // 이미지의 출력 순서 변경에 사용 int x = 50, y = 50; // 이미지가 표시될 좌표 // 생성자에서 이미지를 읽어 배열에 저장 public AnimationTest6() { for(int i=1 ; i<=img.length ; i++) { String filename = String.format("./src/images/Duke%02d.gif", i); img[i-1] = Toolkit.getDefaultToolkit().getImage(filename); } } @Override public void paint(Graphics g) { g.drawImage(img[count], x, y, this); } @Override public void run() { while(true) { x++; if(++count == 10) { count = 0; } try { Thread.sleep(100); } catch (InterruptedException e) { } repaint(); } } public static void main(String[] args) { Frame win = new Frame("손흔드는 펭귄"); win.setBounds(100, 100, 720, 320); win.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); AnimationTest6 ani = new AnimationTest6(); win.add(ani); win.setVisible(true); new Thread(ani).start(); } } ``` ``` package com.me.animationtest; import java.awt.Canvas; import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class AnimationTest7 extends Frame implements Runnable { Image img[] = new Image[10]; int w = 55, h = 68, x = 50, y = 50; // 프레임에 표시할 그래픽을 메모리에서 미리 그려서 저장해 놓을 변수를 만든다. Image buffer, bg; // buffer에 저장된 이미지를 표시할 캔버스를 선언한다. Canvas can; public AnimationTest7() { String filename = "./src/images/bg.png"; bg = Toolkit.getDefaultToolkit().getImage(filename); for(int i=1 ; i<=img.length ; i++) { filename = String.format("./src/images/Duke%02d.gif", i); img[i-1] = Toolkit.getDefaultToolkit().getImage(filename); } setTitle("손흔드는 펭귄 더블 버퍼링"); setBounds(100, 100, 720, 320); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); add(can = new Canvas() { @Override // 캔버스에 그림 그리기 public void paint(Graphics g) { g.drawImage(buffer, 0, 0, this); } @Override // 업데이트시 화면을 지우지 않고 다시 그리기 public void update(Graphics g) { paint(g); } }); setVisible(true); } public static void main(String[] args) { AnimationTest7 ani = new AnimationTest7(); new Thread(ani).start(); } @Override public void run() { // 프레임의 크기와 동일한 이미지를 생성한다. buffer = createImage(can.getWidth(), can.getHeight()); // 이미지의 그래픽 객체를 만든다. Graphics buffer_g = buffer.getGraphics(); while(true) { for(int i=0 ; i<img.length ; i++) { if(++x >= 720) x = -55; try { Thread.sleep(1); } catch (InterruptedException e) { } // 메모리 상에서 그리기 작업을 한다. buffer_g.setColor(Color.WHITE); buffer_g.fillRect(0, 0, 720, 320); // buffer_g.drawImage(bg, 0, 0, this); buffer_g.drawImage(img[i], x, y, this); // 화면을 다시 그려라 can.repaint(); } } } } ``` ``` package com.me.eventtest; import java.awt.Frame; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class EventTest01 extends Frame implements WindowListener { public EventTest01() { setTitle("WindowListener를 구현해 윈도우 닫기"); setBounds(100, 100, 720, 320); // 현재 클래스가 직접 WindowListener를 구현하므로 this이다. addWindowListener(this); setVisible(true); } public static void main(String[] args) { EventTest01 win = new EventTest01(); } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { dispose(); } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } } ``` ``` package com.me.eventtest; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Frame;import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class EventTest02 extends Frame { Button btn1 = new Button("눌렀냐"); public EventTest02() { setTitle("버튼에 ActionListener 걸기"); setBounds(100, 100, 720, 320); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { dispose(); } }); btn1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("눌렀냐~~~~ 아프자나~~~~"); new EventTest02(); } }); add(btn1); setVisible(true); } public static void main(String[] args) { EventTest02 win = new EventTest02(); } } ``` <file_sep>/_java/OOPS - Method Overriding.md ``` class A { void display() { System.out.println("A"); } } class B extends A { void display() { System.out.println("B"); } } class C extends A { void display() { System.out.println("C"); } } public class MethodOverridingTest { public static void main(String[] args) { A a = new A(); B b = new B(); C c = new C(); a.display(); b.display(); c.display(); } } ``` ##OUTPUT ``` A B C ```<file_sep>/_java/EXCEPTION HANDLING - Divide by zero.md ``` import java.util.Scanner; class DivisionByZero { public static void main(String[] args) { int a, b, result; Scanner input = new Scanner(System.in); System.out.println("Input two integers"); a = input.nextInt(); b = input.nextInt(); // try block try { result = a / b; System.out.println("Result = " + result); } // catch block catch (ArithmeticException e) { System.out.println("Exception caught: Division by zero."); } } } ``` ##OUTPUT ``` Input two integers 3 0 Exception caught: Division by zero ```<file_sep>/_java/A026 카드 섞기, 로또 생성.md ``` import java.util.Random; public class CardNumber { public static void main(String[] args) { int card[] = new int[52]; String number[] = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; String symbol[] = {"♠","◇","♥","♧"}; System.out.println("섞기전 ======================================"); for(int i=0 ; i<52 ; i++) { card[i] = i; } for(int i=0 ; i<52 ; i++) { System.out.printf("%s%2s ", symbol[card[i]/13], number[card[i]%13]); if((i+1) % 13 == 0) { System.out.println(); } } System.out.println("섞은후 ======================================"); Random ran = new Random(); for(int i=0 ; i<1000 ; i++) { int r = ran.nextInt(51) + 1; int temp = card[0]; card[0] = card[r]; card[r] = temp; } for(int i=0 ; i<52 ; i++) { System.out.printf("%s%2s ", symbol[card[i]/13], number[card[i]%13]); if((i+1) % 13 == 0) { System.out.println(); } } } } ``` ``` import java.util.Random; public class LottoNumber { public static void main(String[] args) { // 1. 추첨기를 준비한다.(배열) int lotto[] = new int[45]; // 2. 추첨기에 공을 넣는다. for(int i=0 ; i<45 ; i++) { lotto[i] = i + 1; } // for(int i=0 ; i<45 ; i++) { // System.out.printf("출력 서식", 출력할 내용); // 출력 서식 문자 : d(정수), f(실수), c(문자), s(문자열) // 출력 서식의 형식 : %[-][0][n][.m]서식문자 // [-] : 왼쪽으로 맞춰 출력 // [0] : 남는 자리에 0을 출력 // [n] : 전체 자리수 // [.m] : 소수점 아래 자리수 // System.out.printf("%2d ", lotto[i]); // System.out.print(String.format("%2d ", lotto[i])); // if((i+1) % 10 == 0) { // System.out.println(); // } // } // 3. 섞는다. Random ran = new Random(); for(int i=0 ; i<1000000 ; i++) { int r = ran.nextInt(44) + 1; int temp = lotto[0]; lotto[0] = lotto[r]; lotto[r] = temp; } for(int i=0 ; i<45 ; i++) { System.out.printf("%2d ", lotto[i]); if((i+1) % 10 == 0) { System.out.println(); } } // 4. 앞의 숫자 6개가 1등 번호, 7번째 숫자는 뽀나스 System.out.print("\n1등 번호 : "); for(int i=0 ; i<6 ; i++) { System.out.printf("%2d ", lotto[i]); try { // 프로그램을 지정된 시간동안 멈춘다. Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("뽀나스 : " + lotto[6]); } } ``` <file_sep>/_htmlCss/A015 in-line 태그 이해.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>navigation1</title> <style type="text/css"> * { margin:0; padding:0} ul,ol,li { list-style:none;} .gnb { margin:50px; width:200px;} .gnb li{ display:block; line-height:27px; border-bottom:1px solid #666} .gnb li a{ color:#06C; text-decoration:none; display:block; background:url(img/arr1.png) no-repeat 0 9px; padding-left:20px; } .gnb li a:hover { color:#FF6600; background-color:#FFFF99; /*padding-left:30px;*/ background-position:0 -10px;} </style> </head> <body> <ul class="gnb"> <li><a href="#">HOME</a></li> <li><a href="#">PROFILE</a></li> <li><a href="#">PORTFOLIO</a></li> <li><a href="#">GALLERY</a></li> <li><a href="#">BOARD</a></li> </ul> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>navigation1</title> <style type="text/css"> * { margin:0; padding:0} ul,ol,li { list-style:none;} .gnb { margin:50px; width:750px;} .gnb li{ display:block; line-height:40px; float:left;} .gnb li a{color:#666; text-decoration:none; display:block; width:150px; text-align:center; border-bottom:1px solid #ddd; border-top:1px solid #F0F0F0} .gnb li a:hover { background:url(img/arr2.png) no-repeat center bottom; background-color:#F2F2F2; border-bottom-color: #bfbdbd; color:#333; font-weight:bold} </style> </head> <body> <ul class="gnb"> <li><a href="#">HOME</a></li> <li><a href="#">PROFILE</a></li> <li><a href="#">PORTFOLIO</a></li> <li><a href="#">GALLERY</a></li> <li><a href="#">BOARD</a></li> </ul> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>navi- inline</title> <style type="text/css"> *{ margin:0; padding:0 } ul,ol,li { list-style:none} .top_menu{ margin:50px; display:block; overflow:hidden;} .top_menu li{ display:inline; /*display:inline-block;*/ padding:0 9px 0 11px; background:url(img/more.png) no-repeat left center ; white-space:nowrap; margin-left:-2px;} .top_menu li a{ text-decoration:none; color:#666666} .top_menu li a:hover{ text-decoration:underline; color:#000} </style> </head> <body> <ul class="top_menu"> <li><a href="#">MENU1</a></li> <li><a href="#">MENU2</a></li> <li><a href="#">MENU3</a></li> <li><a href="#">MENU4</a></li> </ul> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> <style type="text/css"> div{ border:1px solid #000; margin:10px; width:500px;} .div1 { white-space:normal;} .div2 { white-space:nowrap;} .div3 { white-space:pre} .div4 { white-space:pre-line} </style> </head> <body> white-space:noraml <div class="div1"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> white-space:nowrap <div class="div2"> Lorem Ipsum is simply dummy text of the printing and typesetting industry.<br /> Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> white-space:pre <div class="div3"> Lorem Ipsum is simply dummy text of the printing and typesetting industry.<br /> Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> white-space:pre-line <div class="div4"> Lorem Ipsum is simply dummy text of the printing and typesetting industry.<br /> Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </div> </body> </html> ``` <file_sep>/_htmlCss/A009 form과 제로보드, 그누보드, XE보드.md ``` ★외우기 1. div : 큰 영역을 나누는 것 2. h1~h6 : 제목 처리하는 사각형(용도가 있음) 3. p : 글의 문단처리 사각형, 작고 외톨이형 사각형(홈페이지 우측하단에 있는 TOP버튼 처럼) 4. ul li : 작으면서, 2개 이상의 비슷한 사각형 5. dl dt dd : 등급이 다른 사각형을 2개 이상 만들 때 a 링크 img 이미지 span inline에서 글자부분 수정 strong inline에서 특정부분 bold처리(웹표준) ``` ``` ★외우기 1. div : 큰 영역을 나누는 것 2. h1~h6 : 제목 처리하는 사각형(용도가 있음) 3. p : 글의 문단처리 사각형, 작고 외톨이형 사각형(홈페이지 우측하단에 있는 TOP버튼 처럼) 4. ul li : 작으면서, 2개 이상의 비슷한 사각형 5. dl dt dd : 등급이 다른 사각형을 2개 이상 만들 때 a 링크 img 이미지 span inline에서 글자부분 수정 strong inline에서 특정부분 bold처리(웹표준) ``` ``` style- #header ul li#li01 {margin-left:0;} body- <li id="li01">home</li> 하나하나 이름주기 번거롭다면 첫번째 선택자에 first-child를 넣어주면 됩니다. #header ul li:first-child {margin-left:0;} li의 first-child를 선택하여 수정. 첫번째만 first로 선택가능. 그 외에는 이름값을 주어야함. <ul></ul, <ol></ol> 똑같이 사용, 똑같은 <li> 들어감 2개일 땐 ol 사용해도 좋음. 이름 넣어주는게 편함 ul은 쩜이 들어가고 ol은 숫자과 들어감 ul과 ol 초기화 (똑같음) ul li, ol li{list-style:none;} -----------------------특별한 경우 ( 특별한 사각형이 필요 ) 선택자 { position:absolute; } absolute-특별한 사각형으로 취급 안썼으면 static으로 기본 처리 { position:static; width:100px; height:100px; } *margin : 간격 조절하지 않는다. top / left / right / bottom : 위치 조절 (일반적인 경우에 사용안함) float / clear 값이 없다. layer 가 존재한다. (층을 조절할 수 있음) ( z-index:1; ) z-index:2~수만까지 가능; #box { position:absolute; width:500px; height:500px; background-color:red; z-index:2;} #box02 { position:absolute; width:500px; height:500px; background-color:blue; left:200px; top:200px; z-index:1;} - 사각형과 사각형이 겹쳐 있을 때? #box { position:absolute; width:500px; height:500px; background-color:red; } #box02 { position:absolute; width:500px; height:500px; background-color:blue; left:200px; top:200px; } 나중에 그린 blue가 위에 겹쳐짐 ( 포지션이 스태틱일 경우 위아래 두개 그려짐) left:200px; top:200px; right, bottom 으로 값을 줄 수 있음.(margin값이랑 비슷) 일반적인 경우는 위치가 먼저 그려진 사각형에서 마진값이 들어갔는데 특별한 경우는 위치가 0 by 0 에서부터 값을 가짐 - 상하좌우 정중앙 배치? - 높이 값이 %값을 가질 때? #box { position:absolute; width:100%; height:50%; background-color:red; } - 기준이 없는 사각형안에서 위치 맞출 때(ex:배경에 둥둥 떠있는 사각형) -----------------------일반적인 경우 ( 일반적인 사각형 position:static; (생략가능) ) ``` ``` position:static; 생략가능 ( 일반적인 사각형 ) position:absolute; ( 특별한 사각형 ) position:fixed; ( 고정형 사각형 - 헤더바 고정 ) 화면이 스크롤 되어도 움직이지 않는 사각형 position:relative; -style #wrap { width:1000px; height:5000px; background-color:orange; } #header { position:fixed; width:900px; height:70px; background-color:blue; } -body <div id="wrap"> <div id="header"></div> </div> 1000 x 5000 사각형 안에 있는 900 x 70 사각형이 스크롤 되어도 고정 됨. 특별한 사각형에서 left값 50%를 주고 margin-left:부모사각형의 반px; 를주면 부모 사각형 옆에 붙어서 화면에 반응하여 중앙에 위치 부모사각형이 위에 붙어있으면 top을 줘도 되지만 떨어져있을 경우 기준잡기 애매하기 때문에 부모를 기준으로 margin값을 준다. #box { position:absolute; width:700px; height:600px; background-color:red; left:50%; top:50%;} ★사각형의 왼쪽 상단 꼭지점이 브라우저의 중앙으로 위치한다. 꼭지점을 이동시켜줘야 도형이 중앙으로 이동 #box { position:absolute; width:700px; height:600px; background-color:red; left:50%; top:50%; margin-left:-350px; margin-top:-300px;} margin-left, margin-top 값을 줘야함 (margin-top값 유의) 기준이 없는 사각형안에서 위치 맞출 때 : 중앙에서 맞추는 경우에만 쓰면 됨. <style> * {margin:0; padding:0;} #box { position:absolute; width:700px; height:600px; background-color:red; left:50%; top:50%; margin-left:-350px; margin-top:-300px;} // 굳이 left, top으로 %값을 주지않아도 되는 간단한 것은 부모와의 거리를 재서 margin값 주기 #box #small { position:absolute; width:400px; height:400px; background-color:orange; margin-left:150px; margin-top:100px;} #box #qmenu01 { position:absolute; width:100px; height:300px; background-color:blue; left:50%; margin-left:350px;} #box #qmenu02 { position:absolute; width:100px; height:300px; background-color:black; margin-left:-100px; } #box #qmenu03 { position:absolute; width:100px; height:100px; background-color:blue; bottom:0; left:50%; margin-left:450px;} </style> <body> <div id="box"> <div id="small"></div> <div id="qmenu01"></div> <div id="qmenu02"></div> <div id="qmenu03"></div> </div> </body> 위아래 같은 코드 (상속없는게 더 나음) <style> * {margin:0; padding:0;} #box { position:absolute; width:700px; height:600px; background-color:red; left:50%; top:50%; margin-left:-350px; margin-top:-300px;} #box #small { position:absolute; width:400px; height:400px; background-color:orange; margin-left:150px; margin-top:100px;} #qmenu01 { position:absolute; width:100px; height:300px; background-color:blue; left:50%; top:50%; margin-top:-300px; margin-left:350px;} #qmenu02 { position:absolute; width:100px; height:300px; background-color:blue; left:50%; top:50%; margin-top:-300px; margin-left:-450px;} #topbtn { position:absolute; width:100px; height:100px; background-color:blue; left:50%; top:50%; margin-left:450px; margin-top:200px;} </style> <body> <div id="box"> <div id="small"></div> </div> <div id="qmenu01"></div> <div id="qmenu02"></div> <div id="topbtn"></div> </body> position:relative; 관계형-> absolute와 관계를 잘 맺기 위해. 부모가 float값을 갖거나 그러면 absolute를 가질 수 없기 때문에 relative. position:relative; -> absolute 사각형의 기준을 만들어 줘야 할 때. 보통의 홈페이지는 일반적인 경우를 80% 특별한 경우를 20% 정도 사용 position:absolute, relative. 최대한 일반적인 경우를 이용 overflow:hidden; 부모에게 주면 삐져나간 부분을 가려줌 자식에다가 글을 썼는데 도형을 넘어가면 자식에다가 overflow:hidden ``` ``` 선택자 1. id 2. class 3. tag 4. 종속선택자 ( #header h1 ) 5. 멀티선택자 ( #header, h1, h2, h3 ) 6. 자식선택자 ( > ) 7. 인접선택자 ( + ) 8. 형제선택자 ( ~ ) #box h1 ~ { } <div id="box"> <h1></h1> <p></p> <p></p> <h3></h3> <h4></h4> </div> ----- 쇼핑몰 제작 - 솔루션 구매 ( 50~ 300 ) - 쇼핑몰 사이트 이용 ( 월 5만원~ ) 1. 카페24 ( www.cafe24.com ) -> 쇼핑몰 개설 - 카페24쇼핑몰만들기. 2. 메이크샵 3. 고도몰 - 순수 제작 ( 500 ~ ----- ftp 호스팅 ( 닷홈 www.dothome.co.kr ) - 상업적인 용도 - 3G 신청.. - 트래픽 내 홈페이지 전체 파일 용량(50M) x 사람수 = 트래픽 (3,000) design365.dothome.co.kr ftp주소 : design365.dothome.co.kr id: pwd: <EMAIL> index.html 0. 저장 ( 호스팅 ) 1. 박스그리기 body ( div,h1~h6,p, ul li, ol li, dl dt dd, a, img, span, strong ) 2. 선택자 ( id, class ... > ~ + ) 3. 박스꾸미기 ( width, height, margin, padding... ) 4. 박스에 다른 요소 넣기 1. 다른 박스 2. 이미지 body <img src=" " alt="" /> css ( 배경 ) background-image:url( ); background-positin:가로 세로; background-repeat:no-repeat; 3. 글자 ( font-size..... ) 5. 특별한 경우에 박스 그리기 ( position:absolute, position:fixed, position:relative ) 6. table 7. form ------ 종속(자손) 선택자 ul#ul01 li { } 자식 선택자 > ul#ul01 > li ul#ul02 li ul#ul02 > li ul#ul01 > li:first-child { } ul#ul01 > li:first-child { } <ul id="ul01"> <li></li> <li></li> <li></li> </ul> 사각형 만들고 - 사각형 - 이미지 - 글자 - 표 - 폼 테이블 - 틀 만들 때 x - 표 만들 때 0 table tr ( table row ) 줄 th ( table header) 제목 칸 td ( table data) 데이터 칸 테이블 > 줄(rows) > 칸(column) colspan="?" : 칸 합치기 (합쳐진 칸 수) rowspan="?" : 줄 합치기 ``` ``` 웹디자인 책추천 : 크리에이티브 디자이너를 위한 웹표준 - 웹표준 핵심가이드북 - 기초심화 table은 틀 만들때도 사용됬는데 이제는 사용금지 : 표 만들때만 사용 <table> <tr> <th></th> <th></th> </tr> <tr> <td></td> <td></td> </tr> </table> th 두개면 td도 두개. (정신건강에 좋음) th나 td만 선을 가지고있음 (tr은 가지고 있지 않다. table { border:1px solid silver; width:600px; height:600px; } table tr th { border:1px solid blue; background-color:silver; } table tr td { border:1px solid red; background-color:orange; } table tr td.td03 { border:1px solid red; background-color:lime; } (class는 . 으로 연결하는듯) <table> <tr> <th>학생</th> <th>이름</th> </tr> <tr> <td>01</td> <td>홍길동</td> </tr> <tr> <td class="td03">02</td> <td class="td03">전우치</td> </tr> </table> table 부모의 역할 tr이 자식의 역할 <table cellspacing="0"> 테이블과 칸이 가지고 있는 간격을 0으로 조절 </table> <table cellspacing="0" cellpadding="20"> 칸안에 있는 간격을 조절 </table> table 고유 속성 style - td에서 따로 속성을 조절 할 수도 있다 cellpadding도 padding의 특성을 따라감(칸이 같이 늘어남) <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style> table { border-top:2px solid black; border-right:1px solid black; width:898px; height:178px; } table tr td { border-left:1px solid red; border-bottom:1px solid red; text-align:center; } table tr td.bline{ border-bottom:2px solid red; } table tr td.rline{ border-left:2px dotted red; } table tr td#hanaline{ border-left:none; } </style> </head> <body> <table cellspacing="0"> <tr> <td rowspan="3" class="bline" id="hanaline">하나투어</td> // 선 3개를 합병(이하 td에는 td추가 불필요) <td class="rline">ARS상담</td> <td>상세메뉴</td> </tr> <tr> <td class="rline">해외여행</td> <td>패키지</td> </tr> <tr> <td class="bline rline">자유여행</td> // 클래스 두개로 그룹만듬 <td class="bline">에어텔</td> </tr> </table> </body> </html> 사각형에 들어가는 요소 - 사각형 - 이미지 - 글자 - 테이블(표) - 폼 (회원가입 양식이 폼) 1. <input type="text"> maxlength="숫자" : 글자 수 제한 2. password 3. checkbox 4. radio ( 같은 요소는 name값을 똑같이 한다 ) 5. textarea 글쓰는 창 (시작과 끝이 있는 마크업 태그) 6. select -> option 선택창(리스트 형식으로) <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style> input#myid { width:300px; height:50px; } </style> </head> <body> <input type="text" id="myid" maxlength="10"/> <input type="password" id="mypwd" maxlength="8"/> <input type="checkbox"/> 남자<input type="radio" name="people"/> 여자<input type="radio" name="people"/> // 같은 "name"값을 양자택일 하는 기능 <textarea></textarea> <select> <option>2000년</option> <option>1970년</option> </select> </body> </html> ``` ``` <form> input type="text" maxlength="12" 한줄짜리 텍스트 받는 것. (최대 글자수를 조절 가능) input type="password" maxlength="10" 암호 입력받는 텍스트 (최대 글자수를 조절 가능) input type="checkbox" (복수 선택가능) input type="radio" name="people" (양자택일 같은 name으로 묶어서 다자택일 가능) input type="file" <textarea></textarea> (여러줄의 글자를 입력할 때 사용하는 form 태그) <select> <option>~~~~년</option> <option>~~~~년</option> </select> (옵션값을 가지고 있는 선택 태그) <label></label> <input type="file" /> (파일 선택 할 수 있는 태그) </form>(폼태그 안에 들어가줘야함, 프로그래머가 처리하는 부분) <form><input type="file" /></form> #loginid label { width:80px; display:block; float:left;} #loginpwd label { width:80px; display:block; float:left;} <li id="loginid"> <label>아이디</label><input type="text"/> </li> <li id="loginpwd"> <label>비밀번호</label><input type="password"/> </li> form태그는 라벨처리해서 글자를 감싸준다. <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style> * { margin:0; padding:0; } ul li { list-style:none; } #login { width:946px; font-size:12px; margin:100px auto; } #sectionleft { width:494px; float:left; } h3 { margin-bottom:21px; } #loginid label { width:106px; float:left; margin-top:12px; } #loginid input { width:349px; height:38px; } #loginpwd label { width:106px; float:left; margin-top:12px; } #loginpwd input { width:349px; height:38px; } #logbtn { margin-left:106px; margin-bottom:12px; } .marginb { margin-bottom:21px; } #submenu li { float:left; } p { float:left; margin-left:106px; margin-right:59px; } #submenu li:after { content:"|"; margin-left:10px; margin-right:10px; } #submenu li#none:after { content:""; } #sectionright { margin-top:44px; float:left; } </style> </head> <body> <div id="login"> <div id="sectionleft"> <h3><image src="img/log1.jpg"></h3> <ul> <li id="loginid" class="marginb"><label>아이디</label><input id="idpart" type="text" maxlength="10"></li> <li id="loginpwd" class="marginb"><label>비밀번호</label><input id="pwdpart" type="password" maxlength="10"></li> <li id="logbtn"><img src="img/log3.jpg"></li> <li> <ul id="submenu"> <p><input type="checkbox"><label>아이디기억</label></p> <li>회원가입</li> <li>아이디 찾기</li> <li id="none">비밀번호 찾기</li> </ul> </li> </ul> </div> <div id="sectionright"><image src="img/log2.jpg"></div> </div> </body> </html> ---밑에는 내가 한것● <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>login</title> <style> * { margin:0; padding:0; } ul li {list-style:none;} #login { width:1008px; height:278px; margin:100px auto; border:1px solid silver;} #login #sectionleft { width:455px; float:left; border:1px solid red; margin:30px 0 0; padding-left:25px;} #login #sectionright{ width:500px; float:left; border:1px solid red; margin:70px 0 0; } #login #sectionleft tr td.btm {border-right:1px solid silver; float:left; } #login #sectionleft tr td#idmemory {border-right:none;} #login #sectionleft tr td#pwd {border-right:none;} #loginid label { width:80px; display:block; float:left;} #loginid input { width:349px; height: 40px; margin-bottom:20px;} #loginpwd input { width:349px; height: 40px; margin-bottom:20px; } #loginpwd label { width:80px; display:block; float:left;} #btmsection img{ margin-left:80px; } </style> </head> <body> <div id="login"> <div id="sectionleft"> <h3>LOGIN</h3> <ul> <li id="loginid"> <label>아이디</label><input type="text"/> </li> <li id="loginpwd"> <label>비밀번호</label><input type="password"/> </li> <li id="btmsection"> <img src="img/login.jpg" alt="로그인" /> <table> <tr> <td class="btm" id="idmemory"> <input type="checkbox" />아이디기억 </td> <td class="btm"> 회원가입 </td> <td class="btm"> 아이디찾기 </td> <td class="btm" id="pwd"> 비밀번호찾기 </td> </tr> </table> </li> </ul> </div> <div id="sectionright"> <img src="img/rightimg.jpg" alt="오른쪽이미지" /> </div> </div> </body> </html> html 태그 안에 style이나 form 적용하는 것 - 내부 CSS 한개의 경우엔 내부css사용 초기화 같은 것을 ( * margin:0 ~~) 파일로 만들어 놓고 연결 - 외부 CSS (모듈화)(자바에서의 pakage같은 개념) 새로만들기해서 CSS파일 만들어서 STYLE 속성들을 이대로 저장 #wrap { width:1000px; height:700px; background-color:silver; margin:0 auto;} #wrap h1 { color:blue; } 저장한 스타일시트는 (casting style sheet) <link rel="stylesheet" href="default.css" /> 스타일 태그위에 일괄적용. 별도의 CSS를 많이 따로따로 준비해 놓는다. (하나의 폴더로 관리) (업데이트가 많이 필요할 것 같은것, 감을 익혀서 사용) <link rel="stylesheet" href="폴더명/default.css" /> ---------------------------- @charset "utf-8"; /* CSS Document */ html, body { width:100%; height:100%; } html, body, h1, h2, h3, h4, h5, h6, ul, li, ol, dl, dt, dd, p, a, span, img, form, input { padding : 0; margin : 0; border : 0; } body {letter-spacing : -1px;} img { border:none; vertical-align : top; } ul li, oi, li { list-style:none; } a {text-decoration:none;} ---------------------------- -기본 초기화 reset.css css폴더에서 img폴더에 있는 jpg를 불러올때는 background-image:url("../img/visual.jpg") css 파일 내용으로서, css 파일 기준으로 한번 나가주고 다시 img 폴더로 이동해서 .jpg를 불러온다. ``` ``` 게시판 붙히기. 기존에 존재하는 게시판 ( php 무료게시판 ) - 제로보드 - 그누보드 - xe보드 www.dothome.co.kr 기본제공 제로보드 스킨 바꾸기 www.xpressengine.com/zb4_skin_user 게시판안되면 신규 웹호스팅 신청 -> 에이치ttp://본인아이디.dothome.co.kr/bbs/admin.php 새그룹추가 -> 게시판 추가 -------- #freeboard { width:600px; height:500px; background-color:silver; } <div id="freeboard"> <iframe src="에이치ttp://본인아이디.dothome.co.kr/bbs/zboard.php?id=QnA" width="550" height="450" frameborder="0"></iframe> </div> -------- iframe = 다른 html을 강제로 때려넣는 기능 frameborder = 티 안나게 틀을 없애줌 margin 겹침현상의 발생원인은 여백의 공유. - javascript & jQuery 준비해야함. 사진이 없어서 밑밑해가지고 찾아봤습니다. http://cc0photo.com/ 무료 이미지를 배포하는 곳입니다. 관련 태그가 부족하고 이미지도 좀 부족하지만 가볍게 찾기에 좋은 것 같습니다. ``` <file_sep>/_cpp/최대공약수, 최소공배수 구하기.md ``` #include <cstdio> #include <iostream> using namespace std; int main() { //유클리드 호제법을 이용한 최대공약수, 최소공배수 구하기 //1. 입력받은 2개의 숫자를 큰수, 작은수를 판단한다. //2. 큰수를 작은수로 나눈다. 나머지가 0일 경우 작은수가 최대공약수, // 입력받은 숫자의 곱을 최대공약수로 나누면 최소공배수가 된다. //3. 나머지가 0이 아닐 경우는 큰수에 작은수를 작은수에 나머지를 넣고 2부터 반복한다. int a, b, big, small; cout << "숫자 2개를 입력하세요 : "; cin >> a >> b; if(a > b) { big = a; small = b; } else { big = b; small = a; } while(true) { int nmg = big % small;// 큰수를 작은수로 나눈 나머지 if(nmg == 0) {// 나머지가 0인가? break;// 나머지가 0이라면 반복을 탈출한다. } //나머지가 0이 아니면 이곳으로 온다. big = small; small = nmg; } cout << "최대공약수 : " << small << endl; cout << "최소공배수 : " << a * b / small << endl; } ``` <file_sep>/_javascript/A018 축 이동, for문.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>축 axis</title> <script src="js/jquery-1.7.2.min.js" ></script> <script src="js/jquery-ui.min.js"></script> <script> $(function(){ n=0 $('#box').draggable({'axis':'x'}) $('#box').mousedown(function(e){start_x = e.clientX}) $('#box').mouseup(function(e){ end_x = e.clientX gap = Math.abs(start_x - end_x) if( gap > 30){ if( start_x > end_x){ n++ if(n==3){n=2} $(this).stop().animate({left:-500*n}) } if( start_x < end_x ){ n-- if(n==-1){n=0} $(this).stop().animate({left:-500*n}) } } if( gap <30){ $(this).animate({left:-500*n}) } }) }) </script> <style> #boxWrap{width:500px; height:300px;overflow:hidden; margin:0 auto; position:relative; } #box{ width:1500px; height:300px; position:absolute; left:0; top:0 } .page{ width:500px; height:300px; float:left;} .page1{ background-color:#FFCC00} .page2{ background-color:#33CCFF} .page3{ background-color:#6C3} </style> </head> <body> <div id="boxWrap"> <div id="box"> <div class="page page1">page1</div> <div class="page page2">page2</div> <div class="page page3">page3</div> </div> </div> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>축 axis</title> <script src="js/jquery-1.7.2.min.js" ></script> <script src="js/jquery-ui.min.js"></script> <script> $(function(){ $(window).scroll(function(){ var ab= $(this).scrollTop() $('p').text(ab) }) }) </script> <style> #boxWrap{width:500px; height:300px;overflow:hidden; margin:0 auto; position:relative; } #box{ width:1500px; height:300px; position:absolute; left:0; top:0 } .page{ width:500px; height:300px; float:left;} .page1{ background-color:#FFCC00} .page2{ background-color:#33CCFF} .page3{ background-color:#6C3} </style> </head> <body> <div id="boxWrap"> <div id="box"> <div class="page page1">page1</div> <div class="page page2">page2</div> <div class="page page3">page3</div> </div> </div> <p></p> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>for 반복문</title> <script> /* for(i=1; i<=8; i++){ document.write('<img src="img/m'+i+'.jpg" />') } */ for(i=1; i<=9 ; i++){ for(j=1 ; j <=9; j++){ document.write( i +'*'+ j +'='+ i*j +'<br />') } if(i == 5){ break} document.write('<hr />') } </script> </head> <body> </body> </html> ``` <file_sep>/_java/A019 KeyListener.md ``` package com.me.mouseeventtest; import java.awt.Frame; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class KeyboardEventTest1 extends Frame{ public KeyboardEventTest1() { setTitle("키보드 이벤트"); setBounds(750, 200, 400, 400); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { // System.out.println(e.getKeyChar() +"키가 눌렸다 떨어짐"); } @Override public void keyReleased(KeyEvent e) { // System.out.println(e.getKeyChar() +"키가 떨어짐"); } @Override public void keyPressed(KeyEvent e) { // getKeyChar() : 입력한 키보드 문자를 얻어온다. // getKeyCode() : 입력한 키보드 문자를 코드 값을 얻어온다. KeyPressed에 걸어준다. int code = e.getKeyCode(); switch(code){ case KeyEvent.VK_SPACE: System.out.println("SpaceBar 눌림"); break; case KeyEvent.VK_BACK_SPACE: System.out.println("Back SpaceBar 눌림"); break; case KeyEvent.VK_LEFT: System.out.println("왼쪽 방향키 눌림"); break; case KeyEvent.VK_RIGHT: System.out.println("오른쪽 방향키 눌림"); break; case KeyEvent.VK_UP: System.out.println("위쪽 방향키 눌림"); break; case KeyEvent.VK_DOWN: System.out.println("아래쪽 방향키 눌림"); break; default: System.out.println(e.getKeyChar() +"키가 눌림"); } } }); setVisible(true); } public static void main(String[] args) { new KeyboardEventTest1(); } } ``` <file_sep>/_java/OOPS - Encapsulation.md ``` public class EncapsulationExample { private String manufacturer; private String operating_system; public String model; private int cost; // Constructor to set properties/characteristics of object EncapsulationExample(String manufac, String operatSys, String mod, int cst) { this.manufacturer = manufac; this.operating_system = operatSys; this.model = mod; this.cost = cst; } // Method to get access Model property of Object public String getModel() { return this.model; } public String getManufacturer() { return this.manufacturer; } public int getcost() { return this.cost; } public String getOperatingSystem() { return this.operating_system; } public static void main(String[] args) { EncapsulationExample en = new EncapsulationExample("Microsoft", "Windows", "2007", 500); System.out.println("Manufacturer: " + en.getManufacturer()); System.out.println("OS: " + en.getOperatingSystem()); System.out.println("Model: " + en.getModel()); System.out.println("Cost: " + en.getcost()); } } ``` ## OUTPUT ``` Manufacturer: Microsoft OS: Windows Model: 2007 Cost: 500 ```<file_sep>/_javascript/A003 text,attr,prepend,before,wrap 등 제이쿼리 명령.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery명령</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(function(){ //text() , html(), attr('속성','값') $('h1').text()// 지정한 선택자의 텍스트값 $('h1').text('제이쿼리-Jquery') // 선택자의 텍스트값을 지정한값으로 교체 $('h2 em').text( $('h1').text() ) //alert($('h2').html()) $('h2').html('<strong style="color:red">제이쿼리</strong>') $('h2').html('<em>' + $('h1').text() + '</em>') //attr('속성','값') //attr('속성') //$('ul li img').attr('alt', $('ul li').text() ) //$('ul li').html('<img src="img/m1.jpg" alt="인사이드 아웃" />' // +$('ul li img').attr('alt')) $('ul li span').text($('ul li img').attr('alt')) }) </script> </head> <body> <h1>JQUERY</h1> <h2><em>JQEURY</em>의 명령들을 살펴보자</h2> <ul> <li><img src="img/m1.jpg" alt="인사이드아웃" /><span>영화1</span></li> </ul> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery명령</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(function(){ $('ul:first').prepend('<li id="m0">HOME</li>') $('ul:first').append('<li id="end">end Menu</li>') $('ul:first').before('<h2>메뉴목록</h2>') $('ul:first').after('<hr />') $('ul').wrapAll('<div class="navWrap"></div>') $('ul').wrap('<div class="nav"></div>') $('.nav').wrapInner('<div class="gnb"></div>') }) </script> </head> <body> <h1>JQUERY</h1> <h2><em>JQEURY</em>의 명령들을 살펴보자</h2> <ul> <li id="m1">MENU1</li> <li id="m2">MENU2</li> <li id="m3">MENU3</li> <li id="m4">MENU4</li> <li id="m5">MENU5</li> </ul> <ul> <li id="m1">MENU1</li> <li id="m2">MENU2</li> <li id="m3">MENU3</li> <li id="m4">MENU4</li> <li id="m5">MENU5</li> </ul> </body> </html> ``` <file_sep>/KNOU.java.test/src/knou/test/applet/InitThreadTest.java package knou.test.applet; import java.applet.Applet; import java.awt.BorderLayout; import java.awt.Canvas; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Image; import java.awt.MediaTracker; import java.awt.ScrollPane; import java.net.URL; class MyCanvas2 extends Canvas { Image image; MediaTracker mt; Applet applet; URL relativeURL; public MyCanvas2(Applet a, URL u) { applet = a; relativeURL = u; } public void LoadImage(String f, Cursor c) { setCursor(new Cursor(Cursor.WAIT_CURSOR)); mt = new MediaTracker(this); try { for(long i=0; i<1000000000; i++); // 시간 끌기 image = applet.getImage(relativeURL, f); } catch(Exception e) {} mt.addImage(image, 0); try {mt.waitForAll();} catch(InterruptedException e) {} setSize(image.getWidth(this), image.getHeight(this)); this.getParent().validate(); setCursor(c); } public void paint(Graphics g) { if(image!=null)g.drawImage(image, 0, 0, this); else g.drawString("Loading image...", 10, 50); } } public class InitThreadTest extends Applet implements Runnable { MyCanvas2 canvas; ScrollPane sp; Cursor cur_cursor; public void init() { setLayout(new BorderLayout()); canvas = new MyCanvas2(this, getCodeBase()); sp = new ScrollPane(); sp.add(canvas); add(sp); cur_cursor = getCursor(); } public void start() { (new Thread(this)).start(); } @Override public void run() { canvas.LoadImage("githubkr.jpg", cur_cursor); } } <file_sep>/KNOU.java.test/src/knou/test/awt/BorderLayoutTest.java package knou.test.awt; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.Label; import java.awt.Scrollbar; public class BorderLayoutTest extends Frame { private Scrollbar s1,s2; public BorderLayoutTest() { super("BorderLayout"); setSize(300,300); setLayout(new BorderLayout(10,10)); Label l_east = new Label("EAST", Label.CENTER); l_east.setBackground(Color.red); Label l_west = new Label("WEST", Label.CENTER); l_west.setBackground(Color.blue); Label l_south = new Label("SOUTH", Label.CENTER); l_south.setBackground(Color.green); Label l_north = new Label("NORTHHHHH", Label.RIGHT); l_north.setBackground(Color.yellow); Label l_center = new Label("CENTER", Label.CENTER); l_center.setBackground(Color.gray); add(l_east, BorderLayout.EAST); add(l_south, BorderLayout.SOUTH); add(l_west, BorderLayout.WEST); add(l_north, BorderLayout.NORTH); add(l_center, BorderLayout.CENTER); } public static void main(String[] args) { Frame f = new BorderLayoutTest(); f.setVisible(true); } } <file_sep>/_jspServlet/A005 JSP Action tag.md ## JSP 액션 태그의 사용 JSP 액션을 사용하면 자바로 직접 코딩하는 것보다 빠르고 쉽게 원하는 기능을 작성할 수 있습니다.<br /> 다음은 JSP 2.2에서 제공하는 주요 액션들(Standard Actions) 입니다.<br /> 각 액션 태그들이 어떤 자바 코드를 생성하는지 살펴봅니다.<br /> | Action | Describe | |:----------------- |:---------------------------------------------:| | <jsp:useBean> | 자바 인스턴스를 준비합니다. 보관소에서 자바 인스턴스를 꺼내거나, 자바 인스턴스를 새로 만들어 보관소에 저장하는 코드를 생성합니다. 자바 인스턴스를 자바 빈(Java Bean)이라고 부릅니다. | | <jsp:setProperty> | 자바 빈의 프로퍼티 값을 설정합니다. 자바 객체의 셋터(setter) 메서드를 호출하는 코드를 생성합니다. | | <jsp:getProperty> | 자바 빈의 프로퍼티 값을 꺼냅니다. 자바 객체의 겟터(getter) 메서드를 호출하는 코드를 생성합니다. | | <jsp:include> | 정적(HTML, 텍스트 파일 등) 또는 동적 자원(서블릿/JSP)을 인클루딩 하는 자바 코드를 생성합니다. | | <jsp:forward> | 현재 페이지의 실행을 멈추고 다른 정적 자원(HTML, 텍스트 파일 등)이나 동적 자원(서블릿/JSP)으로 포워딩하는 자바 코드를 생성합니다. | | <jsp:param> | jsp:include, jsp:forward, jsp:params의 자식 태그로 사용할 수 있습니다. | | <jsp:plugin> | OBJECT 또는 EMBED HTML 태그를 생성합니다. | | <jsp:element> | 임의의 XML 태그나 HTML 태그를 생성합니다. | <file_sep>/_javascript/A013 animate, setInterval.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>setInterval</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ /* set1 = setInterval(function(){ $('#box1').css({marginLeft:0}) $('#box1').animate({marginLeft:100},'slow') },2000) $('button:eq(1)').click(function(){ set1=setInterval(function(){ $('#box1').css({marginLeft:0}) $('#box1').animate({marginLeft:100},'slow') },2000) }) $('button:eq(1)').click() */ $('button:eq(1)').click(function(){ set1=setInterval(function(){ $('#box1').css({marginLeft:0}) $('#box1').animate({marginLeft:100},'slow') },2000) }).click() // 두번째 박스 와 버튼 set2 = setInterval(function(){ $('#box2').css({marginLeft:0}) $('#box2').animate({marginLeft:300},'slow') },2000) $('button:first').click(function(){ clearInterval(set1) }) }) </script> <style> #box1{ width:100px; height:100px; background-color:red} #box2{ width:100px; height:100px; background-color:blue} </style> </head> <body> <div id="box1">box1</div> <div id="box2">box2</div> <button>clear</button> <button>set1</button> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>setInterval</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ var n = 0 /* set1=setInterval(function(){ n++ $('#box1').animate({marginLeft:100*n},200,'swing') },1000) rotate = setInterval(function(){ n+=3 $('#box1').css({transform: 'rotate('+ n +'deg)'}) },30) */ }) </script> <style> #box1{ width:100px; height:100px; background-color:red; margin:50px ; border-radius:100px; box-shadow:3px 3px 2px rgba(0,0,0,0.3); opacity:1; border:5px solid #ddd; } .gra{/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#b7deed+0,71ceef+50,21b4e2+53,b7deed+100;Shape+1+Style */ background: #b7deed; /* Old browsers */ background: -moz-linear-gradient(left, #b7deed 0%, #71ceef 50%, #21b4e2 53%, #b7deed 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, right top, color-stop(0%,#b7deed), color-stop(50%,#71ceef), color-stop(53%,#21b4e2), color-stop(100%,#b7deed)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(left, #b7deed 0%,#71ceef 50%,#21b4e2 53%,#b7deed 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(left, #b7deed 0%,#71ceef 50%,#21b4e2 53%,#b7deed 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(left, #b7deed 0%,#71ceef 50%,#21b4e2 53%,#b7deed 100%); /* IE10+ */ background: linear-gradient(to right, #b7deed 0%,#71ceef 50%,#21b4e2 53%,#b7deed 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#b7deed', endColorstr='#b7deed',GradientType=1 ); /* IE6-9 */ } </style> </head> <body> <div id="box1" class="gra">box1</div> </body> </html> ``` <file_sep>/_htmlCss/A013 CSS 외부파일로 작성.md ``` .css파일의 부분. (css를 외부파일로 작성) @charset "utf-8"; /* CSS Document */ /* reset */ body,ul,dl,li,dl,dt,dd,h1,h2,h3,h4,h5,h6,from,input,fieldest,button { margin:0; padding:0;} body,h1,h2,h3,h4,h5,h6,th,td,input,button { font:12px/1.5 "돋음"} ul,ol,li { list-style:none; } img { border:none;} a { text-decoration:none; } /* layout */ .box_width { width:960px; margin:0 auto;} #headerWrap { background-color:#F93; } #header { height:100px; } #nav { height:40px; background-color:#ECCC79; } #mainContents { } #footerWarp { background-color:#999; clear:both; } #footer { height:100px; } /* header */ .logo {} .t_menu { float:right;} .t_menu li { display: inline;} /* nav */ .gnb { width:500px; margin:0 auto; } .gnb li { float:left; width:100px; line-height:40px; text-align:center; } .gnb li a { color:#333333; display:block; } .gnb li a:hover { background-color:#E8FCCD; color:#F00; } /* mainContents */ .slider { height:300px; background-color:#E8FCCD; } .con_box { float:left; } .box { width:320px; height:250px; float:left; outline:1px solid #000; background-color:#FFFFFF; } /* footer */ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>layout02</title> <link href="css/index.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="headerWrap"> <div id="header" class="box_width"> <h1 class="logo">LOGO</h1> <ul class="t_menu"> <li><a href="#">LOGIN</a></li> <li><a href="#">회원가입</a></li> <li><a href="#">SITE MAP</a></li> <li><a href="#">고객지원</a></li> </ul> </div><!--//header--> <div id="nav"> <!--<h2>메뉴목록</h2>--> <ul class="gnb"> <li><a href="#">MENU01</a></li> <li><a href="#">MENU02</a></li> <li><a href="#">MENU03</a></li> <li><a href="#">MENU04</a></li> </ul><!--//gnb--> </div><!--//nav--> </div><!--//headerWrap--> <div id="mainContents" class="box_width"> <div class="slider"> slider </div><!--//slider--> <div class="con_box"> <div class="box">box01</div> <div class="box">box02</div> <div class="box">box03</div> </div><!--//con_box--> </div><!--//mainContents--> <div id="footerWarp"> <div id="footer" class="box_width"> <address>주소</address> <p>copyright</p> </div> </div> <!--//footerWarp--> </body> </html> ``` <file_sep>/_java/OOPS - Methods Example - BicycleDemo.md ``` //The following Bicycle class is one possible //implementation of a bicycle //This class shows how to use methods in a class public class BicycleDemo { public static void main(String[] args) { // Create two different // Bicycle objects Bicycle bike1 = new Bicycle(); Bicycle bike2 = new Bicycle(); // Invoke methods on // those objects bike1.changeCadence(50); bike1.speedUp(10); bike1.changeGear(2); bike1.printStates(); bike2.changeCadence(50); bike2.speedUp(10); bike2.changeGear(2); bike2.changeCadence(40); bike2.speedUp(10); bike2.changeGear(3); bike2.printStates(); } } class Bicycle { int cadence = 0; int speed = 0; int gear = 1; void changeCadence(int newValue) { cadence = newValue; } void changeGear(int newValue) { gear = newValue; } void speedUp(int increment) { speed = speed + increment; } void applyBrakes(int decrement) { speed = speed - decrement; } void printStates() { System.out.println("cadence:" + cadence + " speed:" + speed + " gear:" + gear); } } ``` ##OUTPUT ``` cadence:50 speed:10 gear:2 cadence:40 speed:20 gear:3 ```<file_sep>/_java/COLLECTION - Basic Of HashSet.md ``` package com.sunil; import java.util.HashSet; public class HashSetBasic { public static void main(String[] args) { HashSet<String> hs=new HashSet<String>(); hs.add("Java"); hs.add("Android"); hs.add("Php"); hs.add("Ajax"); System.out.println(hs); hs.add("Python"); System.out.println(hs); // Can't add duplicate System.out.println("Is Java added :"+hs.add("Java")); // remove from HashSet hs.remove("Php"); // Size of HashSet System.out.print("Size of ArrayList after removing Php :"+hs.size()); System.out.println(); System.out.println("Is java is in list :"+hs.contains("Java")); // HashSet to array Object[] a=hs.toArray(); System.out.print("Array :"); for (Object object : a) { System.out.print(object+" "); } System.out.println(); //clear whole HashSet hs.clear(); System.out.print(hs+" "+"Is HashSet empty after clear :"+ hs.isEmpty()); } } ``` ##OUTPUT ``` [Java, Php, Android, Ajax] [Java, Php, Android, Ajax, Python] Is Java added :false Size of ArrayList after removing Php :4 Is java is in list :true Array :Java Android Ajax Python [] Is HashSet empty after clear :true ```<file_sep>/_java/EXCEPTION HANDLING - Mutiple Catch Blocks.md ``` import java.net.MalformedURLException; import java.net.URL; public class MyMultipleCatchBlocks { public static void main(String a[]) { MyMultipleCatchBlocks mmcb = new MyMultipleCatchBlocks(); mmcb.execute(1); mmcb.execute(2); } public void execute(int i) { try { if (i == 1) { getIntValue("7u"); } else { getUrlObj("www.junksite.com"); } } catch (NumberFormatException nfe) { System.out.println("Inside NumberFormatException... " + nfe.getMessage()); } catch (MalformedURLException mue) { System.out.println("Inside MalformedURLException... " + mue.getMessage()); } catch (Exception ex) { System.out.println("Inside Exception... " + ex.getMessage()); } } public int getIntValue(String num) { return Integer.parseInt(num); } public URL getUrlObj(String urlStr) throws MalformedURLException { return new URL(urlStr); } } ``` ##OUTPUT ``` Inside NumberFormatException... For input string: "7u" Inside MalformedURLException... no protocol: www.junksite.com ```<file_sep>/_htmlCss/A008 용도별 사각형(box).md ``` <body> <div id="a"> <div id="b"></div> </div> </body> ------★외우기 1. div : 큰 영역을 나누는 사각형 (division) 2. h1, h2, h3, h4, h5, h6 ( heading,제목/타이틀 ) : 제목 영역 사각형, h1이 제일 큰 제목( 크기별, 중요도별 분류) h1 : 회사 로고, 가장 중요한 메인 메세지(이미지를 넣거나 글자를 넣거나 가능) 3. p ( Paragraph,문단 ) : 글자의 문단처리. <!-- 지금까지는 독립적으로 사용 <p> ~ </p> --> 4. ul li ( unordered, list item ) : 작고, 비슷한 사각형이 2개 이상 나열 될 때. UX (menu btn) - 많이 사용됨. 5. a : 링크 걸어주는 사각형 6. img : 이미지 넣어주는 사각형 7. span : inline (글자 등등) 에서 사용되는 사각형 (텍스트에서의 한 줄) - width height margin 등 안먹히고 글자색~ 가능 8. strong : inline 에서 글자를 굵게 하는 사각형 ( b태그랑 똑같음 - 쓰지는 않음 - 장애인에게 strong이 강하게 말해줌) 9. dl dt dd : 하나의 사각형 안에 중요한 사각형과 평범한 사각형이 있을 때 <dl> <dt></dt> 장군같은 느낌 <dd></dd> 병사같은 느낌 <dd></dd> <dd></dd> </dl> 코딩의 초기화 : 필요 없어진 속성값을 없애는 작업 * { margin:0; padding:0; } // 모든 태그에 들어 있는 간격 값을 초기화 ul li { list-style:none; } // 리스트의 점 모양을 없애줌 img { border:none; } // 이미지에 링크 걸었을때 박스를 없애줌 a { text-decoration:none; color:black; } // 글자에 링크걸었을 때 밑줄 없애줌 <style> h1 { width:200px; height:100px; background-color:blue; color:white;} </style> <body> <h1>안녕하세요</h1> <h2>마크업 언어입니다.</h2> <h3>대한민국입니다. kor</h3> <H6>000-0000-0000 입니다.</H6> <p>안녕하세요 저는 한국에 거주하고 있고, <br>IT업무에 종사 하고 있고...</p> </body> 실행화면 <style> ul { margin-left:200px; } </style> <body> <div> 큰방 <ul> 작은방 <li></li> 보석함 같은 느낌 <li></li> <li></li> </ul> </div> </body> <style> /* 코딩의 초기화 시작 */ * { margin:0; padding:0 ; } ul li { list-style:none; } img { border:none; } a { text-decoration:none; color:black; } ul { width:600px; height:70px; background-color:blue; } ul li#li01 { width:100px; height:50px; color:white; float:left; margin-left:100px;} // li한개만 지정, #li01붙히면 그것만 지정 </style> <body> <div> <h2>보석함</h2> <ul> <li id="li01">반지</li> <li>귀걸이</li> <li>목걸이</li> </ul> </div> </body> ``` ``` <style> /* 코딩의 초기화 시작 */ * { margin:0; padding:0 ; } ul li { list-style:none; } img { border:none; } a { text-decoration:none; color:black; } ul { width:527px; height:351px; background-color:pink; padding:58px 0 0 58px; } ul li { width:153px; height:132px; background-color:blue; float:left; margin-right:9px;} <!-- 전체에 마진값 줬다가 필요없는 마진값이 있어서 분개함 --> #li01, #li02, #li03 { margin-bottom:17px; } // li값을 상속받고 콤마로 이어서 특정값만 추가속성 #li03, #li06 { margin-right:0; } </style> <body> <div> <ul> <li id="li01">01</li> <!-- 하나하나 줘야되는 불편함이 있어서 비슷한 것을 그룹화 하는 클래스 개념만들어짐 --> <li id="li02">02</li> <li id="li03">03</li> <li>04</li> <li>05</li> <li>06</li> </ul> </div> </body> ``` <file_sep>/_cpp/if문과 다중 반복문(for문) 사용 방법.md ``` #include <cstdio> #include <iostream> using namespace std; int main() { int n; cout << "심판 인원수 : "; cin >> n; //입력받은 n개 만큼 배열을 만든다. 가변 배열 int *jumsu = new int[n]; //심판수 만큼 점수를 입력받고 점수의 합계를 구한다. int sum = 0; for(int i=0 ; i<n ; i++) { cout << i + 1 << "번째 심판의 점수 : "; cin >> jumsu[i]; sum += jumsu[i]; } //최대값과 최소값을 판단한다. part #1 //최대값을 기억할 기억 장소는 아주 작은 값을 최소값을 기억할 기억장소는 아주 큰 값을 //초기치로 입력하고 0번째 데이터 부터 마지막 데이터 까지 비교한다. //int max = 0, min = 10; //for(int i=0 ; i<n ; i++) { // if(max < jumsu[i]) { // jumsu[i] 값이 최대값 보다 큰가? // max = jumsu[i]; // 최대값을 jumsu[i]로 바꾼다. // } else if(min > jumsu[i]) { // jumsu[i] 값이 최소값 보다 작은가? // min = jumsu[i]; // 최소값을 jumsu[i]로 바꾼다. // } //} //최대값과 최소값을 판단한다. part #2 //최대값과 최소값을 기억할 기억 장소에 배열의 0번째 값을 초기치로 입력하고 //1번째 데이터 부터 마지막 데이터 까지 비교한다. //int max = jumsu[0], min = jumsu[0]; int max, min; max = min = jumsu[0]; for(int i=1 ; i<n ; i++) { if(max < jumsu[i]) { // jumsu[i] 값이 최대값 보다 큰가? max = jumsu[i]; // 최대값을 jumsu[i]로 바꾼다. } else if(min > jumsu[i]) { // jumsu[i] 값이 최소값 보다 작은가? min = jumsu[i]; // 최소값을 jumsu[i]로 바꾼다. } } cout << "최대값 : " << max << endl; cout << "최소값 : " << min << endl; //cout << "최대값과 최소값을 제외한 나머지 점수의 평균 : " << // (sum - max - min) / (n - 2.) << endl; printf("최대값과 최소값을 제외한 나머지 점수의 평균 : %5.2f\n", (sum - max - min) / (n - 2.)); } ``` ``` #include <cstdio> #include <iostream> using namespace std; int main() { //다중 반복은 바깥쪽 반복의 변수 값이 1번 바뀔때 안쪽 반복문은 완전히 1번 실행된다. for(int i=0 ; i<5 ; i++) { //바깥쪽 반복문의 제어 변수를 안쪽 반복문에서 다시 사용하면 안된다. for(int j=0 ; j<3 ; j++) { cout << "i = " << i << ", j = " << j << endl; } cout << "===================================" << endl; } } ``` <file_sep>/_jspServlet/A011 Design Pattern and Framework.md ## 디자인 패턴 아무리 자바 가상머신이 가비지를 찾아서 자동으로 없애 준다 해도, 이 작업 또한 CPU를 사용하는 일이기에 시스템 성능에 영향을 끼칩니다. 따라서 개발자는 늘 인스턴스의 생성과 소멸에 대해 관심을 가지고 시스템 성능을 높일 수 있는 방향으로 구현해야 합니다. 또한, 중복 작업을 최소화하여 유지보수를 좋게 만드는 방법을 찾아야 합니다. 이것은 개발자의 의무입니다. 이런 개발자들의 노력은 시스템에 적용되어 많은 시간 동안 시스템이 운영되면서 검증됩니다. 디자인 패턴은 이렇게 검증된 방법들을 체계적으로 분류하여 정의한 것입니다. 디자인 패턴은 이미 실무에서 사용되고 검증된 방법이기 때문에 시스템 개발에 디자인 패턴을 활용하면 시행착오를 최소화할 수 있습니다. ## 프레임워크 디자인 패턴이 특정 문제를 해결하기 위한 검증된 방법이라면, 프레임워크(Framework)는 이런 디자인 패턴을 적용해 만든 시스템 중에서 우수 사례(Best Practice)를 모아 하나의 개발 틀로 표준화시킨 것입니다. 프레임워크의 대표적인 예로 국내외적으로 많이 사용하고 있으며 범용 시스템 개발에 사용할 수 있는 스프링 프레임워크가 있으며 스프링 프레임워크 보다 기능은 작지만, 웹 MVC 프레임워크로 특화된 스트럿츠가 있습니다. 국내에서는 스트럿츠 보다는 스프링 MVC 프레임워크를 더 많이 사용합니다. MyBatis(이전 이름 iBatis)는 데이터베이스 연동을 쉽게 해주는 프레임워크입니다. MyBatis를 사용하면 개발자는 더 이상 JDBC 프로그래밍을 할 필요가 없습니다. 자바스크립트를 위한 MVC 프레임워크도 있습니다. Angular와 Ember가 요즘 주목받는 자바스크립트 프레임워크입니다. <file_sep>/_java/A006 Thread 개념.md ``` package com.me.threadtest1; // Runnable 인터페이스를 구현하고 run() 메소드를 override 해서 스레드를 작성 public class AlphaThread implements Runnable{ @Override public void run() { for(char ch='a'; ch<='z'; ch++){ System.out.print(ch); try { Thread.sleep(200); } catch (InterruptedException e) { } } } } ---------- package com.me.threadtest1; // Thread 클래스를 상속받고 run() 메소드를 override 해서 스레드 작성 // run() 안에 만들고 main() 메소드에서 start()로 실행한다. public class DigitThread extends Thread{ @Override public void run() { for(int i=1; i<=26; i++){ System.out.print(i); try { Thread.sleep(200); } catch (InterruptedException e) { } } } } ----------- package com.me.threadtest1; public class ThreadTest1 { public static void main(String[] args) { // Thread 클래스를 상속받아 작성한 스레드 실행방법 // Thread 클래스를 상속받아 작성한 클래스의 객체를 만들고 생성된 객체에서 start() 메소드로 // 스레드를 실행한다. DigitThread digit = new DigitThread(); // digit.run(); // run() 이라는 일반 메소드가 실행된다. 이런 식으로 활용 x digit.start(); // new DigitThread().start(); // 실행만 할 경우 익명 메소드로 활용 가능 // Runnable 인터페이스를 구현해 작성한 스레드 실행방법 // Thread 클래스의 객체를 만들고 Thread 클래스의 생성자 메소드 인수로 Runnable 인터페이스를 구현한 // 객체를 익명 개체로 만들어 넘겨주고 Thread 클래스의 객체에서 start() 메소드로 스레드를 실행한다. AlphaThread alpha = new AlphaThread(); Thread thread = new Thread(alpha); // Thread thread = new Thread(new AlphaThread()); thread.start(); // for(int i=65; i<=90; i++){ // System.out.print((char)i); // } for(char ch='A'; ch<='Z'; ch++){ System.out.print(ch); try { Thread.sleep(200); } catch (InterruptedException e) { } } } // main() } // class ``` ``` package com.me.threadtest2; public class Play extends Thread{ @Override public void run() { while(true){ System.out.println("음악을 연주중~~~"); try { Thread.sleep(500); } catch (InterruptedException e) { } } } } ------------ package com.me.threadtest2; public class ThreadTest2 { public static void main(String[] args) { Play play = new Play(); // 데몬 스레드 : 다른 스레드가 모두 종료되면 같이 종료되는 스레드 play.setDaemon(true); // 데몬 스레드로 지정 play.start(); for(int i=1 ; i<=10 ; i++){ System.out.println("게임을 실행중~~~"); if(i==9){ System.out.println("엄마가 와서 게임을 종료합니다.ㅠㅠ"); break; } try { Thread.sleep(500); } catch (InterruptedException e) { } } } } ``` ``` package com.me.threadtest3; public class CalcThread { // 공유 영역으로 사용할 클래스 변수를 멤버로 선언한다. ShareArea shareArea; public CalcThread() { } // shareArea에 초기화 하는 생성자 메소드를 만든다. public CalcThread(ShareArea shareArea) { this.shareArea = shareArea; } public ShareArea getShareArea() { return shareArea; } // shareArea를 초기화 하는 setter 메소드를 만든다. public void setShareArea(ShareArea shareArea) { this.shareArea = shareArea; } } ---------- package com.me.threadtest3; public class PrintThread { // 공유 영역으로 사용할 클래스 변수를 멤버로 선언한다. ShareArea shareArea; public PrintThread() { } // shareArea에 초기화 하는 생성자 메소드를 만든다. public PrintThread(ShareArea shareArea) { this.shareArea = shareArea; } public ShareArea getShareArea() { return shareArea; } // shareArea를 초기화 하는 setter 메소드를 만든다. public void setShareArea(ShareArea shareArea) { this.shareArea = shareArea; } } -------------- package com.me.threadtest3; // PrintThread 클래스와 CalcThread 에서 공유 영역으로 사용할 클래스 public class ShareArea { double result; // 연산 결과 boolean ready; // 연산 완료 여부 } -------------- package com.me.threadtest3; public class ThreadTest3 { public static void main(String[] args) { // 공유 영역으로 사용할 클래스(ShareArea)의 객체를 만든다. ShareArea shareArea = new ShareArea(); // ======================================= // 공유 영역을 공유할 클래스(PrintThread, CalcThread)의 객체를 만든다. // PrintThread printThread = new PrintThread(); // CalcThread calcThread = new CalcThread(); // 공유 영역을 사용할 객체의 멤버에 공유 영역의 주소를 직접 넣어준다. // 아래의 두 줄의 식은 같은 객체의 주소를 기억한다. // printThread.shareArea = shareArea; // calcThread.shareArea = shareArea; // 이 방식은 멤버가 private 으로 선언되어 있으면 사용할 수 없다. // ======================================= // 공유 영역의 주소를 생성자 메소드를 통해 전달해 넣어준다. // PrintThread printThread = new PrintThread(shareArea); // CalcThread calcThread = new CalcThread(shareArea); // 이 방식은 공유 영역의 주소를 전달받는 생성자 메소드가 있어야 한다. // ======================================= // 공유 영역의 주소를 setter 메소드를 통해 넣어준다. PrintThread printThread = new PrintThread(); CalcThread calcThread = new CalcThread(); printThread.setShareArea(shareArea); calcThread.setShareArea(shareArea); // ======================================= // 공유 영역 확인 테스트 printThread.shareArea.result = 100; System.out.println(calcThread.shareArea.result); } } // getter 와 setter 이용하는게 가장 많음 // bin - 멤버과 게터 세터만 있는 것 ``` <file_sep>/KNOU.java.test/src/knou/test/awt/ScrollbarTest.java package knou.test.awt; import java.awt.Frame; import java.awt.Graphics; import java.awt.Insets; import java.awt.Scrollbar; public class ScrollbarTest extends Frame { private Scrollbar s1; public ScrollbarTest(String title) { super(title); setSize(200,200); setLayout(null); s1 = new Scrollbar(Scrollbar.HORIZONTAL); add(s1); } public void paint(Graphics g) { Insets insets = this.getInsets(); s1.setBounds(insets.left, this.getHeight() - insets.bottom - 20, this.getWidth() - insets.left - insets.right, 20); } public static void main(String[] args) { Frame f = new ScrollbarTest("Scrollbar"); f.setVisible(true); } } <file_sep>/_java/OOPS - Single Inheritance.md ``` import java.io.*; class Student { private int roll_no; private String name; void get_data(int roll_no,String name) { this.roll_no = roll_no; this.name = name; } void display() { System.out.print("\nThe Student Details are:"); System.out.print("\nRoll no: "+roll_no); System.out.print("\nName: "+name); } } class Marks extends Student { private int mark1,mark2; Marks(int mark1,int mark2) { this.mark1 = mark1; this.mark2 = mark2; } void display_marks() { System.out.print("\nMarks1: "+mark1); System.out.print("\nMarks2: "+mark2); float avg; avg = (mark1+mark2)/2; System.out.println("\nAverage: "+avg); } } public class SingleInheritance { public static void main(String s[]) throws Exception { int roll_no,mark1,mark2; String name; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("\nEnter Roll_no: "); roll_no = Integer.parseInt(br.readLine()); System.out.print("\nEnter Name: "); name = br.readLine(); System.out.print("\nEnter Marks1: "); mark1 = Integer.parseInt(br.readLine()); System.out.print("\nEnter Marks2: "); mark2 = Integer.parseInt(br.readLine()); Marks m = new Marks(mark1,mark2); m.get_data(roll_no,name); m.display(); m.display_marks(); } } ``` ###OUTPUT ``` Enter Roll_no: 2 Enter Name: John Enter Marks1: 45 Enter Marks2: 65 The Student Details are: Roll no: 2 Name: John Marks1: 45 Marks2: 65 Average: 55.0 ```<file_sep>/_htmlCss/A002 글자 속성, padding,margin.md ``` 실무에서 EditPlus 더 많이 사용함 (하드코어 용도) margin 바깥 간격 padding 안쪽 간격 #box { width:700px; height:600px; background-color:orange; padding-left:100px; } <!-- width:800됨 --> padding 간격이 커지는 만큼 자기 사이즈도 커진다 (줄이려면 width값 조절) padding-left/right 값 만큼 width 크기가 커진다. padding-top/bottom 값 만큼 height 크기가 커진다. #box { width:865px; height:600px; background-color:orange;padding-left:256px; padding-right:169px; } padding-left 값과 padding-right 값을 더해서 width값을 빼줘야 width:865px(본래값)을 유지할 수 있다. <style> #box { width:1000px; height:700px; padding:256px 0 0 128px; } <!-- height(256) width(128) 값 수정해줘야 본래값 유지 --> </style> 사각형(틀) 만들기 1. 다른 사각형 2. 글자 3. 이미지 4. 표 5. 폼 사각형 안에 사각형 넣기 2. 글자속성 (외우기★) (1) 글자 폰트 ( font-family:"맑은 고딕"; ) <!-- font-family:"맑은 고딕", "arial", "돋움"; (첫번째 폰트 없으면 뒤에 폰트 여러개 가능, 하나만 표기하는게 좋은방식, 영어는 더블 쿼테이션 생략가능(특수기호 포함은 안됨))--> (2) 글자 크기 ( font-size:11px; ) (3) 글자 굵기 ( font-weight:bold;, font-weight:normal; ) <!-- 안쓰면 normal 상태 --> (4) 줄간 ( line-height:30px; ) <!-- 글자사이즈 포함 밑에 간격인데 font-size:20px 일때 줄간 15px은 적용이 안됨. 글 위, 아래 간격까지 포함해서 글 밑 5px 간격 주고 싶다면 30px 줘야함. --> (5) 자간 ( letter-spacing:2px; ) <!-- 마이너스 간격도 있어서 겹치기 가능 --> (6) 글자 색 ( color:blue; ) - blue, red, white, gray, silver, black, orange, olive, navy, lime, fuchsia, green, yellow (7) 정렬 ( text-align ) (8) 글자 들여쓰기 ( text-indent ) (9) 글자 꾸미기(밑줄 등등) ( text-decoration ) <style> #box { width : 300px; height:300px; margin:300px auto; border:1px solid red; color:orange; font-size:20px; font-family:"맑은 고딕"; } </style> <body> <div id="box"> 웹 퍼블리셔 웹 디자인 </div> </body> ``` ``` <!DOCTYPE HTML> <!-- margin 이용 --> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style> #box01 { width:1000px; height:700px; background-color:#ff0000; border:1px solid white;} #box02 { width:927px; height:629px; background-color:#fc00ff; margin:23px 33px; border:1px solid white;} #box03 { width:775px; height:525px; background-color:#03ff00; margin:50px 80px; } #box04 { width:550px; height:375px; background-color:#0100ff; margin:76px 106px; float:left; } #box05 { width:365px; height:250px; background-color:#00ffea; margin:60px 95px; } #leftBox { width:90px; height:200px; background-color:#e0434e; margin-top:27px; margin-left:32px; float:left; } #centerBox { width:90px; height:200px; background-color:#e0434e; margin-top:27px; margin-left:17px; float:left; } #rightBox { width:90px; height:200px; background-color:#e0434e; margin-top:27px; margin-left:22px; float:left; } </style> </head> <body> <div id="box01"> <div id="box02"> <div id="box03"> <div id="box04"> <div id="box05"> <div id="leftBox"></div> <div id="centerBox"></div> <div id="rightBox"></div> </div> </div> </div> </div> </div> </body> </html> ``` ``` <!doctype HTML> <!-- padding 이용 --> <html> <head> <title>untitle</title> <meta charset="utf-8"> <style> #box01 { width:967px; height:677px; background-color:#ff0000; border:1px solid white;padding:23px 0 0 33px;} #box02 { width:847px; height:579px; background-color:#fc00ff; border:1px solid white; padding:50px 0 0 80px;} #box03 { width:669px; height:449px; background-color:#03ff00; padding:76px 0 0 106px;} #box04 { width:455px; height:315px; background-color:#0100ff; float:left; padding:60px 0 0 95px; } #box05 { width:333px; height:223px; background-color:#00ffea; padding:27px 0 0 32px; } #leftBox { width:90px; height:200px; background-color:#e0434e; float:left; } #centerBox { width:90px; height:200px; background-color:#e0434e; margin-left:17px; float:left; } #rightBox { width:90px; height:200px; background-color:#e0434e; margin-left:22px; float:left; } </style> </head> <body> <div id="box01"> <div id="box02"> <div id="box03"> <div id="box04"> <div id="box05"> <div id="leftBox"></div> <div id="centerBox"></div> <div id="rightBox"></div> </div> </div> </div> </div> </div> </body> </html> ``` <file_sep>/_java/A003 형변환, 가변 인자 메소드.md ``` package com.me.abstractclasstest; class Base{ String name; public void say(){ System.out.println(name + "님 하이용~~~~~"); } } class Sub extends Base{ int age; @Override public void say() { System.out.println(name + "님은 " + age + "살 이네요."); } } public class UpDownCastingTest { public static void main(String[] args) { Base base = new Base(); // 당연히 가능 base.name = "홍길동"; base.say(); Sub sub = new Sub(); // 이것도 당연히 가능 sub.name = "김을동"; sub.age = 15; sub.say(); // 부모 클래스 타입에 자식 클래스 타입을 대입하면 에러가 발생되지 않는다. // 이런 방식을 UpCasting 이라 한다. // Base b = new Sub(); // 자식 클래스 타입에 부모 클래스 타입을 대입했으므로 에러가 발생된다. // 이런 방식을 DownCasting 이라 한다. // Sub s = new Base(); // 클래스로 만든 변수를 참조형 변수라 한다. // 참조형 변수는 객체 자체를 기억하지 않고 메모리에 객체가 생성된 주소를 기억한다. // 부모 클래스 타입의 b에는 자식 클래스 타입 sub의 주소가 들어간다. Base b = sub; // 부모 클래스의 say()가 아닌 부모 클래스 타입이 참조하고 있는 자식 클래스 타입의 say()가 실행된다. // 이것이 하나의 메소드가 서로 다른 클래스에서 다양하게 실행되는 다형성의 기초가 된다. b.name = "킴을똥"; b.say(); // Casting을 해서 부모 타입의 객체를 자식에 대입할 수 있다. // instanceof 연산자 : instanceof 앞의 객체를 instanceof 뒤의 클래스 타입으로 // 안전하게 형변환이 가능한가 판단한다. if(base instanceof Sub){ Sub s = (Sub)base; System.out.println("Base 타입의 base를 Sub 클래스 타입으로 형변환 가능"); }else{ System.out.println("Base 타입의 base를 Sub 클래스 타입으로 형변환 불가능"); } try{ Sub s = (Sub)base; System.out.println("Base 타입의 base를 Sub 클래스 타입으로 형변환 가능"); } catch(ClassCastException e){ System.out.println("Base 타입의 base를 Sub 클래스 타입으로 형변환 불가능"); } finally{ System.out.println("try {Sub s = (Sub)base;}"); } if(sub instanceof Base) { Base b1 = (Base)sub; System.out.println("Sub 타입의 sub를 Base 클래스 타입으로 형변환 가능"); } else { System.out.println("Sub 타입의 sub를 Base 클래스 타입으로 형변환 불가능"); } try{ Base b1 = (Base)sub; System.out.println("Sub 타입의 sub를 Base 클래스 타입으로 형변환 가능"); } catch(ClassCastException e){ System.out.println("Sub 타입의 sub를 Base 클래스 타입으로 형변환 불가능"); } finally{ System.out.println("try {Base b1 = (Base)sub;}"); } } } ``` ``` package com.me.abstractclasstest; // 다형성 : 하나의 메소드가 서로 다른 클래스에서 다양하게 실행된다. // 다형성을 구현하기 위해서는 반드시 동일한 부모를 가져야 하며 부모와 자식에 동일한 메소드가 존재해야 한다. // 추상 클래스는 추상 메소드를 1개 이상 포함한 클래스로 상속을 위해서 만들며 이를 상속받은 자식 클래스에서는 // 반드시 추상 메소드를 override로 구현해서 사용하도록 규칙을 정한다. abstract class Shape{ // 추상 클래스, abstract 예약어를 사용해 만든다. int x, y; // 인스턴스 멤버 변수 abstract public void draw(); // 추상 메소드, abstract 예약어를 사용해 만든다. public void move(int x, int y){ this.x = x; this.y = y; // getClass() : 클래스 정보를 가져오고 getName() : 클래스 이름만 가져옴 System.out.println(getClass().getName() + "을 " + this.x + ", " + this.y + "만큼 이동"); } } class Point extends Shape{ @Override public void draw() { System.out.println("점을 그린다."); } } class Line extends Shape{ @Override public void draw() { System.out.println("선을 그린다."); } } class Circle extends Shape{ @Override public void draw() { System.out.println("원을 그린다."); } } class Rect extends Shape{ @Override public void draw() { System.out.println("사각형을 그린다."); } } class TriAngle extends Shape{ @Override public void draw() { System.out.println("삼각형을 그린다."); } } public class AbstractClassTest2 { public static void main(String[] args) { Shape point = new Point(); point.draw(); Shape line = new Line(); line.draw(); Shape circle = new Circle(); circle.draw(); Shape rect = new Rect(); rect.draw(); Shape tri = new TriAngle(); tri.draw(); } } // class : AbstarctClassTest2 ``` ``` package com.me.abstractclasstest; // 가변 인자 메소드 public class VarArgs { public static void main(String[] args) { // 메소드 인수의 개수가 서로 다를 경우 많은 수의 오버로딩이 필요하다. System.out.println("sum(1,2) = " + sum(1,2)); System.out.println("sum(1,2,3) = " + sum(1,2,3)); System.out.println("sum(1,2,3,4) = " + sum(1,2,3,4)); System.out.println("sum(1,2,3,4,5) = " + sum(1,2,3,4,5)); // 메소드의 인수를 배열로 구현하면 메소드 오버로딩은 필요없지만 인수를 배열로 선언해야 하고 // 배열에 초기치를 입력해서 전달해야 하는 번거로움은 있다. System.out.println("sum(1,2) = " + sum(new int[] {1,2})); System.out.println("sum(1,2,3) = " + sum(new int[] {1,2,3})); System.out.println("sum(1,2,3,4) = " + sum(new int[] {1,2,3,4})); System.out.println("sum(1,2,3,4,5) = " + sum(new int[] {1,2,3,4,5})); // 아직 가변인자메소드 안나옴 (시간 - 11:25) } // static은 static만 호출할 수 있다. (main은 static 메소드) // 같은 이름의 메소드가 여러개 있을 경우 자바는 인수의 개수와 타입으로 메소드를 구분한다. // 같은 이름의 메소드를 인수의 개수와 타입만 다르게 해서 여러개 만들어 사용하는 것을 메소드 오버로드라 한다. private static int sum(int i, int j) { return i+j; } private static int sum(int i, int j, int k) { return i+j+k; } private static int sum(int i, int j, int k, int l) { return i+j+k+l; } private static int sum(int i, int j, int k, int l, int m) { return i+j+k+l+m; } // 위의 메소드들은 인수를 모두 변수로 받고 있으므로 많은 수의 오버로딩이 필요하다. 이를 해결하기 위해서 // 인수를 배열로 받아보자. 그러면 많은 수의 메소드 오버로딩이 필요없다. private static int sum(int[] a){ int sum = 0; for(int i : a){ sum += i; } return sum; } } ``` <file_sep>/_cpp/클래스와 생성자 그리고 멤버 함수(setter, getter, toString).md ``` #include <cstdio> #include <iostream> #include <iomanip> #include <string> using namespace std; class Score { // 설계도 // private : 현재 클래스에서만 접근이 가능하고 다른 클래스에서는 접근 할 수 없다. // public : 모든 위치에서 접근이 가능하다. // 일반적으로 멤버 변수는 private으로 멤버 함수는 public으로 접근 권한을 설성한다. // 멤버 변수를 private으로 하는 이유는 클래스 외부에서 데이터를 함부로 조작할 수 없게 하기 위해서이다. 정보 은폐라 한다. private: // 클래스의 기본 접근 권한은 private 이다. 즉, 생략하면 private으로 지정된다. string name; int java, jsp, spring, total; double average; public: // 생성자 함수의 이름은 클래스의 이름과 같고 리턴 타입을 적지 않는다. // 동일한 이름의 함수가 여러개 나올 수 있다. 이 경우 C++는 괄호 안의 인수의 개수, 개수도 같으면 인수의 형식으로 함수를 구분한다. // 생성자 함수는 객체가 생성되는 순간 자동으로 실행되며 주로 멤버 변수를 초기화 하기 위해서 사용한다. // 생성자 함수를 정의하지 않으면 C++ 컴파일러가 아무런 일도 하지 않는 생성자 함수를 자동으로 만들어 준다. // Score() { // cout << "객체가 생성되었습니다." << endl; // } // ~Score() { // 소멸자(파괴자) 함수 : 객체가 소멸되는 순간 자동으로 실행된다. // cout << "악~~~~ 살려줘~~~~ ㅠㅠ" << endl; // } // 멤버 변수의 접근 권한이 private일 경우 데이터를 전달하는 방법은 객체가 생성되는 순간 생성자 함수를 이용하는 방법이 있다. // name, java, jsp, spring 데이터를 넘겨받아 해당 멤버 변수를 초기화하고 total, average을 계산하는 생성자 함수 Score(string name, int java, int jsp, int spring); // 생성자 함수의 원형만 정의하고 실제 함수는 클래스 밖에서 정의한다. void toString(); // 총점과 평균을 출력하는 멤버 함수의 원형 // 객체가 생성된 후 멤버 변수 초기화를 하려면 setter 함수를 만들어 해야 한다. // setter 함수는 set으로 시작하고 뒤에 멤버 변수 이름이 나오는 함수를 말한다. void setName(string name) { this->name = name; } void setJava(int java) { this->java = java; } void setJsp(int jsp) { this->jsp = jsp; } void setSpring(int spring) { this->spring = spring; } // private 멤버의 값을 얻어와야 한다면 getter 함수를 만들어 해야 한다. // getter 함수는 get으로 시작하고 뒤에 멤버 이름이 나오는 함수를 말한다. bool 값을 얻어오는 getter는 get말고 is로 시작하게 만든다. string getName() { return name; } int getJava() { return java; } int getJsp() { return jsp; } int getSpring() { return spring; } int getTotal() { return total; } double getAverage() { return average; } // 총점과 평균을 계산하는 함수 void culc() { total = this->java + this->jsp + this->spring; average = total / 3.; } }; // 클래스 외부에서 함수를 정의하려면 반드시 함수명 앞에 "클래스이름::"을 붙여서 정의해야 하고 클래스 내부에는 함수의 원형이 있어야 한다. Score::Score(string name = "", int java = 0, int jsp = 0, int spring = 0) { // 디폴트 생성자 함수 // this는 자기 자신의 클래스의 주소를 기억하는 포인터이다. // 멤버 변수와 지역 변수가 이름이 같을 경우 지역 변수에 더 높은 우선 순위가 부여되므로 멤버에 this->를 붙여서 멤버임을 알린다. this->name = name; this->java = java; this->jsp = jsp; this->spring = spring; culc(); // 총점과 평균을 계산하는 함수를 호출한다. } // 총점과 평균을 출력하는 멤버 함수 정의 void Score::toString() { cout << "총점 : " << total << endl; cout << "평균 : " << average << endl; } int main() { // 클래스 변수(객체, 인스턴스) 선언방법 : [class] 클래스(설계도)이름 변수(객체, 인스턴스, 제품)명; class Score s1; // 기본 생성자 함수(Score())가 실행된다. // s.name = "홍길동"; // 멤버 변수 name이 private으로 접근 권한이 설정되어 에러가 발생된다. class Score s2("홍길동", 100, 95, 77); // 생성자 함수 Score(string name, int java, int jsp, int spring)가 실행된다. s2.toString(); s1.setName("임꺽정"); s1.setJava(74); s1.setJsp(85); s1.setSpring(69); s1.culc(); s1.toString(); cout << s1.getName() << endl; // s1의 private 멤버 name을 얻어와서 출력한다. cout << s2.getName() << endl; // s1의 private 멤버 name을 얻어와서 출력한다. } ``` <file_sep>/_javascript/A005 click 이벤트.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>event1</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('.btn1').click(function(){ //alert('버튼을 클릭했습니다.') //alert($('input').val()) input_txt = $('input').val() document.write(input_txt+'로 이메일 전송하였습니다.') }) }) </script> </head> <body> <input type="text" /> <button class="btn1">alert창</button> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>event1</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('a:first').click(function(){ $('img').attr('src','img/m1.jpg') return false }) $('a:eq(1)').click(function(){ $('p img').attr('src','img/m2.jpg') return false }) }) </script> </head> <body> <button class="btn2">영화2</button> <a href="http://www.daum.net">영화1</a> <a href="http://www.daum.net">영화2</a> <a href="http://www.daum.net">영화3</a> <p><img src="img/m1.jpg" alt="인사이드아웃" /></p> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>event3</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ $('a').click(function(){ $('img').attr('src', $(this).attr('href')) return false }) $('button').click(function(){ $('img').attr('src', $(this).attr('data-link') ) }) /* $('a.m1').click(function(){ $('img').attr('src','img/m1.jpg') return false }) $('a.m2').click(function(){ $('img').attr('src','img/m2.jpg') return false }) $('a.m3').click(function(){ $('img').attr('src','img/m3.jpg') return false }) $('a.m4').click(function(){ $('img').attr('src','img/m4.jpg') return false }) */ }) </script> </head> <body> <!-- html5 사용사속성 'data-'로 시작 --> <button data-link="img/m1.jpg">m1</button> <button data-link="img/m2.jpg">m2</button> <button data-link="img/m3.jpg">m3</button> <button data-link="img/m4.jpg">m4</button> <a href="img/m1.jpg" class="m1">영화1</a> <a href="img/m2.jpg" class="m2">영화2</a> <a href="img/m3.jpg" class="m3">영화3</a> <a href="img/m4.jpg" class="m4">영화4</a> <p><img src="img/m1.jpg" alt="인사이드아웃" /></p> </body> </html> ``` <file_sep>/_java/FILE HANDLING - Delete a directory.md ``` import java.io.File; public class DirectoryDeleteTest { public static boolean deleteFile(String filename) { boolean exists = new File(filename).delete(); return exists; } public static void test(String type, String filename) { System.out.println("The following "+type+ " called "+filename+(deleteFile(filename)? " was deleted." : " does not exist.")); } public static void main(String args[]) { test("directory", File.seperator + "docs" + File.seperator); } } ``` ##OUTPUT ``` The following directory called docs was deleted. ```<file_sep>/_java/PATTERN - Alphabet Pattern 1.md ``` /* A BB CCC DDDD EEEEE */ import java.util.*; public class AlphabetPattern { public static void main(String... arg) { int line,row,col; char ch = 'A'; Scanner scanner = new Scanner(System.in); System.out.print("Enter number of lines : "); line = scanner.nextInt(); for(row = 1;row <= line; row++) { for (col = 1; col <= row; col++) { System.out.print(""+ch); } System.out.println(); ch++; } } } ``` ###OUTPUT ``` Enter number of lines : 5 A BB CCC DDDD EEEEE ```<file_sep>/_cpp/완전수, 소수 구하기 그리고 요일 구하기.md ``` #include <cstdio> #include <iostream> using namespace std; int main() { //1증감 연산자(++ : 1증가, -- : 1감소) //a++ : a에 저장된 값을 사용하고 1증가 한다. //++a : a에 저장된 값을 1증가 하고 사용한다. //a-- : a에 저장된 값을 사용하고 1감소 한다. //--a : a에 저장된 값을 1감소 하고 사용한다. /* int a = 100, b; b = a++; cout << "a = " << a << ", b = " << b << endl; b = ++a; //b = ++a + ++a + ++a + ++a; cout << "a = " << a << ", b = " << b << endl; */ //초기치와 조건식을 비교해 참이면 반복을 시작한다. //증감치 만큼 변수값을 변경하고 조건식을 비교해 참이면 반복한다. //for(변수 = 초기치 ; 조건식 ; 증감치) { //조건이 참일동안 반복할 문장; //...; //} /* int sum = 0; for(int i=1 ; i<=100 ; i++) { sum += i; } cout << sum << endl; */ long long int n, sum = 0; cout << "완전수를 판별할 수를 입력하세요 : "; cin >> n; for(long long int i=1 ; i<=n/2 ; i++) { if(n % i == 0) {// i가 n의 약수인가? sum += i;// 약수의 합 cout << i << endl; } } if(sum == n) {// 자신을 제외한 약수의 합이 자신과 같은가? cout << n << "은(는) 완전수" << endl; } else if(sum == 1) { cout << n << "은(는) 소수" << endl; } else { cout << n << "은(는) 완전수 아님" << endl; } } ``` <file_sep>/_javascript/BASIC - Hello World.md ``` <html> <body> <script> document.write("Hello World"); </script> </body> </html> ``` ##OUTPUT ``` Hello World ```<file_sep>/_java/A024 난수 만들기.md ``` import java.util.Random; public class RandomTest { public static void main(String[] args) { // for(int i=0 ; i<100 ; i++) { // System.out.print((int)(Math.random() * 6) + 1 + " "); // Math.random() : 0 이상 1 미만인 무작위 수(난수)를 발생시킨다. // if((i+1)%10 == 0) { // System.out.println(); // } // } Random ran = new Random(); for(int i=0 ; i<100 ; i++) { System.out.print(ran.nextInt(45) + 1 + " "); if((i+1)%10 == 0) { System.out.println(); } } } } ``` <file_sep>/_java/BASIC - If Else.md ``` public class IfElseDemo { public static void main(String args[]) { int x = 30; if( x == 10 ) { System.out.print("Value of X is 10"); } else if( x == 20 ) { System.out.print("Value of X is 20"); } else if( x == 30 ) { System.out.print("Value of X is 30"); } else { System.out.print("This is else statement"); } } } ``` ##OUTPUT ``` Value of X is 30 ```<file_sep>/_java/COLLECTION - HashMap class.md ``` import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class HashMapTest { public static void main(String[] args) { HashMap<Integer,String> hm=new HashMap<Integer,String>(); hm.put(1,"android"); hm.put(2,"java"); hm.put(3,"php"); hm.put(4, "c++"); hm.put(5, "javascript"); System.out.println(hm+" "); System.out.println(); //following are the ways to access the HashMap Iterator iterator = hm.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry mapEntry = (Map.Entry) iterator.next(); System.out.println("The key is: " + mapEntry.getKey() + ",value is :" + mapEntry.getValue()); } System.out.println(); for (Entry<Integer, String> entry : hm.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } System.out.println(); for (Object key : hm.keySet()) { System.out.println("Key : " + key.toString() + " Value : " + hm.get(key)); } } } ``` ##OUTPUT ``` {1=android, 2=java, 3=php, 4=c++, 5=javascript} The key is: 1,value is :android The key is: 2,value is :java The key is: 3,value is :php The key is: 4,value is :c++ The key is: 5,value is :javascript Key : 1 Value : android Key : 2 Value : java Key : 3 Value : php Key : 4 Value : c++ Key : 5 Value : javascript Key : 1 Value : android Key : 2 Value : java Key : 3 Value : php Key : 4 Value : c++ Key : 5 Value : javascript ```<file_sep>/_java/A018 MouseListener.md ``` package com.me.mouseeventtest; import java.awt.Color; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Panel; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MouseEventTest1 extends Frame{ Panel panel1, panel2; public MouseEventTest1() { setTitle("마우스 이벤트"); setBounds(800, 200, 400, 400); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); setLayout(new GridLayout(2, 1)); panel1 = new Panel(); panel1.setBackground(Color.CYAN); add(panel1); panel2 = new Panel(); add(panel2); panel1.addMouseListener(new MouseListener() { @Override public void mouseReleased(MouseEvent e) { System.out.println("마우스 버튼이 떨어질 때 동작하는 메소드"); panel2.setBackground(Color.BLUE); } @Override public void mousePressed(MouseEvent e) { System.out.println("마우스 버튼이 눌러질 때 동작하는 메소드"); panel2.setBackground(Color.RED); } @Override public void mouseExited(MouseEvent e) { System.out.println("마우스 포인터가 마우스 리스너가 걸린 영역에서 나갈 때 동작하는 메소드"); panel2.setBackground(Color.MAGENTA); } @Override public void mouseEntered(MouseEvent e) { System.out.println("마우스 포인터가 마우스 리스너가 걸린 영역으로 들어올 때 동작하는 메소드"); panel2.setBackground(Color.PINK); } @Override public void mouseClicked(MouseEvent e) { System.out.println("마우스 버튼이 클릭될 때 동작하는 메소드(누르고 땠을 때)"); panel2.setBackground(Color.GREEN); } }); setVisible(true); } public static void main(String[] args) { new MouseEventTest1(); } } ``` ``` package com.me.mouseeventtest; import java.awt.Color; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Panel; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MouseEventTest2 extends Frame implements MouseListener{ Panel panel1, panel2; public MouseEventTest2() { setTitle("마우스 이벤트"); setBounds(800, 200, 400, 400); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); setLayout(new GridLayout(2, 1)); panel1 = new Panel(); panel1.setBackground(Color.CYAN); add(panel1); panel2 = new Panel(); add(panel2); panel1.addMouseListener(this); setVisible(true); } public static void main(String[] args) { new MouseEventTest2(); } // MouseListener 인터페이스를 구현하면 밑에 쫙 나옴. @Override public void mouseReleased(MouseEvent e) { System.out.println("마우스 버튼이 떨어질 때 동작하는 메소드"); panel2.setBackground(Color.BLUE); } @Override public void mousePressed(MouseEvent e) { System.out.println("마우스 버튼이 눌러질 때 동작하는 메소드"); panel2.setBackground(Color.RED); } @Override public void mouseExited(MouseEvent e) { System.out.println("마우스 포인터가 마우스 리스너가 걸린 영역에서 나갈 때 동작하는 메소드"); panel2.setBackground(Color.MAGENTA); } @Override public void mouseEntered(MouseEvent e) { System.out.println("마우스 포인터가 마우스 리스너가 걸린 영역으로 들어올 때 동작하는 메소드"); panel2.setBackground(Color.PINK); } @Override public void mouseClicked(MouseEvent e) { System.out.println("마우스 버튼이 클릭될 때 동작하는 메소드(누르고 땠을 때)"); panel2.setBackground(Color.GREEN); } } ``` ``` package com.me.mouseeventtest; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class MouseEventTest3 extends Frame{ Panel panel1, panel2; Label label; int size = 20; public MouseEventTest3() { setTitle("마우스 버튼 이벤트"); setBounds(800, 200, 400, 400); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); setLayout(new GridLayout(2, 1)); panel1 = new Panel(); panel1.setBackground(Color.CYAN); add(panel1); panel2 = new Panel(new BorderLayout()); label = new Label("Label"); label.setFont(new Font("Serif", Font.BOLD, size)); label.setAlignment(Label.CENTER); panel2.add(label); add(panel2); panel1.addMouseListener(new MouseAdapter() { // 마우스 버튼 @Override public void mouseClicked(MouseEvent e) { // if(e.getModifiers() == e.BUTTON1_MASK){ // System.out.println("왼쪽 버튼 눌림"); // } else if(e.getModifiers() == e.BUTTON2_MASK){ // System.out.println("가운데 버튼(휠) 눌림"); // } else if(e.getModifiers() == e.BUTTON3_MASK){ // System.out.println("오른쪽 버튼 눌림"); // } if(e.getButton() == 1){ System.out.println("왼쪽 버튼 눌림"); } else if(e.getButton() == 2){ System.out.println("가운데 버튼(휠) 눌림"); } else if(e.getButton() == 3){ System.out.println("오른쪽 버튼 눌림"); } // getClickCount() : 마우스 버튼이 클릭된 횟수를 얻는다. if(e.getClickCount() == 2){ System.out.println("더블 클릭"); } else{ System.out.println("클릭"); } } }); panel1.addMouseWheelListener(new MouseWheelListener() { // 마우스 휠 @Override public void mouseWheelMoved(MouseWheelEvent e) { if(e.getWheelRotation() < 0){ System.out.println("업 스크롤"); // label의 크기가 점점 커짐. label.setFont(new Font("Serif", Font.BOLD, size++)); } else{ System.out.println("다운 스크롤"); // label의 크기가 점점 작아짐. label.setFont(new Font("Serif", Font.BOLD, size--)); } } }); panel1.addMouseMotionListener(new MouseMotionListener() { // 마우스 포인터 @Override public void mouseMoved(MouseEvent e) { // getPoint() : 마우스 포인터의 x, y좌표를 얻어온다. // getX() : 마우스 포인터의 x좌표를 얻어온다. // getY() : 마우스 포인터의 y좌표를 얻어온다. System.out.println("마우스가 움직입니다. 좌표 : " + e.getPoint()); System.out.println("마우스가 움직입니다. X좌표 : " + e.getX()); System.out.println("마우스가 움직입니다. Y좌표 : " + e.getY()); } @Override public void mouseDragged(MouseEvent e) { System.out.println("마우스가 드래그되고 있습니다. 좌표 : " + e.getPoint()); System.out.println("마우스가 드래그되고 있습니다. X좌표 : " + e.getX()); System.out.println("마우스가 드래그되고 있습니다. Y좌표 : " + e.getY()); } }); setVisible(true); } public static void main(String[] args) { new MouseEventTest3(); } } ``` <file_sep>/_java/SYSTEM - Find IP Address of Machine.md ``` import java.net.*; public class IPAddress{ public static void main(String args[]){ try{ InetAddress ipAddr = InetAddress.getLocalHost(); System.out.println("\nIP address of the machine: " + ipAddr.getHostAddress()); } catch(UnknownHostException ex){ ex.printStackTrace(); } } } ``` __OUTPUT__ ``` IP address of the machine: 192.168.1.36 ``` <file_sep>/_java/PATTERN - Number Pattern 1.md ``` ------------------ 1 12 123 1234 12345 ------------------- public class NumberPat1 { public static void main(String arg[]) { for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { System.out.print(j); } System.out.println(); } } } ``` ##OUTPUT ``` 1 12 123 1234 12345 ```<file_sep>/_cpp/배열을 사용하는 여러 방법.md ``` #include <cstdio> #include <iostream> #include <iomanip> using namespace std; int main() { int a[5][5] = {0, }; int count = 0; // 1~25 까지 1씩 증가할 변수 // 배열에 숫자를 채운다. for(int i=0 ; i<5 ; i++) { // 행 // 짝수행은 왼쪽에서 오른쪽으로 홀수행은 오른쪽에서 왼쪽으로 채운다. if(i % 2 == 0) { // 짝수인감? for(int j=0 ; j<5 ; j++) { // 열이 왼쪽에서 오른쪽으로 진행된다. a[i][j] = ++count; } } else { for(int j=4 ; j>=0 ; j--) { // 열이 오른쪽에서 왼쪽으로 진행된다. a[i][j] = ++count; } } } // 배열의 내용을 출력한다. for(int i=0 ; i<5 ; i++) { // 행 for(int j=0 ; j<5 ; j++) { // 열 cout << setw(2) << a[i][j] << " "; } cout << endl; // 1행 출력하고 줄바꿈 } } ``` ``` #include <cstdio> #include <iostream> #include <iomanip> using namespace std; int main() { int a[5][5] = {0, }; int count = 0; // 1~25 까지 1씩 증가할 변수 int start = 0, end = 4; // 반복 시작 값과 끝 값을 초기화 int sign = 1; // 증가치의 부호 변경에 사용할 변수 // 배열에 숫자를 채운다. for(int i=0 ; i<5 ; i++) { // 행 // i가 짝수면 0(start) 부터 5(end+sign)가 아닐때 까지 1(sign)씩 증가한다. // i가 홀수면 4(start) 부터 -1(end+sign)이 아닐때 까지 1(sign)씩 감소한다. for(int j=start ; j!=end+sign ; j+=sign) { a[i][j] = ++count; } // 위와 같은 식을 Visual Basic으로 코딩하면 아래와 같다. // for i = start to end step sign // count = count + 1 // a(i, j) = count; // next i int temp = start; start = end; end = temp; sign *= -1; } // 배열의 내용을 출력한다. for(int i=0 ; i<5 ; i++) { // 행 for(int j=0 ; j<5 ; j++) { // 열 cout << setw(2) << a[i][j] << " "; } cout << endl; // 1행 출력하고 줄바꿈 } } ``` ``` #include <cstdio> #include <iostream> #include <iomanip> using namespace std; int main() { int a[5][5] = {0, }; int count = 0; // 1~25 까지 1씩 증가할 변수 int k = 5; // 반복문의 반복 횟수 제어에 사용할 변수 int sign = 1; // 증가치의 부호 변경에 사용할 변수 int row = 0, col = -1; // 배열의 행, 열 첨자에 사용될 변수 // 배열에 숫자를 채운다. while(true) { for(int i=0 ; i<k ; i++) { // 행방향 채우기 col += sign; a[row][col] = ++count; } if(--k == 0) { break; } for(int i=0 ; i<k ; i++) { // 열방향 채우기 row += sign; a[row][col] = ++count; } sign *= -1; } // 배열의 내용을 출력한다. for(int i=0 ; i<5 ; i++) { // 행 for(int j=0 ; j<5 ; j++) { // 열 cout << setw(2) << a[i][j] << " "; } cout << endl; // 1행 출력하고 줄바꿈 } } ``` <file_sep>/_java/BASIC - Command Line Argument.md ``` class CommandLineArgs { public static void main(String args[]) { int a, b, c; a = Integer.parseInt(args[0]); b = Integer.parseInt(args[1]); c = Integer.parseInt(args[2]); if (a > b && a > c) { System.out.println("Largest Number is : " + a); } else if (b > c) { System.out.println("Largest Number is : " + b); } else { System.out.println("Largest Number is : " + c); } } } ``` ##OUTPUT ``` java LargestNumber 2 5 7 Largest Number is : 7 ```<file_sep>/_cpp/포인터 사용 이해하기.md ``` #include <cstdio> #include <iostream> #include <iomanip> using namespace std; int main() { int a = 100; // 일반 변수 : 값을 기억한다. int *p1; // 포인터 변수 : 일반 변수의 주소를 기억한다. // p1 = a; // 포인터 변수에 일반 변수의 값을 넣으려 했으므로 에러가 발생된다. p1 = &a; // & : 번지 연산자, & 뒤의 변수가 생성된 메모리의 주소를 얻어온다. cout << "a가 생성된 메모리의 주소 : " << &a << endl; cout << "p1에 저장된 a의 주소 : " << p1 << endl; // * : 참조 연산자, 포인터 변수에 기억된 주소에 저장된 값을 얻어온다. cout << "p1에 저장된 주소에 저장된 값 : " << *p1 << endl; int b[] = {1, 3, 5, 7, 9}; int *p2; p2 = b; // 배열의 이름은 그 배열의 시작 주소를 의미하는 번지 상수이므로 에러가 발생되지 않는다. // p2 = b[0]; // 배열 요소는 일반 변수와 똑같이 취급되므로 에러가 발생된다. // p2 = &b[0]; // 배열 요소도 일반 변수와 똑같이 취급되므로 번지 연산자 &를 붙여줘야 한다. cout << "b가 알고있는 배열의 시작 주소 : " << b << endl; cout << "b[0]가 생성된 메모리의 주소 : " << &b[0] << endl; cout << "p2에 저장된 b[0]의 주소 : " << p2 << endl; for(int i=0 ; i<5 ; i++) { cout << "b[" << i << "] = " << b[i] << endl; } for(int i=0 ; i<5 ; i++) { cout << "p2[" << i << "] = " << p2[i] << endl; } // 포인터에 실행하는 가감연산은 1당 포인터에 기억된 자료형의 크기만큼 커지고 작아진다. for(int i=0 ; i<5 ; i++) { cout << "*(p2 + " << i << ") = " << *(p2 + i) << endl; } for(int i=0 ; i<5 ; i++) { cout << "p2 + " << i << " = " << p2 + i << endl; } for(int i=0 ; i<5 ; i++) { cout << "*p2 + " << i << " = " << *p2 + i << endl; } } ``` ``` #include <cstdio> #include <iostream> #include <iomanip> using namespace std; #include <string> // 문자열을 처리할 수 있는 string 클래스를 사용하기 위한 헤더 파일 int main() { // 문자열은 문자열의 끝을 의미하는 null(\0)이 자동으로 붙기때문에 1개 크게 잡아야 한다. // char str[4] = "test"; // 에러 발생 // char str[] = "test"; // 배열의 크기를 안적으면 필요한 만큼 잡아주므로 에러가 발생되지 않는다. char *str = "test"; // 포인터는 배열과 같은 의미로 사용할 수 있으므로 에러가 발생되지 않는다. char *number[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; char *symbol[] = {"♠", "◇", "♥", "♧"}; printf("%s\n", str); cout << str << endl; // char name[10]; // 배열의 크기 이상의 문자열은 입력 받을 수 없다. // char *name; // 포인터가 선언만 되어있고 주소가 할당되지 않았으므로 에러 발생 // char *name = new char[10]; // 포인터를 선언하며 메모리를 할당했으므로 에러는 발생되지 않지만 배열과 똑같이 쓰인다. string jumin; // string 클래스로 변수를 선언해 문자열을 입력받는다. string number1[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; // at(index) : 문자열에서 index 번째 문자를 얻어온다. // size() : 문자열의 개수를 얻어온다. cout << "주민등록번호 : "; cin >> jumin; if(jumin.at(6) - '0' == 1) { cout << "남자" << endl; } else { cout << "여자" << endl; } } ``` <file_sep>/_cpp/진수 변환.md ``` #include <cstdio> #include <iostream> using namespace std; int main() { //선 비교 후 실행, 최초(진입) 조건이 거짓이면 {} 블록을 한번도 실행하지 않는다. //while(조건식) { // 조건이 참일 동안 실행 할 문장; // ...; //} //while(true) { // 무한 Loop // 반복을 탈출할 조건과 break가 반드시 있어야 한다. // if(조건식) { // break; // } //} //선 실행 후 비교, 최초(진입) 조건이 거짓이더라도 {} 블록을 한번은 실행한다. //do { // 조건이 참일 동안 실행 할 문장; // ...; //} while(조건식); // ";" 빼먹지 말자 int dec, n; cout << "10진수와 변환할 진법 : "; cin >> dec >> n; //배열 선언 방법 //자료형 배열명[첨자]; // 쓰레기가 한가득 //자료형 배열명[] = {초기치}; // 초기치의 수만큼 배열을 자동으로 만든다. int bin[8] = {0, }; // 모두 0으로 초기화 int mok, nmg, count = 7; while(true) { mok = dec / n; // 몫을 구한다. nmg = dec % n; // 나머지를 구한다. bin[count--] = nmg; // 나머지를 배열에 넣어주고 배열의 첨자를 1 작게한다. if(mok == 0) { // 몫이 0인가? //exit(0); // 프로그램 강제종료 //return 0; // 프로그램 강제종료 break; // 몫이 0이면 진법계산을 종료한다. } dec = mok; // 다음 반복을 위해 dec에 mok을 넣어준다. } //cout << count << endl; for(int i=count+1 ; i<8 ; i++) { if(bin[i] < 10) { cout << bin[i] << " "; } else { cout << (char)(bin[i] + 55) << " "; } } cout << endl; } ``` <file_sep>/_cpp/윤년구하기.md ``` #include <cstdio> #include <iostream> using namespace std; int main() { int year; cout << "윤년/평년을 판단할 년도를 입력하세요 : "; //scanf("입력서식", &변수명); // Visual C++ 6.0 까지 //scanf_s("입력서식", &변수명); // Visual Stduio 2008 부터 //scanf_s("%d", &year); //배열의 이름은 그 배열의 시작위치를 기억하는 번지 상수이므로 &를 붙이지 않는다. cin >> year; //관계(비교) 연산자 //>(크다, 초과), >=(크거나 같다, 이상), <(작다, 미만), <=(작거나 같다, 이하) //==(같다), !=(같지 않다) //논리 연산자 //&&(AND, 논리곱) : 모든 조건이 참일때 참, ~이고, ~이면서, ~중에서 //||(OR, 논리합) : 모든 조건 중에서 1개 이상 참일때 참, ~또는, ~이거나 //!(NOT, 논리부정) //C++은 0은 false로 0이 아닌 나머지 모든 숫자는 true로 취급한다. //윤년/평년 판별식 //4로 나눠 떨어지고(&&) 100으로 나눠 떨어지지 않거나(||) 400으로 나눠 떨어지면 윤년 //cout << "3 < 4 = " << (3 < 4) << endl; //cout << "3 > 4 = " << (3 > 4) << endl; //cout << "true = " << true << endl; //cout << "false = " << false << endl; //cout << "!(!(3)) = " << !(!(3)) << endl; //cout << "!(!(-3)) = " << !(!(-3)) << endl; //if(조건식) { // 조건이 참일 경우 실행할 문장; // ...; //} else { // 조건이 거짓일 경우 실행할 문장; // ...; //} //프로그램의 여러곳에서 사용되는 값은 변수에 넣어서 사용하면 편리하다. //int isYoun = year%4 == 0 && year%100 != 0 || year%400 == 0; bool isYoun = year%4 == 0 && year%100 != 0 || year%400 == 0; //sizeof() : 괄호 안의 기억장소가 메모리에서 차지하는 크기를 출력한다. cout << sizeof(isYoun) << endl; if(isYoun) { cout << year << "년은 윤년입니다." << endl; } else { cout << year << "년은 평년입니다." << endl; } //삼항(조건) 연산자 //조건식 ? 참일 경우 실행할 내용 : 거짓일 경우 실행할 내용; cout << year << "년은 " << (isYoun ? "윤년" : "평년") << "입니다." << endl; } ``` <file_sep>/_htmlCss/A023 기업형 사이트 구조.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="user-scalable=yes, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, width=device-width" /> <title>html layout구조</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link href="css/common.css" rel="stylesheet" type="text/css" /> <link href="css/main.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="headerWrap"> <header id="header" class="box_width"> <h1 class="logo"><a href="#"><img src="img/logo.png" width="161" height="37" alt="LG엔시스 로고" /></a></h1> <div class="top"> <ul class="t_menu"> <li><a href="#">LOGIN</a></li> <li><a href="#">JOIN</a></li> <li><a href="#">SITEMAP</a></li> <li><a href="#">ENGLISH</a></li> <li class="tm5"><a href="#">고객지원</a></li> </ul> <div class="schBox"> <form action="#"> <fieldset> <legend>검색</legend> <label for="inputSch" class="hide">검색</label> <input type="text" id="inputSch" /> <button id="btnSch">찾기</button> </fieldset> </form> </div> </div><!--//top --> <nav id="nav"> <ul class="gnb"> <li class="m1"><h2 class="m_title"><a href="#">기업소개</a></h2> <ul class="sub"> <li><a href="#">기업소개</a></li> <li><a href="#">브랜드</a></li> <li><a href="#">CEO</a></li> <li><a href="#">정도경영</a></li> <li><a href="#">오시는길</a></li> </ul> </li> <li class="m2"><h2 class="m_title"><a href="#">사업소개</a></h2> <ul class="sub"> <li><a href="#">사업소개</a></li> <li><a href="#">구축사례</a></li> <li><a href="#">만화로보는 엔시스</a></li> <li><a href="#">파트너안내</a></li> </ul> </li> <li class="m3"><h2 class="m_title"><a href="#">제품소개</a></h2></li> <li class="m4"><h2 class="m_title"><a href="#">홍보센터</a></h2></li> <li class="m5"> <h2><a href="#"><img src="img/jops-button.png" alt="인재채용" width="87" height="26" /></a> </h2> </li> </ul> </nav><!--//nav--> </header><!--//header--> </div><!--//headerWrap--> <div id="slider"> <div class="view_img"> <ul class="wrap_img"> <li><img src="img/slideimg01.jpg" width="1024" height="424" alt="" /></li> <li><img src="img/slideimg02.jpg" width="1024" height="424" alt="" /></li> <li><img src="img/slideimg03.jpg" width="1024" height="424" alt="" /></li> </ul> <div class="view_txt"> <ul class="wrap_txt"> <li><img src="img/txtimg01.png" alt="스마트한 혁명" width="316" height="328" /></li> <li><img src="img/txtimg02.png" alt="스마트 그린" width="316" height="328" /></li> <li><img src="img/txtimg03.png" alt="스마트 패러다임" width="316" height="328" /></li> </ul> <ul class="btn"> <li><img src="img/slidOn-icon.png" alt="on" /></li> <li><img src="img/slid-icon.png" alt="off" /></li> <li><img src="img/slid-icon.png" alt="off" /></li> <li><img src="img/slidPlay-icon.png" alt="일시정지" /></li> </ul> </div> </div><!--//view --> </div><!--//slider --> <div id="mainContents" class="box_width"> <ul class="mbox"> <!-- 1th box --> <li> <h3 class="mb_title"><img src="img/tit_m1.gif" alt="보도자료" /></h3> <ul class="mb_sub"> <li><a href="#">정부지원 UHD사업에 렌더링 협력업체 단독 선정</a></li> <li><a href="#">비즈머스와 클라우드 어플라이언스 사업 추진</a></li> <li><a href="#">UHD시대 CG인프라는 LG엔시스 '스마트 렌더'</a></li> <li><a href="#">LG엔시스, 2014년 매출 8천억 돌파</a></li> </ul> </li> <!-- 2th box --> <li> <h3 class="mb_title"><img src="img/tit_m2.gif" alt="구축사례" /></h3> <ul class="mb_sub"> <li><a href="#">수협중앙회 사이버보안관제센터 구축</a></li> <li><a href="#">한국항공우주연구원 데이터 유출방지 솔루션</a></li> <li><a href="#">한국과학기술정보연구원 Sopra UPB</a></li> <li><a href="#">금융감독원 재해복구시스템 구축</a></li> </ul> </li> <!-- 3th box --> <li> <h3 class="mb_title hide"><img src="img/tit_m3.png" alt="홍보영상" /></h3> <a href="#"><img src="img/img_video.jpg" alt="홍보영상" /></a> </li> <!-- 4th box --> <li> <h3 class="mb_title hide"><img src="img/tit_m5.gif" alt="채용공고" /></h3> <a href="#"><img src="img/img_career.jpg" alt="여러분의 꿈과 열정-LG엔시스가 함께합니다." /></a> </li> <!-- 5th box --> <li> <h3 class="mb_title hide">웹진</h3> <a href="#"><img src="img/main_webzine_2014_v3.jpg" alt="조화와 상생의시대 -2015년 2호" /></a> </li> <!-- 6th box --> <li> <h3 class="mb_title"><img src="img/tit_m6.gif" alt="이벤트" /></h3> <ul class="mb_sub"> <li><a href="#">[문화이벤트] 국민연극 라이어</a></li> <li><a href="#">LG엔시스 웹진 이벤트에 참여하면 선물이 팡팡</a></li> </ul> </li> </ul> </div><!--//mainContents--> <div id="footerWrap"> <footer id="footer" class="box_width"> </footer><!--//footer--> </div><!--//footerWrap--> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="user-scalable=yes, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, width=device-width" /> <title>html layout구조</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link href="css/common.css" type="text/css" rel="stylesheet" /> <link href="css/main.css" type="text/css" rel="stylesheet" /> </head> <body> <div id="headerWrap" > <header id="header" class="box_width"> <h1 class="logo"><a href="#"><img src="img/logo.png" width="161" height="37" alt="LG엔시스 로고" /></a></h1> <div class="top"> <ul class="t_menu"> <li><a href="#">LOGIN</a></li> <li><a href="#">JOIN</a></li> <li><a href="#">SITEMAP</a></li> <li><a href="#">ENGLISH</a></li> <li class="tm5"><a href="#">고객지원</a></li> </ul> <div class="schBox"> <form action="#"> <fieldset> <legend>검색</legend> <label for="inputSch" class="hide">검색</label> <input type="text" id="inputSch" /> <button id="btnSch">찾기</button> </fieldset> </form> </div> </div><!--//top --> <nav id="nav" > <ul class="gnb"> <li class="m1"><h2 class="m_title"><a href="#">기업소개</a></h2> <ul class="sub"> <li><a href="#">기업소개</a></li> <li><a href="#">브랜드</a></li> <li><a href="#">CEO</a></li> <li><a href="#">정도경영</a></li> <li><a href="#">오시는길</a></li> </ul> </li> <li class="m2"><h2 class="m_title"><a href="#">사업소개</a></h2> <ul class="sub"> <li><a href="#">사업소개</a></li> <li><a href="#">구축사례</a></li> <li><a href="#">만화로보는 엔시스</a></li> <li><a href="#">파트너안내</a></li> </ul> </li> <li class="m3"><h2 class="m_title"><a href="#">제품소개</a></li></h2> <li class="m4"><h2 class="m_title"><a href="#">홍보센터</a></li></h2> <li class="m5"><h2><a href="#"><img src="img/jops-button.png" alt="인재채용" width="87" height="26" /></a></h2></li> </ul> </nav><!--//nav--> </header> <!--//header--> </div><!--//headerWrap--> <div id="slider" class="box_width"> <div class="view_img"> <ul class="wrap_img"> <li><img src="img/slideimg01.jpg" width="1024" height="424" alt="" /></li> <li><img src="img/slideimg02.jpg" width="1024" height="424" alt="" /></li> <li><img src="img/slideimg03.jpg" width="1024" height="424" alt="" /></li> </ul> <div class="view_txt"> <ul class="wrap_txt"> <li><img src="img/txtimg01.png" alt="스마트 혁명" width="316" height="328" /></li> <li><img src="img/txtimg02.png" alt="스마트 그린" width="316" height="328" /></li> <li><img src="img/txtimg03.png" alt="스마트 패러다임" width="316" height="328" /></li> </ul> <ul class="btn"> <li><img src="img/slidOn-icon.png" alt="on" /></li> <li><img src="img/slid-icon.png" alt="off" /></li> <li><img src="img/slid-icon.png" alt="off" /></li> <li><img src="img/slidPlay-icon.png" alt="일시정지" /></li> </ul> </div><!--//view_txt --> </div><!--//view--> </div><!--//slider --> <div id="mainContents" class="box_width"> <ul class="mbox clearfix"> <!--1th box--> <li> <h3 class="mb_title"><img src="img/tit_m1.gif" alt="보도자료" /></h3> <ul class="mb_sub"> <li><a href="#">정부지원 UHD사업에 렌더링 협력업체 단독 선정</a></li> <li><a href="#">비즈머스와 클라우드 어플라이언스 사업 추진</a></li> <li><a href="#">UHD시대 CG인프라는 LG엔시스 '스마트 렌더'</a></li> <li><a href="#">LG엔시스, 2014년 매출 8천억 돌파</a></li> </ul> <a href="#"><span class="more">더보기</span></a> </li> <!--//1th box--> <!--2th box--> <li> <h3 class="mb_title"><img src="img/tit_m2.gif" alt="구축사례" /></h3> <ul class="mb_sub"> <li><a href="#">수협중앙회 사이버보안관제센터 구축</a></li> <li><a href="#">한국항공우주연구원 데이터 유출방지 솔루션</a></li> <li><a href="#">한국과학기술정보연구원 Sopra UPB</a></li> <li><a href="#">금융감독원 재해복구시스템 구축</a></li> </ul> <a href="#"><span class="more">더보기</span></a> </li> <!--//2th box--> <!--3th box--> <li class="margin_none"> <h3 class="mb_title hide"><img src="img/tit_m3.png" alt="홍보영상" /></h3> <a href="#"><img src="img/img_video.jpg" alt="홍보영상" width="333" height="188" /></a> </li> <!--//3th box--> <!--4th box--> <li> <h3 class="mb_title hide"><img src="img/tit_m5.gif" alt="채용공고" /></h3> <a href="#"><img src="img/img_career.jpg" alt="여러분의 꿈과 열정 LG엔시스가 함께합니다." width="332" height="188" /></a> </li> <!--//4th box--> <!--5th box--> <li> <h3 class="mb_title hide">웹진</h3> <a href="#"><img src="img/main_webzine_2014_v3.jpg" alt="꿈의 영역,현실로 다가온다.인공지는 로봇 시대 웹진 IT전망대" /></a> </li> <!--//5th box--> <!--6th box--> <li class="margin_none"> <h3 class="mb_title"><img src="img/tit_m6.gif" alt="이벤트" /></h3> <ul class="mb_sub"> <li><a href="#">[문화이벤트] 국민연극 라이어</a></li> <li><a href="#">LG엔시스 웹진 이벤트에 참여하면 선물이 팡팡</a></li> </ul> <a href="#"><span class="more">더보기</span></a> </li> <!--//6th box--> </ul> </div><!--//mainContents--> <div id="footerWrap"> <footer id="footer" class="box_width"> <ul class="f_menu"> <li><h2><a href="#">기업소개</a></h2> <ul class="f_sub"> <li><a href="#">기업소개</a></li> <li><a href="#">브랜드</a></li> <li><a href="#">CEO</a></li> <li><a href="#">정도경영</a></li> <li><a href="#">오시는길</a></li> </ul> </li> <li><h2><a href="#">사업소개</a></h2> <ul class="f_sub"> <li><a href="#">사업소개</a></li> <li><a href="#">구축사례</a></li> <li><a href="#">만화로보는 엔시스</a></li> <li><a href="#">파트너안내</a></li> </ul> </li> <li><h2><a href="#">제품소개</a></h2> <ul class="f_sub"> <li><a href="#">사업소개</a></li> <li><a href="#">구축사례</a></li> <li><a href="#">파트너안내</a></li> <li><a href="#">사업소개</a></li> <li><a href="#">구축사례</a></li> <li><a href="#">파트너안내</a></li> </ul> </li> <li><h2><a href="#">홍보센터</a></h2> <ul class="f_sub"> <li><a href="#">사업소개</a></li> <li><a href="#">구축사례</a></li> <li><a href="#">파트너안내</a></li> <li><a href="#">사업소개</a></li> <li><a href="#">구축사례</a></li> <li><a href="#">파트너안내</a></li> </ul> </li> <li><h2><a href="#">고객지원</a></h2> <ul class="f_sub"> <li><a href="#">사업소개</a></li> <li><a href="#">구축사례</a></li> <li><a href="#">파트너안내</a></li> </ul> </li> <li><h2><a href="#">인재채용</a></h2></li> </ul><!--//f_menu--> <div class="f_menu_r"> <select id="f_company"> <option>Family site</option> <option>(주)LG</option> <option>LG CNS</option> <option>파트너넷</option> </select> <ul> <li><a href="#"><img src="img/footer_sinmungo.png" alt="정도경영신문고"/></a></li> <li><a href="#">협력회사 상생고</a></li> <li><a href="#">개인정보취급방침</a></li> <li><a href="#">이용약관</a></li> <li><a href="#">이메일 무단수집 거부</a></li> </ul> </div> <div class="f_bottom"> <address class="addr">서울시 마포구 마포대로 LG마포빌딩 (02)3773-1114</address> <p class="copyright">COPYROGHT 2015 LG-NSys Inc ALL Rights Reserved</p> </div> </footer><!--//footer--> </div><!--//footerWrap--> </body> </html> ``` <file_sep>/_jspServlet/A001 Servlet-Programming.md ### 서블릿 프로그래밍 자바에서는 웹 브라우저와 웹 서버를 활용하여 좀 더 쉽게 서버 애플리케이션을 개발할 수 있도록 **서블릿(Servlet)**이라는 기술을 제공하고 있다. 이 서블릿 기술을 이용하여 웹 애플리케이션을 개발하는 것을 보통 **서블릿 프로그래밍**이라 부른다. ### CGI 프로그램과 서블릿 * CGI의 이해 - 사용자가 직접 아이콘을 더블 클릭하거나 명령 창(또는 터미널)을 통해 실행시키는 프로그램을 일반적으로 **애플리케이션** 또는 **데스크톱 애플리케이션** 이라고 한다. 반면에 사용자가 웹 서버를 통해 간접적으로 실행시키는 프로그램이 **웹 애플리케이션**. * CGI 프로그램 - CGI 프로그램은 C나 C++, JAVA와 같은 컴파일 언어로 작성할 수 있으며 Perl, PHP, Python, VBScript 등 스크립트 언어로도 작성할 수 있다. 컴파일 방식은 기계어로 번역된 코드를 실행하기에 속도가 빠르지만, 변경 사항 발생시 재 컴파일하고 재배포 해야하는 문제가 있다. ### 서블릿 자바 CGI프로그램은 C/C++ 처럼 컴파일 방식이다. 자바로 만든 CGI 프로그램을 **서블릿(Servlet)**이라고 부르는데, 자바 서블릿이 다른 CGI 프로그램과 다른 점은 웹 서버와 직접 데이터를 주고받지 않으며 전문 프로그램에 의해 관리된다는 것. <file_sep>/_javascript/A006 mousedown,click으로 body 속성값 바꾸기.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Event5</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ /* $('.m_list li a').click(function(){ $('p img').attr('src',$(this).attr('href')) .attr('alt',$(this).attr('title')) return false }) $('.m_list li a').mouseover(function(){ $(this).text( $(this).attr('title')) }).mouseout(function(){ $(this).text($(this).attr('data-txt')) }).click(function(){ return false }) */ //mouseup, mousedown, dblclick <----click이벤트 같이 처리 // a 링크 걸려있을 경우 $('.m_list li a').mousedown(function(){ $(this).text( $(this).attr('title')) }).click(function(){ return false }) }) </script> </head> <body> <ul class="m_list"> <li><a href="img/m1.jpg" title="인사이드아웃" data-txt="영화1">영화1</a></li> <li><a href="img/m2.jpg" title="연평해전" data-txt="영화2">영화2</a></li> <li><a href="img/m3.jpg" title="픽셀" data-txt="영화3">영화3</a></li> <li><a href="img/m4.jpg" title="쓰리썸머나잇" data-txt="영화4">영화4</a></li> </ul> <p><img src="img/m1.jpg" alt="인사이드아웃" /></p> </body> </html> ``` <file_sep>/_java/FILE HANDLING - Create a file.md ``` import java.io.*; public class CreateFileTest { public static void main(String args[]) { try { if(new File("output.txt").createNewFile()) System.out.println("Successfully created File."); else System.out.println("Failed to create file."); } catch (IOException e) { System.err.println(e.getMessage()); } } } ``` ###OUTPUT ``` Successfully created File. ```<file_sep>/_java/PATTERN - Binary Pattern.md ``` /* 1 01 101 0101 10101 */ public class BinaryPattern { public static void main(String s[]) { int i, j; int count = 1; for (i = 1; i <= 5; i++) { for (j = 1; j <= i; j++) { System.out.format("%d", count++ % 2); if(j==i && i!=5) System.out.println(""); } if (i % 2 == 0) count = 1; else count = 0; } } } ``` ###OUTPUT ``` 1 01 101 0101 10101 ```<file_sep>/KNOU.java.test/src/knou/test/awt/PulldownMenu2.java package knou.test.awt; import java.awt.CheckboxMenuItem; import java.awt.Frame; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; class MenuListener implements ActionListener { public void actionPerformed(ActionEvent ev) { System.out.println(ev.getActionCommand()); } } class CheckMenuListener implements ItemListener { public void itemStateChanged(ItemEvent ev) { System.out.println(ev.getItem() + "\t"); if (ev.getStateChange() == ItemEvent.SELECTED) System.out.println("SELECTED"); else System.out.println("DESELECTED"); } } public class PulldownMenu2 extends Frame{ MenuBar mb; ActionListener al; public void SetMenu() { Menu m, sm; mb = new MenuBar(); m = new Menu("Menu1"); m.add(new MenuItem("MenuItem1")); sm = new Menu("SubMenu1", true); sm.add(new MenuItem("SubMenuItem1")); sm.add(new CheckboxMenuItem("SubMenuItem2")); m.add(sm); m.add(new MenuItem("menuItem2")); mb.add(m); setMenuBar(mb); //이벤트 리스너 등록 for(int i=0; i<mb.getMenuCount(); i++) { m=mb.getMenu(i); registerListener((MenuItem)m); } } private void registerListener(MenuItem mi) { mi.addActionListener(al); if(mi instanceof Menu) { Menu mm = (Menu)mi; for(int i=0; i<mm.getItemCount(); i++){ registerListener(mm.getItem(i)); } } else if (mi instanceof CheckboxMenuItem) { ((CheckboxMenuItem)mi).addItemListener(new CheckMenuListener()); } } public PulldownMenu2() { al=new MenuListener(); } public static void main(String[] args) { PulldownMenu2 f = new PulldownMenu2(); f.setSize(200,200); f.setVisible(true); f.SetMenu(); } } <file_sep>/_java/A038 슈퍼클래스와 서브클래스의 상속관계.md ``` public class InteritanceTest { public static void main(String[] args) { Parent parent = new Parent("홍길동", true); System.out.println(parent); Child child = new Child("홍길자", false); System.out.println(child); } } // 부모(상위, 슈퍼, 기반) 클래스 public class Parent { private String name; private boolean gender; public Parent() { } public Parent(String name, boolean gender) { this.name = name; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } @Override public String toString() { return "부모 클래스의 toString() : " + name + "(" + (gender ? "남" : "여") + ")"; } } // 부모(Parent) 클래스를 상속받는 자식(하위, 서브, 파생) 클래스 // 상속 방법 : public class 자식클래스 extends 부모클래스 // 자바는 다중 상속을 지원하지 않는다. 부득이하게 다중 상속 효과를 내고 싶으면 인터페이스를 사용한다. public class Child extends Parent { // 부모 클래스의 변수 name, gender 그리고 모든 메소드(생성자, getter, setter, toString)를 상속 받았다. // 자식 클래스에서 사용할 멤버 변수를 만든다. private int age; private String nickName; // 부모 클래스로 부터 상속받은 멤버 변수가 private으로 정의되어 있을 경우 멤버에 초기값을 할당하기 위해서 // 부모 클래스의 생성자 메소드를 상속받아 자식 클래스의 생성자 메소드를 정의한다. public Child() { // 부모 클래스의 생성자 메소드 Parent()를 호출한다. super(); } public Child(String name, boolean gender) { // 부모 클래스의 생성자 메소드 Parent(String name, boolean gender)를 호출한다. super(name, gender); } } ``` <file_sep>/_htmlCss/A010 float 속성.md ``` 선택자 { 속성 : 값 }의 형태로 사용됩니다. 1.태그선택자 (예약어 사용) - tag 2.클래스선택자 (.) - 사용자가 임의의 클래스를 만들어서 원하는 선택자에 값을 부여 3.아이디선택자 (#) - id : 단일한값 block 태그는 width 안주면 화면에 100% #wrap { width:960px; } #header { height:100px; background-color:lime; // width가 화면에 100% float -> 위에 block에 사용하면 흐름을 따로 얻는다. (겹쳐서 위로 올라가짐) clear -> 겹치는 부분을 없애줌 ( clear:left/right/both ) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>기본2단 레이아웃-float이해하기</title> <style type="text/css"> #wrap { width:960px; } #header { height:100px; background-color:#9C3;} #nav{ height:40px; background-color:#333;} #aside{ float:left; width:150px; height:400px; background-color:#FFCCFF} #contents{ width:810px; background-color:#FF9900; float:right;} #footer{ height:100px; background-color:#CCC; clear:both} </style> </head> <body> <div id="wrap"> <div id="header"> </div><!--//header--> <div id="nav"> </div><!--//nav--> <div id="aside"> </div><!--//aside--> <div id="contents"> <p>fasfasf </p> <p>dsa</p> <p>fdsa</p> <p>fdasf</p> <p>asf</p> <p>saf</p> <p>dasfd</p> <p>asf</p> <p>asdf</p> <p>dasfd</p> <p>asd</p> <p>fasd</p> <p>fas</p> <p>fas</p> <p>fas</p> <p>fds</p> <p> fdsafdas fdsafdsafd fdas fddasfd sadf asdf dsaf dsa fd asf </p> </div><!--//contents--> <div id="footer"> </div><!--//footer--> </div> </body> </html> ``` <file_sep>/_java/A022 성별 확인.md ``` import java.util.Scanner; public class GenderCheck { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("주민등록번호 13자리를 '-'없이 입력하세요 : "); String jumin = sc.nextLine(); // System.out.println("입력한 문자의 개수 : " + jumin.length()); // System.out.println(jumin.charAt(6)); // charAt(index) : 문자열에서 index 번째 위치의 문자 1개를 얻어온다. // 관계 연산자 // >(초과), >=(이상), <(미만), <=(이하), ==(같다), !=(같지 않다) // 논리 연산자 // &&(AND, ~이고, ~이면서, ~중에서), ||(OR, ~또는, ~이거나), !(NOT, 논리부정) // if(조건식) { // 조건이 참일 경우 실행할 문장; // ...; // } else { // 조건이 거짓일 경우 실행할 문장; // ...; // } // 주민등록번호의 7번째 문자가 1 또는 3이면 남자 그렇치 않으면 여자 char gender = jumin.charAt(6); boolean isGender = gender == '1' || gender == '3' || gender == '5'; // 논리값을 기억하는 boolean형 변수나 boolean 값을 리턴하는 메소드 앞에는 "is" 붙여서 만든다. if(isGender) { System.out.println("남자"); } else { System.out.println("여자"); } // 삼항 연산자(간단한 if) // 조건식 ? 조건이 참일 경우 실행할 문장 : 조건이 거짓일 경우 실행할 문장; System.out.println(isGender ? "남자" : "여자"); } } ``` <file_sep>/_javascript/A016 갤러리, 마우스휠 읽기, 툴팁.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>갤럭시 갤러리</title> <script src="js/jquery-1.11.0.min.js"></script> <script> $(function(){ var slide_img_w = $('#slide img').width() var slide_img_h = $('#slide img').height() var wrapImg_img_count = $('#wrapImg img').size() var slideTime = 500 var slideIntervalTime = 1000 //alert(slide_img_count) $('#viewImg').css({width:slide_img_w, height:slide_img_h}) $('#wrapImg').css({ width:slide_img_w * wrapImg_img_count, height:slide_img_h, left:-slide_img_w }) n=1 //btnNext() $('.btnNext').click(function(){ n++ if(n==wrapImg_img_count){ $('#wrapImg').css({left:-slide_img_w*1}) n=2 } $('#wrapImg').stop().animate({left:-slide_img_w*n},slideTime) $('.icon li img').attr('src','img/ico_slider.png') $('.icon li:eq('+ (n-1) +') img').attr('src','img/ico_slider_on.png') if(n==9){ $('.icon li:first img').attr('src','img/ico_slider_on.png') } }) //btnPrev() $('.btnPrev').click(function(){ n-- if(n==-1){ $('#wrapImg').css({left:-slide_img_w*(wrapImg_img_count-2)}) n=wrapImg_img_count-3 } $('#wrapImg').stop().animate({left:-slide_img_w*n},slideTime) //아이콘 이전 $('.icon li img').attr('src','img/ico_slider.png') $('.icon li:eq('+ (n-1) +') img').attr('src','img/ico_slider_on.png') if(n==0){ $('.icon li:last img').attr('src','img/ico_slider_on.png') } }) /*setInterval() setInterval(function(){ $('.btnNext').click()},slideIntervalTime) */ //icon li() //icon img 속성 data-n 삽입 - each function(index) $('.icon img').each(function(index) { $(this).attr('data-n',index+1) }) /*********************************** $('.icon li img').click(function(){ $('.icon li img').attr('src','img/ico_slider.png') $(this).attr('src','img/ico_slider_on.png') n = parseInt($(this).attr('data-n')) $('#wrapImg').animate({left:-slide_img_w * n }) }) **************************************************/ // 클릭한 대상의 index값을 구해와서 아이콘 작업--index() $('.icon li').click(function(){ $('.icon li img').attr('src','img/ico_slider.png') $('img',this).attr('src','img/ico_slider_on.png') n=parseInt($(this).index()+1) $('#wrapImg').animate({left:-slide_img_w * n }) }) }) </script> <style> *{margin:0; padding:0} ul,ol,li { list-style:none} #slide{ width:960px; height:520px; position:relative; margin:0 auto; } #btnGrp li{ position:absolute ; z-index:10; top:40%;} #btnGrp button{ width:50px; height:50px} #btnGrp .btnPrev{ left:0; cursor:pointer} #btnGrp .btnNext{ right:0; cursor:pointer} #viewImg{ position:relative;overflow:hidden; margin:0 auto} #wrapImg{ position:absolute; left:0; top:0; z-index:5 } #wrapImg img{ float:left} .icon{ position:absolute; left:402px; bottom:0px; z-index:10} .icon li{ float:left; margin:0 3px; cursor:pointer} </style> </head> <body> <div id="slide"> <ul id="btnGrp"> <li class="btnPrev"><button>< </button></li> <li class="btnNext"><button>> </button></li> </ul> <div id="viewImg"> <ul id="wrapImg"> <li><img src="img/s4_gallery_08.png" alt="" /></li> <li><img src="img/s4_gallery_01.png" alt="" /></li> <li><img src="img/s4_gallery_02.png" alt="" /></li> <li><img src="img/s4_gallery_03.png" alt="" /></li> <li><img src="img/s4_gallery_04.png" alt="" /></li> <li><img src="img/s4_gallery_05.png" alt="" /></li> <li><img src="img/s4_gallery_06.png" alt="" /></li> <li><img src="img/s4_gallery_07.png" alt="" /></li> <li><img src="img/s4_gallery_08.png" alt="" /></li> <li><img src="img/s4_gallery_01.png" alt="" /></li> </ul> </div><!--//viewImg--> <ul class="icon"> <li><img src="img/ico_slider_on.png" alt="on" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> </ul> </div><!--//slide --> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>mousewheel</title> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/jquery.mousewheel.js"></script> <script> $(function(){ $('body').mousewheel(function(e, delta){ if( delta > 0){ document.write('위<br />') }else { document.write('아래<br />') } }) }) </script> <style> html,body{ height:100%} </style> </head> <body> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>tooltip</title> <script src="js/jquery-1.11.0.min.js"></script> <script> $(function(){ $('.tooltip').css({display:'none'}) $('a').mouseover(function(){ $('.tooltip').fadeIn() }).mouseout(function(){ $('.tooltip').fadeOut() }) $('a').mousemove(function(e){ $('.tooltip').css({left:e.clientX + 20, top:e.clientY -25}) }) }) </script> <style type="text/css"> .tooltip{ position:absolute; width:300px; height:70px; background-color:#F60; background-color:rgba(225,216,134,0.9); border-radius:10px ; border:3px solid #999; padding:10px; color:#333; box-shadow:2px 2px 3px rgba(0,0,0,0.7) } </style> </head> <body> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the <a href="#">industry's standard dummy text</a><span class="tooltip">툴팁:설명글이 들어갈 영역</span> ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. </p> </body> </html> ``` <file_sep>/_java/PATTERN - Number Pattern 7.md ``` /* 1 23 456 7890 12345 */ public class NumberPat7 { public static void main(String arg[]) { int t = 1; for (int i = 1; i <= 5; i++) { for (int j = 1; j <= i; j++) { if(t==10) t=0; System.out.print(t++); } System.out.println(); } } } ``` ##OUTPUT ``` 1 23 456 7890 12345 ```<file_sep>/_htmlCss/A005 포토샵 slice툴, background 스타일.md ``` CSS를 하기에 앞서서 포토샵을 잠깐 소개할게요. 알려드린다고 하기에는 좀 뭐한 것이 저는 디자이너가 아니라 포토샵을 잘 사용하지는 못합니다! james_special-32 그냥 웹 페이지에서 프론드 단을 만져야 할 경우 포토샵을 이용하면 조금 편하게 사이즈를 구할 수 있는데요. 그것만 소개해볼게요. 포토샵에서 필요한 이미지를 불러옵니다. 일반 이미지 일 수도 있구요. 페이지의 프레임을 나눈 이미지 파일이 될 수도 있습니다. 하여튼 왼쪽에 보이는 슬라이스 툴(Slice Tool)을 선택해주세요. 위 사진과 같이 5개의 영역으로 쪼갰습니다. 사진을 쪼개서 한번에 따로따로 저장하는 법을 알려드릴게요. 아까 그 상태에서 'ctrl + alt + shift + s' 를 눌러줍니다. 위 처럼 Save for Web 창이 뜰꺼예요. 1. 이미지의 속성을 정합니다. (gif, png, jpg 등등) 2. 사진의 퀄러티를 정합니다. (높을 수록 원본에 가깝고 큰 사진 이미지에 유리해집니다.) 3. High나 Low가 아닌 직접 값을 변경합니다. (사진의 용량에 큰 영향을 끼칩니다.) 4. 쪼갠 사진들을 shift로 필요한 것만 다중 선택하셔서 Save를 눌러줍니다. Slices와 Settings을 위 처럼 만들어 주시구요. 'Setting'에서 손 볼 것이 하나 있습니다. 'Put Images in Folder'의 체크를 풀어주세요. 괜히 체크해놓으면 이상한 폴더에 이미지 파일들이 들어가게 됩니다. 파일 루트를 짜는데에 있어서 좀 번거로워져요. 제가 설정한 경로에 쪼개어진 사진들이 들어간 것을 볼 수 있습니다. 슬라이스 영역을 'ctrl + 더블클릭' 하게 되면 파일명을 설정할 수 있게 됩니다요. width값과 height값도 여기에서 확인 할 수 있습니다. X와 Y라는 값은 왼쪽 제일 위에 있는 점으로 부터 얼마만큼 떨어져있는 가를 표시해줍니다. 또, slice툴로 공백영역을 선택해서 margin값을 미리 구해놓을 수 있어요. 저장해두면 slice영역이 사라지지 않기 때문에 유용하게 사용할 수 있습니다. 이제 본격적인 공부를 시작해 보죠. div 안에 div 있을 경우 명시하는게 좋음 #article #leftbox { } <body> <div id="header"><img src="img/header.jpg" width="1659" height="58" alt="메뉴"></div> <div id="visual"><img src="img/mainImg.jpg" width="1659" height="540" alt="메인이미지"></div> <div id="title"><img src="img/introduce.jpg" alt="인트로듀스" /></div> <div id="article"> <div id="leftbox"><img src="img/leftSection.jpg" width="308" height="602" alt="왼쪽 내용"></div> <div id="centerbox"><img src="img/centerSection.jpg" alt="중간 내용" /></div> <div id="rightbox"><img src="img/rightSection.jpg" alt="오른쪽 내용" /></div> </div> <div id="article"> 부분에 들어갈 3가지 이미지를 따로 설정하는 건 틀을 잡아주고 작업하는게 더 좋기 때문임. 이미지 사이 간격은 div로 박스를 잡기보다 margin으로 간격줌. ---- <style> #visual { width:1659px; height:540px; background-image:url("img/mainImg.jpg"); } #visual #textbox { width:500px; height:500px; background-color:red; margin-left:500px; } </style> <body> <div id="visual"> <div id="textbox"></div> </div> </body> body 태그 안에서 img 태그를 사용하는 것보다 background-image:url("img/mainImg.jpg"); ★외우기 <!-- 활용 가치가 더 높음 --> ---- <body> 이미지 <img src="" alt="" /> </body> <!-- body안에 있는 div안에 div넣는 것처럼, <img src~> 는 그 안에 얹거나 글 쓰거나 그리는 일을 못함 --> 위 두개 이미지 처리하는 방법의 차이 - style에서 배경이미지로 처리해야 할 때 (background-image:url("폴더/이미지명.확장자"); 1. 이미지 위에 다른 요소 ( 블록, 이미지, 글자 )를 또 넣어야 할 상황이 올 것 같을 때. 2. 이미지 크기가 width:1000px 이상 인 큰 이미지. (웹에서 가로값은 스트레스 받음 / 스크롤이 생기는 이유도 있음) 3. 마우스 hover 기능이 들어 갈 때 4. 이미지 위치점 맞추기 비교적 쉽다 (body 보다) 위 4가지 경우 외에는 body영역에서 <img src=>로 넣으면됨. ---- background-postion:가로px 세로px; (왼쪽 아래쪽 방향으로 움직임) background-postion:-200px -100px; (오른쪽 위쪽 방향으로 움직임) background-postion:center center; = background-postion:center; (가로 세로 정중앙 맞춰줌) background-postion:left top; background-postion:right bottom; :left/ right/ center/ top/ bottome ---- <style> #bg {width:700px; height:500px; background-color:silver; margin:200px auto 0; background-image:url("img/mainImg.jpg"); color:white; font-size:40px; background-position:-400px -20px; background-repeat:no-repeat} </style> <body> <div id="bg"> 안녕하세요. </div> </body> -사진 생략 ``` <file_sep>/_java/PATTERN - Number Pattern 3.md ``` ------------------ 12345 1234 123 12 1 ------------------- public class NumberPat3 { public static void main(String arg[]) { for (int i = 1, r = 5; i <= 5; i++, r--) { for (int j = 1; j <= r; j++) { System.out.print(j); } System.out.println(); } } } ``` ##OUTPUT ``` 12345 1234 123 12 1 ```<file_sep>/_java/PATTERN - Christmas Tree Pattern.md ``` public class ChristmasTreePattern { public static void main(String... arg) { drawChristmasTree( 4 ); } private static void drawChristmasTree(int n) { for (int i = 0; i < n; i++) { triangle( i+1 , n ); } } private static void triangle(int n, int max) { for (int i = 0; i < n; i++) { for (int j = 0; j < max-i-1; j++) { System.out.print(" "); } for (int j = 0; j < i*2+1; j++) { System.out.print("X"); } System.out.println(""); } } } ``` ###OUTPUT ``` X X XXX X XXX XXXXX X XXX XXXXX XXXXXXX ```<file_sep>/_javascript/A019 for문 응용(script를 body태그에서 사용).md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>for응용</title> <script> var navArr = new Array('Home','제품분류1','제품분류2','히트상품','세일상품','이달의 신상품','QnA','고객센터','커뮤니티') var pdArr = new Array('상품1','상품2','상품3','상품4') pdArr.push('상품add1') pdArr.push('상품add2') pdArr.push('상품add3') </script> <style> * { margin:0; padding:0} ul,ol,li { list-style:none} body, th, td{ font:"맑은 고딕",Arial, sans-serif;} a { text-decoration:none;} img { border:none;} #wrap{ width:960px; margin:0 auto} #nav{ height:40px; background-color:#333} #nav .gnb{} #nav .gnb li{ float:left; width:100px; line-height:40px; text-align:center;} #nav .gnb li a{ color:#FFFFFF} #slider{ height:200px; background-color:#FFFF99} #contents{} #contents .product{ height:300px; float:left; border:1px solid #CCC; width:218px; margin:10px; } #contents .product table{ width:100%} #contents .product table th { background-color:#CCCCCC; height:40px} #contents .product table img { width:100%; height:200px;} #footer{ clear:both; height:100px; background-color:#CCC} </style> </head> <body> <div id="wrap"> <div id="nav"> <ul class="gnb"> <script> for( var i in navArr){ document.write('<li><a href="#">'+navArr[i]+'</a></li>') } </script> </ul> </div> <div id="slider">slider</div> <div id="contents"> <script> for(i=1; i<=16; i++){ var str = '' str+='<div class="product">' str+='<table>' str+='<tr><th>'+pdArr[i-1]+'</th></tr>' str+='<tr><td><img src="img/m'+i+'.jpg" /></td></tr>' str+='<tr><td>가격</td></tr>' str+='<tr><td>제품설명</td></tr>' str+='</table>' str+='</div>' document.write(str) } </script> </div><!--//contents--> <div id="footer"> footer </div> </div> </body> </html> ``` <file_sep>/_java/COLLECTION - HashSet Class.md ``` import java.util.HashSet; import java.util.Iterator; public class HashSetTest { public static void main(String[] args) { //Creating HashSet of type String HashSet<String> al=new HashSet<String>(); al.add("Java"); al.add("Android"); al.add("Php"); al.add("Ajax"); System.out.println(al); // Using Iterator Iterator<String> itr=al.iterator(); while(itr.hasNext()) { System.out.print(itr.next()+" "); } System.out.println(); // Using enhance for-loop for (String string : al) { System.out.print(string +" "); } } } ``` ##OUTPUT ``` [Java, Php, Android, Ajax] Java Php Android Ajax Java Php Android Ajax ```<file_sep>/_cpp/배열 자동으로 채우기.md ``` #include <cstdio> #include <iostream> #include <iomanip> using namespace std; int main() { int a[5][5] = {0, }; int count = 0; // 1~25 까지 1씩 증가할 변수 int k = 5; // 반복문의 반복 횟수 제어에 사용할 변수 int sign = 1; // 증가치의 부호 변경에 사용할 변수 int row = 0, col = -1; // 배열의 행, 열 첨자에 사용될 변수 // 배열에 숫자를 채운다. while(true) { for(int i=0 ; i<k ; i++) { // 행방향 채우기 col += sign; a[row][col] = ++count; } if(--k == 0) { break; } for(int i=0 ; i<k ; i++) { // 열방향 채우기 row += sign; a[row][col] = ++count; } sign *= -1; } // 배열의 내용을 출력한다. for(int i=0 ; i<5 ; i++) { // 행 for(int j=0 ; j<5 ; j++) { // 열 cout << setw(2) << a[i][j] << " "; } cout << endl; // 1행 출력하고 줄바꿈 } } ``` ``` #include <cstdio> #include <iostream> #include <iomanip> using namespace std; int main() { int n; do { cout << "배열의 차수를 홀수로 입력하세요 : "; cin >> n; if(n%2 != 0) { break; } cout << n << "이 홀수냐" << endl; } while(true); // 1차원 가변배열 만들기 // int *a = new int[n]; // int a[] = new int[n]; >> 자바코딩 // 2차원 가변배열 만들기 int **a = new int*[n]; // 행 for(int i=0 ; i<n ; i++) { a[i] = new int[n]; // 열 } // int a[][] = new int[n][n]; >> 자바코딩 int row = 0, col = n / 2; // 1이 채워질 자리 for(int i=1 ; i<=n*n ; i++) { // 마방진에 채워질 숫자 a[row][col] = i; // 마방진에 숫자를 채운다 // 다음 숫자가 채워질 자리를 잡아준다. if(i%n == 0) { // 5의 배수 다음 수는 행만 1증가 row++; } else { // 나머지 수는 행 1감소 열 1증가 if(--row < 0) { row = n - 1; } if(++col > n - 1) { col = 0; } } } for(int i=0 ; i<n ; i++) { for(int j=0 ; j<n ; j++) { cout << setw(4) << a[i][j]; } cout << endl; } } ``` <file_sep>/_java/A015 Checkbox 클래스, ActionListener.md ``` package com.me.eventtest; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JOptionPane; public class EventTest03 extends Frame implements WindowListener, ActionListener { Button btn1, btn2, btn3; Panel panel; public EventTest03() { setTitle("버튼에 액션 리스너 걸기"); setBounds(900, 100, 400, 200); // addWindowListener(new WindowAdapter() { // @Override // public void windowClosing(WindowEvent e) { // dispose(); // } // }); addWindowListener(this); // WindowListener 인터페이스를 구현했을 경우 btn1 = new Button("눌러봥"); btn2 = new Button("눌러보라니까"); btn3 = new Button("정말 누르냐"); btn1.addActionListener(this); // ActionListener 인터페이스를 구현했을 경우 btn2.addActionListener(this); // ActionListener 인터페이스를 구현했을 경우 btn3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(btn3, "눌렀냐"); // int confirm = JOptionPane.showConfirmDialog(btn3, "눌렀냐"); // if(confirm == 0) { // System.out.println("예"); // } else if(confirm == 1) { // System.out.println("아니오"); // } else { // System.out.println("취소"); // } // try { // int age = Integer.parseInt(JOptionPane.showInputDialog("나이를 입력하세요")); // System.out.println(age >= 19 ? "성인" : "미성년자"); // } catch(NumberFormatException e1) { // System.out.println("나이를 입력하지 않으셨네요"); // } } }); panel = new Panel(new GridLayout(1, 2)); panel.add(btn1); panel.add(btn2); add(panel, BorderLayout.NORTH); add(btn3, BorderLayout.SOUTH); setVisible(true); } public static void main(String[] args) { EventTest03 win = new EventTest03(); } // WindowListener 인터페이스의 추상 메소드 ============================================== @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowClosing(WindowEvent e) { dispose(); } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public void windowOpened(WindowEvent e) { } // ActionListener 인터페이스의 추상 메소드 ============================================= @Override public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); // if((Button)obj == btn1) { if((Button)e.getSource() == btn1) { JOptionPane.showMessageDialog(btn1, "1번 버튼이 눌렸어요"); } else { JOptionPane.showMessageDialog(btn2, "2번 버튼이 눌렸어요"); } } } ``` ``` package com.me.eventtest; import java.awt.BorderLayout; import java.awt.Checkbox; import java.awt.CheckboxGroup; import java.awt.Frame; import java.awt.Label; import java.awt.Panel; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class EventTest04 extends Frame implements ItemListener{ // Checkbox는 체크 상자(여러개 선택가능) 또는 라디오 상자(1개만 선택가능) Checkbox football, baseball, handball; // CheckboxGroup은 Checkbox 컴포넌트로 라디오 상자를 생성하려 할 경우에 Checkbox 컴포넌트를 그룹으로 묶어준다. CheckboxGroup hobby = new CheckboxGroup(); Label label = new Label("이곳에 선택한 체크 상자의 이름이 나온다."); public EventTest04() { setTitle("체크 상자/ 라디오 상자에 리스너 걸기"); setBounds(200, 200, 400, 200); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); // Checkbox("레이블", 선택여부) : 체크 상자 // 레이블 : 체크상자 이름 // 선택여부 : 선택되지 않은 상태(false 또는 생략), 선택된 상태(true) // 체크 상자는 2개 이상 선택할 수 있고 라디오는 1개만 선택할 수 있다. // Checkbox("레이블", 선택여부, 그룹 객체명) : 라디오 상자 // 그룹 객체명을 생략하면 체크 상자가 되고 그룹 객체명을 적으면 라디오 상자가 생성된다. football = new Checkbox("축구", false, hobby); baseball = new Checkbox("야구", true, hobby); handball = new Checkbox("핸드볼", false); // addItemListener는 체크 상자나 라디오 상자가 선택되면 발생하는 이벤트이다. // football.addItemListener(new ItemListener() { // @Override // public void itemStateChanged(ItemEvent e) { // label.setText(e.getItem().toString() + " 항목이" + // (e.getStateChange() == 1 ? " 선택됨" : " 해제됨") ); //// getItem() : 선택된 체크 상자나 라디오 상자의 레이블 문자열을 얻어온다. //// getStateChange() : 체크 상자가 선택되면 1, 해제되면 2를 리턴한다. // } // }); football.addItemListener(this); // baseball.addItemListener(new ItemListener() { // @Override // public void itemStateChanged(ItemEvent e) { // label.setText(e.getItem().toString() + " 항목이" + // (e.getStateChange() == 1 ? " 선택됨" : " 해제됨") ); // } // }); baseball.addItemListener(this); // handball.addItemListener(new ItemListener() { // @Override // public void itemStateChanged(ItemEvent e) { // label.setText(e.getItem().toString() + " 항목이" + // (e.getStateChange() == 1 ? " 선택됨" : " 해제됨") ); // } // }); handball.addItemListener(this); Panel panel = new Panel(); panel.add(football); panel.add(baseball); panel.add(handball); add(panel, BorderLayout.NORTH); label.setAlignment(Label.CENTER); add(label, BorderLayout.SOUTH); setVisible(true); } public static void main(String[] args) { EventTest04 win = new EventTest04(); } @Override public void itemStateChanged(ItemEvent e) { // Object obj = e.getSource(); label.setText(e.getItem().toString() + " 항목이" + (e.getStateChange() == 1 ? " 선택됨" : " 해제됨")); } } ``` <file_sep>/_java/FILE HANDLING - Copy File using Byte Stream.md ``` /* author: Creativecub */ import java.io.*; public class CopyFile { public static void main(String args[]) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("input.txt"); out = new FileOutputStream("output.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } ``` ##OUTPUT ``` file : input.txt Welcome to Programming Hub file : output.txt Welcome to Programming Hub ```<file_sep>/KNOU.java.test/src/knou/test/applet/FrameApplet.java package knou.test.applet; import java.applet.Applet; import java.awt.Button; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; class ExternalFrame extends Frame { public ExternalFrame() { setTitle("Ext Fr"); MenuBar mb = new MenuBar(); Menu m = new Menu("File"); m.add(new MenuItem("open")); m.add(new MenuItem("close")); mb.add(m); setMenuBar(mb); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent ev) { Window w = (Window) ev.getSource(); w.dispose(); } }); } } public class FrameApplet extends Applet { static Frame ext_frame = null; public FrameApplet() { Button b = new Button("frame"); setLayout(new FlowLayout()); add(b); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ev) { if(ext_frame == null) { ext_frame = new ExternalFrame(); ext_frame.setSize(300,200); ext_frame.setVisible(true); } else { ext_frame = new ExternalFrame(); ext_frame.setSize(500, 200); ext_frame.setVisible(true); } } }); } public void destroy() { ext_frame.dispose(); } } <file_sep>/KNOU.java.test/src/knou/test/awt/CheckboxTest.java package knou.test.awt; import java.awt.Checkbox; import java.awt.CheckboxGroup; import java.awt.FlowLayout; import java.awt.Frame; public class CheckboxTest { public static void main(String[] args) { Frame f = new Frame("Checkbox"); f.setLayout(new FlowLayout()); f.add(new Checkbox("Whiskey", true)); f.add(new Checkbox("Beer")); CheckboxGroup group = new CheckboxGroup(); f.add(new Checkbox("Yes", false, group)); f.add(new Checkbox("No", true, group)); f.setSize(300,80); f.setVisible(true); } } <file_sep>/_java/A004 Collection, interface.md ``` package com.me.collectiontest; import java.util.HashMap; public class MapTest { public static void main(String[] args) { HashMap<Integer, String> hmap = new HashMap<>(); hmap.put(1, "홍길동"); // 입력, add가 아니라 put이다. hmap.put(2, "홍길동"); hmap.put(3, "임꺽정"); hmap.put(4, "일지매"); hmap.put(9, "장길산"); // 키 값은 반드시 연속적일 필요는 없다. hmap.put(6, "홍경래"); System.out.println(hmap.size() + " : " + hmap); hmap.put(2, "홍길자"); // 수정, 충돌, 기존의 키 값에 덮어쓰기를 한다. System.out.println(hmap.size() + " : " + hmap); // ArrayList의 get()은 지정된 위치의 값을 얻어오고 HashMap의 get()은 지정된 키 값에 해당되는 // 값을 얻어온다. System.out.println(hmap.get(9)); hmap.remove(4); // 삭제 System.out.println(hmap.size() + " : " + hmap); hmap.clear(); // 모두 삭제 System.out.println(hmap.size() + " : " + hmap); } } ``` ``` package com.me.collectiontest; public class Person implements Comparable<Person> { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return name + "(" + age + ")"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + age; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Person other = (Person) obj; if (age != other.age) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override // compareTo() 메소드는 자신(this)과 인수로 넘어온 객체(o)를 비교한다. // 자신이 크면 1 또는 양수, 같으면 0, 작으면 -1 또는 음수를 리턴하도록 구현한다. public int compareTo(Person o) { // return this.name.compareTo(o.name); // name의 오름차순 // return -this.name.compareTo(o.name); // name의 내림차순 // return this.age - o.age; // age의 오름차순 // return o.age - this.age; // age의 내림차순 // 이름의 오름차순 정렬, 이름이 같으면 나이의 내림차순 정렬 if(this.name.compareTo(o.name) == 0) { // 이름이 같은가? return o.age - this.age; // 이름이 같으면 나이의 내림차순 } else { return this.name.compareTo(o.name); // 이름이 다르면 이름의 오름차순 } } } ``` ``` package com.me.collectiontest; import java.util.HashSet; import java.util.TreeSet; public class SetTest1 { public static void main(String[] args) { // HashSet은 데이터의 중복을 허용하지 않고 입력 순서와는 상관없이 랜덤하게 들어간다. HashSet<String> hset = new HashSet<>(); hset.add("홍길동"); // add(value) : 입력 System.out.println(hset.size() + " : " + hset); // size() : 데이터의 개수 hset.add("임꺽정"); System.out.println(hset.size() + " : " + hset); hset.add("성춘향"); System.out.println(hset.size() + " : " + hset); hset.add("일지매"); System.out.println(hset.size() + " : " + hset); hset.add("장길산"); System.out.println(hset.size() + " : " + hset); hset.add("홍길동"); // 중복되는 데이터는 입력되지 않는다. System.out.println(hset.size() + " : " + hset); hset.remove("장길산"); // remove(value) : 삭제 System.out.println(hset.size() + " : " + hset); hset.clear(); // clear() : 전부 삭제 System.out.println(hset.size() + " : " + hset); System.out.println("====================================================="); // Treeset은 데이터의 중복을 허용하지 않고 입력 순서와는 상관없이 오름차순 정렬되서 들어간다. TreeSet<String> tset = new TreeSet<>(); tset.add("홍길동"); // add(value) : 입력 System.out.println(tset.size() + " : " + tset); // size() : 데이터의 개수 tset.add("임꺽정"); System.out.println(tset.size() + " : " + tset); tset.add("성춘향"); System.out.println(tset.size() + " : " + tset); tset.add("일지매"); System.out.println(tset.size() + " : " + tset); tset.add("장길산"); System.out.println(tset.size() + " : " + tset); tset.add("홍길동"); // 중복되는 데이터는 입력되지 않는다. System.out.println(tset.size() + " : " + tset); tset.remove("장길산"); // remove(value) : 삭제 System.out.println(tset.size() + " : " + tset); tset.clear(); // clear() : 전부 삭제 System.out.println(tset.size() + " : " + tset); } } ``` ``` package com.me.collectiontest; import java.util.HashSet; import java.util.TreeSet; public class SetTest2 { public static void main(String[] args) { // 클래스로 만든 객체의 중복 여부를 비교하려면 HashSet에 저장할 클래스(Person)에서 equals(), // hashCode() 메소드를 override 해줘야 한다. // override 하지 않으면 각 객체의 hashCode를 비교하기 때문에 new로 생성한 중복되는 내용을 가지는 // 객체라 하더라도 서로 다른 hashCode를 가지게 되므로 계속 입력되는 현상이 발생된다. HashSet<Person> hset = new HashSet<>(); hset.add(new Person("이성계", 78)); hset.add(new Person("이성계", 78)); hset.add(new Person("이성계", 23)); hset.add(new Person("이방원", 38)); hset.add(new Person("이성계", 55)); System.out.println(hset); // 클래스로 만든 객체를 TreeSet에 저장하려면 중복 데이터 여부를 검사하고 정렬하기 위해 객체의 내용을 // 비교해야 한다. // 객체 내부의 내용을 비교해서 정렬을 하려면 TreeSet에 저장할 클래스에 Comparable 인터페이스를 // 구현하고 compareTo() 메소드를 override 해야한다. TreeSet<Person> tset = new TreeSet<>(); tset.add(new Person("이성계", 78)); tset.add(new Person("이성계", 78)); tset.add(new Person("이성계", 23)); tset.add(new Person("이방원", 38)); tset.add(new Person("이성계", 55)); tset.add(new Person("김선덕", 42)); tset.add(new Person("한석봉", 17)); System.out.println(tset); } } ``` ``` package com.me.interfacetest; // 인터페이스는 정적(static) 멤버 변수와 추상 메소드로만 구성된 특별한 클래스이다. // 자바는 다중 상속이 불가능하므로 다중 상속을 피해서 여려개의 클래스를 물려받기 위해서 사용되고 부모로 // 인정되므로 자식을 관리할 수 있어 다형성을 구현하려 할 경우에 사용되기도 한다. // 클래스가 아니므로 상속(extends)이라 하지 않고 구현(implements)이라 한다. class Point { int x, y; public void move() { } } class Shape { static final double PI = 3.141592; // 정적 멤버, 상수 public void draw() { } public void erase() { } } // class Line extends Point, Shape { } // 에러 발생, 자바는 다중 상속을 지원하지 않는다. interface Draw { public static final double PI = 3.141592; // 정적 멤버, 상수 // 앞의 내용을 생략하면 자동으로 public static final를 붙여준다. int LIMIT = 1000; public abstract void move1(); // 추상 메소드 // 앞의 내용을 생략하면 자동으로 public abstract을 붙여준다. void erase(); } interface Graphic { void resize(); void rotate(); } // 인터페이스는 클래스의 특별한 형태이므로 extends 예약어를 사용하면 인터페이스가 인터페이스를 상속 받을 // 수 있고 자바는 인터페이스의 다중 상속은 지원한다. // interface Graphics extends Point { } // 에러 발생, 인터페이스는 클래스를 상속받을 수 없다. // class Line extends Graphic { } // 에러 발생, 클래스는 인터페이스를 상속받을 수 없다. interface Graphics extends Draw, Graphic { // 아무 내용도 없는 인터페이스를 표시 인터페이스라 한다. } // Line 클래스는 Point 클래스를 상속받고 Draw, Graphic 인터페이스를 구현해서 만든다. class Line extends Point implements Draw, Graphic { @Override public void resize() { // TODO Auto-generated method stub } @Override public void rotate() { // TODO Auto-generated method stub } @Override public void erase() { // TODO Auto-generated method stub } @Override public void move1() { // TODO Auto-generated method stub } } public class InterfaceTest1 { } ``` <file_sep>/_htmlCss/A025 로그인 창.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>login</title> <style type="text/css"> body,p,div,h1,h2,h3,h4,h5,h6,ul,ol,li,dl,dt,dd,form,fieldset,input,button { margin:0; padding:0;} body,th,td,h1,h2,h3,h4,h4,h6,input,button { font:12px/1.5 "돋움",dotum,sans-serif} img,fieldset { border:none;} a { text-decoration:none;} legend { display:none;} #loginBox{ width:400px; height:400px; margin:100px auto; background-color:#CCC } #loginBox form {padding:20px 40px 30px 60px; border-bottom:1px solid #666; height:100px;} #loginBox fieldset { height:70px;} #loginBox .line{ height:30px; display:block; float:left;} #loginBox label, #loginBox input, #loginBox button{ float:left;} #loginBox label{display:block; width:60px; padding-top:5px} #loginBox input { border:1px solid #CCC; padding:3px; width:130px;} #loginBox #btnLogin { width:54px; height:54px; margin:-29px 0 0 5px} .h2_title{ font:24px Arial, Helvetica, sans-serif; text-align:center; padding:20px 0 0 0 } </style> </head> <body> <div id="loginBox"> <h2 class="h2_title">login</h2> <form action="#"> <fieldset> <legend>로그인</legend> <p class="line"> <label>아이디</label> <input type="text" id="uid" /> </p> <p class="line"> <label>비밀번호</label> <input type="text" id="upw" /> </p> <button id="btnLogin">로그인</button> </fieldset> <ul> <li><a href="#">아이디 / 비밀번호</a>찾기</li> <li><a href="#">회원가입</a></li> </ul> </form> <div> <ul> <li>fdsafdasfdasfdasfdsa</li> <li>dfasfdsafdsa</li> </ul> </div> </div> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>login</title> <style type="text/css"> *{margin:0; padding:0;} body, input, button {font:12px "돋움", Arial,sans-serif; color:#333;} ul, ol, li { list-style:none; } img, fieldset { border:none} legend{ display:none; } .login_box{ width:350px; height:350px; background-color:#F0F0F0; margin:200px auto 0 auto; border:1px solid #CCC;} .login_box .h1_title{ text-align:center; font-size:36px; color:#333333; line-height:72px; border-bottom:1px solid #ccc;} .login_box form{ padding:30px 0 0 30px; height:150px; border-bottom:1px solid #ccc;} .login_box fieldset{ display:block; } .login_box .line{clear:both; } .login_box .checkbox{margin:5px 0 0 0;} /*.login_box label, .login_box input, .login_box button{float:left;} */ .login_box .line_label{ display:block; width:150px; padding-top:5px;} .login_box .cb{font:10px "고딕체", Arial,sans-serif; color:#666} .login_box input .text { padding:3px; width:200px; border:1px solid #999; color:#666; } .login_box button{ width:110px; height:30px; margin:10px 0 0 200px;} .login_box .etc { padding:20px 40px 0 40px; } .login_box .etc li{ line-height:20px; padding:0 0 10px 10px; color:#666; background:url(img/more.png) no-repeat 0 4px;} </style> </head> <body> <div class="login_box"> <h1 class="h1_title">LOGIN</h1> <form action="#"> <fieldset> <legend>로그인</legend> <p class="line"> <label for="uid" class="line_label">Your email or username</label> <input type="text" id="uid" maxlength="8" size="40" class="text"/> </p> <p class="line"> <label for="upw" class="line_label">Your password</label> <input type="text" id="upw" size="40" class="text"/> </p> <p class="checkbox"> <input type="checkbox" class="cb"/> <label class="cb"><em>Keep me logged in</em></label> </p> <button id="btnLogin">LOGIN</button> </fieldset> </form> <ul class="etc"> <li> <a href="#">Forgot password or your ID?</a> </li> <li><a href="#">Not a member yet?</a> </li> </ul> </div> </body> </html> ``` <file_sep>/_java/OOPS - Hybrid Inheritance.md ``` interface A { public void methodA(); } interface B extends A { public void methodB(); } interface C extends A { public void methodC(); } class D implements B, C { public void methodA() { System.out.println("MethodA"); } public void methodB() { System.out.println("MethodB"); } public void methodC() { System.out.println("MethodC"); } public static void main(String args[]) { D obj1= new D(); obj1.methodA(); obj1.methodB(); obj1.methodC(); } } ``` ## OUTPUT ``` MethodA MethodB MethodC ```<file_sep>/_htmlCss/A006 body, style 이미지 처리 차이.md ``` 큰이미지이거나 진짜 배경이미지로 사용할 거라면 <style>태그에서 background-image:url("폴더명/이미지명.확장자"); 을 사용하는 편이 좋습니다. <body>도 보이지않는 브라우저 전체의 사각형이에요. ( div처럼 ) <style> body {background-image:url("image.jpg"); } <!-- 반복되면서 좌우 스크롤 생기지않음 --> </style> <body> <img src="img/image.jpg"> <!-- 이미지 하나만 보이고 크기에 따라서 스크롤이 생김 --> </body> 배경처리(background-image)의 장점 1. 스크롤이 생기지 않는다. 2. 무한 반복 (가로방향, 세로방향으로 무한 반복 : 패턴으로 만들어짐) 3. 위치 바꾸기가 비교적 쉽다. 4. 색을 추가로 넣을 수 있다. <style> body {background-image:url("img/bg01.jpg"); background-repeat:no-repeat;} </style> <!-- <body> 에 아무런 속성없이 생성가능, no-repeat은 반복 실행안함 --> ★외우기 background-repeat:no-reapeat; 반복안함 background-repeat:repeat-x; 가로반복 background-repeat:repeat-y; 세로반복 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>demo08</title> <style> * {margin:0; padding:0;} <!-- 초기화를 해줘야 기본간격 없어짐 --> body {background-image:url("img/bg03.jpg"); background-repeat:repeat-x;} <!-- background-color:#FF0000 주면 나머지 배경에 색을 채워줌 --> #main {width:938px; margin:0 auto;} </style> </head> <body> <div id="main"><img src="img/main02.jpg"></div> </body> </html> 실행예시 사진 위에 사진 올리는 게 쉬워집니다~^^ 뒷 배경으로 사용할 경우 반복시키면 해상도에 영향을 받지 않아요. 그리고 주석태그 까지 쓰게 될 경우 background 속성이 안 먹을 수 있으니, 주의해서 사용해주세요. 웹디자인 및 코딩시 이미지 처리 요령(용량 = 속도) 1. 이미지 없이 작업하는 게 가장 좋다. 2. 이미지가 있으면 패턴화 시켜서 작업한다. 3. 어쩔 수 없는 경우는 이미지를 크게 배경으로 사용하고 압축률을 조절한다. - Save as.. 저장 / Save for Web... 저장 -> Save for Web... 저장이 용량면에서 1/2 * 저장 이미지 포맷 1. jpeg (.jpg) -> 압축값 조절 high (배경) / very high (얼굴, 중요한 이미지) 2. png24 -> 투명 값이 들어있는 이미지 3. gif -> 움직이는 그림 만들어서 넣을 때 * {margin:0; padding:0;} body {background-image:url("img/bg04.jpg"); background-repeat:no-repeat; background-position:center top;} <!-- background-position 으로 정렬 --> 모니터 해상도의 크기가 1440 ~ 4000 ~ 이상으로 가면 이미지 적용이 힘들어짐 현재는 통상적으로 2000px 이미지사용, 이미지 저장은 RPG (CMYK는 사용하지 않는다. 아마도 인쇄용?) 무료이미지 사이트 추천 www.sxc.hu www.picjumbo.com http://unspalash.com www.deviantart.com http://splitshire.com www.gratisography.com http://wefunction.com/category/free-photos http://pixabay.com http://www.morguefile.com http://allowto.co.kr ?http://compfight.comhttp://compfight.com http://www.imcreator.com/free ?http://photopin.com/free-photos ``` <file_sep>/_java/BASIC - BufferedReader Example.md ``` import java.io.*; class BufferedReaderExample { public static void main(String[] args)throws Exception { String str; int i; float f; double d; long l; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter String"); str = br.readLine(); System.out.println("Enter Integer"); i = Integer.parseInt(br.readLine()); System.out.println("Enter float"); f = Float.parseFloat(br.readLine()); System.out.println("Enter double"); d = Double.parseDouble(br.readLine()); System.out.println("String : "+str); System.out.println("Integer : "+i); System.out.println("Float : "+f); System.out.println("Double : "+d); } } ``` ##OUTPUT ``` Enter String 4 Enter Integer 4 Enter float 23.5 Enter double 22.4421312 String : 4 Integer : 4 Float : 23.5 Double : 22.4421312 ```<file_sep>/_java/A031 최대공약수, 최소공배수, 완전수.md ``` import java.util.Scanner; // 유클리드 호제법을 이용해 최대공약수, 최소공배수 구하기 // 1. 두 개의 숫자(a, b)를 입력받고 큰수(big)와 작은수(small)를 구한다. // 2. 큰수를 작은수로 나눈 나머지가 0이면 작은수가 최대공약수이고 입력받은 두 수의 곱을 최대공약수로 나누면 // 최소공배수가 된다. // 3. 큰수를 작은수로 나눈 나머지가 0이 아니면 작은수를 큰수에 넣고 나머지를 작은수에 넣은후 2를 반복한다. public class Euclid { public static void main(String[] args) { // 두 개의 숫자를 입력받는다. Scanner sc = new Scanner(System.in); System.out.print("숫자 2개를 입력하세요 : "); int a = sc.nextInt(); int b = sc.nextInt(); // 입력받은 두 개의 숫자의 큰수와 작은수를 구한다. int big, small; if(a > b) { big = a; small = b; } else { big = b; small = a; } // while(조건식) { // 선 비교 후 실행 // 조건이 참일 경우 실행할 문장; // ...; // } // break; // 반복문의 {} 블록을 탈출한다. // continue; // 반복문의 {} 블록을 처음부터 다시 실행한다. while(true) { // 무한 Loop int r = big % small; // 큰수를 작은수로 나눈 나머지를 구한다. if(r == 0) { // 나머지가 0인가, 나눠서 떨어졌는가 break; // 나머지가 0이라면 무한 Loop를 탈출한다. } big = small; // 큰수에 작은수를 넣는다. small = r; // 작은수에 나머지를 넣는다. } // do { // 선 실행 후 비교 // 조건이 참일 경우 실행할 문장; // ...; // } while(조건식); // ";" 빼먹으면 오류가 발생된다. // do { // int r = big % small; // if(r == 0) { // break; // } // big = small; // small = r; // } while(true); System.out.println(a + "와 " + b + "의 최대공약수는 " + small + "입니다."); System.out.println(a + "와 " + b + "의 최소공배수는 " + (a*b)/small + "입니다."); } } ``` ``` // 자기 자신을 제외한 약수의 합이 자신과 같은 수 public class PerNum { public static void main(String[] args) { int count = 0; // 바깥쪽 반복문의 변수 값이 1번 변할때 안쪽 반복문은 완전히 한 번 실행된다. for(int i=4 ; i<=10000 ; i++) { // 완전수를 판별할 수 int sum = 0; // 바깥쪽 반복의 제어변수와 안쪽 반복의 제어변수는 이름이 같으면 안된다. for(int j=1 ; j<=i/2 ; j++) { // 약수를 판별할 수 // j<=i/2 : 자기 자신을 제외하고 나눠서 떨어뜨릴수 있는 가장 큰수는 자신의 절반을 넘지 않는다. int r = i % j; // 나머지 if(r == 0) { // 나눠서 떨어졌으면 약수의 합계를 계산한다. // 자신이 연산에 참여하는 경우 반드시 변수를 초기화 해줘야 한다. sum += j; // 약수의 합계 } } // System.out.println(i + ", " + sum); // 약수의 합계와 자신이 같으면 완전수 if(i == sum) { // count++ : count에 저장된 값을 사용하고 count 값을 1증가한다. // ++count : count에 저장된 값을 1증가하고 count 값을 사용한다. // count-- : count에 저장된 값을 사용하고 count 값을 1감소한다. // --count : count에 저장된 값을 1감소하고 count 값을 사용한다. // count++; // 완전수의 개수를 카운트 System.out.println(++count + "번째 완전수는 " + i); } } } } ``` <file_sep>/_java/OOPS - Parameterized Construct.md ``` class ParameterizedConstructor { ParameterizedConstructor(int num1, int num2) { int addition; addition = num1 + num2; System.out.println("Addition of Numbers: "+addition); } public static void main(String args[]) { ParameterizedConstructor p = new ParameterizedConstructor(30, 40); } } ``` ##OUTPUT ``` Addition of Numbers: 70 ```<file_sep>/_cpp/요일 구하기.md ``` #include <cstdio> #include <iostream> using namespace std; int main() { int year, month, day; cout << "요일을 계산할 날짜 입력 : "; cin >> year >> month >> day; //1년 1월 1일 부터 전년도 까지 지나온 날짜수를 계산한다. int sum = (year-1) * 365 + (year-1) / 4 - (year-1) / 100 + (year-1) / 400; bool isYoun = year%4 == 0 && year%100 != 0 || year%400 == 0; //전월 까지 지나온 날짜수를 더한다. for(int i=1 ; i<month ; i++) { switch(i) { case 2: sum += isYoun ? 29 : 28; break; case 4: case 6: case 9: case 11: sum += 30; break; default: sum += 31; } } sum += day; switch(sum % 7) { case 0: cout << "일요일" << endl; break; case 1: cout << "월요일" << endl; break; case 2: cout << "화요일" << endl; break; case 3: cout << "수요일" << endl; break; case 4: cout << "목요일" << endl; break; case 5: cout << "금요일" << endl; break; case 6: cout << "토요일" << endl; break; } } ``` <file_sep>/_java/BASIC - Add Two Numbers.md ``` import java.util.Scanner; class AddNumbers { public static void main(String args[]) { int x, y, z; System.out.print("Enter two integers to calculate their sum : "); Scanner in = new Scanner(System.in); x = in.nextInt(); y = in.nextInt(); z = x + y; System.out.println("Sum of entered integers = "+z); } } ``` ##OUTPUT ``` Enter two integers to calculate their sum : 5 6 Sum of entered integers = 11 ```<file_sep>/_java/OOPS - Abstract Example - Game.md ``` abstract class Games { public abstract void start(); public void stop() { System.out.println("Stoppingg game in abstract class"); } } class GameA extends Games { @Override public void start() { System.out.println("Starting Game B"); } } public class AbstractExample { public static void main(String[] args){ Games A = new GameA(); Games B = new GameB(); A.start(); A.stop(); B.start(); B.stop(); } } ``` OUTPUT ``` Strating Game A Stopping game in abstract class Strating Game B Stopping game in abstract class ```<file_sep>/_java/BASIC - Hello World.md ``` public class HelloWorld { public static void main(String args[]) { System.out.println("Hello World!!"); } } ``` ##OUTPUT ``` D:FreeITProjects.org>java HelloWorld Hello World!! ```<file_sep>/_javascript/A014 갤러리 만들기.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>gallery1</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ var n=0 //button next $('.next').click(function(){ n++ if(n==4){ $('.imgWrap').stop().animate({left:0},1000) n=0 } $('.imgWrap').stop().animate({left:-123*n},1000) }) //button prev $('.prev').click(function(){ n-- if(n==-1){ $('.imgWrap').stop().animate({left:-123*3},1000) n=3 } $('.imgWrap').stop().animate({left:-123*n},1000) }) }) </script> <style> * { margin:0; padding:0} ul,ol,li{ list-style:none} #gallery{ width:123px; margin:30px} #view{ overflow:hidden; width:123px; height:179px; position:relative; border:5px solid red} .imgWrap{width:492px;position:absolute;left:0;top:0px} .imgWrap li{ float:left;} </style> </head> <body> <div id="gallery"> <div id="view"> <ul class="imgWrap"> <li><img src="img/m1.jpg" alt="" /></li> <li><img src="img/m2.jpg" alt="" /></li> <li><img src="img/m3.jpg" alt="" /></li> <li><img src="img/m4.jpg" alt="" /></li> </ul> </div> <button class="prev">prev</button> <button class="next">next</button> </div> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>gallery1</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ var n=1 var aniTime = 500 //button next $('.next').click(function(){ n++ if(n==6){ $('.imgWrap').css({left:-123*1}) n=2 } $('.imgWrap').stop().animate({left:-123*n},aniTime) }) //button prev $('.prev').click(function(){ n-- if(n==-1){ $('.imgWrap').css({left:-123*4}) n=3 } $('.imgWrap').stop().animate({left:-123*n},aniTime) }) rolling = setInterval(function(){$('.next').click()},1000) }) </script> <style> * { margin:0; padding:0} ul,ol,li{ list-style:none} #gallery{ width:123px; margin:30px} #view{ overflow:hidden;width:123px; height:179px; position:relative; border:5px solid red} .imgWrap{width:738px;position:absolute;left:-123px;top:0px} .imgWrap li{ float:left;} </style> </head> <body> <div id="gallery"> <div id="view"> <ul class="imgWrap"> <li><img src="img/m4.jpg" alt="" /></li> <li><img src="img/m1.jpg" alt="" /></li> <li><img src="img/m2.jpg" alt="" /></li> <li><img src="img/m3.jpg" alt="" /></li> <li><img src="img/m4.jpg" alt="" /></li> <li><img src="img/m1.jpg" alt="" /></li> </ul> </div> <button class="prev">prev</button> <button class="next">next</button> </div> </body> </html> ``` <file_sep>/_java/OOPS - Class Usage - CircleDemo.md ``` //This example shows how to create an object //of a class and call its methods public class CircleDemo { public static void main(String[] args) { //Creating an object CircleTest c = new CircleTest(); //accessing object method with dot(.) operator String color = c.getColor(); //print color System.out.println(color); } } class CircleTest { // class name double radius = 2.3; // variables String color = "white color"; // methods double getRadius() { // method body return radius; //return statement } String getColor() { // method body return color; //return statement } } ``` ### OUTPUT ``` white color ```<file_sep>/_javascript/FUNCTION - Function With Argument And Return Value.md ``` <!DOCTYPE html> <html> <body> <p>This example calls a function which performs a calculation, and returns the result:</p> <p id="demo"></p> <script> function myFunction(a, b) { return a * b; } document.getElementById("demo").innerHTML = myFunction(4, 5); </script> </body> </html> ``` ##OUTPUT ``` This example calls a function which performs a calculation, and returns the result: 20 ```<file_sep>/_java/EXCRPTION HANDLING - Using Throws Keyword.md ``` import java.io.IOException; class UsingThrows { void m() throws IOException { throw new IOException("device error");// checked exception } void n() throws IOException { m(); } void p() { try { n(); } catch (Exception e) { System.out.println("exception handled"); } } public static void main(String args[]) { UsingThrows obj = new UsingThrows(); obj.p(); System.out.println("normal flow..."); } } ``` ##OUTPUT ``` exception handled normal flow... ```<file_sep>/_java/PATTERN - Pyramid Of Numbers.md ``` import java.io.*; class NumberPayramid { public static void main(String[] args) throws Exception { int row; int i, j , k; int x=1; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter number of rows : "); row = Integer.parseInt(br.readLine()); for (i = 1; i <= row; i++) { for (k =1; k <= row-i; k++) System.out.print(" "); for (j = k+1; j <=row; j++) System.out.print(x); for(int l=row;l>k-1;l--) System.out.print(x); x++; System.out.println(""); } } } ``` ##OUTPUT ``` Enter number of rows : 5 1 222 33333 4444444 555555555 ```<file_sep>/_htmlCss/A018 list와 position 이해.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>list</title> <style type="text/css"> *{ margin:0; padding:0} ul,ol,li { list-style:none;} .list{ width:240px; display:block; float:left; margin:50px} .list li{height:26px; display:block; border-bottom:1px dotted #999 } .list li a{ color:#666666; text-decoration:none; display:block; float:left; line-height:26px; padding-right:20px;} .list li:hover{ background-color:#EAEAEA} .list li a:hover{background:url(img/more.png) right center no-repeat; color:#333333} </style> </head> <body> <ul class="list"> <li><a href="#">사이트 준비중입니다.</a></li> <li><a href="#">사이트 준비중입....</a></li> <li><a href="#">사이트 준비중....</a></li> <li><a href="#">사이트 준비중입니다 곧.....</a></li> </ul> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>position</title> <style type="text/css"> .box1{ background-color:#0CF; position:absolute; margin:0 auto; width:500px; height:300px; z-index:2; } .box2{ background-color:red; position:fixed; left:100px; top:0px; z-index:2; width:50px; height:50px; } </style> </head> <body> <div class="box1">absolute <div class="box box2">fixed</div> </div> </body> </html> ``` <file_sep>/_javascript/A017 홈페이지 스크롤넘기기.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>pagescroll</title> <script src="js/jquery-1.7.2.min.js"></script> <script src="js/jquery.mousewheel.js"></script> <script src="js/jquery.scrollTo-min.js"></script> <script> $(function(){ var sec_h = 1000 $('section').css({height:sec_h, lineHeight:sec_h+'px'}) //li에 data-st $('nav .gnb li').each(function(index){ $(this).attr('data-st',index*sec_h) }) //section data-st $('section').each(function(index){ $(this).attr('data-st',index*sec_h) }) $('nav .gnb li').click(function(){ st = parseInt($(this).attr('data-st')) $(window).scrollTo({left:0,top:st},500) }) $('section').mousewheel(function(e,delta){ st =parseInt($(this).attr('data-st')) if(delta > 0){ // 현재 섹션에서 - 한섹션의 높 $('body,html').stop().animate({ scrollTop:st - sec_h},500) } if(delta < 0){ //현재 섹션에서 + 한화면의 섹션 $('body,html').stop().animate({ scrollTop:st + sec_h},500) } }) }) </script> <style> * { margin:0; padding:0} ul,ol,li { list-style:none; } nav{ color:#FFFFFF; height:40px; position:fixed; width:100%; } .gnb{ width:400px; margin:0 auto;background-color:#000000; height:40px} .gnb li{ float:left; cursor:pointer; width:100px; text-align:center; line-height:40px;} .gnb li:hover{ background-color:#333333} section {font-size:72px; text-align:center;} #page1{ background-color:#09F} #page2{ background-color:#F60} #page3{ background-color:#99CCCC} #page4{ background-color:#FFCC33} </style> </head> <body> <nav> <ul class="gnb"> <li>page1</li> <li>page2</li> <li>page3</li> <li>page4</li> </ul> </nav> <div id="contents"> <section id="page1" >page1</section> <section id="page2" >page2</section> <section id="page3" >page3</section> <section id="page4" >page4</section> </div> </body> </html> ``` <file_sep>/KNOU.java.test/src/knou/test/awt/Test.java package knou.test.awt; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; //이벤트 리스너 구현 class MyListener extends WindowAdapter { public void windowClosing(WindowEvent ev) { System.exit(0); } } class MyFrame extends Frame { public MyFrame(String title) { super(title); this.setSize(400,300); this.setVisible(true); // 이벤트 리스너 등록 this.addWindowListener(new MyListener()); } public void paint(Graphics g) { g.drawString("Hello AWT", 50, 50); } } public class Test { public static void main(String[] args) { MyFrame myFrame = new MyFrame("Hello AWT"); } } <file_sep>/_htmlCss/A021 form 이용한 로그인 페이지.md ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>login</title> <style type="text/css"> *{margin:0; padding:0} body,input,button { font:12px "돋움",Arial,sans-serif; color:#333333} ul,ol,li { list-style:none} img, fieldset { border:none} legend{ display:none;} .login_box{ width:500px; height:500px; background-color:#F0F0F0; margin:200px auto 0 auto; border:1px solid #CCC} .login_box .h1_title{ text-align:center; font-size:36px; color:#333333; line-height:72px; border-bottom:1px solid #ccc} .login_box form{ padding:50px 0 0 60px; height:150px; border-bottom:1px solid #ccc } .login_box fieldset{ display:block;} .login_box .line{ clear:both; padding-top:10px;} .login_box label, .login_box input, .login_box button{ float:left;} .login_box label{ display:block; width:70px; padding-top:5px;} .login_box input { padding:3px; width:200px; border:1px solid #999; color:#666} .login_box #btnLogin{ width:70px; height:56px; margin:-33px 0 0 10px } .login_box .etc{ padding:40px 40px 0 40px} .login_box .etc li{ line-height:20px; padding:0 0 10px 12px; color:#666666; background:url(img/more.png) no-repeat 0 3px; } .login_box .link{ clear:both; padding:20px 0 0 0} .login_box .link li{ display:inline;} .login_box .link li a{ text-decoration:none; color:#3366CC} </style> </head> <body> <div class="login_box"> <h1 class="h1_title">LOGIN</h1> <form action="#"> <fieldset> <legend>로그인</legend> <p class="line"> <label for="uid">아이디</label> <input type="text" id="uid" /> </p> <p class="line"> <label for="upw">비밀번호</label> <input type="text" id="upw" /> </p> <button id="btnLogin">로그인</button> </fieldset> <ul class="link"> <li><a href="#">회원가입</a> / </li> <li><a href="#">아이디 </a> | <a href="#">비밀번호 </a>찾기 </li> </ul> </form> <ul class="etc"> <li>홈페이지 패스워드를 잊으셨거나, 로그인에 문제가 있는 분은 아이디/패스워드 찾기 버튼을 눌러주세요. </li> <li>아이디가 없으신 분은 회원가입 후 이용하실 수 있습니다.</li> <li>웹진 뉴스레터를 수신거부하실 고객님은 마이페이지 > 회원정보수정의 수신거부 선택을 통하여 설정바랍니다. </li> </ul> </div> </body> </html> ``` <file_sep>/_java/A011 당구 만들기.md ``` package com.me.graphictest; import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Panel; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; // 프레임에 그래픽을 표시하려면 Panel 또는 JPanel 클래스를 상속받고 paint()메소드를 override해서 구현한다. // 도형이나 그림에 움직임을 주고 싶으면 Runnable 인터페이스를 구현해서 스레드로 구현해야 한다. public class GraphicTest2 extends Panel implements Runnable{ int x, y; public GraphicTest2(){ this(20, 20); } public GraphicTest2(int x, int y){ this.x = x; this.y = y; } public static void main(String[] args) { Frame win = new Frame("당구"); win.setSize(500, 700); win.setLocation(800, 200); win.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e){ System.exit(0); } }); GraphicTest2 g = new GraphicTest2(); // Runnable 인터페이스를 구현해 스레드를 실행하려 할 경우 Thread 클래스의 생성자로 현재 클래스의 // 객체를 인수로 넘겨주고 Thread 클래스의 객체에서 start() 메소드로 실행한다. Thread thread = new Thread(g); thread.start(); // 프레임에 그래픽을 추가하려면 자기 자신의 객체를 프레임에 추가해야 한다. win.add(g); win.setVisible(true); } @Override public void paint(Graphics g) { // 그래픽 구현 g.setColor(Color.RED); g.fillOval(x, y, 50, 50); } @Override public void run() { // 스레드(움직임) 구현 int swx = 1, swy = 1; while(true){ x += 3 * swx; if(x >= 435 || x <= 0){ swx *= -1; } y += 5 * swy; if(y >= 610 || y <= 0){ swy *= -1; } try { // 영화는 fps가 24로 Thread.sleep(24); 해줌. Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } // ★★★★★ paint() 메소드를 다시 시작한다. 프레임에 다시 그린다. ★★★★★ 애니메이션 적용하려면 반드시 사용해야 함. repaint(); } } } ``` ``` package com.me.animationtest; import java.awt.Frame; import java.awt.Graphics; import java.awt.Image; import java.awt.Panel; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class AnimationTest1 extends Panel implements Runnable{ Image img; // 이미지를 저장할 변수를 선언한다. int w = 55, h = 68; // 이미지의 폭과 높이를 저장해 둔다. // 객체가 생성될 때 생성자 메소드를 통해서 표시할 이미지를 읽어 변수에 저장한다. public AnimationTest1(){ String filename = "./src/images/Duke06.gif"; // 상대주소 표기법 img = Toolkit.getDefaultToolkit().getImage(filename); } public static void main(String[] args) { // images 폴더를 src에 드래그해서 copy files and folders -> OK Frame win = new Frame("이미지 불러오기"); win.setSize(500, 700); win.setLocation(800, 200); win.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e){ System.exit(0); } }); AnimationTest1 g = new AnimationTest1(); // Thread thread = new Thread(g); // thread.start(); win.add(g); win.setVisible(true); } @Override public void paint(Graphics g) { // 그래픽 구현 // 인수가 4개짜리 drawImage() 메소드는 현재 프레임(this)에 img에 저장된 이미지를 시작점(0, 0)부터 // 원본 이미지의 크기와 모양 그대로 표시할 경우 사용한다. g.drawImage(img, 0, 0, this); // dy, dx는 프레임에 표시할 좌표, sx, sy는 이미지의 시작점과 끝점 // 인수가 10개짜리 drawImage() 메소드는 현재 프레임(this)에 이미지를 프레임에 표시할 // 위치(시작점(dx1, dy1) 부터 끝점(dx2, dy2))에 img에 저장된 이미지의 시작점(sx1, sy1) 부터 끝점(sx2, sy2) 까지 // 읽어서 표시할 경우 사용한다. g.drawImage(img, w*1, w*0, w*2, h*1, w*0, h*0, w*1, h*1, this); // 1번째 인수 : 이미지가 저장된 변수명 // 2, 3번째 인수 : 프레임에 이미지가 표시될 시작 좌표 // 4, 5번째 인수 : 프레임에 이미지가 표시될 끝 좌표 // 6, 7번째 인수 : 프레임에 표시될 원본 이미지의 시작 좌표 // 8, 9번째 인수 : 프레임에 표시될 원본 이미지의 끝 좌표 // 10번째 인수 : 이미지를 표시할 프레임 g.drawImage(img, w*2, w*0, w*3, h*1, w*1, h*0, w*0, h*1, this); // 좌우 대칭 g.drawImage(img, w*3, w*0, w*4, h*1, w*0, h*1, w*1, h*0, this); // 상하 대칭 g.drawImage(img, w*4, w*0, w*5, h*1, w*1, h*1, w*0, h*0, this); // 상하좌우 대칭 g.drawImage(img, w*5, w*0, w*6, h*2, w*0, h*0, w*1, h*1, this); // 4배 확대 g.drawImage(img, w*7, w*0, w*7+w/2, h/2, w*0, h*0, w*1, h*1, this); // 1/4배 확대 } @Override public void run() { // 스레드(움직임) 구현 } } ``` <file_sep>/_htmlCss/A004 드림위버로 웹호스팅(FTP).md ``` 드림위버 사용하시는 분들은 굳이 알드라이브를 다운로드 받지 않으셔도 됩니다. (개인적으로 알드라이브 인터페이스가 보기 편하고 좋습니다.) 왜냐하면 드림위버로도 FTP에 접속할 수 있기 때문입니다. moon_and_james-44 드림위버 내에서 처리하기 위한 공간을 만들어줍니다. 1. Site 클릭 -> new site클릭 적당한 Site Name을 만들어 주시고 Local Site Folder는 경로를 지정하는 것인데, index.html이 있는 폴더로 지정해줍니다. 이곳엔 이미지가 있는 img 폴더와 경우에 따라 css폴더도 당연히 있어야겠죠? moon_and_james-83 좌측에 보이는 Site밑에 Servers를 누르시면 처음엔 아무것도 없을텐데요. 웹 호스팅을 하기위해서, 사진에는 보이지 않지만 + 버튼이 있습니다. 상식적으로 new 버튼이라고 생각하시고 눌러주세요. 사진에서 보이는 것 처럼 웹 주소와 id, password를 작성해주시고 Save를 눌러주세요. 이제 화면 우측에 Files에 등록한 Site 이름이 나올텐데요. '가'를 누르시면 웹 호스팅이 됩니다. 다시말해 URL이 연결된다고 보시면 되요. 이때부터 홈페이지 업로드가 가능합니다. 위에 표시를 안해놨는데 Local view는 사용자의 컴퓨터를 보는 거구요. 여기다가 최근 작성한 걸 업로드('다' 버튼) 해주셔야 합니다. 그럼 Remote Server에 업로드가 됩니다. Remote Server는 현재 웹페이지에 올라와있는 자료를 보는거구요. '나' 버튼은 다운로드 버튼이기 때문에 최근작성한 자료를 저장하지 않으면 전에 올라와있던걸 다운받게 되는거니까 주의해야겠죠? 디펜던트 같은 이상한 창이 뜬다면 모르는 말이니 단호박처럼 'No'를 눌러줍니다. moon_and_james-56 FTP(FTP접속기) = File Transfer Protocol <=> 웹호스팅 대표적인 ftp 프로그램 1. 파일질라 2. 알드라이브 3. 드림위버 홈페이지 시작 파일 -> index.html (열리면 index파일부터 찾음 (약속)) index아닌 main을 시작으로 하려면 mjwmmm.dothome.co.kr/main.html 서버에서 index.html은 생략해줌 <br /> 줄바꿈 &nbsp; 띄어쓰기 윈도우 - 워크스페이스 레이아웃 - 클래식 루트폴더 -> img폴더에 이미지 파일 저장 Local Files에서 리플래시 버튼 누르면 업데이트 됨. insert -> image 에서 이미지 바로 업로드가능 <img src="img/intro.jpg" width="700" height="500"> <= 같은뜻 => <img src="img/intro.jpg" /> margin: 0 auto 하려면 box 값을 정해줘야함 #wrap { width:700px; height:500px; font-size:30px; color:blue; margin:150px auto; } <div id="wrap"><img src="img/intro.jpg" /></div> <div id="wrap"><img src="img/intro.jpg" alt="공사중입니다. 2015년 6월 10일날 뵙겠습니다." /></div> 사진을 제대로 보기힘든 시각장애인을 위해, alt로 내용을 써줌, alt가 없을 경우 이미지 파일 이름을 읽어줌. 드림위버는 이미지 크기 써주는데 굳이 안그래도 됨. 포토샵으로 이미지 자르기 2. select (1~2개 정도 자를 때) -> 영역을 잡고 -> alt + i,p 3. slice ( 3개 이상 자를 때) 화면 확대 : ctrl + '+', ctrl + space, 마우스 왼쪽 클릭 화면 원복 : ctrl + '0' ctrl로 슬라이스 선택해서 수정가능. file -> save for web... shift키로 다중 선택하고 -> jpg 세이브-> selected slices 선택 , settings -> other -> put images in folder 체크 해제 체크 해제하지 않으면 이미지 마다 폴더를 만듬. 홈페이지 외관 참고하는 사이트 추천 : www.dbcut.com + 사진 생략 ``` <file_sep>/_java/FILE HANDLING - Create a directory.md ``` import java.io.*; class CreateDirectoryTest { public static void main(String args[]) { if(new File("docs").mkdir()) System.out.println("Successfully created directory."); else System.out.println("Failed to create directory."); } } ``` ##OUTPUT ``` Successfully created directory. ```<file_sep>/_javascript/A001 CSS선택자, jquery nth-child().md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery</title> <script type="text/javascript" src="js/jquery-1.11.3.min.js" > </script> <script type="text/javascript"> $(document).ready(function(){ //alert('jquery시작합니다.') $('.btn').click(function(){ alert('버튼을 클릭하셨습니다.') }) }) </script> <style type="text/css"> .btn{ width:50px; height:30px;} /* css3 */ .btn:first-child{ background-color:#099} .btn:last-child{ background-color:#600} .btn:nth-child(2){ background-color:#00CC99;} .btn:nth-child(odd){ border:3px solid #f00;} .btn:nth-child(even){border:3px solid #0f0} </style> </head> <body> <p> <button class="btn">b1</button> <button class="btn">b2</button> <button class="btn">b3</button> <button class="btn">b4</button> <button class="btn">b5</button> <button class="btn">b6</button> </p> <p> <button class="btn">b1</button> <button class="btn">b2</button> <button class="btn">b3</button> <button class="btn">b4</button> <button class="btn">b5</button> <button class="btn">b6</button> </p> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>css셀렉터</title> <style type="text/css"> *{ margin:0; padding:0} ul,ol,li{list-style:none} .gnb{ margin:50px; width:700px;} .gnb > li{ float:left; width:100px;} /* 자식선택자 */ h1 + h2 { color:red} /* 형제인접 선택자 */ /* 속성선택자 */ a[title] { color:green} a[title="다음"] { color:red} a[href^="http"]{ color:#000} /*지정한 값으로 시작하는 항목 */ a[href$="com"] { background-color:#CCCCCC} a[href*="n"]{ background-color:cyan} /* :nth- */ /* :not */ *:not(a){ color:#FF6600} li:not(:first-child){ background-color:#09F} </style> </head> <body> <h1>선택자</h1> <h2>선택자 유형별로 알아보기</h2> <h2>자식선택자 / 형제인접선택자 </h2> <ul class="gnb"> <li><a href="http://www.daum.net" title="다음">menu1</a> <ul class="sub"> <li><a href="#">m1-sub1</a></li> <li><a href="#">m1-sub2</a></li> <li><a href="#">m1-sub3</a></li> </ul> </li> <li><a href="http://www.naver.com" title="네이버">menu2</a> <ul class="sub"> <li><a href="#">m2-sub1</a></li> <li><a href="#">m2-sub2</a></li> <li><a href="#">m2-sub3</a></li> <li><a href="#">m2-sub4</a></li> </ul> </li> <li><a href="http://www.google.com" title="구글">menu3</a></li> <li><a href="http://www.nate.com" title="네이트">menu4</a></li> </ul> </body> </html> ``` ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jquery nth-child()</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css"> <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script> <script type="text/javascript"> // 여기는 javascript코딩할 자리 </script> <style type="text/css"> td{ border-bottom:1px solid #000} tr:nth-child(odd) { background-color:#CCC;} tr:nth-child(even) {background-color:#FFFFCC} tr:hover{ background-color:} </style> </head> <body> <table class="table width="600" border="0" cellspacing="0" cellpadding="0" summary="표에대한요약 설명"> <caption>영화예매순위</caption> <thead> <tr> <th scope="col">제목1</th> <th scope="col">제목2</th> <th scope="col">제목3</th> <th scope="col">제목4</th> <th scope="col">제목5</th> </tr> </thead> <tfoot> <tr> <td scope="row">합계</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td scope="row">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td scope="row">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td scope="row">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td scope="row">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td scope="row">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <td scope="row">&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tfoot> <tbody> <tr> <th scope="row">가로제목1</th> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <th scope="row">가로제목2</th> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> <tr> <th scope="row">가로제목3</th> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </tbody> </table> </body> </html> ``` <file_sep>/_java/EXCEPTION HANDLING - Throw an Exception.md ``` public class MyExplicitThrow { public static void main(String a[]) { try { MyExplicitThrow met = new MyExplicitThrow(); System.out .println("length of JUNK is " + met.getStringSize("JUNK")); System.out.println("length of WRONG is " + met.getStringSize("WRONG")); System.out.println("length of null string is " + met.getStringSize(null)); } catch (Exception ex) { System.out.println("Exception message: " + ex.getMessage()); } } public int getStringSize(String str) throws Exception { if (str == null) { throw new Exception("String input is null"); } return str.length(); } } ``` ##OUTPUT ``` length of JUNK is 4 length of WRONG is 5 Exception message: String input is null ```<file_sep>/_jspServlet/A000 Dynamic-Web-Project.md ## 웹 프로젝트 폴더 구조 메뉴에서 Window -> Show View -> Navigator를 클릭한 상태에서의 폴더 구조 - src + 자바 소스 파일을 두는 폴더. 이 폴더에 서블릿 클래스나 필터, 리스너 등 필요한 모든 자바 클래스 파일은 둔다. .properties 파일도 이 폴더에 둔다.<br /> - build / classes + 컴파일된 자바 클래스 파일(.class)이 놓이는 폴더. 물론 패키지에 소속된 클래스인 경우 이 폴더에 해당 패키지가 자동으로 만들어진다.<br /> - WebContent + HTML(.html), CSS(.css), JavaScript(.js), JSP, 이미지 파일 등 웹 콘텐츠를 두는 폴더. 웹 애플리케이션을 서버에 배치할 때 이 폴더의 내용물이 그대로 복사 된다.<br /> - WebContent \ WEB-INF + 웹 애플리케이션의 설정과 관련된 파일을 두는 폴더. 이 폴더에 있는 파일은 클라이언트에서 요청할 수 없다. 따라서 HTML이나 JavaScript, CSS 등 클라이언트에서 요청할 수 있는 파일을 이 폴더에 두어서는 안된다!<br /> - WebContent\WEB-INF\web.xml + 웹 애플리케이션 배치 설명서(Deployment Descriptor) 파일이다. 영어 표현을 줄여서 '**DD 파일**'이라고도 부른다. 서블릿이나 필터, 리스너, 매개변수, 기본 웹 페이지 등 웹 애플리케이션 컴포넌트들의 배치 정보를 이 파일에 저장한다. 서블릿 컨테이너는 클라이언트 요청을 처리할 때 이파일의 정보를 참고하여 서블릿 클래스를 찾거나 필터를 실행하는 등의 작업을 수행한다.<br /> - WebContent\WEB-INF\lib + 자바 아카이브(Archive) 파일(.jar)을 두는 폴더. 아카이브란 우리말로 '**기록 보관소**'라는 뜻. 즉 아카이브 파일은 클래스 파일(.class)과 프로퍼티 파일(.properties)들을 모아 놓은 보관소 파일이다. 이러한 이유로 Java ARchive의 합성어를 확장자 명(.jar)으로 사용하고 있다.<br /> <file_sep>/KNOU.java.test/src/knou/first/grade/Extendss.java package knou.first.grade; class Employee{ int nSalary = 0; String szDept = null; public void doJob() { System.out.print("do Something"); } } class Developer extends Employee{ int nSalary = 2; public Developer() { szDept = " Dev "; } public void doJob() { System.out.print("do development"); } } public class Extendss { public static void main(String args[ ]) { Employee emp; emp = new Developer(); emp.doJob(); } }<file_sep>/_jspServlet/A010 What is 'JNDI'.md JNDI는 Java Naming and Directory Interface API의 머리글자입니다. 디렉터리 서비스에 접근하는데 필요한 API이며 애플리케이션은 이 API를 사용하여 서버의 자원을 찾을 수 있습니다. 자원이라함은 데이터베으스 서버나 메시징 시스템과 같이 다른 시스템과의 연결을 제공하는 객체입니다. 특히 JDBC 자원을 데이터 소스라고 부릅니다. 자원을 서버에 등록할 때는 고유한 JNDI 이름을 붙입니다. JNDI 이름은 사용자에게 친숙한 디렉터리 경로 형태를 가집니다. 예를 들어, JDBC 자원에 대한 JNDI 이름은 jdbc/mydb의 형식으로 짓습니다. 다음은 Java EE 애플리케이션 서버에서 자원을 찾을 때 기본 JNDI 이름입니다. | JNDI 이름 | 설명 | |:--------------------------|:-------------------------| | java:comp/env | 응용 프로그램 환경 항목 | | java:comp/env/jdbc | JDBC 데이터 소스 | | java:comp/ejb | EJB 컴포넌트 | | java:comp/UserTransation | UserTransation 객체 | | java:comp/env/mail | JavaMail 연결 객체 | | java:comp/env/url | URL 정보 | | java:comp/env/jms | JMS 연결 객체 | 따라서 'jdbc/mydb'라는 데이터 소스가 있어, 서버에서 이 자원을 찾으려면 'java:comp/env/jdbc/mydb' JNDI 이름으로 찾아야 합니다. <file_sep>/_javascript/A004 다양한 명령.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery명령</title> <script type="text/javascript" src="../day04 - Copy/js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(function(){ //text() , html(), attr('속성','값') $('h1').text()// 지정한 선택자의 텍스트값 $('h1').text('제이쿼리-Jquery') // 선택자의 텍스트값을 지정한값으로 교체 $('h2 em').text( $('h1').text() ) //alert($('h2').html()) $('h2').html('<strong style="color:red">제이쿼리</strong>') $('h2').html('<em>' + $('h1').text() + '</em>') //attr('속성','값') //attr('속성') //$('ul li img').attr('alt', $('ul li').text() ) //$('ul li').html('<img src="img/m1.jpg" alt="인사이드 아웃" />' // +$('ul li img').attr('alt')) $('ul li span').text($('ul li img').attr('alt')) }) </script> </head> <body> <h1>JQUERY</h1> <h2><em>JQEURY</em>의 명령들을 살펴보자</h2> <ul> <li><img src="img/m1.jpg" alt="인사이드아웃" /><span>영화1</span></li> </ul> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery명령</title> <script type="text/javascript" src="../day04 - Copy/js/jquery-1.11.3.min.js"></script> <script type="text/javascript"> $(function(){ $('ul:first').prepend('<li id="m0">HOME</li>') $('ul:first').append('<li id="end">end Menu</li>') $('ul:first').before('<h2>메뉴목록</h2>') $('ul:first').after('<hr />') $('ul').wrapAll('<div class="navWrap"></div>') $('ul').wrap('<div class="nav"></div>') $('.nav').wrapInner('<div class="gnb"></div>') }) </script> </head> <body> <h1>JQUERY</h1> <h2><em>JQEURY</em>의 명령들을 살펴보자</h2> <ul> <li id="m1">MENU1</li> <li id="m2">MENU2</li> <li id="m3">MENU3</li> <li id="m4">MENU4</li> <li id="m5">MENU5</li> </ul> <ul> <li id="m1">MENU1</li> <li id="m2">MENU2</li> <li id="m3">MENU3</li> <li id="m4">MENU4</li> <li id="m5">MENU5</li> </ul> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery명령3</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(document).ready(function(){ //prependTo appendTo $('.more').prependTo('.m1') .addClass('arr') //$('.more').removeClass('arr') //$('.more').appendTo('.m1') $('.m5').replaceWith('<li class="more2">더보기</li>') $('.m4').insertBefore('.m3') $('.m4').insertAfter('.m3') $('.more2').remove() $('.m4').removeAttr('class') }) </script> <style> .arr{ color:red;} </style> </head> <body> <span class="more">▶</span> <ul class="gnb"> <li class="m1">MENU1</li> <li class="m2">MENU2</li> <li class="m3">MENU3</li> <li class="m4">MENU4</li> <li class="m5">MENU5</li> </ul> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>jquery명령3</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ m1_alt = $('.m1 img').attr('alt') m2_alt = $('.m2 img').attr('alt') m3_alt = $('.m3 img').attr('alt') m4_alt = $('.m4 img').attr('alt') m5_alt = $('.m5 img').attr('alt') m_t = '영화제목 : ' $('.m1').append( m_t + m1_alt ) $('.m2').append( m_t + m2_alt ) $('.m3').append( m_t + m3_alt ) $('.m4').append( m_t + m4_alt ) $('.m5').append( m_t + m5_alt ) }) </script> <style> </style> </head> <body> <ul class="movie"> <li class="m1"><img src="img/m1.jpg" alt="인사이드아웃" /></li> <li class="m2"><img src="img/m2.jpg" alt="연평해전" /></li> <li class="m3"><img src="img/m3.jpg" alt="픽셀" /></li> <li class="m4"><img src="img/m4.jpg" alt="쓰리썸머나잇" /></li> <li class="m5"><img src="img/m5.jpg" alt="인시디어스3" /></li> </ul> </body> </html> ``` <file_sep>/_java/OOPS - Multilevel Inheritance Example.md ``` /* @author: CreativeCub */ class Car { public Car() { System.out.println("Class Car"); } public void vehicleType() { System.out.println("Vehicle Type: Car"); } } class Maruti extends Car { public Maruti() { System.out.println("Class Maruti"); } public void brand() { System.out.println("Brand: Maruti"); } public void speed() { System.out.println("Max: 90Kmph"); } } public class Maruti800 extends Maruti { public Maruti800() { System.out.println("Maruti Model: 800"); } public void speed() { System.out.println("Max: 80Kmph"); } public static void main(String args[]) { Maruti800 obj=new Maruti800(); obj.vehicleType(); obj.brand(); obj.speed(); } } ``` ##OUTPUT ``` Class Car Class Maruti Maruti Model: 800 Vehicle Type: Car Brand: Maruti Max: 80Kmph ```<file_sep>/_htmlCss/A024 html5,css3 맛보기.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>html5 &amp; css3</title> <style> * { margin:0; padding:0} ul,ol,li { list-style:none} #wrap{ width:960px; margin:0 auto; position:relative;} header{ height:100px; background-color:#CCCC00;} header nav{ padding-top:20px;/*transform:skewX(-15deg);*/} header nav .gnb li{ background-color:#FF9900; margin:2px 2px; padding:0.5em 2em; float:left; } header nav .gnb .gra{ /* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#1e5799+0,2989d8+50,207cca+51,7db9e8+100 */ background: #1e5799; /* Old browsers */ background: -moz-linear-gradient(top, #1e5799 0%, #2989d8 50%, #207cca 51%, #7db9e8 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(50%,#2989d8), color-stop(51%,#207cca), color-stop(100%,#7db9e8)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* IE10+ */ background: linear-gradient(to bottom, #1e5799 0%,#2989d8 50%,#207cca 51%,#7db9e8 100%); /* W3C */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 ); /* IE6-9 */ } header nav .gnb li:first-child{ background-color:#669933; /*css3*/ transform:rotate(-5deg) scale(1.2); transform-origin:right bottom} header nav .gnb li:first-child:hover{ background-color:#CCCCCC} figure{} section{} section article{ width:319px; float:left; margin-right:1px; background-color:#CCC; height:300px; font:32px/300px "Arial Black", Gadget, sans-serif ; text-align:center; color:#fff; /*css3*/ text-shadow: 1px 1px 2px rgba(0,0,0,0.7); } section .at2{ font:12px/1.5 Arial, Helvetica, sans-serif; width:100%; text-align:left;} section .at2 p{ -moz-column-count: 3; -moz-column-gap: 20px; -webkit-column-count: 3; -webkit-column-gap: 20px; column-count: 3; column-gap: 20px; } aside{ position:absolute; width:50px; height:300px; background-color:#999933; right:-70px; top:120px; margin-right:20px; border-radius:0 5px 5px 0; /* css3 속성 */ box-shadow: 1px 1px 2px rgba(0,0,0,0.7); } footer{height:100px; background-color:#66CCFF; clear:both;} </style> </head> <body> <div id="wrap"> <header> <nav> <ul class="gnb"> <li class="gra">menu1</li> <li>menu2</li> <li>menu3</li> <li>menu4</li> <li>menu5</li> </ul> </nav> </header> <figure> <img src="img/slideimg01.jpg" alt="" width="960" /> <figcaption>이미지 설명</figcaption> </figure> <section> <article> article1 </article> <article> article2 </article> <article> article3 </article> </section> <section> <article class="at2"> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. <NAME>, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. </p> </article> </section> <aside> </aside> <footer> </footer> </div> </body> </html> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>html5 input</title> <body> <input type="email" placeholder="ID" /> <input type="url" placeholder="PW" /> <input type="number" step="10" min="10" max="50"/> <input type="range" step="10" min="10" max="30" /> <input type="search" /> <input type="date" /> <input type="color" /> <input type="week" /> <input type="month" /> <video width="400" height="300" autoplay controls > <!-- mp4는 사파리, ie9, 아이폰,아이패드,안드로이드, 윈도7폰 --> <source src="shtter.mp4" type="video/mp4" > <!-- ogv 구 파이어폭스 ,오페라 --> <source src="shtter.ogv" type="video/ogv" > <!-- webM 파이어폭스4, 오페라, 크롬 --> <source src="shtter.webm" type="video/webm" > </video> </body> </html> ``` <file_sep>/_cpp/정렬하기, 여러가지 정렬 방법.md ``` #include <cstdio> #include <iostream> using namespace std; // 선택정렬 알고리즘을 사용해 정렬할 데이터가 5개일 경우 오름차순 정렬을 하고자 한다면 아래와 같이 한다. // 1회전 : 0번째 값과 1, 2, 3, 4 번째 값을 비교해서 앞의 값이 크면 자리를 교환한다. // 2회전 : 1번째 값과 2, 3, 4 번째 값을 비교해서 앞의 값이 크면 자리를 교환한다. // 3회전 : 2번째 값과 3, 4 번째 값을 비교해서 앞의 값이 크면 자리를 교환한다. // 4회전 : 3번째 값과 4 번째 값을 비교해서 앞의 값이 크면 자리를 교환한다. int main() { int a[] = {8, 3, 4, 9, 1}; // 바깥쪽 반복은 회전수, 선택 위치를 의미한다. for(int i=0 ; i<4 ; i++) { // 안쪽 반복은 비교 대상의 위치를 의미한다. for(int j=i+1 ; j<5 ; j++) { // 앞의 값이 크면 자리를 교환한다. if(a[i] > a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } cout << i + 1 << "회전 결과 : "; for(int j=0 ; j<5 ; j++) { cout << a[j] << " "; } cout << endl; } } ``` ``` #include <cstdio> #include <iostream> using namespace std; int main() { int n, *a; cout << "정렬할 데이터의 수 : "; cin >> n; a = new int[n]; // 입력받은 n개 만큼의 배열을 만든다. for(int i=0 ; i<n ; i++) { // n개 만큼의 데이터를 입력받는다. cout << i + 1 << "번째 데이터 : "; cin >> a[i]; } for(int i=0 ; i<n-1 ; i++) { for(int j=i+1 ; j<n ; j++) { if(a[i] > a[j]) { // 부등호를 "<"로 바꾸면 내림차순 정렬된다. //int temp = a[i]; //a[i] = a[j]; //a[j] = temp; swap(a[i], a[j]); // C++이 제공하는 값 교환 함수 } } cout << i + 1 << "회전 결과 : "; for(int j=0 ; j<n ; j++) { cout << a[j] << " "; } cout << endl; } } ``` ``` #include <cstdio> #include <iostream> using namespace std; int main() { int n, *a, *rank; cout << "석차를 계산할 데이터의 수 : "; cin >> n; a = new int[n]; // 입력받은 n개 만큼의 점수를 저장할 배열을 만든다. rank = new int[n]; // 입력받은 n개 만큼의 석차를 저장할 배열을 만든다. for(int i=0 ; i<n ; i++) { // n개 만큼의 점수를 입력받는고 석차를 초기화한다. cout << i + 1 << "번째 데이터 : "; cin >> a[i]; rank[i] = 1; // 석차를 기억할 기억장소는 반드시 1로 초기화한다. } for(int i=0 ; i<n-1 ; i++) { for(int j=i+1 ; j<n ; j++) { // 부등호의 방향을 반대로 변경하면 오름차순(작은게 1등) 석차가 계산된다. if(a[i] > a[j]) { rank[j]++; // i번째 점수가 크면 j번째 석차를 1증가 한다. } else if(a[i] < a[j]) { rank[i]++; // j번째 점수가 크면 i번째 석차를 1증가 한다. } } } for(int i=0 ; i<n ; i++) { cout << a[i] << "점은 " << rank[i] << "등 입니다." << endl;; } } ``` <file_sep>/_cpp/평균구하기, 문자를 아스키 값으로 변환하기.md ``` #include <cstdio> #include <iostream> using namespace std; int main() { int cpp, java, basic, total; double average; cout << "cpp, java, basic 점수 입력 : "; cin >> cpp >> java >> basic; total = cpp + java + basic; average = total / 3.; //cout << average << endl; printf("평균 : %6.2f\n", average); //if(average >= 90) { // cout << "수" << endl; //} else if(average >= 80) { // cout << "우" << endl; //} else if(average >= 70) { // cout << "미" << endl; //} else if(average >= 60) { // cout << "양" << endl; //} else { // cout << "가" << endl; //} //key에는 정수 값을 기억하는 변수 또는 연산 결과가 정수인 수식이 올 수 있다. //switch(key) { // case value: // key와 value가 같으면 실행할 문장; // ...; // break; // ...; // default: // key와 같은 value가 하나도 없을 경우 실행할 문장; // ...; //} switch((int)average / 10) { case 10: cout << "참잘했어요" << endl; case 9: cout << "수" << endl; break; // {} 블록을 탈출한다. case 8: cout << "우" << endl; break; case 7: cout << "미" << endl; break; case 6: cout << "양" << endl; break; default: cout << "가" << endl; } char ch; cout << "문자 입력 : "; cin >> ch; switch(ch) { case 'a': case 'A': cout << (int)ch << endl; break; case 'b': case 'B': cout << (int)ch << endl; break; case 'c': case 'C': cout << (int)ch << endl; break; } } ``` ``` #include <cstdio> #include <iostream> using namespace std; int main() { int year, month, day; cout << "년, 월, 일 : "; cin >> year >> month >> day; // 1월 1일 부터 전달까지 지나온 날짜의 합을 구한다. int sum = 0; bool isYoun = year%4 == 0 && year%100 != 0 || year%400 == 0; for(int i=1 ; i<month ; i++) { switch(i) { case 2: // sum = sum + 28;과 sum += 28;은 같은 의미로 사용된다. sum += isYoun ? 29 : 28; break; case 4: case 6: case 9: case 11: sum += 30; break; default: sum += 31; } } sum += day; cout << sum << endl; } ``` <file_sep>/_java/A010 keypad button에 그래픽 표시.md ``` package com.me.layouttest; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class LayoutTest1 extends Frame{ Label lb1 = new Label("Test1"); Label lb2 = new Label("Test2"); Panel panel = new Panel(); // 컨테이너 // Panel은 레이아웃 매니저를 지정하지 않으면 FlowLayout이 기본 레이아웃 매니저가 된다. public LayoutTest1(String title) { setTitle(title); setSize(300, 500); setLocation(800, 200); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); // 기본 Layout이 BorderLayout이기 때문에 따로 생성하지않아도 사용가능. setLayout(new BorderLayout()); // 프레임의 레이아웃 매니저 지정, 생략시 BorderLayout lb1.setBackground(Color.GREEN); // 레이블의 배경색 lb1.setAlignment(Label.CENTER); // 레이블의 텍스트 정렬 // add(lb1, BorderLayout.SOUTH); lb2.setBackground(Color.PINK); lb2.setAlignment(Label.CENTER); // add(lb2, BorderLayout.SOUTH); panel.setLayout(new GridLayout(1, 2)); // 패널의 레이아웃 매니저 지정, 생략시 FlowLayout panel.add(lb1); // 패널에 레이블 추가 panel.add(lb2); // 패널에 레이블 추가 add(panel, BorderLayout.SOUTH); // 프레임에 패널 추가 setVisible(true); } public static void main(String[] args) { new LayoutTest1("LayoutTest1"); } } ``` ``` package com.me.layouttest; import java.awt.Button; import java.awt.CardLayout; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Panel; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class LayoutTest2 extends Frame{ Button[] btn = new Button[12]; // 배열만 선언하고 객체는 생성되지 않은 상태 Panel panel = new Panel(); public LayoutTest2(String title) { setTitle(title); setSize(300, 500); setLocation(800, 200); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); setBackground(Color.CYAN); // 가생이에 여백을 주려면 프레임이 아닌 카드레이아웃에 줘야한다.. setLayout(new CardLayout(3, 3)); // 프레임의 레이아웃 매니저 지정 panel.setLayout(new GridLayout(4, 3, 3, 3)); // 프레임의 레이아웃 매니저 지정 String str[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "*", "0", "#"}; Font font = new Font("Serif", Font.BOLD, 30); for(int i=0 ; i<btn.length; i++){ // btn[i] = new Button( String.valueOf(i+1) ); // 버튼 객체 생성 // String.valueOf() : 괄호 안의 숫자를 문자열로 변환한다. // btn[i] = new Button( (i+1) + "" ); // 버튼 객체 생성 btn[i] = new Button( str[i] ); // 버튼 객체 생성 btn[i].setFont(font); // 버튼 객체의 폰트 변경 panel.add(btn[i]); // 버튼을 패널에 올린다. } add("view", panel); // 패널을 프레임에 올린다.. setVisible(true); } public static void main(String[] args) { new LayoutTest2("LayoutTest1"); } } ``` ``` package com.me.graphictest; import java.awt.Color; import java.awt.Frame; import java.awt.Graphics; import java.awt.Panel; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; // 프레임에 그래픽을 표시하려면 Panel 또는 JPanel 클래스를 상속받고 paint()메소드를 override해서 구현한다. public class GraphicTest1 extends Panel{ public static void main(String[] args) { Frame win = new Frame("GraphicTest"); win.setSize(500, 500); win.setLocation(800, 200); win.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e){ System.exit(0); } }); // Pain() 메소드를 통해 작성한 그래픽을 프레임에 표시하려면 Panel 또는 JPanel 클래스를 상속받은 // 자기 자신의 객체를 만들고 자기 자신의 객체를 프레임에 추가한다. // GraphicTest1 graphic = new GraphicTest1(); // win.add(graphic); win.add(new GraphicTest1()); win.setVisible(true); } @Override public void paint(Graphics g) { // 시작점(100, 50) 부터 문자열을 출력한다. g.drawString("프레임에 글자 출력하기", 100, 50); // 시작점(100, 100) 부터 끝점(250, 250) 까지 선을 그린다. g.drawLine(100, 100, 250, 250); // 시작점(100, 100) 부터 너비(100), 높이(100) 만큼의 사각형을 그린다. g.drawRect(100, 100, 100, 100); g.drawRoundRect(300, 100, 100, 100, 80, 80); // 모서리가 둥근 사각형 g.setColor(Color.RED); // 도형 색을 바꾼다. // 시작점(100, 100) 부터 너비(100), 높이(100) 만큼의 사각형에 내접하는 원을 그린다. g.drawOval(100, 100, 100, 100); g.setColor(Color.GREEN); g.fillRect(100, 300, 100, 100); // 색이 채워진 사각형 g.setColor(Color.YELLOW); g.fillOval(100, 300, 100, 100); g.setColor(Color.BLUE); // 시작점(300, 300) 부터 너비(100), 높이(100) 만큼의 사각형에 내접하는 90도 위치에서 시작하고 // 시계 반대 방향으로 225도 만큼 진행하는 호를 그린다. g.drawArc(300, 300, 100, 100, 90, 225); } } ``` <file_sep>/_java/COLLECTION - ArrayList Class.md ``` import java.util.ArrayList; import java.util.Iterator; public class ArrayListTest { public static void main(String[] args) { //creating arraylist of type String ArrayList<String> al=new ArrayList<String>(); //adding object in arraylist al.add("Java"); al.add("C"); al.add("C++"); al.add("php"); System.out.print("ArrayList :"+al); System.out.println(); //getting Iterator from arraylist to traverse elements Iterator itr=al.iterator(); while(itr.hasNext()) { System.out.print(itr.next()+" "); } System.out.println(); //Using Enhance for-loop for (String string : al) { System.out.print(string+" "); } } } ``` ##OUTPUT ``` ArrayList :[Java, C, C++, php] Java C C++ php Java C C++ php ```<file_sep>/_java/A028 요일 구하기.md ``` import java.util.Scanner; public class WeekTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("요일을 계산할 년, 월, 일을 입력하세요 : "); int y = sc.nextInt(); int m = sc.nextInt(); int d = sc.nextInt(); // 4로 나눠 떨어지고(&&) 100으로 나눠 떨어지지 않거나() 400으로 나눠 떨어지면 윤년 boolean isYoun = y%4 == 0 && y%100 != 0 y%400 == 0; // if(isYoun) { // System.out.println("윤년"); // } else { // System.out.println("평년"); // } // System.out.println(isYoun ? "윤년" : "평년"); // 1년 1월 1일 부터 전년도 까지 지나온 날수를 계산한다. int sum = (y-1) * 365 + (y-1) / 4 - (y-1) / 100 + (y-1) / 400; // 날수에 전달 까지 지나온 날수를 더한다. for(int i=1 ; i<m ; i++) { switch(i) { case 2: sum = sum + (isYoun ? 29 : 28); break; case 4: case 6: case 9: case 11: sum = sum + 30; break; default: sum = sum + 31; } } // 날수에 일을 더한다. sum = sum + d; // 요일을 출력한다. switch(sum % 7) { case 0: System.out.println("일요일"); break; case 1: System.out.println("월요일"); break; case 2: System.out.println("화요일"); break; case 3: System.out.println("수요일"); break; case 4: System.out.println("목요일"); break; case 5: System.out.println("금요일"); break; case 6: System.out.println("토요일"); } } } ``` <file_sep>/_java/EXCEPTION HANDLING - Using Finally.md ``` class UsingFinally { public static void main(String[] args) { try { int a = 3/0; System.out.println(a); } catch (Exception e) { System.out.println(e); } finally { System.out.println("finally block will execute always."); } } } ``` ##OUTPUT ``` java.lang.ArithmeticException: / by zero finally block will execute always. ```<file_sep>/_java/OOPS - Constructor Overloading.md ``` public class Constructor1 { int id; String name; int age; Constructor1(int i,String n) { id = i; name = n; } Constructor1(int i,String n,int a) { id = i; name = n; age=a; } void display() { System.out.println(id+" "+name+" "+age); } public static void main(String[] args) { Constructor1 co = new Constructor1(1,"Sam"); Constructor1 co1 = new Constructor1(2,"Roy",25); co.display(); co1.display(); } } ``` ##OUTPUT ``` 1 Sam 0 2 Roy 25 ```<file_sep>/KNOU.java.test/src/knou/test/awt/WindowEventTest4.java package knou.test.awt; import java.awt.Frame; import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; class MyListener4 extends WindowAdapter { public void windowClosing(WindowEvent ev){ Window w = ev.getWindow(); w.dispose(); } @Override public void windowActivated(WindowEvent arg0) { System.out.println("Activated"); } @Override public void windowClosed(WindowEvent arg0) { System.out.println("Closed"); } @Override public void windowDeactivated(WindowEvent arg0) { System.out.println("Deactivated"); } @Override public void windowDeiconified(WindowEvent arg0) { System.out.println("Deiconified"); } @Override public void windowIconified(WindowEvent arg0) { System.out.println("Iconified"); } @Override public void windowOpened(WindowEvent arg0) { System.out.println("Opened"); } } public class WindowEventTest4 extends Frame{ public static void main(String[] args) { WindowEventTest4 f = new WindowEventTest4(); f.addWindowListener(new MyListener4()); f.setSize(300,300); f.setVisible(true); } } <file_sep>/KNOU.java.test/src/knou/test/applet/ButtonApplet2.java package knou.test.applet; import java.applet.Applet; import java.applet.AppletContext; import java.awt.Button; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.net.MalformedURLException; import java.net.URL; public class ButtonApplet2 extends Applet implements ActionListener { Button b; CanvasApplet applet; public ButtonApplet2() { b=new Button("naver.com"); setLayout(new FlowLayout()); add(b); b.addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == b) { AppletContext ac = getAppletContext(); try { ac.showDocument(new URL("http://www.naver.com")); } catch(MalformedURLException ex) {} } } } <file_sep>/_java/OOPS - Inheritance - Accessing parent class property with super keyword.md ``` class Parent { String name; } class Inheritance extends Parent { String name; public void displaydetails() { //refers to parent class member super.name = "Parent"; name = "Child"; System.out.println(super.name+" and "+name); } public static void main(String[] args) { Inheritance obj = new Inheritance(); obj.displaydetails(); } } ``` ##OUTPUT ``` Parent and Child ```<file_sep>/KNOU.java.test/src/knou/test/awt/MyListener.java package knou.test.awt; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; public class MyListener implements WindowListener{ @Override public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub System.exit(0); } @Override public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } public static void main(String[] args) { MyFrame myFrame=new MyFrame("Hello WT"); } } class MyFrame extends Frame { public MyFrame(String title) { super(title); this.setSize(400,300); this.setVisible(true); //이벤트 리스터 등록 this.addWindowListener(new MyListener()); } public void paint(Graphics g) { g.drawString("Hello A", 150, 150); } }<file_sep>/_javascript/A015 좌우로 넘기는 갤러리.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>갤럭시 갤러리</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ var slide_img_w = $('#slide img').width() var slide_img_h = $('#slide img').height() var wrapImg_img_count = $('#wrapImg img').size() var slideTime = 500 var slideIntervalTime = 1000 //alert(slide_img_count) $('#viewImg').css({width:slide_img_w, height:slide_img_h}) $('#wrapImg').css({ width:slide_img_w * wrapImg_img_count, height:slide_img_h, left:-slide_img_w }) n=1 //btnNext() $('.btnNext').click(function(){ n++ if(n==wrapImg_img_count){ $('#wrapImg').css({left:-slide_img_w*1}) n=2 } $('#wrapImg').stop().animate({left:-slide_img_w*n},slideTime) $('.icon li img').attr('src','img/ico_slider.png') $('.icon li:eq('+ (n-1) +') img').attr('src','img/ico_slider_on.png') if(n==9){ $('.icon li:first img').attr('src','img/ico_slider_on.png') } }) //btnPrev() $('.btnPrev').click(function(){ n-- if(n==-1){ $('#wrapImg').css({left:-slide_img_w*(wrapImg_img_count-2)}) n=wrapImg_img_count-3 } $('#wrapImg').stop().animate({left:-slide_img_w*n},slideTime) //아이콘 이전 $('.icon li img').attr('src','img/ico_slider.png') $('.icon li:eq('+ (n-1) +') img').attr('src','img/ico_slider_on.png') if(n==0){ $('.icon li:last img').attr('src','img/ico_slider_on.png') } }) /*setInterval() setInterval(function(){ $('.btnNext').click()},slideIntervalTime) */ //icon li() }) </script> <style> *{margin:0; padding:0} ul,ol,li { list-style:none} #slide{ width:960px; height:520px; position:relative; margin:0 auto; } #btnGrp li{ position:absolute ; z-index:10; top:40%;} #btnGrp button{ width:50px; height:50px} #btnGrp .btnPrev{ left:0; cursor:pointer} #btnGrp .btnNext{ right:0; cursor:pointer} #viewImg{ position:relative;overflow:hidden; margin:0 auto} #wrapImg{ position:absolute; left:0; top:0; z-index:5 } #wrapImg img{ float:left} .icon{ position:absolute; left:402px; bottom:0px; z-index:10} .icon li{ float:left; margin:0 3px; cursor:pointer} </style> </head> <body> <div id="slide"> <ul id="btnGrp"> <li class="btnPrev"><button>< </button></li> <li class="btnNext"><button>> </button></li> </ul> <div id="viewImg"> <ul id="wrapImg"> <li><img src="img/s4_gallery_08.png" alt="" /></li> <li><img src="img/s4_gallery_01.png" alt="" /></li> <li><img src="img/s4_gallery_02.png" alt="" /></li> <li><img src="img/s4_gallery_03.png" alt="" /></li> <li><img src="img/s4_gallery_04.png" alt="" /></li> <li><img src="img/s4_gallery_05.png" alt="" /></li> <li><img src="img/s4_gallery_06.png" alt="" /></li> <li><img src="img/s4_gallery_07.png" alt="" /></li> <li><img src="img/s4_gallery_08.png" alt="" /></li> <li><img src="img/s4_gallery_01.png" alt="" /></li> </ul> </div><!--//viewImg--> <ul class="icon"> <li><img src="img/ico_slider_on.png" alt="on" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> <li><img src="img/ico_slider.png" alt="off" /></li> </ul> </div><!--//slide --> </body> </html> ``` <file_sep>/KNOU.java.test/src/knou/first/grade/MyClass3.java package knou.first.grade; class MyClass1 {} class MyClass2 extends Object{ @Override public String toString() { // TODO Auto-generated method stub return "This MyClass2 class"; } } public class MyClass3 { public static void main(String[] args) { MyClass1 my_class1 = new MyClass1(); MyClass2 my_class2 = new MyClass2(); System.out.println(my_class1.toString()); System.out.println(my_class2.toString()); System.out.println(my_class1); System.out.println(my_class2); } } <file_sep>/_java/BASIC - Switch Statement.md ``` public class SwitchCaseDemo { public static void main(String args[]) { char grade = 'C'; switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : System.out.println("Good"); break; case 'C' : System.out.println("Well done"); break; case 'D' : System.out.println("You passed"); case 'F' : System.out.println("Better try again"); break; default : System.out.println("Invalid grade"); } System.out.println("Your grade is " + grade); } } ``` ##OUTPUT ``` Well done Your grade is C ```<file_sep>/_java/OOPS - Using Final Keyword.md ``` class Superclass { //Final variable final int i = 10; //final method final void display() { System.out.println("Super Class Method"); System.out.println("\nValue of final variable : " + i); } } class FinalKeyword extends Superclass { public static void main(String args[]) { FinalKeyword obj = new FinalKeyword(); obj.display(); } } ``` ###OUTPUT ``` Super Class Method Value of final variable : 10 ```<file_sep>/_java/EXCEPTION HANDLING - Array Index Out of Bounds.md ``` class ArrayIndexOutOfBounds { public static void main(String[] args) { String languages[] = { "C", "C++", "Java", "Perl", "Python" }; try { for (int c = 1; c <= 5; c++) { System.out.println(languages[c]); } } catch (Exception e) { System.out.println(e); } } } ``` ##OUTPUT ``` C++ Java Perl Python java.lang.ArrayIndexOutOfBoundsException: 5 ```<file_sep>/_java/A039 슈퍼, 서브클래스의 생성자.md ``` public class InheritanceTest1 { public static void main(String[] args) { Parent parent1 = new Parent("홍길동", true); System.out.println(parent1); Parent parent2 = new Parent("홍길자", false); System.out.println(parent2); Child child1 = new Child("임꺽정", true); System.out.println(child1); Child child2 = new Child("임꺽숙", false, 20, "꺽숙이"); System.out.println(child2); } } // 부모(상위, 슈퍼, 기반) 클래스 public class Parent { // private String name; // private boolean gender; // protected : 부모(현재) 클래스와 부모 클래스를 상속받은 자식 클래스에서만 접근이 가능하다. // 상속 관계가 있는 클래스는 private 대신 protected로 멤버 변수의 접근 권한을 지정한다. protected String name; protected boolean gender; public Parent() { } public Parent(String name, boolean gender) { this.name = name; this.gender = gender; } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } @Override public String toString() { return "부모(Parent) 클래스의 toString() : " + name + "(" + (gender ? "남" : "여") + ")"; } } // 자식(하위, 서브, 파생) 클래스 public class Child extends Parent { // 부모(Parent) 클래스의 멤버 변수 name, gender, getter & setter 메소드 // 생성자 메소드, toString() 메소드를 상속받았다. private int age; private String nickName; // 부모 클래스의 private 멤버인 name, gender에 초기치를 전달하기 위해 부모 클래스의 생성자 메소드 // 개수 만큼 자식 클래스의 생성자 메소드를 만든다. public Child() { // 부모 클래스의 Parent() 생성자 메소드를 호출한다. super(); } public Child(String name, boolean gender) { // 부모 클래스의 Parent(String name, boolean gender) 생성자 메소드를 호출한다. // 부모 클래스의 private 멤버에 부모 클래스의 생성자 메소드를 통해 초기치를 입력한다. // super(name, gender); // 부모 클래스의 private 멤버에 부모 클래스의 setter 메소드를 통해 초기치를 입력한다. // super.setName(name); setName(name); // super.setGender(gender); setGender(gender); } // 부모 클래스와 자식 클래스의 모든 멤버 변수에 초기치를 전달하는 생성자 메소드를 만든다. public Child(String name, boolean gender, int age, String nickName) { // super(name, gender); // ① // setName(name); // ② // setGender(gender); // ② this.name = name; // ③ this.gender = gender; // ③ this.age = age; this.nickName = nickName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } @Override public String toString() { if(age == 0) { // 나이가 넘어오지 않으면 부모 클래스의 toString() 메소드를 실행한다. return super.toString(); } else { // 나이가 넘어왔으면 자식 클래스의 toString() 메소드를 실행한다. // return "자식(child) 클래스의 toString() : " + name + "(" + (gender ? "남" : "여") + ") - " + // age + ", " + nickName; return super.toString() + " - " + age + ", " + nickName; } } } ``` <file_sep>/_java/OOPS - Wrapper Example.md ``` public class Wrapper { public static void main(String args[]) { byte b = 3; int i = 10; float f = 4.5f; double d = 90.7; //data types to objects - wrapping Byte b_obj = new Byte(b); Integer i_obj = new Integer(i); Float f_obj = new Float(f); Double d_obj = new Double(d); // printing the values from objects System.out.println("Values of Wrapper objects "); System.out.println("Byte object : " + b_obj); System.out.println("Integer object : " + i_obj); System.out.println("Float object : " + f_obj); System.out.println("Double object : " + d_obj); // objects to data types (retrieving data types from objects) - unwrapping byte bv = b_obj.byteValue(); int iv = i_obj.intValue(); float fv = f_obj.floatValue(); double dv = d_obj.doubleValue(); //printing the values from data types System.out.println("\nUnwrapped values "); System.out.println("byte value : " + bv); System.out.println("int value : " + iv); System.out.println("float value : " + fv); System.out.println("double value : " + dv); } } ``` ###OUTPUT ``` Values of Wrapper objects Byte object : 3 Integer object : 10 Float object : 4.5 Double object : 90.7 Unwrapped values byte value : 3 int value : 10 float value : 4.5 double value : 90.7 ```<file_sep>/_java/A032 입력값의 석차와 평균.md ``` import java.util.Scanner; public class RankingTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("석차를 계산할 점수의 수 : "); int n = sc.nextInt(); double jumsu[] = new double[n]; int rank[] = new int[n]; // 석차를 기억할 배열 for(int i=0 ; i<jumsu.length ; i++) { System.out.print(i + 1 + "번째 점수 : "); jumsu[i] = sc.nextDouble(); // 석차를 기억할 기억장소는 초기치를 반드시 1로 지정한다. rank[i] = 1; } for(int i=0 ; i<jumsu.length-1 ; i++) { for(int j=i+1 ; j<jumsu.length ; j++) { // 부등호의 방향을 반대로 변경하면 작은게 1등(오름차순) 석차가 계산된다. if(jumsu[i] < jumsu[j]) { rank[i]++; } else if(jumsu[i] > jumsu[j]) { rank[j]++; } } } for(int i=0 ; i<n ; i++) { System.out.printf("%5.1f점은 %d등\n", jumsu[i], rank[i]); } } } ``` ``` import java.util.Scanner; public class SelectionSortTest { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("심판의 수 : "); int n = sc.nextInt(); // 입력받은 숫자의 크기만큼 배열을 만든다. double a[] = new double[n]; // 생성된 배열에 배열의 크기 만큼 데이터를 입력받고 총점을 구한다. double sum = 0; for(int i=0 ; i<a.length ; i++) { System.out.print(i + 1 + "번째 심판의 점수 : "); a[i] = sc.nextDouble(); // sum += a[i]; } // 선택 정렬시 바깥쪽 반복은 회전수와 선택 위치를 의미한다. for(int i=0 ; i<a.length-1 ; i++) { // 선택 정렬시 안쪽 반복은 비교 대상을 의미한다. for(int j=i+1 ; j<a.length ; j++) { // System.out.println("i : " + i + ", j : " + j); // 앞의 값이 크면 값을 교환한다. if(a[i] > a[j]) { // 부등호를 "<"로 변경하면 내림차순 정렬이 된다. double temp = a[i]; a[i] = a[j]; a[j] = temp; } } // 정렬 결과를 회전마다 출력한다. System.out.print(i + 1 + "회전 : "); for(int j=0 ; j<a.length ; j++) { System.out.print(a[j] + " "); } System.out.println(); } // 최대값과 최소값을 제외한 점수의 평균을 출력한다. // double avg = (sum - a[0] - a[n-1]) / (n - 2); for(int i=1 ; i<n-1 ; i++) { sum += a[i]; } double avg = sum / (n - 2); System.out.println("평균 점수 : " + avg); } } ``` <file_sep>/_java/A034 ArrayList,DecimalFormat,NumberFormat,SimpleDateFormat.md ``` import java.util.ArrayList; import java.util.Date; public class ArrayListTest2 { public static void main(String[] args) { ArrayList<BookVO> list = new ArrayList<BookVO>(); BookVO book1 = new BookVO("JAVA", "홍길동", "SBS", new Date(2012,5,21), 35000); System.out.println(book1); BookVO book2 = new BookVO("JSP", "홍길자", "MBC", new Date(2013,11,4), 32500); System.out.println(book2); // add(value) : ArrayList의 맨 뒤에 value를 추가한다. list.add(book1); // size() : ArrayList에 저장된 데이터의 개수를 얻어온다. System.out.println(list.size() + " : " + list); // add(index, value) : ArrayList의 index번째 위치에 value를 삽입한다. list.add(0, book2); System.out.println(list.size() + " : " + list); // get(index) : ArrayList에 index 번째 값을 얻어온다. System.out.println(list.get(0)); BookVO book3 = new BookVO("SPRING", "홍길숙", "KBS", new Date(2010,7,15), 43000); // set(index, value) : ArrayList에 index 번째 값을 value로 수정한다. list.set(0, book3); System.out.println(list.size() + " : " + list); list.add(book2); System.out.println(list.size() + " : " + list); String str = ""; // for(int i=0 ; i<list.size() ; i++) { // str += list.get(i) + "\n"; // } // 향상된 for : JDK 1.5에서 추가, 배열 또는 ArrayList의 모든 값을 대상으로 작업할 경우에 사용한다. // for(배열또는ArrayList의자료형 변수명 : 배열명또는ArrayList이름) { // 작업할 내용; // ...; // } for(BookVO book : list) { str += book + "\n"; } System.out.println(str); // remove(index) : ArrayList에 index 번째 값을 제거한다. list.remove(1); System.out.println(list.size() + " : " + list); // clear() : ArrayList의 모든 데이터를 제거한다. list.clear(); System.out.println(list.size() + " : " + list); } } ``` ``` import java.text.DecimalFormat; import java.util.Arrays; // 여러권의 책(BookVO class) 정보를 기억할 클래스 public class BookList1 { // 멤버 변수 정의 private static int sum; // 책 가격의 합계를 계산할 변수 private int size; // 배열의 크기, 최대로 저장 가능한 책의 수 private int count; // 배열의 첨자, 현재 저장된 책의 수 private BookVO[] booklist; // 책 정보를 저장할 배열 선언(크기는 지정되지 않은 상태) // 생성자 메소드 정의 // 기본 생성자 메소드, 배열의 크기가 전달되지 않으면 10개 짜리 배열을 만드는 생성자 메소드 public BookList1() { // booklist = new BookVO[10]; // 현재 클래스의 생성자 메소드인 BookList1(int size)를 실행한다. this(10); } // 객체가 생성될 때 배열의 크기를 넘겨받아 넘겨받은 크기 만큼 배열을 만드는 생성자 메소드 public BookList1(int size) { this.size = size; booklist = new BookVO[this.size]; // 실제로 사용할 배열을 만든다. count = 0; // System.out.println(booklist.length); } // getter & setter 메소드 정의 public int getSize() { return size; } public void setSize(int size) { this.size = size; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } public BookVO[] getBooklist() { return booklist; } public void setBooklist(BookVO book) { // 전통적인 예외처리 기법(if 사용) // if(count < size) { // this.booklist[count++] = book; // System.out.println(book.getTitle() + "을(를) 넣었습니다."); // } else { // System.out.println("책꽃이가 작아서 " + book.getTitle() + "을(를) 넣을 수 없습니다."); // } // try ~ catch : 자바의 예외(Exception)처리 // 예외가 발생될 것으로 예상되는 문장을 try 블록에 적는다. // 예외가 발생되면 해당 예외를 처리할 문장을 catch 블록에 적는다. try { this.booklist[count++] = book; // System.out.println(book.getTitle() + "을(를) 넣었습니다."); sum += book.getPrice(); // 책이 1권 들어올 때 마다 가격의 합계를 구한다. } catch(ArrayIndexOutOfBoundsException e) { System.out.println("책꽃이가 작아서 " + book.getTitle() + "을(를) 넣을 수 없습니다."); // e.getMessage() : Exception의 메시지를 얻어온다. // System.out.println(e.getMessage()); // e.printStackTrace(); // 예외 발생 정보를 추적한다. } catch(Exception e) { // Exception은 모든 Exception의 조상 클래스이다. } finally { // 예외의 발생 여부와 관계없이 무조건 실행해야 할 문장을 적는다. } } // toString() 메소드 override @Override public String toString() { DecimalFormat df = new DecimalFormat("#,##0원"); String str = ""; if(count != 0) { str += "===============================================\n"; str += " 도서명 저자 출판사 출판일 가격\n"; str += "===============================================\n"; int total = 0; for(BookVO book : booklist) { if(book == null) { break; } str += book + "\n"; total += book.getPrice(); } str += "===============================================\n"; str += " 가격합계 : " + df.format(sum) + "\n"; str += " 가격합계 : " + df.format(total) + "\n"; str += "===============================================\n"; } else { str += "책 엄거덩"; } return str; } } ``` ``` import java.util.Date; public class BookTest1 { public static void main(String[] args) { // 5권의 책을 저장할 수 있는 책꽃이 객체 생성 BookList1 booklist = new BookList1(5); // 책꽃이에 넣을 책 객체를 만든다. BookVO book1 = new BookVO("JAVA", "홍길동", "SBS", new Date(2012,5,21), 35000); BookVO book2 = new BookVO("JSP", "홍길자", "MBC", new Date(2013,11,4), 32500); BookVO book3 = new BookVO("SPRING", "홍길숙", "KBS", new Date(2010,7,15), 43000); BookVO book4 = new BookVO("HTML", "홍길용", "OBS", new Date(2011,3,9), 25000); BookVO book5 = new BookVO("jQUERY", "홍길녀", "CNN", new Date(2012,7,8), 31000); BookVO book6 = new BookVO("JAVASCRIPT", "홍길도", "NBC", new Date(2008,1,20), 28000); // 책꽃이에 책을 넣는다. booklist.setBooklist(book1); booklist.setBooklist(book2); booklist.setBooklist(book3); booklist.setBooklist(book4); // booklist.setBooklist(book5); // booklist.setBooklist(book6); System.out.println(booklist); } } ``` ``` import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Date; // 책 1권의 정보를 기억할 클래스 public class BookVO { // 멤버 변수 정의 private String title; // 도서명 private String author; // 저자 private String publisher; // 출판사 private Date date; // 출판일 private int price; // 가격 // 생성자 메소드 정의 public BookVO() { } public BookVO(String title, String author, String publisher, Date date, int price) { this.title = title; this.author = author; this.publisher = publisher; // 넘겨받은 날짜(date)의 년도에서 1900을 빼서 다시 날짜(date)에 넣어준다. date.setYear(date.getYear() - 1900); // 넘겨받은 날짜(date)의 월에서 1을 빼서 다시 날짜(date)에 넣어준다. date.setMonth(date.getMonth() - 1); this.date = date; this.price = price; } // getter & setter 메소드 정의 public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPublisher() { return publisher; } public void setPublisher(String publisher) { this.publisher = publisher; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } // toString() 메소드 override @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd."); NumberFormat nf = NumberFormat.getCurrencyInstance(); // 화폐기호, 천단위 "," // NumberFormat nf = NumberFormat.getPercentInstance(); // 백분율, 천단위 "," DecimalFormat df = new DecimalFormat("#,##0'EA'"); return String.format("%-10s %s %s %s %s %s", title, author, publisher, sdf.format(date), nf.format(price), df.format(price)); } } ``` <file_sep>/_java/A033 ArrayList,제네릭,getter,setter,override,생성자.md ``` import java.util.ArrayList; public class ArrayListTest1 { public static void main(String[] args) { int a[] = new int[10]; // <E> : 제네릭이라 부르며 ArrayList에 저장될 데이터의 타입을 반드시 클래스로 적어준다. // ArrayList에 기본 자료형 데이터를 저장해야 할 경우에는 기본 자료형을 클래스화 해 놓은 랩퍼 클래스를 // 사용한다. 랩퍼 클래스의 이름은 기본 자료형의 첫 문자를 대문자로 적으면 된다. // 단, Character와 Integer는 풀 네임을 모두 적어야 한다. // ArrayList list = new ArrayList(); // JDK 1.5 전에 사용하던 코딩방식 ArrayList<Integer> list = new ArrayList<Integer>(); // JDK 1.5 이후 코딩방식 // ArrayList<Integer> list = new ArrayList(); // JDK 1.7 이후 코딩방식 for(int i=0 ; i<10 ; i++) { a[i] = i + 1; // add(value) : ArrayList에 value 값을 추가한다. list.add(i + 1); } for(int i=0 ; i<10 ; i++) { System.out.print("a[" + i + "] = " + a[i]); // get(index) : ArrayList의 index 번째 value 값을 얻어온다. System.out.println(", list[" + i + "] = " + list.get(i)); } for(int i=10 ; i<20 ; i++) { // 배열의 첨자가 배열의 크기를 넘어가므로 ArrayIndexOutOfBoundsException이 발생된다. // 즉, 배열은 선언시 지정된 크기를 변경할 수 없다. // a[i] = i + 1; // 에러 list.add(i + 1); } for(int i=10 ; i<20 ; i++) { // System.out.println("a[" + i + "] = " + a[i]); System.out.println("list[" + i + "] = " + list.get(i)); } } } ``` ``` public class PersonTest { public static void main(String[] args) { PersonVO personVO1 = new PersonVO(); // System.out.println("personVO1 : " + personVO1); PersonVO personVO2 = new PersonVO("홍길동", true, "아싸~~1빠~~"); System.out.println(personVO2); PersonVO personVO3 = new PersonVO("홍길동", true, "아싸~~1빠~~"); System.out.println(personVO3); PersonVO personVO4 = new PersonVO("홍길동", true, "아싸~~1빠~~"); System.out.println(personVO4); if(personVO2.equals(personVO3)) { System.out.println("같다"); } else { System.out.println("같지않다"); } personVO2.count = 10; System.out.println(personVO3.count); System.out.println(personVO2.getName()); personVO2.setName("홍길자"); System.out.println(personVO2); System.out.println(personVO3); System.out.println(personVO4); } } * 위의 코딩은 밑의 PersonVO 클래스를 이용합니다. import java.text.SimpleDateFormat; import java.util.Date; // VO(Value Object) 클래스 : 1건의 데이터를 기억하는 클래스 // Bean : 자바의 최소 작업단위, 멤버 변수와 getter & setter 메소드로만 구성된 클래스 public class PersonVO { // 1. ★★★★★ 멤버 변수를 정의한다. ★★★★★ // 멤버 변수는 현재 클래스 안에있는 모든 메소드에서 사용할 경우 만든다. // 멤버 변수의 종류는 정적(static) 멤버 변수와 인스턴스 멤버 변수로 구분한다. // 정적 멤버 변수는 현재 클래스로 생성되는 모든 객체에서 공유한다. // 인스턴스 멤버 변수는 현재 클래스로 생성되는 모든 객체에서 독립된 기억공간을 가진다. // 멤버 변수에 초기치를 주지 않으면 숫자는 0, 문자는 공백, 불린은 false, 클래스는 null을 초기치 들어간다. // 정적 멤버 변수 static int count; // 일련번호 자동증가에 사용될 정적 멤버 변수 // 인스턴스 멤버 변수 private int no; // 일련번호(자동증가) private String name; // 이름 private boolean gender; // 성별 private String memo; // 메모 private Date writeDate; // 작성일(자동입력) // 2. 생성자 메소드를 정의한다. // 생성자 메소드를 정의하지 않으면 아무일도 하지 않는 기본 생성자를 자바 컴파일러가 알아서 만든다. // 생성자 이름은 반드시 클래스 이름과 같아야 하고 리턴타입을 적지 않는다. // 생성자의 중요한 용도는 객체가 생성되는 순간 멤버에 초기값(데이터)을 전달하려 할 경우에 사용된다. // 기본 생성자 메소드 public PersonVO() { // super(); // 부모 클래스의 생성자 메소드를 호출한다. // this(); // 현재 클래스의 생성자 메소드를 호출한다. // super()와 this()는 반드시 생성자 메소드의 첫 줄에 적어야 한다. // super()를 생략하면 자바 컴파일러가 자동으로 super()를 붙여준다. // super; // 부모 클래스를 의미한다. // this; // 현재 클래스를 의미한다. System.out.println("까꿍~~~~~~"); } // 멤버 변수(필드)에 초기값을 전달하는 생성자 public PersonVO(String name, boolean gender, String memo) { no = ++count; this.name = name; this.gender = gender; this.memo = memo; writeDate = new Date(); // 객체가 생성되는 순간 컴퓨터의 날짜와 시간을 넣어준다. } // 3. ★★★★★ getter & setter 메소드를 정의한다. ★★★★★ // getter : get으로 시작하고 멤버 이름이 나오는 메소드, private 멤버의 내용을 얻어올 때 사용된다. // setter : set으로 시작하고 멤버 이름이 나오는 메소드, private 멤버의 내용을 수정할 때 사용된다. public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } // 멤버 변수의 타입이 boolean일 경우 getter는 get으로 시작하지 않고 is로 시작된다. public boolean isGender() { return gender; } public void setGender(boolean gender) { this.gender = gender; } public String getMemo() { return memo; } public void setMemo(String memo) { this.memo = memo; } public Date getWriteDate() { return writeDate; } public void setWriteDate(Date writeDate) { this.writeDate = writeDate; } // 4. toString() 메소드를 override(재정의) 한다. // override : 부모 클래스에서 상속받은 메소드를 무시하고 다시 정의해 사용한다. @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd(E)"); return "번호 : " + no + ", 이름 : " + name + ", 성별 : " + (gender ? "남" : "여") + ", 메모 : " + memo + ", 작성일 : " + sdf.format(writeDate); } // 5. 객체의 내용을 비교해야 한다면 equals(), hashCode() 메소드를 override 한다. @Override // 객체에 저장된 내용이 같으면 같은 해시코드를 가지게 한다. public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (gender ? 1231 : 1237); result = prime * result + ((memo == null) ? 0 : memo.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override // 객체의 멤버 변수에 저장된 내용을 비교한다. public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PersonVO other = (PersonVO) obj; if (gender != other.gender) return false; if (memo == null) { if (other.memo != null) return false; } else if (!memo.equals(other.memo)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } // 6. 기타 필요한 기능을 정의한다. } ``` <file_sep>/KNOU.java.test/src/knou/test/awt/GridLayoutTest.java package knou.test.awt; import java.awt.Button; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Scrollbar; public class GridLayoutTest extends Frame { private Scrollbar s1, s2; public GridLayoutTest() { super("GridLayout!"); setSize(300,100); setLayout(new GridLayout(3, 3, 10, 10)); add(new Button("button1")); add(new Button("button2")); add(new Button("button3")); add(new Button("button4")); add(new Button("button5")); add(new Button("button6")); add(new Button("button7")); add(new Button("button8")); add(new Button("button9")); } public static void main(String[] args) { Frame f = new GridLayoutTest(); f.setVisible(true); } } <file_sep>/_java/A016 Choice class.md ``` package com.me.eventtest; import java.awt.Button; import java.awt.Choice; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JOptionPane; public class EventTest05 { Frame mainFrame; // 프레임 Label headerLabel; // 프레임 상단의 레이블 Label bottomLabel; // 프레임 하단의 레이블 Panel controlPanel; // 프레임 중단의 패널, panel, addPanel이 올라갈 패널 Panel panel; // 콤보상자, 보기, 삭제 단추가 올라갈 패널 Panel addPanel; // 텍스트 필드, 추가 단추가 올라갈 패널 Choice choice; // 콤보 상자 Button showBtn; // 보기 단추 Button deleteBtn; // 삭제 단추 TextField textField; // 텍스트 필드 Button addBtn; // 추가 단추 public EventTest05() { // 프레임을 만들고 셋팅한다. mainFrame = new Frame("Java Choice Test"); mainFrame.setSize(400, 400); mainFrame.setLocation(400, 200); // 프레임에 3행 1열짜리 GridLayout을 지정한다. mainFrame.setLayout(new GridLayout(3, 1)); // 프레임 상단의 레이블 headerLabel = new Label(); headerLabel.setText("콤보상자 테스트"); // 레이블 텍스트 지정 headerLabel.setFont(new Font("Serif", Font.BOLD, 30)); // 레이블 글꼴 설정 headerLabel.setAlignment(Label.CENTER); // 레이블 텍스트 정렬 mainFrame.add(headerLabel); // 프레임 상단에 레이블 추가 // 프레임 중단에 패널 셋팅 // controlPanel에 2행 1열짜리 GirdLayout을 지정한다. controlPanel = new Panel(new GridLayout(2, 1)); panel = new Panel(); // 콤보 상자가 올라갈 때 패널 객체 생성 choice = new Choice(); // 콤보 상자 객체 생성 choice.add("사과"); // 콤보 상자에 목록추가 choice.add("포도"); choice.add("메론"); choice.add("베리베리 스트로베리"); panel.add(choice); // panel에 콤보 상자 추가 showBtn = new Button("보기"); // 보기단추 객체 생성 panel.add(showBtn); // panel에 보기 단추 추가 deleteBtn = new Button("삭제"); // 삭제 단추 객체 생성 panel.add(deleteBtn); // panel에 삭제 버튼 추가 // showBtn(보기) 단추 액션 리스너 // 프레임 하단의 레이블에 콤보 상자에서 선택된 값 보여주기 showBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // getSelectedIndex() : 콤보 상자에서 선택된 목록의 위치를 얻어온다. // getItem() : 콤보 상자에서 선택된 위치의 값을 얻어온다. String str = "선택된 값 : " + choice.getItem(choice.getSelectedIndex()) + "."; bottomLabel.setText(str); } }); // deleteBtn(삭제) 단추 액션 리스너 // 콤보 상자에서 선택된 값 삭제하기 deleteBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String str = choice.getItem(choice.getSelectedIndex()) + " 를(을) 삭제 하시겠습니까?"; // showConfirmDialog를 이용해 삭제 메시지를 출력하고 사용자의 판단을 기다린다. // "예" 버튼은 0, 아니오 버튼은 1, 취소 버튼은 2가 리턴되 confirm 변수에 저장된다. int confirm = JOptionPane.showConfirmDialog(choice, str); // showConfirmDialog에서 "예" 단추를 클릭했을 경우 콤보 상자의 선택된 목록을 지운다. if(confirm == 0){ // remove(index) : 콤보 상자에서 선택된 위치의 값을 지운다. bottomLabel.setText(choice.getItem(choice.getSelectedIndex()) + "를(을) 삭제했습니다."); // 뒤에 쓰면 getItem이 현재값을 불러옴 choice.remove(choice.getSelectedIndex()); JOptionPane.showMessageDialog(choice, "삭제 완료"); } else { JOptionPane.showMessageDialog(choice, "삭제를 취소합니다."); } } }); addPanel = new Panel(); // 텍스트 필드가 올라갈 패널 객체 생성 textField = new TextField(); // 텍스트 필드 객체 생성 textField.setColumns(20); // 텍스트 필드 크기 변경 // textField.setEchoChar('*'); // 텍스트 필드 대체 문자 설정 addPanel.add(textField); // addPanel에 텍스트 필드 추가 addBtn = new Button("추가"); // 추가 단추 객체 생성 addPanel.add(addBtn); // addPanel에 추가 단추 추가 // addBtn(추가) 단추에 액션 리스너 지정 // 텍스트 필드에 입력된 값을 콤보 상자에 추가하기 addBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 텍스트 필드에 입력된 내용을 공백을 제외하고 얻어와서 콤보 상자에 추가한다. // setText() : 텍스트 필드에 값을 넣는다. // getText() : 텍스트 필드의 값을 얻어온다. String str = textField.getText().trim(); // trim(); 불필요한 빈칸을 없앤다. /*if(str.equals("")){ // 전부 공백 넣는 것을 막아줌(null값) JOptionPane.showMessageDialog(choice, "공백입니다"); } else { choice.add(str); textField.setText(""); } 위 아래가 같은 내용*/ if(str.length() > 0){ // 얻어올 내용이 있으면 콤보 상자에 추가한다. choice.add(str); textField.setText(""); bottomLabel.setText(str + " 추가완료"); // 추가한 값이 콤보 상자에 보이게 한다. // select(index) : 콤보 상자의 index 번째 값을 보여준다. // getItemCount() : 콤보 상자의 목록 개수를 얻어온다. choice.select(choice.getItemCount() - 1); } else{ // 얻어올 내용이 없으면 콤보 상자에 추가하지 않는다. JOptionPane.showMessageDialog(addBtn, "공백입니다"); textField.setText(""); // requestFocus() : 지정된 컴포넌트로 포커스(커서)를 옮긴다. textField.requestFocus(); } } }); controlPanel.add(panel); // controlPanel에 panel 추가 controlPanel.add(addPanel); // controlPanel에 addPanel 추가 mainFrame.add(controlPanel); // 프레임 중단에 레이블 추가 // 프레임 하단의 레이블 셋팅 bottomLabel = new Label(); bottomLabel.setText("이곳에 선택한 콤보상자의 목록이 나와요."); bottomLabel.setAlignment(Label.CENTER); mainFrame.add(bottomLabel); // 프레임 하단에 레이블 추가 mainFrame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); mainFrame.setVisible(true); } public static void main(String[] args) { EventTest05 win = new EventTest05(); } } ``` <file_sep>/_jspServlet/A009 Connection of DataSource.md ##Question DBConnectionPool로써 커넥션풀을 따로 관리하다가 DataSource로 변경 사용할 경우. if(connection != null) connPool.returnConnection(connection); -> try {if(connection != null) connection.close();} catch~ "커넥션 객체를 닫으면 다시 사용할 수 없지 않느냐?, 닫지 말고 이전처럼(connPool.~) 반납해야 하는 것 아니냐?" ##Answer DataSource가 만들어 주는 Connection 객체는 DriverManager가 만들어주는 커넥션 객체를 한번 더 포장한 것입니다. 1. MemberDao가 DataSource에게 커넥션을 달라고 요청합니다. 2. DataSource는 DriverManager가 생성한 커넥션을 리턴하는 것이 아니라, 커넥션 대행 객체(Proxy Object)를 리턴합니다. 아파치 DBCP 컴포넌트의 BasicDataSource를 사용할 경우, PoolableConnection 객체를 반환합니다. 바로 이 객체가 커넥션의 대행 객체입니다. 이 대행 객체에는 진짜 커넥션을 가리키는 참조 변수(_conn)와 커넥션풀을 가리키는 참조 변수(_pool)가 들어 있습니다. 물론, 대행 객체도 Connection처럼 보이기 위해, java.sql.Connection 인터페이스를 구현하였습니다. 구현하였다는 의미는 외부에서 요청이 들어왔을 때, 자신이 직접 실행한다는 것이 아니라 진짜 커넥션에게 위임한다는 것입니다. 따라서 DataSource가 만들어 준 커넥션 대행 객체에 대해 close()를 호출하면, 커넥션 대행 객체는 진짜 커넥션 객체를 커넥션풀에 반납합니다. 그러니 커넥션이 닫힐까 걱정할 필요가 없습니다. <file_sep>/_java/OOPS - Class Example - Circle.md ``` //This is a simple example of a Class. //This program shows the structure of a class. public class Circle { // class name double radius = 2.3; // variables String color = "white"; // methods double getRadius() { // method body return radius; //return statement } String getColor() { // method body return color; //return statement } } ``` ## OUTPUT ``` [This program has no output] ```<file_sep>/README.md # soloLearn practice harder <file_sep>/_java/OOPS - Inheritance Example.md ``` class Box { double width; double height; double depth; Box() { } Box(double w, double h, double d) { width = w; height = h; depth = d; } void getVolume() { System.out.println("Volume is : " + width * height * depth); } } public class MatchBox extends Box { double weight; MatchBox() { } MatchBox(double w, double h, double d, double m) { super(w, h, d); weight = m; } public static void main(String args[]) { MatchBox mb1 = new MatchBox(10, 20, 30, 40); mb1.getVolume(); System.out.println("width of MatchBox is " + mb1.width); System.out.println("height of MatchBox is " + mb1.height); System.out.println("depth of MatchBox is " + mb1.depth); System.out.println("weight of MatchBox is " + mb1.weight); } } ``` ##OUTPUT ``` Volume is : 6000.0 width of MatchBox is 10.0 height of MatchBox is 20.0 depth of MatchBox is 30.0 weight of MatchBox is 40.0 ```<file_sep>/_java/COLLECTION - Basic of HashMap.md ``` import java.util.HashMap; public class HashMapBasics { public static void main(String[] args) { HashMap<Integer,String> hm=new HashMap<Integer,String>(); hm.put(1,"android"); hm.put(2,"java"); hm.put(3,"php"); hm.put(4,"c++"); hm.put(5,"javascript"); hm.put(6, "html"); System.out.println(hm+" "); System.out.println(); System.out.println("Value at 1 is android :"+hm.containsKey(1)); System.out.println("Value at 1 :"+hm.get(1)); System.out.println("java is present :"+hm.containsValue("java")); //remove hm.remove(2); hm.remove(6, "html"); System.out.println("Size after remove operation :"+hm.size()); //replace hm.replace(5, "jquery"); hm.replace(4, "c++", "scala"); System.out.println("HashMap after replace "+hm); hm.clear(); System.out.println(hm+" Is Map is empty "+hm.isEmpty()); } } ``` ##OUTPUT ``` {1=android, 2=java, 3=php, 4=c++, 5=javascript, 6=html} Value at 1 is android :true Value at 1 :android java is present :true Size after remove operation :4 HashMap after replace {1=android, 3=php, 4=scala, 5=jquery} {} Is Map is empty true ```<file_sep>/KNOU.java.test/src/knou/test/awt/CardLayoutTest2.java package knou.test.awt; import java.awt.CardLayout; import java.awt.Frame; import java.awt.Label; import java.awt.Scrollbar; public class CardLayoutTest2 extends Frame { private Scrollbar s1, s2; CardLayout cl; public CardLayoutTest2() { super("CardLayout"); setSize(300,200); cl = new CardLayout(); setLayout(cl); add("1", new Label("Hi", Label.CENTER)); add("2", new Label("Hi 2", Label.CENTER)); add("3", new Label("Hi 3", Label.CENTER)); } public void Rotate() throws Exception { cl.first(this); Thread.sleep(1000); while(true) { cl.next(this); Thread.sleep(1000); } } public static void main(String[] args) throws Exception { CardLayoutTest2 f2 = new CardLayoutTest2(); f2.setVisible(true); f2.Rotate(); } } <file_sep>/KNOU.java.test/src/knou/test/applet/Browser2AppletTest.java package knou.test.applet; import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; public class Browser2AppletTest extends Applet { public void paint(Graphics g) { g.drawString("브라우저에서 Applet 제어", 10, 50); } public void setBgColor(int r, int g, int b) { setBackground(new Color(r,g,b)); } } <file_sep>/_java/OOPS - Abstract Example - Shape.md ``` abstract class Shape { abstract void draw(); } class Rectangle extends Shape { void draw() { System.out.println("Draw Rectangle"); } } class Traingle extends Shape { void draw() { System.out.println("Draw Traingle"); } } class AbstractTest { public static void main(String args[]) { Shape s1 = new Rectangle(); s1.draw(); s1 = new Traingle(); s1.draw(); } } ``` __OUTPUT__ ``` Draw Rectangle Draw Traingle ```<file_sep>/_java/OOPS - Method Overloading.md ``` class MethodOverloading { public void display(int number) { System.out.println("Integer value: " + number); } public void display(float number) { System.out.println("Float value: " + number); } public void display(char character) { System.out.println("Character value: " + character); } } public class MethodOverloadingTest { public static void main(String args[]) { MethodOverloading ob = new MethodOverloading(); ob.display(20); ob.display(0.33f); ob.display('z'); } } ``` ##OUTPUT ``` Integer value: 20 Float value: 0.33 Character value: z ```<file_sep>/_java/A009 CardLayout, GridLayout, BorderLayout.md ``` package com.me.layout; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Frame; import java.awt.Label; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class BorderLayoutTest extends Frame{ Label lb1 = new Label("test1"); Label lb2 = new Label("test2"); Label lb3 = new Label("test3"); Label lb4 = new Label("test4"); Label lb5 = new Label("test5"); public BorderLayoutTest(String title) { setTitle(title); setSize(400, 400); setLocation(800, 200); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); // BorderLayout은 프레임을 5개 구역으로 나누고 컴포넌트를 특정 방향으로 배치하는 레이아웃 매니저이다. // 프레임은 레이아웃 매니저를 지정하지 않으면 기본값으로 BorderLayout을 레이아웃 매니저로 가진다. BorderLayout border = new BorderLayout(); setLayout(border); lb1.setBackground(Color.RED); lb2.setBackground(Color.BLUE); lb3.setBackground(Color.GREEN); lb4.setBackground(Color.ORANGE); lb5.setBackground(Color.PINK); add(lb1, BorderLayout.NORTH); // 위쪽 add(lb2, BorderLayout.SOUTH); // 아래쪽 add(lb3, BorderLayout.EAST); // 오른쪽 add(lb4, BorderLayout.WEST); // 왼쪽 // add("West", lb4); // 왼쪽, 방향을 먼저 쓸 경우 첫 문자만 대문자로 한다. (옛날 코딩) add(lb5, BorderLayout.CENTER); // 중앙 - 기본 값 // add(lb5); setVisible(true); } public static void main(String[] args){ new BorderLayoutTest("FlowLayoutTest"); } } ``` ``` package com.me.layout; import java.awt.Color; import java.awt.Cursor; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class GridLayoutTest extends Frame{ Label lb1 = new Label("test1"); Label lb2 = new Label("test2"); Label lb3 = new Label("test3"); Label lb4 = new Label("test4"); Label lb5 = new Label("test5"); Label lb6 = new Label("test6"); Label lb7 = new Label("test7"); Label lb8 = new Label("test8"); Label lb9 = new Label("test9"); public GridLayoutTest(String title) { setTitle(title); setSize(400, 400); setLocation(800, 200); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); // GridLayout은 컴포넌트들을 프레임을 격자(Grid) 형태로 나누고 차례차례 배치하는 레이아웃 매니저이다. GridLayout grid = new GridLayout(3, 3, 5, 5); // new GridLayout(3, 3) : 여백없이 3행 3열로 분할 // new GridLayout(3, 3, 0, 5) : 세로 여백 0, 가로 여백 5, 3행 3열로 분할 // new GridLayout(3, 3, 5, 0) : 세로 여백 5, 가로 여백 0, 3행 3열로 분할 // new GridLayout(3, 3, 5, 5) : 세로 여백 5, 가로 여백 5, 3행 3열로 분할 setLayout(grid); // 마우스 아이콘 모양 변경하기 Cursor cursor1 = new Cursor(Cursor.HAND_CURSOR); // 손가락 setCursor(cursor1); // 프레임 전체에 적용 Cursor cursor2 = new Cursor(Cursor.WAIT_CURSOR); // 사용 중, 모래시계(XP) lb1.setCursor(cursor2); // 지정 Label에만 적용 Cursor cursor3 = new Cursor(Cursor.DEFAULT_CURSOR); // 기본값, 화살표 lb5.setCursor(cursor3); // 지정 Label에만 적용 lb1.setBackground(Color.BLUE); add(lb1); lb2.setBackground(Color.CYAN); add(lb2); lb3.setBackground(Color.DARK_GRAY); add(lb3); lb4.setBackground(Color.GRAY); add(lb4); lb5.setBackground(Color.GREEN); add(lb5); lb6.setBackground(Color.LIGHT_GRAY); add(lb6); lb7.setBackground(Color.MAGENTA); add(lb7); lb8.setBackground(Color.ORANGE); add(lb8); lb9.setBackground(Color.PINK); add(lb9); setVisible(true); } public static void main(String[] args){ new GridLayoutTest("FlowLayoutTest"); } } ``` ``` package com.me.layout; import java.awt.CardLayout; import java.awt.Color; import java.awt.Frame; import java.awt.Label; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class CardLayoutTest extends Frame{ Label lb1 = new Label("test1"); Label lb2 = new Label("test2"); Label lb3 = new Label("test3"); public CardLayoutTest(String title) { setTitle(title); setSize(400, 400); setLocation(800, 200); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); // CardLayout은 프레임에 카드를 여러장 엎어놓은 것 처럼 컴포넌트를 배치하는 레이아웃 매니저이다. CardLayout card = new CardLayout(); setLayout(card); lb1.setBackground(Color.RED); lb2.setBackground(Color.GREEN); lb3.setBackground(Color.BLUE); add("aaa", lb1); // add("카드이름", 컴포넌트이름) add("bbb", lb2); add("ccc", lb3); setVisible(true); // card.show 는 setVisible 다음에 나와야 한다. (윈도우를 띄워놓고 다음에 바꾼다) while(true){ try {Thread.sleep(1);} catch (InterruptedException e1) {} card.show(this, "aaa"); // 카드 레이아웃 매니저에서 다른 카드 호출 방법 (현재 윈도우, "카드이름") try {Thread.sleep(1);} catch (InterruptedException e1) {} card.show(this, "bbb"); try {Thread.sleep(1);} catch (InterruptedException e1) {} card.show(this, "ccc"); } } public static void main(String[] args){ new CardLayoutTest("FlowLayoutTest"); } } ``` <file_sep>/_java/A017 ActionListener 구현.md ``` package com.me.eventtest; import java.awt.Button; import java.awt.Choice; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JOptionPane; public class EventTest06 extends Frame implements ActionListener{ Label headerLabel; Label bottomLabel; Panel controlPanel; Panel panel; Panel addPanel; Choice choice; Button showBtn; Button deleteBtn; TextField textField; Button addBtn; public EventTest06() { setTitle("Java Choice Test"); setSize(400, 400); setLocation(400, 200); setLayout(new GridLayout(3, 1)); // 프레임 상단의 레이블 headerLabel = new Label(); headerLabel.setText("콤보상자 테스트"); headerLabel.setFont(new Font("Serif", Font.BOLD, 30)); headerLabel.setAlignment(Label.CENTER); add(headerLabel); // 프레임 중단에 패널 셋팅 controlPanel = new Panel(new GridLayout(2, 1)); panel = new Panel(); choice = new Choice(); choice.add("사과"); choice.add("포도"); choice.add("메론"); choice.add("베리베리 스트로베리"); panel.add(choice); showBtn = new Button("보기"); panel.add(showBtn); deleteBtn = new Button("삭제"); panel.add(deleteBtn); // showBtn(보기) 단추 액션 리스너 showBtn.addActionListener(this); // deleteBtn(삭제) 단추 액션 리스너 deleteBtn.addActionListener(this); addPanel = new Panel(); textField = new TextField(); textField.setColumns(20); addPanel.add(textField); addBtn = new Button("추가"); addPanel.add(addBtn); // addBtn(추가) 단추에 액션 리스너 지정 addBtn.addActionListener(this); controlPanel.add(panel); controlPanel.add(addPanel); add(controlPanel); // 프레임 하단의 레이블 셋팅 bottomLabel = new Label(); bottomLabel.setText("이곳에 선택한 콤보상자의 목록이 나와요."); bottomLabel.setAlignment(Label.CENTER); add(bottomLabel); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); setVisible(true); } public static void main(String[] args) { EventTest06 win = new EventTest06(); } @Override public void actionPerformed(ActionEvent e) { // 반드시 최상위에 이벤트 값을 불러온다. (Button으로 해도 상관없긴 함) Object obj = e.getSource(); if((Button)obj == showBtn){ System.out.println("보기 버튼 클릭"); // ----------------------------------------------------------------------------------------------------여기에 추가 String str = "선택된 값 : " + choice.getItem(choice.getSelectedIndex()) + "."; bottomLabel.setText(str); // ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲ } else if((Button)obj == deleteBtn){ System.out.println("삭제 버튼 클릭"); // ----------------------------------------------------------------------------------------------------여기에 추가 String str = choice.getItem(choice.getSelectedIndex()) + " 를(을) 삭제 하시겠습니까?"; int confirm = JOptionPane.showConfirmDialog(choice, str); if(confirm == 0){ bottomLabel.setText(choice.getItem(choice.getSelectedIndex()) + "를(을) 삭제했습니다."); choice.remove(choice.getSelectedIndex()); JOptionPane.showMessageDialog(choice, "삭제 완료"); } else { JOptionPane.showMessageDialog(choice, "삭제를 취소합니다."); } // ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲ } else if((Button)obj == addBtn){ System.out.println("추가 버튼 클릭"); // ----------------------------------------------------------------------------------------------------여기에 추가 String str = textField.getText().trim(); if(str.length() > 0){ choice.add(str); textField.setText(""); bottomLabel.setText(str + " 추가완료"); choice.select(choice.getItemCount() - 1); } else{ JOptionPane.showMessageDialog(addBtn, "공백입니다"); textField.setText(""); textField.requestFocus(); } // ▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲ } } } // end of class ``` ``` package com.me.eventtest; import java.awt.Button; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.List; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JOptionPane; public class EventTest07 extends Frame{ Label headerLabel, bottomLabel; Panel listPanel, buttonPanel; List leftList, rightList; // 목록 상자 Button viewBtn, deleteBtn; public EventTest07(){ setTitle("목록 상자 테스트"); setBounds(600, 200, 400, 400); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); setLayout(new GridLayout(4, 1)); // 상단 레이블 headerLabel = new Label("목록 상자 테스트"); headerLabel.setFont(new Font("Serif", Font.BOLD, 30)); headerLabel.setAlignment(Label.CENTER); add(headerLabel); // 중단 목록 상자 listPanel = new Panel(); // 목록 상자가 올라갈 패널 생성 // 목록 상자 생성시 첫 번째 인수는 한번에 보여줄 목록의 갯수를 의미하고, 두 번째 인수는 생략하면(false) 단일 // 목록이, true를 쓰면 다중 목록이 선택된다. leftList = new List(4, false); // 왼쪽 목록 상자 생성 leftList.add("감자"); // 왼쪽 목록 상자에 목록 추가 leftList.add("고구마"); leftList.add("오이"); leftList.add("호박"); listPanel.add(leftList); rightList = new List(4, true); rightList.add("사과"); rightList.add("포도"); rightList.add("배"); rightList.add("수박"); listPanel.add(rightList); add(listPanel); // 중단 버튼 buttonPanel = new Panel(); viewBtn = new Button("선택한 목록 보기"); deleteBtn = new Button("선택한 목록 삭제"); buttonPanel.add(viewBtn); buttonPanel.add(deleteBtn); add(buttonPanel); // 중단의 버튼에 액션 리스너 지정 viewBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // getItem(index) : 목록 상자에서 선택된 index에 해당하는 값을 얻어온다. // getSelectedIndex() : 목록 상자에서 선택된 목록의 index 값을 얻어온다. // String str = "첫 번째 목록에서 선택한 값 : " + leftList.getItem(leftList.getSelectedIndex()) + "\n"; // getSelectedItem() : 목록 상자에서 선택된 목록 값을 얻어온다. 단일 목록 String str = "첫 목록 선택 값 : " + leftList.getSelectedItem(); str += ", 둘째 목록 선택 값 : "; // getSelectedItems() : 목록 상자에서 선택된 목록 값들을 얻어온다. 다중 목록 for(String value : rightList.getSelectedItems()){ str += value + " "; } bottomLabel.setText(str); } }); deleteBtn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // 단일 선택 목록상자에서 삭제하기 // getSelectedIndex() : 단일 선택 목록에서 선택된 위치를 얻어온다. 한개도 선택되지 않으면 -1을 리턴한다. if(leftList.getSelectedIndex() >= 0){ // 목록 상자의 목록이 선택 되었는가? leftList.remove(leftList.getSelectedIndex()); } else { JOptionPane.showMessageDialog(leftList, "왼쪽 목록 상자에서 삭제할 목록이 선택되지 않았습니다."); bottomLabel.setText("왼쪽 목록 상자에서 삭제할 목록이 선택되지 않았습니다."); } // 다중 선택 목록 상자에서 삭제하기 int delCount = 0; if(rightList.getSelectedIndexes().length > 0){ // getSelectedIndexes() : 다중 선택 목록에서 선택된 위치들을 얻어온다. for(int delPosition : rightList.getSelectedIndexes()){ rightList.remove(delPosition - delCount); delCount++; } } else { JOptionPane.showMessageDialog(rightList, "오른쪽 목록 상자에서 삭제할 목록이 선택되지 않았습니다."); } } }); // 하단 레이블 bottomLabel = new Label("여기에 선택한 목록이 나옵니다."); bottomLabel.setAlignment(Label.CENTER); add(bottomLabel); setVisible(true); } public static void main(String[] args) { new EventTest07(); } // main() } // end of class ``` ``` package com.me.eventtest; import java.awt.Button; import java.awt.Font; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.List; import java.awt.Panel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JOptionPane; // EventTest07의 내용을 ActionListener를 구현해서 만듬. public class EventTest08 extends Frame implements ActionListener{ Label headerLabel, bottomLabel; Panel listPanel, buttonPanel; List leftList, rightList; // 목록 상자 Button viewBtn, deleteBtn; public EventTest08(){ setTitle("목록 상자 테스트"); setBounds(600, 200, 400, 400); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dispose(); } }); setLayout(new GridLayout(4, 1)); // 상단 레이블 headerLabel = new Label("목록 상자 테스트"); headerLabel.setFont(new Font("Serif", Font.BOLD, 30)); headerLabel.setAlignment(Label.CENTER); add(headerLabel); // 중단 목록 상자 listPanel = new Panel(); // 목록 상자가 올라갈 패널 생성 // 목록 상자 생성시 첫 번째 인수는 한번에 보여줄 목록의 갯수를 의미하고, 두 번째 인수는 생략하면(false) 단일 // 목록이, true를 쓰면 다중 목록이 선택된다. leftList = new List(4, false); // 왼쪽 목록 상자 생성 leftList.add("감자"); // 왼쪽 목록 상자에 목록 추가 leftList.add("고구마"); leftList.add("오이"); leftList.add("호박"); listPanel.add(leftList); rightList = new List(4, true); rightList.add("사과"); rightList.add("포도"); rightList.add("배"); rightList.add("수박"); listPanel.add(rightList); add(listPanel); // 중단 버튼 buttonPanel = new Panel(); viewBtn = new Button("선택한 목록 보기"); deleteBtn = new Button("선택한 목록 삭제"); buttonPanel.add(viewBtn); buttonPanel.add(deleteBtn); add(buttonPanel); // 중단의 버튼에 액션 리스너 지정 viewBtn.addActionListener(this); deleteBtn.addActionListener(this); // 하단 레이블 bottomLabel = new Label("여기에 선택한 목록이 나옵니다."); bottomLabel.setAlignment(Label.CENTER); add(bottomLabel); setVisible(true); } public static void main(String[] args) { new EventTest08(); } // main() @Override public void actionPerformed(ActionEvent e) { Object obj = e.getSource(); if( (Button)obj == viewBtn ){ String str = "첫 목록 선택 값 : " + leftList.getSelectedItem(); str += ", 둘째 목록 선택 값 : "; for(String value : rightList.getSelectedItems()){ str += value + " "; } bottomLabel.setText(str); } else if ( (Button)obj == deleteBtn){ // 단일 선택 목록상자에서 삭제하기 // getSelectedIndex() : 단일 선택 목록에서 선택된 위치를 얻어온다. 한개도 선택되지 않으면 -1을 리턴한다. if(leftList.getSelectedIndex() >= 0){ // 목록 상자의 목록이 선택 되었는가? leftList.remove(leftList.getSelectedIndex()); } else { JOptionPane.showMessageDialog(leftList, "왼쪽 목록 상자에서 삭제할 목록이 선택되지 않았습니다."); bottomLabel.setText("왼쪽 목록 상자에서 삭제할 목록이 선택되지 않았습니다."); } // 다중 선택 목록 상자에서 삭제하기 int delCount = 0; if(rightList.getSelectedIndexes().length > 0){ // getSelectedIndexes() : 다중 선택 목록에서 선택된 위치들을 얻어온다. for(int delPosition : rightList.getSelectedIndexes()){ rightList.remove(delPosition - delCount); delCount++; } } else { JOptionPane.showMessageDialog(rightList, "오른쪽 목록 상자에서 삭제할 목록이 선택되지 않았습니다."); } } } } // end of class ``` <file_sep>/_javascript/A012 선택하면 커지는 기능.md ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>modal</title> <script src="js/jquery-1.11.3.min.js"></script> <script> $(function(){ $(window).resize(function(){ var winWidth = $(window).width() var winHeight = $(window).height() var viewImgWidth= $('#viewImg').width() var viewImgHeight= $('#viewImg').height() var viewImgX = (winWidth/2)-(viewImgWidth/2) var viewImgY = (winHeight/2)-(viewImgHeight/2) $('#viewImg').css({left:viewImgX, top:viewImgY}) }).resize() $('#imgList li a').click(function(){ //$('#viewImg').fadeIn() $('#viewImg img').before('<img src="' +$(this).attr('href') + '" />') $('#viewImg img:last').fadeOut('slow',function(){ $(this).remove() }) //$('#viewImg img').attr('src',$(this).attr('href')) return false }) $('#viewImg').click(function(){ $(this).fadeOut() }) }) </script> <style> * { margin:0; padding:0} ul,ol,li { list-style:none} img { border:none;} #imgList{ margin:50px; width:300px;} #imgList li{ float:left; width:80px; height:80px; overflow:hidden; margin:5px;} #imgList li:hover{ outline:3px solid #CCC; opacity:0.9} #imgList li a{} #viewImg{ position:absolute; z-index:1; left:0; top:0; /*display:none; */ border:5px solid #39F; width:300px; height:300px;} #viewImg img{ width:300px; height:300px; position:absolute;} </style> </head> <body> <ul id="imgList"> <li><a href="img/m1_b.jpg"><img src="img/m1.jpg"></a></li> <li><a href="img/m2.jpg"><img src="img/m2.jpg"></a></li> <li><a href="img/m3.jpg"><img src="img/m3.jpg"></a></li> <li><a href="img/m4.jpg"><img src="img/m4.jpg"></a></li> <li><a href="img/m5.jpg"><img src="img/m5.jpg"></a></li> <li><a href="img/m6.jpg"><img src="img/m6.jpg"></a></li> <li><a href="img/m7.jpg"><img src="img/m7.jpg"></a></li> <li><a href="img/m8.jpg"><img src="img/m8.jpg"></a></li> </ul> <div id="viewImg"><img src="img/m1_b.jpg" /></div> </body> </html> ``` <file_sep>/_java/A027 과목 평균.md ``` import java.util.Scanner; public class Sungjuk { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("3과목 점수를 입력하세요 : "); int java = sc.nextInt(); int jsp = sc.nextInt(); int spring = sc.nextInt(); int total = java + jsp + spring; double avg = (double)total / 3; System.out.printf("%5.1f점은 ", avg); // if(avg == 100) { // System.out.println("참잘했어요"); // System.out.println("수"); // } else if(avg >= 90) { // System.out.println("수"); // } else if(avg >= 80) { // System.out.println("우"); // } else if(avg >= 70) { // System.out.println("미"); // } else if(avg >= 60) { // System.out.println("양"); // } else { // System.out.println("가"); // } // 조건에 따라서 여러 곳으로 분기를 해야 할 경우 사용한다. // switch 문장의 () 안에는 정수, 문자, 문자열 만 나오게 해야한다. switch((int)avg / 5) { // case에는 비교하는 연산자를 사용할 수 없다. case 20: System.out.println("참잘했어요"); case 19: System.out.println("A+"); break; case 18: System.out.println("A"); break; case 17: System.out.println("B+"); break; case 16: System.out.println("B"); break; case 15: System.out.println("C+"); break; case 14: System.out.println("C"); break; case 13: System.out.println("D+"); break; case 12: System.out.println("D"); break; // 위에 적은 case에 해당되지 않는 경우 default: System.out.println("F"); } } } ``` <file_sep>/_java/COLLECTION - Sort a Map by value.md ``` import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; public class SortMap { public static void main(String a[]) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put("VB.net", 20); map.put("Java", 55); map.put("Python", 7); map.put("C++", 68); map.put("Javascript", 26); map.put("C", 86); Set<Entry<String, Integer>> set = map.entrySet(); List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set); Collections.sort( list, new Comparator<Map.Entry<String, Integer>>() { public int compare( Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2 ) { return (o2.getValue()).compareTo( o1.getValue() ); } }); System.out.println("In Descending Order:"); for(Map.Entry<String, Integer> entry:list) { System.out.println(entry.getValue()+")\t"+entry.getKey()); } } } ``` ##OUTPUT ``` 86) C 68) C++ 55) Java 26) Javascript 20) VB.net 7) Python ```<file_sep>/_cpp/캐스팅.md ``` #include <cstdio> #include <iostream> using namespace std; // #include "config.h" // 헤더 파일이 시스템 폴더에 있으면 <> 사이에 적고 그렇치 않으면 "" 사이에 적는다. int main() { cout << hex << 255 << endl; cout << oct << 255 << endl; cout << dec << 255 << endl; printf("%x\n", 255); printf("%o\n", 255); printf("%d\n", 255); //변수 선언 방법 //자료형 변수명; //자료형 변수명 = 초기치; //c언어의 자료형 //char(1바이트) : 1문자를 기억한다. 문자열은 배열이나 포인터를 사용해야 한다. //int(4바이트) : -2147483648 ~ 2147483647 사이의 정수를 기억한다. //long long int(8바이트) : 2^63 ~ 2^63-1 사이의 정수를 기억한다. //float(4바이트) : 단정도형, 소수점 아래 6자리 표현 //double(8바이트) : 배정도형, 소수점 아래 16자리 표현, 정밀한 계산이 가능하다. //void : 자료형(리턴값) 없음 long long int a = 2147483648L; cout << a << endl; int b = 8, c = 5; cout << "b + c = " << b + c << endl; cout << "b - c = " << b - c << endl; cout << "b * c = " << b * c << endl; // 곱셈 //정수와 정수의 연산은 결과값이 정수다. cout << "b / c = " << b / c << endl; // 나눗셈, 몫 cout << "b % c = " << b % c << endl; // 나머지 //묵시적 형변환 //자료형의 크기가 다른 자료의 연산 결과는 자료형의 크기가 큰 자료형으로 변환된다. cout << "8 / 5 = " << 8 / 5. << endl; cout << "A + 32 = " << 'A' + 32 << endl; cout << "a - 32 = " << 'a' - 32 << endl; //명시적 형변환(캐스팅) //프로그래머가 직접 cast 연산자를 사용해 자료형을 그 순간만 변경한다. cout << "8 / 5 = " << 8 / (double)5 << endl; cout << "b / c = " << b / (double)c << endl; cout << "A + 32 = " << (char)('A' + 32) << endl; cout << "a - 32 = " << (char)('a' - 32) << endl; } ``` <file_sep>/Eclipse_Java_Project/src/StringTokenizerEx.java import java.util.StringTokenizer; public class StringTokenizerEx { public static void main(String[] args) { String s = "name=kitae&addr=seoul&age=21"; StringTokenizer st = new StringTokenizer(s, "&="); int n = st.countTokens(); System.out.println("토큰 개수 = " + n); while(st.hasMoreTokens()) { String token = st.nextToken(); System.out.println(token); } } } <file_sep>/_java/A001 추상화 개념.md ``` package com.me.abstractclasstest; // 추상클래스 : 1개 이상의 추상메소드를 포함한 클래스를 말하며 abstract 예약어를 사용해서 만든다. // 일반 멤버 변수와 일반 메소드도 가질 수 있다. // 인터페이스 : 모든 멤버 변수가 static이고 모든 멤버 메소드가 추상 메소드인 클래스를 말한다. abstract class Product{ // 추상메소드란 {} 블록이 없는 메소드로 abstract 예약어를 사용해서 만들고 // 추상메소드가 포함된 추상 클래스를 상속받은 클래스에서 반드시 override 해서 사용해야 한다. // 프로그래머에게 반드시 override 해서 사용해야 할 메소드임을 알려준다. 강제한다. 규칙을 정한다. // public void kindOf(){ } // 아무 일도 하지 않는 일반 메소드 public abstract void kindOf(); // 반드시 ";" 를 찍어줘야 한다. 추상메소드 } // Product 클래스를 상속받아 Camera 클래스를 만든다. // Product 클래스는 추상 클래스이므로 Product 클래스에서 정의된 모든 추상 메소드를 Camera 클래스에서 // override 해야 한다. class Camera extends Product{ @Override public void kindOf() { } } // 한 파일에 여러 개의 클래스를 만들어야 할 경우 파일의 이름과 같은 이름을 가지는 클래스에만 // public을 붙힐 수 있다. public class AbstractClassTest1 { } ``` ``` package com.me.abstractclasstest; class Base{ String name; public void say(){ System.out.println(name + "님 하이용~~~~~"); } } class Sub extends Base{ int age; @Override public void say() { System.out.println(name + "님은 " + age + "살 이네요."); } } public class UpDownCastingTest { public static void main(String[] args) { Base base = new Base(); // 당연히 가능 base.name = "홍길동"; base.say(); Sub sub = new Sub(); // 이것도 당연히 가능 sub.name = "김을동"; sub.age = 15; sub.say(); } } ``` ``` package com.me.inheritancetest; // Monster를 상속받아 Boss 클래스를 만든다. public class Boss extends Monster{ // 멤버 변수는 부모(Monster) 클래스의 멤버를 그대로 사용할 것이므로 별도로 정의하지 않았다. public Boss() { super(); // 부모(Monster) 클래스의 생성자 Monster()를 호출한다. } public Boss(int level) { super(level); // 부모(Monster) 클래스의 생성자 Monster(int level)를 호출한다. } @Override public void attack() { System.out.println(level + " 레벨의 보스몹에게 공격을 받았습니다."); System.out.println(demage * DEFAULT + " 만큼의 피해를 입었습니다."); } public void specialAttack(){ attack(); System.out.println("추가로 " + demage + " 만큼의 피해를 입었습니다."); } } ----- package com.me.inheritancetest; public class InheritanceTest2 { public static void main(String[] args) { Monster goblin_lv1 = new Monster(); goblin_lv1.attack(); Monster goblin_lv10 = new Monster(10); goblin_lv10.attack(); Boss goblinBoss_lv1 = new Boss(); goblinBoss_lv1.attack(); System.out.println(); Boss goblinBoss_lv10 = new Boss(10); goblinBoss_lv10.specialAttack(); } } ------ package com.me.inheritancetest; public class Monster { final static int DEFAULT = 3; // 상수 // final이 변수 앞에 붙으면 변수 값을 수정할 수 없다. // 프로그램에서 같은 값을 가지는 숫자 또는 문자가 여러번 나올 경우 변수에 담아서 사용하면 편리하다. // 이것을 상수라 하며 상수는 변경할 수 없는 값이므로 final로 만들고 일반 변수와 구분하기 위해 // 대문자로 만들어서 사용한다. // final이 메소드 앞에 붙으면 override를 할 수 없다. // final이 클래스 앞에 붙으면 상속할 수 없다. int level; int demage; // 기본생성자, alt+shift+s -> 생성자 superclass로 생성 public Monster() { // 1 level 몹을 생성하는 생성자 this(1); // 현재 클래스의 생성자 Moster(int level)를 호출한다. } public Monster(int level) { // 넘겨받은 level의 몹을 생성하는 생성자 this.level = level; this.demage = this.level * DEFAULT; } // 모든 멤버 변수가 접근권한이 default 이므로 getter와 setter 메소드는 만들지 않았다. public void attack(){ System.out.println(level + " 레벨의 몹에게 공격을 받았습니다."); System.out.println(demage + " 만큼의 피해를 입었습니다."); } } ``` <file_sep>/_java/A021 Scanner.md ``` import java.util.Scanner; public class ScannerTest1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // 자바의 기본 자료형 // boolean(1bit) : true or false // byte(1byte) // char(2byte) : 1문자 // short(2byte) : 정수(-32768 ~ 32767) // int(4byte) : 정수(-2147483648 ~ 2147483647) // float(4byte) : 실수, 소수점 아래 6자리 // long(8byte) : 정수, -2의 63승 ~ 2의 63승 -1 // double(8byte) : 실수, 소수점 아래 16자리 // 묵시적 형변환 // 서로 길이가 다른 자료형의 연산 결과는 길이가 긴 자료형으로 자동으로 조정된다. // 명시적 형변환 // 캐스트 연산자를 사용해 자료의 형태를 강제로 변환한다. System.out.print("주소 : "); String addr = sc.nextLine(); // next() : 한 단어, 띄어쓰기 전 까지 // nextLine() : 한 줄, 키보드 버퍼가 비어있으면 입력을 요구하고 비어있지 않으면 끝까지 읽어들인다. System.out.print("이름 : "); String name = sc.nextLine(); System.out.println(name + "님은 " + addr + "에 삽니다."); System.out.print("나이 : "); int age = sc.nextInt(); // nextInt()로 입력을 받으면 숫자만 변수에 전달되고 키보드 버퍼에 엔터키는 그대로 남는다. System.out.print("별명 : "); // ★★★★★★★★★★★★★★★★★★★★★★★★★ sc.nextLine(); // 키보드 버퍼를 비운다. // ★★★★★★★★★★★★★★★★★★★★★★★★★ String nickName = sc.nextLine(); System.out.println(name + "(" + age + ") - " + nickName); } } ``` <file_sep>/_htmlCss/A007 hover, background-position.md ``` 배경이미지 속성 <=> background 속성 background-image background-repeat background-attachment: fixed; background-position; 가로px 세로px background-color 이미지는 두가지 방법으로 넣기 가능 <body>에 넣거나 <style>에 넣거나 <style> { background-image:url("img/bg.jpg"); background-repeat:repeat-x; } </style> <div> <img src="img/title.jpg" alt="봉사사진" /> </div> * alt를 써주는 것이 시각장애인 분들에게 도움이 됩니다. 호버(마우스 관련) hover ( mouseover / mouseout ) <style> #box { color:red; font-size:30px; } #box:hover { color:blue; font-size:40px; text-decoration:underline; } <!-- box:hover 띄어쓰기 금지 / 유일한 다이내믹한 기능 / 글자로 하면 폰트 옵션 다 들어감 ,이미지도 마찬가지 --> </style> ``` ``` <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <style> #but01 { width:64px; height:19px; background-image:url("img/ux01.jpg"); background-position:-7px -11px; text-indent:-9999px;} <!--팁: text-indent:-9999px; 는 비장애인을 위해 글자는 안보이게 처리 --> #but01:hover { background-position:-7px -34px; } <!-- 이미지를 위 아래로 그려놓고 마우스오버 되면 백그라운드 포지션으로 밑으로 이동해서 보여줌 --> #but02 a { width:90px; height: 19px; background-image:url("img/ux01.jpg"); background-position:-129px -11px; text-indent:-9999px; float:left; margin-left:30px; } #but02 a:hover { background-position:-129px -34px; } <!-- a링크 적용 --> </style> </head> <body> <div id="but01">about</div> <!-- 장애인들을 위해서, background 처리된 이미지파일 이름 안읽고 about 읽음 --> <div id="but02"><a href="http://www.naver.com" target="_blank">business</a></div> <!-- 스타일에서 a링크 적용하지 않으면 링크 안걸림 --> </body> </html> ``` ``` 사각형 종류 body : 몸통 사각형 div : 큰 영역 사각형 a : 링크 걸어주는 사각형 포토샵에서 슬라이스 걸어놓으면 이미지에 대한 x,y 좌표값이 나옴 상속 #box {width:500px; height:500px; background-color:blue; } #box {width:400px; margin-left:100px; } 위에 값은 마지막껄로 적용됨. #box {width:500px; height:500px; background-color:blue; } #box:hover { width:200px; height:200px; background-color:red; } 위에 값을 바꿀 수 있음 (유산 상속 거부) <!doctype html> <html> <head> <meta charset="utf-8"> <title>homework</title> <style> #but01 a { width:44px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:0 -323px; float:left; } #but01 a:hover { background-position:0 -373px; } #but02 a { width:44px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-44px -323px; float:left; } #but02 a:hover { background-position:-44px -373px; } #but03 a { width:44px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-88px -323px; float:left; } #but03 a:hover { background-position:-88px -373px; } #but04 a { width:44px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-132px -323px; float:left; } #but04 a:hover { background-position: -132px -373px; } #but05 a { width:44px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-176px -323px; float:left; } #but05 a:hover { background-position: -176px -373px; } #but06 a { width:44px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-220px -323px; float:left; } #but06 a:hover { background-position: -220px -373px; } #but07 a { width:54px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-264px -323px; float:left; } #but07 a:hover { background-position: -264px -373px; } #but08 a { width:46px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-318px -323px; float:left; } #but08 a:hover { background-position: -318px -373px; } #but09 a { width:68px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-364px -323px; float:left; } #but09 a:hover { background-position: -364px -373px; } #but10 a { width:46px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-432px -323px; float:left; } #but10 a:hover { background-position: -432px -373px; } #but11 a { width:44px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-478px -323px; float:left; } #but11 a:hover { background-position: -478px -373px; } #but12 a { width:51px; height:39px; text-indent:-9999px; background-image:url("img/naver.png"); background-position:-522px -323px; float:left; } #but12 a:hover { background-position: -522px -373px; } </style> </head> <body> <div id="but01"><a href="#">라이프</a></div> <div id="but02"><a href="#">스포츠</a></div> <div id="but03"><a href="#">경제</a></div> <div id="but04"><a href="#">뮤직</a></div> <div id="but05"><a href="#">영화</a></div> <div id="but06"><a href="#">웹툰</a></div> <div id="but07"><a href="#">TV/동영상</a></div> <div id="but08"><a href="#">책/공연</a></div> <div id="but09"><a href="#">네이버캐스트</a></div> <div id="but10"><a href="#">차/테크</a></div> <div id="but11"><a href="#">게임</a></div> <div id="but12"><a href="#">공익/나눔</a></div> </body> </html> ``` <file_sep>/_cpp/일반 변수와 포인터 변수의 비교.md ``` #include <cstdio> #include <iostream> #include <iomanip> #include <string> using namespace std; int main() { // int n, sum = 0; // cout << "배열의 개수 입력 : "; // cin >> n; // int *a = new int[n]; // 1차원 가변 배열 // for(int i=0 ; i<n ; i++) { // cout << i + 1 << "번째 데이터 : "; // cin >> a[i]; // sum += a[i]; // } // cout << sum << endl; // char *week[] = {"일","월","화","수","목","금","토"}; // for(int i=0 ; i<7 ; i++) { // cout << week[i] << "요일" << endl; // } int a = 100; // 일반 변수는 값을 기억한다. int *p1; // 포인터 변수는 일반 변수의 주소를 기억한다. p1 = &a; // 포인터 변수에는 &(번지 연산자)를 붙여서 변수의 주소를 넣어야 한다. cout << "a가 기억한 값 : " << a << endl; cout << "a가 메모리에 생성된 주소값 : " << &a << endl; cout << "p1이 기억한 a의 주소값 : " << p1 << endl; cout << "p1이 기억한 주소에 저장된(참조하는) 값(a에 저장된 값) : " << *p1 << endl; cout << "===================================================================" << endl << endl; // 2차원 가변 배열 // int **a = new int*[n]; // 행 // for(int i=0 ; i<n ; i++) { // a[i] = new int[n]; // 열 // } int **p2; // 포인터의 포인터, 이중 포인터, 포인터 변수의 주소를 기억한다. // p2 = &a; // 일반 변수의 주소를 이중 포인터에 넣었으므로 에러가 발생된다. // p2 = p1; // 포인터 변수의 값을 이중 포인터에 넣었으므로 에러가 발생된다. p2 = &p1; cout << "p1이 메모리에 생성된 주소값 : " << &p1 << endl; cout << "p2가 기억한 p1의 주소값 : " << p2 << endl; cout << "p2가 참조하는 값(p1에 저장된 값) : " << *p2 << endl; cout << "p2가 참조하는 값에 저장된 주소가 참조하는 값(a에 저장된 값) : " << **p2 << endl; cout << "===================================================================" << endl << endl; int ***p3; // 포인터의 포인터의 포인터, 삼중 포인터, 이중 포인터 변수의 주소를 기억한다. // p3 = &a; // 일반 변수의 주소를 삼중 포인터에 넣었으므로 에러가 발생된다. // p3 = &p1; // 포인터 변수의 주소를 삼중 포인터에 넣었으므로 에러가 발생된다 // p3 = p2; // 이중 포인터 변수의 값을 삼중 포인터에 넣었으므로 에러가 발생된다. p3 = &p2; cout << "p3가 참조하는 값에 저장된 주소가 참조하는 값에 저장된 주소가 참조하는 값(a에 저장된 값) : " << ***p3 << endl; } ``` ``` #include <cstdio> #include <iostream> #include <iomanip> #include <string> using namespace std; // 인수로 주소가 날아오면 함수는 포인터로 받는다. void change(int *a, int *b, int *c) { int temp = *a; *a = *b; *b = temp; *c = 12345; // 포인터 변수 c가 참조하는(n) 값을 변경했다. } int main() { int a[] = {8, 3, 4, 9, 1}; int n = 100; cout << "함수를 호출하기 전 n값 : " << n << endl; for(int i=0 ; i<4 ; i++) { for(int j=i+1 ; j<5 ; j++) { if(a[i] > a[j]) { change(&a[i], &a[j], &n); // call by reference(참조에 의한 호출), call by address(주소에 의한 호출) // 함수를 호출할 때 실인수로 기억장소의 주소를 넘겨주고 가인수에서 포인터로 받게한다. // 주소값을 직접 전달하므로 side effect(부작용) 현상이 발생될 수 있다. } } cout << i + 1 << "회전 결과 : "; for(int j=0 ; j<5 ; j++) { cout << a[j] << " "; } cout << endl; } cout << "함수를 호출한 후 n값 : " << n << endl; } ``` <file_sep>/_java/EXCEPTION HANDLING - Using Only Try Block.md ``` import java.net.MalformedURLException; import java.net.URL; public class MyTryBlockOnly { public static void main(String a[]) throws MalformedURLException { try { URL url = new URL("http://www.google.com"); } finally { System.out.println("In finally block"); } } } ``` ##OUTPUT ``` In finally block ```
d5ba62edcf307d5800fee44a97ecadf7c838ad4d
[ "Markdown", "Java" ]
211
Markdown
nowStackOverflow/allcode_test
8e8f7c1be90a208999356725143f7294b8d3f913
8582a9ab7ad31f8a0c94d3b847a835307804c84c
refs/heads/master
<file_sep>#!/bin/bash echo "--[MOUNTING FILESYSTEM]--" TARGET=$1 umount -R /mnt &>/dev/null echo "- mount /" echo "TARGET: $TARGET" # STANDARD mount ${TARGET}2 /mnt ; mkdir /mnt/boot mount ${TARGET}1 /mnt/boot; mkdir /mnt/home mount ${TARGET}3 /mnt/home; echo "- refreshing repositories" pacman -Syy &>/dev/null echo "- Installing base packages" # pacstrap /mnt base pacman-contrib linux linux-firmware - EDIT pacstrap /mnt base pacman-contrib linux linux-firmware &>/dev/null echo "- Installing extra utilities" pacstrap /mnt zip unzip vim nmon ncdu htop syslog-ng lsb-release bash-completion exfat-utils usb_modeswitch neofetch &>/dev/null echo "- Installing custom fonts" pacstrap /mnt terminus-font &>/dev/null echo "- Installing SSH and sudo" pacstrap /mnt openssh sudo &>/dev/null echo '- chroot to new install' mkdir /mnt/scripts cp *.sh /mnt/scripts &>/dev/null cp font.txt /mnt/scripts &>/dev/null genfstab -U /mnt >> /mnt/etc/fstab arch-chroot /mnt /scripts/post-chroot.sh <file_sep>#!/bin/bash #ARCH INSTALLER BY <NAME> # OPT="--color always -q --noprogressbar --noconfirm --logfile pacman-$0.log" echo "--[MIRROR CONFIGURATION]--" echo "- Downloading new mirrors" curl -s https://www.archlinux.org/mirrorlist/all/ -o mirrorlist_download #sed 's/\#S/S/' mirrorlist_download > mirrorlist cat mirrorlist_download |tail -n +6|grep -v -e "^$">mirrorlist_temp file="mirrorlist_temp" echo -e "- Generating mirrors by country:" while IFS= read line do # display $line or do something with $line a=${line:0:2} if [ "$a" == "##" ]; then country=${line:3:100} echo -n "." code=$(sed 's/\ /\_/g' <<<$country) file="mirrorlist_$code" echo "## $country">$file else if [ "$a" == "#S" ]; then server=${line:1:300} echo "$server">>${file} fi fi done <"$file" echo -e "\n" mv mirrorlist_temp mirrorlist_all_default ls mirrorlist_* echo "" read -p "type the full name of the mirror that you want to use: " mirror cp $mirror /etc/pacman.d/mirrorlist pacman -Syy $OPT 1>/dev/null <file_sep>#!/bin/bash OPT="--noconfirm --color always -q --noprogressbar --logfile pacman-$0.log" echo "--[REFRESHING PACKAGES]--" pacman -Sy $OPT &>/dev/null echo "--[FONT SIZE]--" while [ "$ask" != "n" ]; do read -p "change font (y/n) ? type 'n' for no change and continue install : " ask if [ "$ask" == "y" ]; then for a in {12..32..2};do echo -n "$a " ;done echo "" read -p "Enter the desired font size: " size fsize=$(($size+0)) if [ $fsize -gt 11 ]; then #&& [ $fsize -lt 33]; then if [ $fsize -lt 33 ]; then pacman -S terminus-font $OPT &>/dev/null setfont ter-v${fsize}n echo "FONT=ter-v${fsize}n" > font.txt fi fi fi done <file_sep>#!/bin/bash # THIS SCRIPT ASSUMES YOU HAVE AN INTERNET CONNECTION ALREADY AVAILABLE function cleanup #CLEANUP FILES { echo "- Cleanup" \rm mirrorlist_* mirrorlist *.temp &>/dev/null } sed -e 's/#Color/Color/' /etc/pacman.conf >pacman.temp #ENABLE COLOR IN PACMAN cp pacman.temp /etc/pacman.conf &>/dev/null cleanup umount -R /mnt &>/dev/null ./select-font.sh ./select-mirror.sh ./select-disk.sh cleanup<file_sep>#!/bin/bash find /usr/share/zoneinfo -maxdepth 1 -type d |tail -n +2|sort|sed 's/\/usr\/share\/zoneinfo\///' read -p "- Select time zone location: " tzl #find /usr/share/zoneinfo/$tzl -maxdepth 1 -type f ls /usr/share/zoneinfo/$tzl read -p "- Select time zone region: " tzr full="/usr/share/zoneinfo/$tzl/$tzr" cp $full /etc/localtime &>/dev/null
8ea55f6a8aa7638cd046bfb33fef2f2779200cc4
[ "Shell" ]
5
Shell
fretzo/arch_installer
662f8a1e2d7096711ef39ec3666d6962bdb7cc3c
a6be4ce29f0cad8a3a15683ea3eb2b7fd8d7ca55
refs/heads/main
<file_sep>import logo from './logo.svg'; import './App.css'; import { Button, CloseButton } from 'react-bootstrap'; import 'bootstrap/dist/css/bootstrap.min.css'; import { FaUser, FaEnvelopeOpenText, FaPhoneAlt, FaAddressBook, FaChalkboardTeacher, FaClipboardList, FaAward, FaDollarSign, FaBell, FaDotCircle, FaRegCircle, FaRegPlusSquare } from "react-icons/fa"; // This is style const interviewBoard = { width: '60%', height: '620px', margin: '1% 0% 0% 20%' } function App() { return ( <div className="interview-box shadow-lg p-3 mb-5 bg-body rounded" style={interviewBoard}> {/* Header Part start from here */} <header class="hd container"> <div class="row d-flex justify-content-between hdr"> <div class="col-md-10"> <h4><strong>Create New job</strong></h4> </div> <div class="col-md-2 close-btn"> <CloseButton /> </div> </div> <div> <ul class="row container"> <div class="col-md-3 bd green1"> <li class="circle-icon"> <span><FaDotCircle /></span> Basic Information</li> </div> <div class="col-md-3 bd green2"> <li class="circle-icon"> <span><FaDotCircle /></span> Job Summary</li> </div> <div class="col-md-3 bd orange"> <li class="circle-icon"> <span><FaDotCircle /></span> Job Application Form</li> </div> <div class="col-md-3 bd text"> <li class="circle-icon"> <span><FaRegCircle /> </span> Interview Pipeline</li> </div> </ul> </div> </header> {/* Header Part END here */} {/* Main Body Part start from here */} <main class="container"> <div> <h5 class="text-muted preview">Job Application Form</h5> <p class="text-muted">Candidates are to apply with this information.</p> <div class="row p-icon text-muted"> <div class="col-md-2 d-flex justify-content-center align-items-center b-radius"> <FaUser /> Name </div> <div class="col-md-2 d-flex justify-content-center align-items-center b-radius"> <FaEnvelopeOpenText /> Email </div> <div class="col-md-2 d-flex justify-content-center align-items-center b-radius"> <FaPhoneAlt /> Phone </div> <div class="col-md-2 d-flex justify-content-center align-items-center b-radius"> <FaAddressBook /> Address </div> <div class="col-md-2 d-flex justify-content-center align-items-center b-radius"> <FaChalkboardTeacher /> Education </div> <div class="col-md-2 d-flex justify-content-center align-items-center b-radius"> <FaClipboardList /> Resume </div> <div class="col-md-2 d-flex justify-content-center align-items-center b-radius"> <FaAward /> experience </div> <div class="col-md-3 d-flex justify-content-center align-items-center b-radius"> <FaDollarSign /> Expected salary </div> <div class="col-md-3 d-flex justify-content-center align-items-center b-radius"> <FaBell /> Notice period </div> </div> </div> </main> <div class="row container additional"> <div class="col-md-12"> <p class="text-muted">Additional Example...........................................................................................<button class="btn-success add-btn">+</button></p> </div> </div> {/* Main body Part END here */} {/* Footer Part start from here */} <footer class="container ftr"> <div class="row d-flex justify-content-between align-items-center"> <div class="col-md-8"> <h6 class="text-muted">CANCEL</h6> </div> <div class="col-md-4 d-flex justify-content-around"> <Button variant="outline-secondary">PREV</Button> <Button variant="success">NEXT</Button> </div> </div> </footer> {/* Footer Part END here */} </div > ); } export default App;
44b8e2a053e0165d5ce43ca3c0482a78654edcc2
[ "JavaScript" ]
1
JavaScript
devloperhamza2020/interview-task
0be8ff083581baa8cc5b8bfec2fd8490a31b8b64
02d84039fd86bd632e6c44d3b80105387c9deab7
refs/heads/master
<repo_name>hentaiRin/TouHouDisk<file_sep>/application/controllers/Bin.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Bin extends MY_Controller{ public $origin; public function __construct() { parent::__construct(); $this->origin = 'original'; $this->load->helper('url'); } /** * 索引图片处理 * * @access public * @return void */ public function index() { $file_p = explode('/', trim($_SERVER['REQUEST_URI'], '/')); $origin_file = 'assets/'.$this->origin.'/'.$file_p[1]; if(file_exists($origin_file)){ $this->load->library('create_image'); $this->create_image->config['quality'] = 100; $query = $this->create_image->zoom($file_p[1], $file_p[0]); $mew_img = $_SERVER['REQUEST_URI']; }else{ $query = false; $mew_img = ''; } // 判断是否处理成功 if($query === TRUE) { redirect($mew_img); } else { show_404(); } } /*退出登录清除session 、cookie*/ public function log_out() { } public function download(){ $size = 1024; $flag = 0; for(;;){ $temp = file_get_contents('assets/index.jpg', false, null, $size * $flag, $size); if(!empty($temp)){ file_put_contents('assets/news_img/cache_'.$flag, $temp); $flag++; }else{ break; } } } public function copy(){ $flag = 0; $file = fopen('assets/news_img/index.jpg', 'ab'); for(;;){ if(file_exists('assets/news_img/cache_'.$flag)){ fwrite($file, file_get_contents('assets/news_img/cache_'.$flag)); $flag++; }else{ break; } } } public function file(){ $this->load->library('file_list'); $arr = $this->file_list->file_open_list('F:\Pictures'); $front['w'] = (int)$this->input->get('w'); $front['h'] = (int)$this->input->get('h'); $front['i'] = (int)$this->input->get('i'); $this->load->library('create_image'); if(empty($arr) || !isset($arr[$front['i']])){ $file = FCPATH.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'index.jpg'; }else{ $file = $arr[$front['i']]; } $this->create_image->show_original($file, $front['w'], $front['h']); } }<file_sep>/application/controllers/Run.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * 欢迎界面 */ class Run extends MY_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { echo 'Happy Helloween!!'; } public function charset(){ header("Content-type: text/html; charset=gb2312"); echo PHP_OS; $command = "chcp"; $output = array(); //echo exec($command, $output); echo exec($command); var_dump($output); } public function url_code(){ $pid = $this->input->get('pid'); if(empty($pid)){ $pid = 0; } $uri = trim($_SERVER['REQUEST_URI'], '/'); $uri = explode('/', $uri); if(isset($uri[3])){ $page_size = (int)$uri[3]; if($page_size <= 0){ $page_size = 300; } }else{ $page_size = 300; } if(isset($uri[2])){ $page = (int)$uri[2]; if($page <= 0){ $page = 1; } }else{ $page = 1; } $offset = ($page - 1) * $page_size; $this->load->model('file_model'); $data = $this->file_model->get_list(array('parent_path' => $pid), $offset, $page_size); $file = $this->file_model->get_file($pid); if(empty($file)){ $data['pid'] = 0; }else{ $data['pid'] = $file['parent_path']; } $data['page'] = $page; $data['base_path'] = 'uploads/link/cache/'; $this->load->view('img_list', $data); } public function create_md5_url(){ exit('功能已停用'); set_time_limit(120); //$path = 'uploads'.DIRECTORY_SEPARATOR.'link'.DIRECTORY_SEPARATOR.'picture'.DIRECTORY_SEPARATOR; $path = 'uploads'.DIRECTORY_SEPARATOR.'link'.DIRECTORY_SEPARATOR; $this->load->library('file_list'); $arr = $this->file_list->open_dir('picture', $path); } } <file_sep>/application/views/img_list.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"/> <title>图片列表</title> <style> *{ margin: 0; padding: 0; } .main{ width: 100%; } .last-page{ margin-top: 50px; width: 100%; height: 35px; line-height: 35px; text-align: left; font-size: 30px; color:#009f95; } .last-page a{ margin-left: 15px; } .content{ width: 100%; margin-top: 50px; } .page{ width: 100%; height: 50px; margin-top: 10px; } .div-row{ float: left; width: 25%; text-align: center; margin-left: 5%; } .title{ text-align: center; line-height: 25px; font-size: 18px; height: 25px; } .row_content{ margin-top: 5px; } </style> </head> <body> <div class="main"> <div class="last-page"> <a href="<?=base_url('run/url_code/1?pid='.$pid)?>">返回上层</a> </div> <div class="content"> <?php foreach($data as $k => $v){?> <div class="div-row"> <div class="title"><?=$v['real_name']?></div> <div class="row_content"> <?php if($v['file_type'] == 2){?> <a target="_balnk" href="<?=base_url($base_path.$v['filename'].'.'.$v['ext'])?>"> <img src="<?=base_url($base_path.$v['filename'].'.'.$v['ext'])?>" alt="" height="280"> </a> <?php }else{?> <a href="<?=base_url('run/url_code/1?pid='.$v['id'])?>"> <img src="<?=base_url('original/dir.jpg')?>" alt="" height="280"> </a> <?php }?> </div> </div> <?php }?> </div> <div class="page"> </div> </div> </body> </html> <file_sep>/application/libraries/Create_image.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Create_image { public $config; private $_image_size_param; public function __construct($config = array()) { $this->_init($config); # code... } public function do_img($file, $w = 4, $h = 3){ $mine = getimagesize($file); $function1 = $this->get_function_name($mine['mime']); //var_dump($function1); $function2 = $this->create_function_name($mine['mime']); $img = $function1($file); $size[0] = imagesx($img); $size[1] = imagesy($img); if($size[0] >= $size[1]){ $width = $size[0]/$w; $height = $size[1]/$h; }else{ $width = $size[0]/$h; $height = $size[1]/$w; } $img_arr = array(); for($i=0;$i<$w;$i++){ for($j=0; $j < $h; $j++){ //$temp_img = imagecreatetruecolor($width, $height); //imagesavealpha($temp_img, true); //imagecopy($temp_img, $img, 0, 0, $width * $i, $height * $j, $width, $height); //$filename = md5_file($file).'_'.$i.$j.'.'.$this->ext($mine['mime']); $img_arr[$i][$j] = array($i, $j); //imagejpeg($temp_img, $filename); /*header('Content-type:image/png'); imagepng($temp_img);*/ //imagedestroy($temp_img); } } return $img_arr; /* clone(){ var self = this; // //加载动态资源 cc.loader.loadRes("img1",cc.SpriteFrame,function(err,spriteFrame){ var texture = spriteFrame.getTexture(); for(var i=0;i<4;i++){ imgArr2[i] = []; imgArray2[i] = []; for(var j=0;j<3;j++){ //碎片放入imgArray二维数组中 imgArray2[i][j] = new cc.SpriteFrame(texture,cc.rect(210*j,240*i,210,240)) ; var blocknode = cc.instantiate(self.blockPrefab); blocknode.position = cc.p(210*j,-240*i-240); blocknode.opacity = 100; imgArr2[i][j] = blocknode; let block = blocknode.getComponent("Block"); block.imgSp.spriteFrame = imgArray2[i][j]; block.initBlock(imgArray2[i][j],self.puIndex2++,cc.v2(j,i)); self.gameMap.addChild(blocknode); } } }) },*/ } /** * 显示图片 * @param $file * @param $x * @param $y * @param int $w * @param int $h */ /*public function show_img($file, $x, $y, $w = 4, $h = 3){ $mine = getimagesize($file); $function1 = $this->get_function_name($mine['mime']); $img = $function1($file); $size[0] = imagesx($img); $size[1] = imagesy($img); if($size[0] >= $size[1]){ $width = $size[0]/$w; $height = $size[1]/$h; }else{ $width = $size[0]/$h; $height = $size[1]/$w; } $temp_img = imagecreatetruecolor($width, $height); imagesavealpha($temp_img, true); imagecopy($temp_img, $img, 0, 0, $width * $x, $height * $y, $width, $height); header('Access-Control-Allow-Origin:*'); header('Content-type:image/png'); imagepng($temp_img); imagedestroy($temp_img); }*/ public function show($file, $w = 4, $h = 3){ $mine = getimagesize($file); $function1 = $this->get_function_name($mine['mime']); $img = $function1($file); $size[0] = imagesx($img); $size[1] = imagesy($img); if($size[0] >= $size[1]){ $width = $size[0]/$w; $height = $size[1]/$h; }else{ $width = $size[0]/$h; $height = $size[1]/$w; } $temp_img = imagecreatetruecolor($width, $height); imagesavealpha($temp_img, true); $col_ellipse = imagecolorallocate($temp_img, 22, 150, 255); imagefilledellipse($temp_img, $width/2, $height/2, $width, $height, $col_ellipse); header('Access-Control-Allow-Origin:*'); header('Content-type:image/png'); imagepng($temp_img); imagedestroy($temp_img); } public function show_original($file, $w = 0, $h = 0){ $mine = getimagesize($file); $width = $mine[0];//获取宽度 $height = $mine[1];//获取高度 //计算缩放比例 if($w == 0 && $h == 0){ $scale = 1; }else{ if($w == 0 && $h != 0){ $scale = $h/$height; }else if($w != 0 && $h == 0){ $scale = $w/$width; }else{ $scale = ($w/$width)>($h/$height)?$h/$height:$w/$width; } } //计算缩放后的尺寸 $sWidth = floor($width*$scale); $sHeight = floor($height*$scale); $function1 = $this->get_function_name($mine['mime']); $img = $function1($file); //创建目标图像资源 $nim = imagecreatetruecolor($sWidth,$sHeight); //等比缩放 imagecopyresampled($nim,$img,0,0,0,0,$sWidth,$sHeight,$width,$height); header('Access-Control-Allow-Origin:*'); header('Content-type:image/png'); imagepng($nim); imagedestroy($img); imagedestroy($nim); } /** * 缩放图片 * @param $file * @param $type */ private function _do_zoom($file, $type){ $base_file = 'uploads/original/'.$file; $mine = getimagesize($base_file); $width = $mine[0];//获取宽度 $height = $mine[1];//获取高度 //计算缩放比例 if($mine[0] >= $mine[1]){ $scale = $this->_image_size_param[$type]/$mine[0]; }else{ $scale = $this->_image_size_param[$type]/$mine[1]; } //计算缩放后的尺寸 $sWidth = floor($width*$scale); $sHeight = floor($height*$scale); $function1 = $this->get_function_name($mine['mime']); $function2 = $this->create_function_name($mine['mime']); $img = $function1($base_file); //创建目标图像资源 $nim = imagecreatetruecolor($sWidth,$sHeight); //等比缩放 imagecopyresampled($nim,$img,0,0,0,0,$sWidth,$sHeight,$width,$height); if($mine[2] == 2){ $query = $function2($nim, 'uploads/'.$type.'/'.$file, $this->config['quality']); }else{ $query = $function2($nim, 'uploads/'.$type.'/'.$file); } imagedestroy($img); imagedestroy($nim); return $query; } /** * 仅复制 * @param $file * @param $type * @return bool */ private function _do_copy($file, $type){ $path = 'uploads/'; return copy($path.'original/'.$file, $path.$type.'/'.$file); } private function _zoom($file, $type){ $path = 'uploads/'; $mine = getimagesize($path.'original/'.$file); $check_length = $mine[0] >= $mine[1]? $mine[0] : $mine[1]; if($check_length > 0 && $check_length < $this->_image_size_param['little']){ return '_do_copy'; }else if($check_length > $this->_image_size_param['little'] && $check_length < $this->_image_size_param['small']){ if($type == 'little'){ return '_do_zoom'; }else{ return '_do_copy'; } }else if($check_length > $this->_image_size_param['small'] && $check_length < $this->_image_size_param['normal']){ if($type == 'little' || $type == 'small'){ return '_do_zoom'; }else{ return '_do_copy'; } } else if($check_length > $this->_image_size_param['normal'] && $check_length < $this->_image_size_param['big']){ if($type == 'little' || $type == 'small' || $type == 'normal'){ return '_do_zoom'; }else{ return '_do_copy'; } } else if($check_length > $this->_image_size_param['big'] && $check_length < $this->_image_size_param['large']){ if($type == 'little' || $type == 'small' || $type == 'normal' || $type == 'big'){ return '_do_zoom'; }else{ return '_do_copy'; } } else if($check_length > $this->_image_size_param['large']){ return '_do_zoom'; } else{ return false; } } /** * 缩放 * @param $file * @param $type * @return bool */ public function zoom($file, $type){ $query = false; if(isset($this->_image_size_param[$type])){ $function = $this->_zoom($file, $type); if($function){ $query = $this->$function($file, $type); } } return $query; } /** * 获取方法名字 * @param $type * @return bool|string */ private function get_function_name($type){ switch($type){ case 'image/png': return 'imagecreatefrompng'; break; case 'image/jpeg': case 'image/jpg': return 'imagecreatefromjpeg'; break; case 'image/gif': return 'imagecreatefromgif'; break; default: exit(); break; } } /** * @param $type * @return bool|string */ private function create_function_name($type){ switch($type){ case 'image/png': return 'imagepng'; break; case 'image/jpeg': case 'image/jpg': return 'imagejpeg'; break; case 'image/gif': return 'imagegif'; break; default: exit(); break; } } /** * @param $type * @return bool|string */ private function ext($type){ switch($type){ case 'image/png': return 'png'; break; case 'image/jpeg': case 'image/jpg': return 'jpg'; break; case 'image/gif': return 'gif'; break; default: exit(); break; } } /** * 参数设置 * @param $config */ private function _init($config){ $this->_image_size_param = array( 'little'=> 120, 'small' => 320, 'normal'=> 690, 'big' => 1024, 'large' => 1920, 'original' => 0 ); $auto_config = array( 'quality' => 80 ); $this->config = array_merge($auto_config, $config); } }<file_sep>/application/core/MY_Controller.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Controller extends CI_Controller{ # 网页顶部的菜单列表 protected $top_menu; public function __construct() { parent::__construct(); $this->load->library('session'); $this->load->library('common'); $this->load->helper('url'); # 定义中国时区 date_default_timezone_set('PRC'); } /* |-------------------------------------------------------------------------- | verify_sms 验证短信是否有效 |-------------------------------------------------------------------------- | Desc: 检查不同用途的短信验证码是否有效 | | @param $phone 手机号 | @param $sms 短信 | @param $sms_type 用途 1 - 注册 2-修改密码 | | @return 是否有效 */ public function verify_sms($phone, $sms, $sms_type) { $query = $this->common->verifySMS($phone, $sms, $sms_type); return $query; } /* |-------------------------------------------------------------------------- | rule_param 校验前台输入数据是否有效 |-------------------------------------------------------------------------- | Desc: 校验前台输入数据是否有效 | | @param $str 被检参数 | @param $type 类型 | | @return 是否有效 */ public function rule_param($str, $type) { switch ($type) { case 'phone': $query = strlen($str) == 11 ? true : false; $msg = "手机号必须为11位数字!"; break; case 'passwd': $query = (strlen($str) >= 6 && strlen($str) <= 18) ? true : false; $msg = "密码长度必须为6-18位!"; default: # code... break; } if(!$query){ $this->common->statusCode(210, $msg); } } /* |-------------------------------------------------------------------------- | 参数检测 |-------------------------------------------------------------------------- | Desc: 检测是否有给定数组中指定参数 | | @param Array 需要匹配的参数数组 | @param Array 被需要匹配的数组 | | @return Array OR FALSE */ public function check_params($arr, $data) { foreach($arr as $key){ $this->common->ParamIsNull($data, $key); } } /** * 将指定数组中的值按js和css分开 * @param $arr * @return array */ public function give_href($arr){ $data = array( 'js' => array(), 'css' => array(), 'icon' => array(), ); if(!empty($arr)){ foreach($arr as $value){ $ext = strtolower(trim(substr(strrchr($value, '.'), 1))); if($ext == 'js'){ $data['js'][] = $value; }elseif($ext == 'css'){ $data['css'][] = $value; }else{ $data['icon'][] = $value; $data['ext'] = $ext; } } } return $data; } } <file_sep>/application/libraries/Verify.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); //验证码类 class Verify { private $CI; private $charset;//随机因子 private $codelen;//验证码长度 private $width;//宽度 private $height;//高度 private $fontsize;//指定字体大小 private $font;//指定的字体 private $fontcolor;//指定字体颜色 private $code;//验证码 private $code_value;//验证码值 private $img;//图形资源句柄 //构造方法初始化 public function __construct($config = array()) { $this->CI = & get_instance(); $this->init_config($config); } //生成随机码 private function createCode() { $_len = strlen($this->charset)-1; for ($i=0;$i<$this->codelen;$i++) { $this->code .= $this->charset[mt_rand(0,$_len)]; } $this->code_value = $this->code; } /** * 算术验证码 */ private function createFormula(){ $a = rand(11, 100); $b = rand(0, 9); $c = rand(0, 1); switch($c){ case 0: $this->code_value = $a + $b; $this->code = $a.' + '.$b.' = ?'; break; default: $this->code_value = $a - $b; $this->code = $a.' - '.$b.' = ?'; break; } $this->codelen = strlen($this->code); } //生成文字 private function createFormulaFont() { $_x = $this->width / $this->codelen; for ($i=0;$i<$this->codelen;$i++) { $this->fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156)); imagettftext($this->img,$this->fontsize,0,$_x*$i+mt_rand(1,5),$this->height / 1.4,$this->fontcolor,$this->font,$this->code[$i]); } } //生成背景 private function createBg() { $this->img = imagecreatetruecolor($this->width, $this->height); $color = imagecolorallocate($this->img, mt_rand(157,255), mt_rand(157,255), mt_rand(157,255)); imagefilledrectangle($this->img,0,$this->height,$this->width,0,$color); } /** * 生成文字 * @param int $angle 判断是否随机旋转角度(0-随机 其它-不随机) */ private function createFont($angle = 0) { $angle = $angle == 0 ? mt_rand(-30,30) : 0; $_x = $this->width / $this->codelen; for ($i=0;$i<$this->codelen;$i++) { $this->fontcolor = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156)); imagettftext($this->img,$this->fontsize,$angle,$_x*$i+mt_rand(1,5),$this->height / 1.4,$this->fontcolor,$this->font,$this->code[$i]); } } //生成线条、雪花 private function createLine() { //线条 for ($i=0;$i<6;$i++) { $color = imagecolorallocate($this->img,mt_rand(0,156),mt_rand(0,156),mt_rand(0,156)); imageline($this->img,mt_rand(0,$this->width),mt_rand(0,$this->height),mt_rand(0,$this->width),mt_rand(0,$this->height),$color); } //雪花 for ($i=0;$i<100;$i++) { $color = imagecolorallocate($this->img,mt_rand(200,255),mt_rand(200,255),mt_rand(200,255)); imagestring($this->img,mt_rand(1,5),mt_rand(0,$this->width),mt_rand(0,$this->height),'*',$color); } } //输出 private function outPut() { header('Content-type:image/png'); imagepng($this->img); imagedestroy($this->img); } //设置SESSION CI用 private function createSession(){ $this->CI->load->library('session'); # 加载session类 $key = strtoupper(md5(VERIFY_KEY.date('Y'))); $arr[$key] = $this->code_value; $this->CI->session->set_userdata( $arr ); } //对外生成 public function doimg($format = 0) { $this->createBg(); switch($format){ case 0: $this->createCode(); break; default: $this->createFormula(); break; } $this->createSession(); $this->createLine(); $this->createFont($format); $this->outPut(); } //获取验证码 /*public function getCode() { return strtolower($this->code); }*/ /** * 设置配置 * @param array $config 配置信息数组 */ private function init_config($config=array()){ $this->codelen = isset($config['length']) ? $config['length'] : 4; $this->charset = isset($config['charset']) ? $config['charset'] : 'abcdefghkmnprstuvwxyzABCDEFGHKMNPRSTUVWXYZ23456789'; $this->fontsize = isset($config['fontsize']) ? $config['fontsize'] : 20; $this->width = isset($config['width']) ? $config['width'] : ($this->codelen * $this->fontsize * 1.5 + $this->codelen * $this->fontsize / 2); $this->height = isset($config['height']) ? $config['height'] : ($this->fontsize * 2.5); $this->font = FCPATH.'assets/font/Verdana.ttf'; } }<file_sep>/README.md # TouHouDisk A cloud~ <file_sep>/application/controllers/Home.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Home extends MY_Controller{ protected $download_path; protected $create_type; public function __construct() { parent::__construct(); $this->download_path = "D:\\Downloads".DIRECTORY_SEPARATOR; $this->create_type = array('diyidan', 'bcy'); } /*加载主页*/ public function index() { } public function do_ajax(){ header('Access-Control-Allow-Origin:*'); $this->common->StatusCode(210, '访问失败'); } /*退出登录清除session 、cookie*/ public function log_out() { } /*public function download(){ $size = 1024; $flag = 0; for(;;){ $temp = file_get_contents('assets/index.jpg', false, null, $size * $flag, $size); if(!empty($temp)){ file_put_contents('assets/news_img/cache_'.$flag, $temp); $flag++; }else{ break; } } }*/ public function copy(){ $flag = 0; $file = fopen('assets/news_img/index.jpg', 'ab'); for(;;){ if(file_exists('assets/news_img/cache_'.$flag)){ fwrite($file, file_get_contents('assets/news_img/cache_'.$flag)); $flag++; }else{ break; } } } public function file(){ $this->load->library('file_list'); $arr = $this->file_list->file_open_list('F:\Pictures'); $front['w'] = (int)$this->input->get('w'); $front['h'] = (int)$this->input->get('h'); $front['i'] = (int)$this->input->get('i'); $this->load->library('create_image'); if(empty($arr) || !isset($arr[$front['i']])){ $file = FCPATH.DIRECTORY_SEPARATOR.'assets'.DIRECTORY_SEPARATOR.'index.jpg'; }else{ $file = $arr[$front['i']]; } $this->create_image->show_original($file, $front['w'], $front['h']); } public function download(){ set_time_limit(180); $front = $this->input->post(); $arr = array('refer', 'url', 'type', 'coser', 'title', 'name'); $this->check_params($arr, $front); if(!in_array($front['type'], $this->create_type)){ $this->common->StatusCode(210, '站点不正确'); } $front['title'] = $this->strFilter($front['title']); $fileType = mb_detect_encoding($front['title'] , array('UTF-8','GBK','LATIN1','BIG5')); $front['title'] = mb_convert_encoding($front['title'] , 'GBK', $fileType); $fileType = mb_detect_encoding($front['coser'] , array('UTF-8','GBK','LATIN1','BIG5')); $front['coser'] = mb_convert_encoding($front['coser'] , 'GBK', $fileType); $option = array( 'http' => array( 'header' => 'Referer:'.$front['refer'] ) ); $handle = file_get_contents($front['url'], false, stream_context_create($option)); if($handle){ $data = array( 'url' => base_url('uploads/cache/'.$front['name']), 'name' => $front['name'] ); $data = array(); $path = $this->download_path.$front['type'].DIRECTORY_SEPARATOR.$front['coser'].DIRECTORY_SEPARATOR.$front['title'].DIRECTORY_SEPARATOR; if(!file_exists($path)){ @mkdir($path, 0777, true); } $res = file_put_contents($path.$front['name'], $handle); if($res){ $this->common->StatusCode(200, '', '', $data); }else{ $this->common->StatusCode(210, '操作失败'); } }else{ $this->common->StatusCode(210, '操作失败'); } } private function strFilter($str){ $str = str_replace('`', '', $str); $str = str_replace('·', '', $str); $str = str_replace('~', '', $str); $str = str_replace('!', '', $str); $str = str_replace('@', '', $str); $str = str_replace('#', '', $str); $str = str_replace('$', '', $str); $str = str_replace('¥', '', $str); $str = str_replace('%', '', $str); $str = str_replace('^', '', $str); $str = str_replace('……', '', $str); $str = str_replace('&', '', $str); $str = str_replace('*', '', $str); $str = str_replace('(', '', $str); $str = str_replace(')', '', $str); $str = str_replace('(', '', $str); $str = str_replace(')', '', $str); $str = str_replace('-', '', $str); $str = str_replace('_', '', $str); $str = str_replace('——', '', $str); $str = str_replace('+', '', $str); $str = str_replace('=', '', $str); $str = str_replace('|', '', $str); $str = str_replace('\\', '', $str); $str = str_replace(';', '', $str); $str = str_replace(';', '', $str); $str = str_replace(':', '', $str); $str = str_replace(':', '', $str); $str = str_replace('\'', '', $str); $str = str_replace('"', '', $str); $str = str_replace(',', '', $str); $str = str_replace('<', '', $str); $str = str_replace('>', '', $str); $str = str_replace('.', '', $str); $str = str_replace('/', '', $str); $str = str_replace('、', '', $str); $str = str_replace('?', '', $str); return trim($str); } }<file_sep>/application/libraries/Fileupload.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * @func 文件上传类 * * @authors <NAME> (<EMAIL>) * @date 2016-10-13 17:12:40 * @version Ver * * @company http://www.scbbc.cn */ class Fileupload{ /** * [pic_upload 头像上传类] * @param [type] $arr [description] * @param integer $mode [description] * @return [type] [description] * "name": "cngeeker_minilogo.png", "type": "image/png", "tmp_name": "/private/var/tmp/php8NsnBe", "error": "0", "size": "5295" * */ public function avatar_upload($data, $mode = 1) { $common = new Common(); if(isset($data['file'])){ #检查大小 if($data['file']['avatar']['size'] > APP_DEFAULT_SIZE){ $common->StatusCode(210, "上传的图片不能大于".(APP_DEFAULT_SIZE/1024/1024)."Mb!"); exit; } #检查文件类型 $ext = strtolower(trim(substr(strrchr($data['file']['avatar']['name'], '.'), 1))); $allowed = array('jpg', 'png', 'gif', 'jpeg'); $isin = in_array($ext, $allowed); if($isin){ $name = 'avatar_'.time().".".$ext; $dir = FCPATH.'assets/avatar/'.$name; if(move_uploaded_file($data['file']['avatar']['tmp_name'], $dir)) { return $name; } else { //$data = json_encode($_FILES); //echo $data; return false; } }else{ $common->StatusCode(210, "不支持该类型的图片!"); exit; } }else{ return false; } } /** * [file_upload 图片上传类] * @param [type] $arr [description] * @param integer $mode [description] * @return [type] [description] */ public function pic_upload($cname, $tag, $data, $mode = 1) { $common = new Common(); if(isset($data['file'][$cname])){ #检查大小 if($data['file'][$cname]['size'] > APP_DEFAULT_SIZE){ $common->StatusCode(210, "上传的图片不能大于".(APP_DEFAULT_SIZE/1024/1024)."Mb!"); exit; } #检查文件类型 $ext = strtolower(trim(substr(strrchr($data['file'][$cname]['name'], '.'), 1))); $allowed = array('jpg', 'png', 'gif', 'jpeg'); $isin = in_array($ext, $allowed); if($isin){ $name = $tag.'_'.time().".".$ext; $dir = FCPATH.'assets/gallery/'.$tag.'/'.$name; if(move_uploaded_file($data['file'][$cname]['tmp_name'], $dir)) { return 'assets/gallery/'.$tag.'/'.$name; } else { //$data = json_encode($_FILES); //echo $data; return false; } }else{ $common->StatusCode(210, "不支持该类型的图片!"); exit; } }else{ return false; } } /** * [qiniu_upload 七牛上传] * @return [type] [description] */ private function qiniu_upload(){ } /** * 朋友圈文件上传 * @param $cname * @param $tag * @param $data * @param $mid * @return bool|string */ public function picture_upload($cname, $tag, $data, $mid) { $common = new Common(); if(isset($data['file'][$cname])){ #检查大小 if($data['file'][$cname]['size'] > APP_DEFAULT_SIZE){ $common->StatusCode(210, "上传的图片不能大于".(APP_DEFAULT_SIZE/1024/1024)."Mb!"); exit; } #检查文件类型 $ext = strtolower(trim(substr(strrchr($data['file'][$cname]['name'], '.'), 1))); $allowed = array('jpg', 'png', 'gif', 'jpeg'); $isin = in_array($ext, $allowed); if($isin){ $name = $cname.'_'.$mid.'_'.time().".".$ext; $dir = FCPATH.'assets/'.$tag.'/'.$name; if(!file_exists($dir)){ @mkdir($dir, 0777, true); } if(move_uploaded_file($data['file'][$cname]['tmp_name'], $dir.$name)) { return 'assets/'.$tag.'/'.$name; } else { //$data = json_encode($_FILES); //echo $data; return false; } }else{ $common->StatusCode(210, "不支持该类型的图片!"); exit; } }else{ return false; } } /** * 多文件上传{数组形式} * @param $cname * @param $tag * @param $data * @param int $mid [用户id * @return array|bool */ public function more_upload($cname, $tag, $data, $mid = 9527) { $error = array(); $info = array(); if(isset($data['file'][$cname])){ $file = $data['file'][$cname]; if(is_array($file['name'])){ for($i = 0; $i<count($file['name']); $i++){ #检查大小 if($file['size'][$i] > APP_DEFAULT_SIZE){ $this->common->StatusCode(210, "上传的图片不能大于".(APP_DEFAULT_SIZE/1024/1024)."Mb!"); exit; } #检查文件类型 $ext = strtolower(trim(substr(strrchr($file['name'][$i], '.'), 1))); $allowed = array('jpg', 'png', 'gif', 'jpeg'); $isin = in_array($ext, $allowed); if($isin){ $name = $tag.$i.$mid."_".time().".".$ext; $dir = FCPATH.'assets/gallery/'.$tag.'/'.$name; if(move_uploaded_file($file['tmp_name'][$i], $dir)) { $info[] = 'assets/gallery/'.$tag.'/'.$name; continue; } else { $error[] = "第".($i+1)."个文件上传出错"; continue; } }else{ $this->common->StatusCode(210, "不支持该类型的图片!"); exit; } } return array( 'name' => $info, 'error' => $error ); }else{ self::pic_upload($cname, $tag, $data, 1); } }else{ return false; } } } /* End of file Fileupload.php */ /* Location: ./application/controllers/Fileupload.php */<file_sep>/application/controllers/Image.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Image extends MY_Controller { function __construct(){ parent::__construct(); $this->load->library('common'); $this->load->helper('url'); } public function upload(){ header('Access-Control-Allow-Origin:*'); $data = $this->common->PostParamsToArray(); $this->load->library('fileupload'); if(isset($data['file']['file']['size']) && intval($data['file']['file']['size']) > 0){ # 判断图片尺寸 if(intval($data['file']['file']['size']) > 1024*1024*5) { $this->common->statusCode(210, "上传的图片大小不能超过5M"); } # 图片上传 $img =$this->fileupload->picture_upload('file','news_img', $data, (rand(0,9).rand(0,9))); if($img){ $data['file'] = $img; }else{ #上传失败 $this->common->statusCode(210, "上传失败"); } }else{ $this->common->statusCode(210, '请上传图片'); } $this->load->driver('cache'); $list = $this->cache->file->get('img_list'); if(empty($list)){ $list = array(); } $this->cache->file->save('img_list', array(array_merge($list, array($data['file']))), 86400*365); $this->common->statusCode(200, '上传成功'); } public function img_list(){ $this->load->driver('cache'); $list['list'] = $this->cache->file->get('img_list'); if(empty($list['list'])){ $list['list'] = array(); } $this->load->view('img_list', $list); } public function show(){ $front = $this->input->get(); $this->load->library('create_image'); //$this->create_image->show_img('assets/index.jpg', $front['x'], $front['y']); $this->create_image->show('assets/index.jpg'); } public function get_pic_list(){ $this->load->library('create_image'); $img['pic'] = $this->create_image->do_img('assets'.DIRECTORY_SEPARATOR.'index.jpg'); $img['res'] = 'assets'.DIRECTORY_SEPARATOR.'index.jpg'; $this->common->statusCode(200, '', '', $img); } public function get_pic_url(){ $img['url'] = base_url('assets'.DIRECTORY_SEPARATOR.'index.jpg'); $this->common->statusCode(200, '', '', $img); } public function img(){ $front['w'] = (int)$this->input->get('w'); $front['h'] = (int)$this->input->get('h'); $front['i'] = $this->input->get('i'); $this->load->library('create_image'); if($front['i'] == 1){ $file = 'assets'.DIRECTORY_SEPARATOR.'index.jpg'; }else{ $file = 'assets'.DIRECTORY_SEPARATOR.'58431818_p0.jpg'; } $this->create_image->show_original($file, $front['w'], $front['h']); } }<file_sep>/application/libraries/File_list.php <?php class File_list { public $file_list; public $charset; public $change_charset; public $CI; public function __construct(){ $this->charset = 'utf8'; $this->change_charset = false; $this->CI = & get_instance(); } /** * 输出目录下的所有文件 * @param $dir * @param array $file_type * @return array */ public function file_open_list($dir, $file_type = array('jpg', 'jpeg', 'png', 'bmg', 'gif')){ return $this->for_array($this->do_open($dir, $file_type)); } /** * 递归打开文件夹 * @param $dir * @param $file_type * @return array */ private function do_open($dir, $file_type){ $files = array(); $ext_array = $file_type; if(@$handle = opendir($dir)) { //注意这里要加一个@,不然会有warning错误提示:) while(($file = readdir($handle)) !== false) { if($file != ".." && $file != ".") { //排除根目录; if(is_dir($dir.DIRECTORY_SEPARATOR.$file)) { //如果是子文件夹,就进行递归 $temp = $this->do_open($dir.DIRECTORY_SEPARATOR.$file, $file_type); if(!empty($temp)){ $files[] = $this->for_array($temp); } } else { //不然就将文件的名字存入数组; $ext = pathinfo($file, PATHINFO_EXTENSION); if(in_array($ext, $ext_array)){ //$dir=char_to_utf8($dir); //$dir=urlencode($dir); if($this->change_charset){ $files[] = $this->char_to_utf8($dir).DIRECTORY_SEPARATOR.$this->char_to_utf8($file); }else{ $files[] = $dir.DIRECTORY_SEPARATOR.$file; } } } } } closedir($handle); return $files; } } /** * 转换字符集 * @param $data * @return mixed|string */ protected function char_to_utf8($data){ if( !empty($data) ){ $fileType = mb_detect_encoding($data , array('UTF-8','GBK','LATIN1','BIG5')); $data = mb_convert_encoding($data , $this->change_charset, $fileType); } return $data; } /** * 转一维数组 * @param $multi * @return array */ public function for_array($multi){ $arr = array(); foreach ($multi as $key => $val) { if( is_array($val) ) { $arr = array_merge($arr, $this->for_array($val)); } else { $arr[] = $val; } } return $arr; } public function open_dir($dir, $path, $ext_array = array('jpg', 'jpeg', 'png', 'gif', 'bmp')){ $bin_path = 'uploads'.DIRECTORY_SEPARATOR.'link'.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR; $command_file = 'mklink "'; $this->CI->load->model('file_model'); $ext = ''; $md5 = md5($path.$dir.DIRECTORY_SEPARATOR); $name = $md5; $type = 1; $real_name = $this->char_to_utf8($dir); $data = array( 'file_type' => $type, 'filename' => $name, 'ext' => $ext, 'real_name' => $real_name, 'parent_path' => $this->CI->file_model->get_parent(md5($path)), 'create_time' => time() ); $this->CI->file_model->file_insert($data); if(@$handle = opendir($path.$dir)) { //注意这里要加一个@,不然会有warning错误提示:) while(($file = readdir($handle)) !== false) { if($file != ".." && $file != ".") { //排除根目录; if(is_dir($path.$dir.DIRECTORY_SEPARATOR.$file)) { //如果是子文件夹,就进行递归 $this->open_dir($file, $path.$dir.DIRECTORY_SEPARATOR); /*$md5 = md5($path.$dir.DIRECTORY_SEPARATOR.$file); $files[] = array( 'path' => $path.$dir.DIRECTORY_SEPARATOR.$file, 'md5' => $md5, 'name' => $this->char_to_utf8($file), 'type' => 1 );*/ } else { //不然就将文件的名字存入数组; $ext = pathinfo($file, PATHINFO_EXTENSION); if(in_array($ext, $ext_array)){ $md5 = md5_file($path.$dir.DIRECTORY_SEPARATOR.$file); if(!file_exists($bin_path.$md5.'.'.$ext)){ $command = $command_file.FCPATH.$bin_path.$md5.'.'.$ext.'" "'.FCPATH.$path.$dir.DIRECTORY_SEPARATOR.$file.'"'; $output = exec($command); } $name = $md5; $type = 2; $real_name = $this->char_to_utf8($file); $data = array( 'file_type' => $type, 'filename' => $name, 'ext' => $ext, 'real_name' => $real_name, 'parent_path' => $this->CI->file_model->get_parent(md5($path.$dir.DIRECTORY_SEPARATOR)), 'create_time' => time() ); $this->CI->file_model->file_insert($data); } } } } closedir($handle); } return true; } }<file_sep>/application/core/MY_Model.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class MY_Model extends CI_Model{ public function __construct() { parent::__construct(); $this->load->database(); } /** * [is_exist 判断是否存在某数据] * @param [string] $t [表名] * @param [string/array] $w [条件字符串或数组] * @return boolean [是否存在] */ public function is_exist($t, $w) { $this->db->select('count(1) as count'); $this->db->where($w); $this->db->from($t); $query = $this->db->get(); $data = $query->row_array(); if($data['count'] > 0){ return true; }else{ return false; } } /* |-------------------------------------------------------------------------- | single_sel - 单数据查询 |-------------------------------------------------------------------------- | Desc: 查询单条数据 | | @param: $t 表名 | @param: $arr 查询的列名 | @param: $w 条件数组/条件字符串 | @param: $con 0 数组/1 字符串 (可选) | | @return: arr 单数组 */ public function single_sel($t, $arr, $w, $con = 0) { if($arr != ""){ $field_str = implode(",", $arr); $this->db->select($field_str); } if($con == 0){ $query = $this->db->get_where($t, $w, 1, 0); }else{ $this->db->where($w); $this->db->limit(1, 0); $this->db->from($t); $query = $this->db->get(); } return $query->row_array(); } /* |-------------------------------------------------------------------------- | multi_sel - 多数据查询 |-------------------------------------------------------------------------- | Desc: 查询多条数据 | | @param: $t 表名 | @param: $arr 查询列名 | @param: $w 查询条件数组/条件字符串 | @param: $con 0 数组/ 1 字符串 | @param: $limit 条数 | @param: $offset 偏移量 | @param: $order_str 排序 | @return: 多数组或多维数组 */ public function multi_sel($t, $arr, $w, $con = 0, $limit = 5, $offset = 0, $order_str = "") { if($arr != ""){ $field_str = implode(",", $arr); $this->db->select($field_str); //查询字段 } if($order_str != ""){ $this->db->order_by($order_str); //排序 } if($con == 0){ $query = $this->db->get_where($t, $w, $limit, $offset); }else{ $this->db->where($w); $this->db->limit($limit, $offset); $this->db->from($t); $query = $this->db->get(); } return $query->result_array(); } /* |-------------------------------------------------------------------------- | custom_sel - 自定义查询 |-------------------------------------------------------------------------- | Desc: 自定义sql语句查询数据 | | @param $sql sql语句 | @param $model 0-返回单数据/1-返回多数据/2-更新或者删除 | | @return 单条数据/多条数据 */ public function custom_sel($sql, $model = 0) { $query = $this->db->query($sql); switch ($model) { case 0: return $query->row_array(); break; case 1: return $query->result_array(); break; case 2: return $this->db->affected_rows(); break; } } /* |-------------------------------------------------------------------------- | insert - 新增数据 |-------------------------------------------------------------------------- | Desc: 新增数据 | | @param: $arr 插入数据数组 | @param: $ref 是否返回数据插入id | @return 是否成功/新数据id */ public function insert($t, $arr, $ref = 0) { $query = $this->db->insert($t, $arr); if($ref == 0){ return $query; }else{ $back = $this->db->insert_id(); return $back; } } /* |-------------------------------------------------------------------------- | update - 更新数据 |-------------------------------------------------------------------------- | Desc: 更新数据 | | @param $t 表名 | @param $arr 更新数据数组 / 计数中字段 | @param $w 条件数组/条件字符串 | @param $is_calc 是否计数 0 否/ 1 是 (可选参数) | @param $count 增加的数量 (可选参数) | | @return 是否更新成功 */ public function update($t, $arr, $w, $is_calc = 0, $count = 1) { $this->db->where($w); if($is_calc > 0){ if($is_calc == 1){ $this->db->set("$arr", "$arr + $count", FALSE); }else{ $this->db->set("$arr", "$arr - $count", FALSE); } $query = $this->db->update($t); }else{ $query = $this->db->update($t, $arr); } return $query; } /* |-------------------------------------------------------------------------- | delete - 删除数据 |-------------------------------------------------------------------------- | Desc: 删除数据 | | @param $t 表名 | @param $w 条件数组/条件字符串 | | @return 是否删除成功 */ public function delete($t, $w) { $this->db->where($w); $query = $this->db->delete($t); return $query; } /* |-------------------------------------------------------------------------- | result_count - 返回数量 |-------------------------------------------------------------------------- | Desc: 根据条件返回数据数量 | | @param $t 表名 | @param $w 条件 | | @return Name Introduce */ public function result_count($t, $w) { $this->db->where($w); $this->db->from($t); $query = $this->db->count_all_results(); return $query; } /* |-------------------------------------------------------------------------- | get_page_count 获取总页数 |-------------------------------------------------------------------------- | Desc: 根据每页数据条数跟总数得出总页数 | | @param count 总数量 | @param pageSize 每页数量 | | @return 总页数 */ protected function get_page_count($count, $pageSize) { if($count == 0){ return 0; }else{ if($count <= $pageSize){ return 1; }else if($count % $pageSize == 0){ return ($count / $pageSize); }else{ return ((int)($count/$pageSize) + 1); } } } /** * 伪删除 */ protected function flag_delete($t, $w){ $this->db->where($w); $arr = array('is_delete' => 1); $query = $this->db->update($t, $arr); return $query; } } <file_sep>/application/libraries/Common.php <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * 公共辅助类 */ class Common { protected $CI; public function __construct() { $this->CI = & get_instance(); } // ------------------------------------------------------------------------ 接口数据处理块 /** * [PostStringToArray POST获取字符串转Array] * 格式:A=a&B=b */ public function PostStringToArray() { $remoteData = file_get_contents("php://input"); $remote = explode('&',$remoteData); $data = array(); foreach ($remote as $item){ $temp = explode('=',$item); $data[$temp[0]] = $temp[1]; } return $data; } /** * [PostParamsToArray 接口返回$_Post获取Array] * 请求中ContentType 必须为 application/x-www-form-urlencoded */ public function PostParamsToArray() { $data = $_POST; if(!empty($_FILES)){ $data['file'] = $_FILES; } return self::FilterData($data); } /** * [GetParamsToArray 接口返回$_Get获取Array] */ public function GetParamsToArray() { $data = $_GET; return self::FilterData($data); } /** * [GetXmlToArray 微信返回解析] */ public function GetXmlToArray() { $postStr = file_get_contents('php://input'); $msg = (array)simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); return $msg; } /** * [GetIpAddress 获取客户端IP地址] */ public function GetIpAddress() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) { $ip = $_SERVER['HTTP_CLIENT_IP']; } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $ip = $_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip = $_SERVER['REMOTE_ADDR']; } return $ip; } /** * [GetClinetType 获取客户端类型] */ public function GetClinetType() { $clinet = $_SERVER['HTTP_USER_AGENT']; return $clinet; } /** * [GetMobileType 获取访问者请求的手机系统类型] */ public function GetMobileType() { $clinet = $this->CI->input->user_agent(); #CI input类库 log_message('error',"检测:".$clinet); if(strpos($clinet, 'okhttp') >= 0 && strpos($clinet, 'okhttp') !== false){ return 1; #Android }else if(strpos($clinet, 'iOS') >= 0 || strpos($clinet, 'iPhone') >= 0 || strpos($clinet, 'iPad') >= 0){ return 2; #iOS; }else{ return 3; #Other Platform } } // ------------------------------------------------------------------------ 令牌&验证码&订单编号处理块 /** * [GenToken 生成随机Token-方法一] * @param integer $len [长度] * @param boolean $md5 [是否为MD5] * @return [type] [返回token令牌] */ function GenToken( $len = 32, $md5 = true ) { # Seed random number generator # Only needed for PHP versions prior to 4.2 mt_srand( (double)microtime()*1000000 ); # Array of characters, adjust as desired $chars = array( 'Q', '@', '8', 'y', '%', '^', '5', 'Z', '(', 'G', '_', 'O', '`', 'S', '-', 'N', '<', 'D', '{', '}', '[', ']', 'h', ';', 'W', '.', '/', '|', ':', '1', 'E', 'L', '4', '&', '6', '7', '#', '9', 'a', 'A', 'b', 'B', '~', 'C', 'd', '>', 'e', '2', 'f', 'P', 'g', ')', '?', 'H', 'i', 'X', 'U', 'J', 'k', 'r', 'l', '3', 't', 'M', 'n', '=', 'o', '+', 'p', 'F', 'q', '!', 'K', 'R', 's', 'c', 'm', 'T', 'v', 'j', 'u', 'V', 'w', ',', 'x', 'I', '$', 'Y', 'z', '*' ); # Array indice friendly number of chars; $numChars = count($chars) - 1; $token = ''; # Create random token at the specified length for ( $i=0; $i<$len; $i++ ) $token .= $chars[ mt_rand(0, $numChars) ]; # Should token be run through md5? if ( $md5 ) { # Number of 32 char chunks $chunks = ceil( strlen($token) / 32 ); $md5token = ''; # Run each chunk through md5 for ( $i=1; $i<=$chunks; $i++ ) $md5token .= md5( substr($token, $i * 32 - 32, 32) ); # Trim the token $token = substr($md5token, 0, $len); } return $token; } /** * [GenCaptcha 生成随机字符串-验证码] * @param [type] $len [长度] * @param [type] $chars [自定义字符] */ public function GenCaptcha($len = 4, $chars = null) { if (is_null($chars)){ $chars = "abcdefghijklmnopqrstuvwxyz0123456789"; } mt_srand(10000000*(double)microtime()); for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){ $str .= $chars[mt_rand(0, $lc)]; } return $str; } /** * [GenCaptcha 生成随机字符串-验证码] * @param [type] $len [长度] * @param [type] $chars [自定义字符] */ public function GenAdminCaptcha($len = 4, $chars = null) { if (is_null($chars)){ $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; } mt_srand(10000000*(double)microtime()); for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){ $str .= $chars[mt_rand(0, $lc)]; } return $str; } /** * GUID唯一编码 */ function guid() { $charid = strtoupper(md5(uniqid(mt_rand(), true))); $uuid = substr($charid, 0, 8). substr($charid, 8, 4). substr($charid,12, 4). substr($charid,16, 4). substr($charid,20,12); return $uuid; } /** * [buildOrderNo 生成订单编号] * @return [int] [返回订单编号] */ function buildOrderNo($mid = '') { /* 选择一个随机的方案 */ //mt_srand((double) microtime() * 1000000); //return date('Ymd') . uniqid() .str_pad($mid,3,0,STR_PAD_LEFT); return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8); } // ------------------------------------------------------------------------ 数据安全处理块 /** * [FilterData 对数据进行安全过滤] * @param [type] $data [原始数据] */ private function FilterData($data) { $data = $this->CI->security->xss_clean($data); return $data; } /** * [ParamIsNull 判断参数是否为空] * @param [type] $param [参数名] */ public function ParamIsNull($data, $paramName) { if(!isset($data["$paramName"])){ self::StatusCode(300,"缺少参数[".$paramName."]"); exit(); }else{ return $data["$paramName"]; } } // ------------------------------------------------------------------------ 返回码处理块 /** * [StatusCode 返回码说明] * @param integer $code [返回码 必须] * @param string $mark [返回说明 不必须] * @param string $token [令牌 不必须] * @param array $array [返回数据 不必须] */ public function StatusCode($code = 200,$mark = '',$token='',$array = array(), $model = 0) { $data = array(); switch ($code) { # 系统繁忙,请求超时 case 100: # 权限不足 case 403: # 无效接口 case 404: # 服务器内部错误 case 500: $data = array('code' => $code, 'time' => time()); break; # 请求成功|带数组 case 200: if(count($array) != 0){ if($token != ''){ $data = array('code' => $code, 'token' => $token, 'datas' => $array, 'time' => time()); }else{ $data = array('code' => $code, 'datas' => $array, 'time' => time()); } }else{ if($model == 0){ $data = array('code' => $code, 'time' => time()); }else{ $data = array('code' => $code, 'datas' => array(), 'time' => time()); } } break; # token无效 case 220: $mark = "登录状态无效或者已过期!"; $data = array('code' => $code, 'mark' => $mark, 'time' => time()); break; # 存在业务错误,描述 case 210: # 接口参数错误,描述 case 300: $data = array('code' => $code, 'mark' => $mark, 'time' => time()); break; # 默认 default: $data = array('code' => $code, 'time' => time()); break; } header('Access-Control-Allow-Origin:*'); echo json_encode($data, JSON_UNESCAPED_UNICODE); exit(); } // ------------------------------------------------------------------------ 数据分页类 /** * [getOffsetSize 获取分页偏移量] * @param [int] $nowPage [当前页码] * @param [int] $pageSize [当前页数] * @return [int] [分页偏移量] */ public function getOffsetSize($nowPage,$pageSize) { if($nowPage <= 1){ $offSize = 0; }else{ $offSize = $pageSize * ( $nowPage - 1); } return $offSize; } /** 计算两组经纬度坐标 之间的距离 * params :lat1 纬度1; lng1 经度1; lat2 纬度2; lng2 经度2; len_type (1:m or 2:km); * return m or km */ function getDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2) { $EARTH_RADIUS=6378.137; $PI=3.1415926; $radLat1 = $lat1 * $PI / 180.0; $radLat2 = $lat2 * $PI / 180.0; $a = $radLat1 - $radLat2; $b = ($lng1 * $PI / 180.0) - ($lng2 * $PI / 180.0); $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2))); $s = $s * $EARTH_RADIUS; $s = round($s * 1000); if ($len_type > 1) { $s /= 1000; } return round($s,$decimal); } /** * [ParseXml 解析微信XML信息] * @param [字符串] $xml [xml信息] * @return [array] 数组 */ public function ParseXml($xml) { $data = (array)simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA); return $data; } /** * [CovertXml 把数组转XML] * @param [type] $data [description] */ public function CovertXml($data) { $xml = "<?xml version='1.0' encoding='utf-8'?><xml>"; foreach($data as $key=>$value){ $xml = $xml."<$key>$value</$key>"; } $xml = $xml."</xml>"; return $xml; } /** * [encrypto 对字符串进行正序排序后sha1加密] * @param [string] $str [来源字符串] * @return [string] [加密字符串] */ public function encrypto($str) { $str = $str."gxssh2016"; $arr=str_split($str);//提取出字符,放入数组 usort($arr,'strcmp');//对字符数组进行排序 $str=implode('',$arr);//形成排序后的字符串 return sha1($str); //sha1加密 } // ------------------------------------------------------------------------ 短信接口 protected function Post($data, $target) { $url_info = parse_url($target); $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n"; $httpheader .= "Host:" . $url_info['host'] . "\r\n"; $httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n"; $httpheader .= "Content-Length:" . strlen($data) . "\r\n"; $httpheader .= "Connection:close\r\n\r\n"; //$httpheader .= "Connection:Keep-Alive\r\n\r\n"; $httpheader .= $data; $fd = fsockopen($url_info['host'], 80); fwrite($fd, $httpheader); $gets = ""; while(!feof($fd)) { $gets .= fread($fd, 128); } fclose($fd); return $gets; } /** * [send_sms 短信验证码] * @param [type] $phone [手机号码] * @param integer $type [短信用途] * @return [type] [返回是否成功] */ public function send_sms($phone, $type = 1, $nickname = "", $orderSN = "", $expressName = "") { $smsCode = rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9).rand(0,9); switch ($type) { # 注册 case 1: $content = "【".APP_SMS_NAME."】"."您好,您此次验证码为".$smsCode.",请您尽快注册。验证码有效时间为".EX_TIME."分钟。"; break; # 登录 case 2: $content = "【".APP_SMS_NAME."】"."您好,您此次验证码为".$smsCode.",请您尽快登录。验证码有效时间为".EX_TIME."分钟。"; break; # 忘记密码 case 3: $content = "【".APP_SMS_NAME."】"."您好,您此次验证码为".$smsCode.",请您尽快验证修改密码。验证码有效时间为".EX_TIME."分钟。"; break; # 更换手机号 case 4: $content = "【".APP_SMS_NAME."】"."您好,您此次验证码为".$smsCode.",请您尽快更改手机号。验证码有效时间为".EX_TIME."分钟。"; break; # 支付密码 case 5: $content = "【".APP_SMS_NAME."】"."您好,您此次验证码为".$smsCode.",请您尽快验证修改支付密码。验证码有效时间为".EX_TIME."分钟。"; break; # 绑定手机号 case 6: $content = "【".APP_SMS_NAME."】"."您好,您此次验证码为".$smsCode.",请您尽快绑定手机号。验证码有效时间为".EX_TIME."分钟。"; break; default: self::StatusCode(210, "暂无该类型短信验证!"); break; } // $target = "http://dc.28inter.com/sms.aspx"; // //替换成自己的测试账号,参数顺序和wenservice对应 // $post_data = "action=send&userid=&account=myapcr&password=<PASSWORD>&mobile=$phone&sendTime=&content=".rawurlencode("$content"); // //$binarydata = pack("A", $post_data); // $gets = self::Post($post_data, $target); // $start = strpos($gets,"<?xml"); // $data = substr($gets,$start); // $xml = simplexml_load_string($data); // var_dump(json_decode(json_encode($xml),TRUE)); //请自己解析$gets字符串并实现自己的逻辑 //<State>0</State>表示成功,其它的参考文档 $post_data = array(); $post_data['userid'] = SMS_ID; $post_data['account'] = SMS_ACCOUNT; $post_data['password'] = <PASSWORD>; $post_data['mobile'] = "$phone"; $sendTime = date("Y-m-d H:i:s"); $post_data['sendtime'] ='';//sendTime; //中文需要转换为UTF8编码格式提交 $post_data['content'] = $content;//iconv('GB2312', 'UTF-8', '$content'); $url='http://dc.28inter.com/sms.aspx?action=send'; $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里,那加上这句。 $result = curl_exec($ch); //$data = explode(" ",$result); $data = (array)simplexml_load_string($result, 'SimpleXMLElement', LIBXML_NOCDATA); if($data['returnstatus'] == "Success" && $data['message'] == "ok"){ $microtime = strtotime($sendTime); $sms = array( 'phone' => $phone, 'type' => $type, 'sms_code' => $smsCode, 'send_time' => $microtime, 'expire_time' => ($microtime + (EX_TIME * 60)) ); return $sms; }else{ self::StatusCode(210, $data['message']); } } /** * [verifySMS 校验短信] * @param [string] [手机号码] * @param [string] [手机验证码] * * @return [type] [返回验证信息] */ public function verifySMS($toPhone, $smsCode, $type) { $arr = $this->CI->session->tempdata(); log_message('error',"校验短信:".json_encode($arr)); $phone = $this->CI->session->tempdata('phone'); #接受短信的手机号 $useMethod = $this->CI->session->tempdata('type'); #短信用途 $sms = $this->CI->session->tempdata('sms_code'); #验证码 $time = $this->CI->session->tempdata('expire_time'); #过期时间 if($toPhone == $phone && $smsCode == $sms && time() <= $time && $type == $useMethod){ return true; }else{ return false; } } }
647f32488694d3029c7c7993046376bbfa1996e7
[ "Markdown", "PHP" ]
13
PHP
hentaiRin/TouHouDisk
fb5c875c1141bdfe2fe2c95c2f0a86555b3067ba
2a6ede1c3e358cb46c919c134875b88978e2378c
refs/heads/master
<repo_name>ig92/cp-course<file_sep>/44-queue/queue.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Person { string name; int infront; int height; }; int main() { std::ios_base::sync_with_stdio(false); // read input data int n; cin >> n; vector<Person> people (n); for (int i = 0; i < n; ++i) cin >> people[i].name >> people[i].infront; // sort sort(people.begin(), people.end(), [](Person a, Person b) {return a.infront < b.infront;}); // check if impossible for (int i = 0; i < n; ++i) { if (i < people[i].infront) { cout << "-1" << endl; return 0; } } // restore the original order vector<int> h (n); for (int i = 0; i < n; ++i) h.insert(h.begin() + i - people[i].infront, i); // assign heights for (int i = 0; i < n; ++i) people[h[i]].height = i + 1; // height must be > 0 // print for (int i = 0; i < n; ++i) cout << people[i].name << " " << people[i].height << endl; return 0; } <file_sep>/31-is-bipartite/bipartite.cpp #define NO_COLOR 0 #define WHITE 1 #define BLACK 2 int color_tree(int i, int current_color, int next_color, vector<int> nodes, int G[][MAX], int n) { nodes[i] = current_color; for (int j = 0; j < n; j++) // consider only my neighborhood if (G[i][j] == 1) // if my neighbour has my color or it does not have any color but recursively we fail to color if ((nodes[j] == NO_COLOR && !color_tree(j, next_color, current_color, nodes, G, n)) || (nodes[j] == current_color)) return false; return true; } bool isBipartite(int G[][MAX], int n) { vector<int> nodes (n); for (int i = 0; i < n; i++) if (nodes[i] == NO_COLOR) if (!color_tree(i, WHITE, BLACK, nodes, G, n)) return false; return true; } <file_sep>/05-sliding-window/sliding.cpp #include <iostream> #include <vector> #include <deque> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } deque<int> q; int maximum = -1; void updateQueue(vector<int> * numbers, int i) { if (q.empty()) { q.push_front(i); } if (numbers->at(i) >= numbers->at(q.front())) { q.clear(); q.push_front(i); maximum = i; } else { while (!q.empty() && (numbers->at(i) >= numbers->at(q.back()))) q.pop_back(); q.push_back(i); maximum = q.front(); } } void print_k_maximums(vector<int> * numbers, int n, int k) { q.clear(); // O(k) for (int i = 0; i < k; ++i) updateQueue(numbers, i); cout << numbers->at(maximum) << " "; // O(n-k) for (int i = k; i < n; ++i) { // if the max is no more in the window if (((i - k) + 1) > maximum) q.pop_front(); updateQueue(numbers, i); cout << numbers->at(maximum) << " "; } cout << endl; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n, k; cin >> n >> k; vector<int> numbers = get_input_sequence<int>(n); print_k_maximums(&numbers, n, k); } return 0; }<file_sep>/18-ilya-queries/ilya.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { std::ios_base::sync_with_stdio(false); string sequence; getline(cin, sequence); vector<int> v (sequence.length()); for (int i = 0; i < sequence.length() - 1; ++i) v[i] = (sequence[i] == sequence[i+1]) ? 1 : 0; // exclusive prefix sum int tmp = v[0]; v[0] = 0; for (int i = 1; i < sequence.length(); ++i) { int t = v[i]; v[i] = v[i-1] + tmp; tmp = t; } int n; cin >> n; for (int i = 0; i < n; ++i) { int l, r; cin >> l; cin >> r; cout << v[r-1] - v[l-1] << endl; } return 0; }<file_sep>/07-towers/towers.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int height [1001]; int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); for (int i = 0; i < n; ++i) height[numbers[i]]++; int maxHeight = 0; int counter = 0; for (int i = 0; i < 1001; ++i) { maxHeight = max(maxHeight, height[i]); if (height[i] > 0) counter++; } cout << maxHeight << " " << counter << endl; return 0; }<file_sep>/03-missing-number/missing.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> vect = get_input_sequence<int>(n-1); int gauss = (n * n + n) >> 1; for (int i = 0; i < n-1; ++i) gauss -= vect.at(i); cout << gauss << endl; } return 0; }<file_sep>/33-learning-languages/languages.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; #define WHITE 0 #define BLACK 1 template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int G[100][100]; void dfs(int i, vector<int> * nodes) { if (nodes->at(i) == BLACK) return; nodes->at(i) = BLACK; for (int j = 0; j < nodes->size(); j++) if (G[i][j] == 1) dfs(j, nodes); } int main() { std::ios_base::sync_with_stdio(false); int n, m; cin >> n >> m; vector<int> langs (m, -1); for (int i = 0; i < n; i++) { int nIthLangs; cin >> nIthLangs; vector<int> ithLangs = get_input_sequence<int>(nIthLangs); for (int j = 0; j < nIthLangs; j++) { // if i is the first one in order to speak this language if (langs[ithLangs[j]-1] == -1) { langs[ithLangs[j]-1] = i; } else { int k = langs[ithLangs[j]-1]; // who talks this language G[i][k] = G[k][i] = 1; } } } // special case when no one speak a language // langs is initialized with -1, that's why -m int sum = 0; for (int i = 0; i < m; i++) sum += langs[i]; if (sum == -m) { cout << n << endl; return 0; } vector<int> vertices (n, WHITE); int counter = 0; for (int i = 0; i < vertices.size(); i++) { if (vertices[i] == WHITE) { counter++; dfs(i, &vertices); } } cout << counter-1 << endl; return 0; }<file_sep>/51-lbs/lbs.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int lis(vector<int> numbers, vector<int> * M, int n) { if (n == 0) return 0; int m = -1; for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) if (numbers[j] < numbers[i]) M->at(i) = max(M->at(i), 1 + M->at(j)); m = max(m, M->at(i)); } return m; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); vector<int> inc (n,1); lis(numbers, &inc, n); reverse(numbers.begin(), numbers.end()); vector<int> dec (n,1); lis(numbers, &dec, n); int max = -1; for (int i = 0; i < n; ++i) if (max < inc[i]+dec[n-i-1]-1) max = inc[i]+dec[n-i-1]-1; cout << max << endl; } return 0; }<file_sep>/58-distinct-subs/distinct.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Suffix { int index; int rank; int nextRank; }; int cmp(Suffix a, Suffix b) { // if the ranks are equal, compare next ranks if (a.rank == b.rank) return a.nextRank < b.nextRank; return a.rank < b.rank; } // O(n logn logn) solution vector<int> buildSuffixArray(string s, int n) { // A structure to store suffixes and their indexes Suffix suffixes[n]; for (int i = 0; i < n; i++) { suffixes[i].index = i; suffixes[i].rank = s[i] - 'A'; suffixes[i].nextRank = -1; if (i < n-1) suffixes[i].nextRank = (s[i+1] - 'A'); } // sort suffixes sort(suffixes, suffixes + n, cmp); int inv[n]; for (int k = 4; k < n; k *= 2) { int rank = 0; int prevRank = suffixes[0].rank; suffixes[0].rank = rank; inv[suffixes[0].index] = 0; // update rank for (int i = 1; i < n; ++i) { if (suffixes[i].rank != prevRank || suffixes[i].nextRank != suffixes[i-1].nextRank) rank++; prevRank = suffixes[i].rank; suffixes[i].rank = rank; inv[suffixes[i].index] = i; } // update nextRank for (int i = 0; i < n; ++i) { int nextIndex = suffixes[i].index + k / 2; suffixes[i].nextRank = -1; if (nextIndex < n) suffixes[i].nextRank = suffixes[inv[nextIndex]].rank; } // sort suffixes sort(suffixes, suffixes + n, cmp); } // build suffix array vector<int> suffixArr; for (int i = 0; i < n; ++i) suffixArr.push_back(suffixes[i].index); return suffixArr; } vector<int> buildLCP(string s, vector<int> suffixArr) { int n = suffixArr.size(); vector<int> lcp(n, 0); // build inverted index int inv[n]; for (int i = 0; i < n; ++i) inv[suffixArr[i]] = i; int k = 0; for (int i = 0; i < n; ++i) { if (inv[i] == n-1) { k = 0; continue; } // next substring in sorted suffixArr int j = suffixArr[inv[i]+1]; // match from kth index on while (i + k < n && j + k < n && s[i+k] == s[j+k]) k++; lcp[inv[i]] = k; if (k > 0) k--; } return lcp; } int countSubstrings(string s) { int n = s.length(); // build suffix array and lcp array vector<int> suffixArr = buildSuffixArray(s, n); vector<int> lcp = buildLCP(s, suffixArr); int result = n * n; // int sum = (n * n - n) / 2; int sum = 0; for (int i = 0; i < n; i++) sum += i; result -= sum; for (int i = 0; i < n-1; i++) result -= lcp[i]; return result; } int main() { int t; cin >> t; cin.ignore(); int ans[t]; while (t-- > 0) { string s; cin >> s; cin.ignore(); ans[t] = countSubstrings(s); } for (int i = sizeof(ans) / sizeof(int) - 1; i > -1 ; --i) { cout << ans[i] << endl; } return 0; } <file_sep>/47-01knapsack/01knapsack.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int knapsack(vector<int> wgt, vector<int> val, int n, int w) { int M [n+1][w+1]; // init for (int i = 0; i <= n; ++i) M[i][0] = 0; for (int i = 0; i <= w; ++i) M[0][i] = 0; for (int i = 1; i <= n; ++i) for (int j = 1; j <= w; ++j) M[i][j] = (wgt[i-1] <= j) ? max(M[i-1][j-wgt[i-1]] + val[i-1], M[i-1][j]) : M[i-1][j]; return M[n][w]; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n, w; cin >> n >> w; vector<int> val = get_input_sequence<int>(n); vector<int> wgt = get_input_sequence<int>(n); cout << knapsack(wgt,val,n,w) << endl; } return 0; } <file_sep>/30-x-shapes/xshapes.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; #define WHITE 0 #define BLACK 2 template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } struct Node { int i; int j; int color; }; int dfs(int i, vector<Node> * nodes, int m, int n) { nodes->at(i).color = BLACK; vector<int> neighbors; if (i - m > 0) neighbors.push_back(i-m); if (i + m < m * n) neighbors.push_back(i+m); if (i % m > 0) neighbors.push_back(i-1); if (i % m < m-1) neighbors.push_back(i+1); for (int j = 0; j < neighbors.size(); j++) { int k = neighbors[j]; if (nodes->at(k).color == WHITE) dfs(k, nodes, m, n); } return 1; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n, m; cin >> n >> m; vector<Node> nodes(m * n); for (int i = 0; i < n; i++) { vector<char> line = get_input_sequence<char>(m); for (int j = 0; j < m; j++) { nodes[i*m+j].i = i; nodes[i*m+j].j = j; nodes[i*m+j].color = (line[j] == 'O') ? BLACK : WHITE; } } int counter = 0; for (int i = 0; i < n * m; i++) if (nodes[i].color == WHITE) counter += dfs(i, &nodes, m, n); cout << counter << endl; } return 0; }<file_sep>/26-trees-queries/treequeries.cpp #include <iostream> #include <vector> #include <algorithm> #include <math.h> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } #define MAX 100001 int table[MAX]; int particularColor[MAX]; int counter[MAX]; struct Query { int id; int i; int j; int k; }; struct Node { int id; int color; int i; int j; bool visited; vector<Node*> children; }; Node nodes[MAX]; int start = 0; int s[MAX]; void traverse(Node * root) { if (root->visited) return; root->visited = true; root->i = start++; s[root->i] = root->id; for (int i = 0; i < root->children.size(); ++i) traverse(root->children[i]); root->j = start-1; } void add(int i) { int color = nodes[s[i]].color; particularColor[color]++; counter[particularColor[color]]++; } void remove(int i) { int color = nodes[s[i]].color; counter[particularColor[color]]--; particularColor[color]--; } int main() { std::ios_base::sync_with_stdio(false); int n, m; cin >> n >> m; // read colors vector<int> colors = get_input_sequence<int>(n); for (int i = 0; i < n; i++) { nodes[i].color = colors[i]; nodes[i].id = i; nodes[i].visited = false; } // read edges for (int i = 0; i < n-1; ++i) { int u, v; cin >> u >> v; nodes[u-1].children.push_back(&nodes[v-1]); nodes[v-1].children.push_back(&nodes[u-1]); } traverse(&nodes[0]); // read queries vector<Query> queries(m); for (int i = 0; i < m; ++i) { int node; cin >> node >> queries[i].k; queries[i].id = i; queries[i].i = nodes[node-1].i; queries[i].j = nodes[node-1].j; } // mo's order int p = sqrt(n); sort(queries.begin(), queries.end(), [p](Query a, Query b) { if (a.i / p == b.i / p) return a.j < b.j; return a.i < b.i; }); int current_i = 0; int current_j = 0; add(0); int answer[m]; for (int i = 0; i < m; ++i) { Query q = queries[i]; while (current_i < q.i) { remove(current_i++); } while (current_i > q.i) { add(--current_i); } while (current_j < q.j) { add(++current_j); } while (current_j > q.j) { remove(current_j--); } answer[q.id] = counter[q.k]; } for (int i = 0; i < m; ++i) cout << answer[i] << endl; return 0; }<file_sep>/36-chain-food/chainfood.cpp #include <iostream> #define MAX 50001 using namespace std; int P[MAX], S[MAX]; int find(int x) { if (x == P[x]) return x; int tmp = P[x]; P[x] = find(P[x]); S[x] += S[tmp]; return P[x]; } int mod3(int x) { int remainder = x % 3; if (remainder < 0) remainder += 3; return remainder; } int main() { int t; cin >> t; while (t-- > 0) { int n, k; cin >> n >> k; for (int i = 1; i <= n; i++) { P[i] = i; S[i] = 0; } int counter = 0; while (k-- > 0) { int type, x, y; cin >> type >> x >> y; if (x > n || y > n) { counter++; continue; } int rx = find(x); int ry = find(y); type--; if (rx == ry) { if (mod3(type + S[y] - S[x]) != 0) counter++; } else { // otherwise, whatever is the type // we need to connect the two sets // with some relation P[rx] = ry; int i = mod3(type + S[y] - S[x]); if (i == 0) i = 3; S[rx] = i; } } cout << counter << endl; } return 0; }<file_sep>/40-wilbur-array/wilbur.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); uint64_t counter = 0; int64_t acc = 0; for (int i = 0; i < n; ++i) { counter += abs(numbers[i]-acc); acc += numbers[i]-acc; } cout << counter << endl; return 0; }<file_sep>/12-inversion-count/invcount.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } uint64_t count_inversions(vector<int> * numbers, uint64_t lb, uint64_t ub) { // base case if (ub - lb + 1 < 2) return 0; // divide uint64_t m = (ub + lb) / 2; uint64_t lftCount = count_inversions(numbers, lb, m); uint64_t rgtCount = count_inversions(numbers, m + 1, ub); // conquer uint64_t mrgCount = 0; vector<int> tmp (ub-lb+1); int u = m + 1; int l = lb; int i = 0; while (l <= m && u <= ub) { if ((*numbers)[l] > (*numbers)[u]) tmp[i++] = (*numbers)[u++]; else { tmp[i++] = (*numbers)[l++]; mrgCount += u-1-m; } } // count the rest if any while (l <= m) { tmp[i++] = (*numbers)[l++]; mrgCount += ub-m; } // copy the rest while (u <= ub) tmp[i++] = (*numbers)[u++]; // copy back to numbers for (int i = lb; i <= ub; ++i) (*numbers)[i] = tmp[i-lb]; return lftCount + rgtCount + mrgCount; } int main(int argc, char const *argv[]) { std::ios_base::sync_with_stdio(false); uint64_t t; cin >> t; while (t-- > 0) { uint64_t n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); cout << count_inversions(&numbers, 0, n-1) << endl; } return 0; } <file_sep>/23-nested-segments/nested.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; struct Segment { int64_t id; int64_t i; int64_t j; }; int A [200000]; int SIZE; int answer[200000]; void add(int64_t i, int64_t qty) { if (i < 1 || i >= SIZE) return; while (i < SIZE) { A[i] += qty; i += i & (-i); } } int64_t sum(int64_t i) { if (i < 1 || i >= SIZE) return 0; int64_t sum = 0; while (i > 0) { sum += A[i]; i -= i & (-i); } return sum; } int main() { std::ios_base::sync_with_stdio(false); int64_t n; cin >> n; vector<Segment> segments (n); for (int64_t id = 0; id < n; ++id) { segments[id].id = id; cin >> segments[id].i >> segments[id].j; } // make all ends positive so we can use it in BIT O(nlogn) sort(segments.begin(), segments.end(), [](Segment a, Segment b) {return a.j < b.j;}); for (int i = 0; i < n; ++i) segments[i].j = i+1; // sort according to starts in descending order sort(segments.begin(), segments.end(), [](Segment a, Segment b) {return a.i > b.i;}); SIZE = n + 1; for (int64_t i = 0; i < n; ++i) { Segment * s = &segments[i]; answer[segments[i].id]= sum(s->j); add(s->j, 1); } for (int64_t i = 0; i < n; ++i) cout << answer[i] << endl; return 0; }<file_sep>/09-megacity/megacity.cpp #include <iostream> #include <vector> #include <algorithm> #include <math.h> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } struct City { double distance = 0; int population = 0; }; int main() { std::ios_base::sync_with_stdio(false); int n, s; cin >> n; cin >> s; // get cities vector<City> cities (n); for (int i = 0; i < n; ++i) { vector<int> data = get_input_sequence<int>(3); cities[i].distance = sqrt(pow(data[0],2) + pow(data[1],2)); cities[i].population = data[2]; } sort(cities.begin(), cities.end(), [](City a, City b) {return a.distance <= b.distance;}); double radius = 0; for (int i = 0; i < n; ++i) { if (s >= 1000000) break; radius = cities[i].distance; s += cities[i].population; } cout.precision(8); if (s < 1000000) { cout << -1 << endl; } else { cout << radius << endl; } return 0; }<file_sep>/29-circular-rmq/circular.cpp #include <vector> #include <iostream> #include <sstream> #include <math.h> #define lft(i) (2*i+1) #define rgt(i) (2*i+2) #define par(i) ((i-1)/2) using namespace std; uint64_t n; int64_t seg_tree[550000]; int64_t lazy[550000]; void build(vector<int64_t> * array, uint64_t low, uint64_t high, uint64_t pos) { if (low == high) { seg_tree[pos] = array->at(low); lazy[pos] = 0; return; } uint64_t mid = (low + high) / 2; build(array, low, mid, lft(pos)); build(array, mid+1, high, rgt(pos)); seg_tree[pos] = min(seg_tree[lft(pos)], seg_tree[rgt(pos)]); lazy[pos] = 0; } int64_t rec_rmq(uint64_t qlow, uint64_t qhigh, uint64_t low, uint64_t high, uint64_t pos) { if (lazy[pos] != 0) { seg_tree[pos] += lazy[pos]; if (low != high) { lazy[lft(pos)] += lazy[pos]; lazy[rgt(pos)] += lazy[pos]; } lazy[pos] = 0; } // total overlap if (qlow <= low && qhigh >= high) return seg_tree[pos]; // no overlap if (qlow > high || qhigh < low) return INT_MAX; uint64_t mid = (low + high) / 2; return min( rec_rmq(qlow, qhigh, low, mid, lft(pos)), rec_rmq(qlow, qhigh, mid+1, high, rgt(pos)) ); } void rec_inc(uint64_t qlow, uint64_t qhigh, uint64_t low, uint64_t high, uint64_t pos, int64_t qty) { if (lazy[pos] != 0) { seg_tree[pos] += lazy[pos]; if (low != high) { lazy[lft(pos)] += lazy[pos]; lazy[rgt(pos)] += lazy[pos]; } lazy[pos] = 0; } // total overlap if (qlow <= low && qhigh >= high) { seg_tree[pos] += qty; if (low != high) { lazy[lft(pos)] += qty; lazy[rgt(pos)] += qty; } return; } // no overlap if (qlow > high || qhigh < low) return; uint64_t mid = (low + high) / 2; rec_inc(qlow, qhigh, low, mid, lft(pos), qty); rec_inc(qlow, qhigh, mid+1, high, rgt(pos), qty); seg_tree[pos] = min(seg_tree[lft(pos)], seg_tree[rgt(pos)]); } void inc(uint64_t i, uint64_t j, int64_t qty) { if (i <= j) { rec_inc(i, j, 0, n-1, 0, qty); } else { // two ranges rec_inc(i, n-1, 0, n-1, 0, qty); rec_inc(0, j, 0, n-1, 0, qty); } } int64_t rmq(uint64_t i, uint64_t j) { if (i <= j) return rec_rmq(i, j, 0, n-1, 0); return min( rec_rmq(i, n-1, 0, n-1, 0), rec_rmq(0, j, 0, n-1, 0) ); } template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); cin >> n; vector<int64_t> numbers = get_input_sequence<int64_t>(n); build(&numbers, 0, n-1, 0); int m; cin >> m; cin.ignore(); for (int i = 0; i < m; ++i) { vector<int> numbers (3); // line string line; getline(cin, line); stringstream ss (line); // take numbers int n = 0; string number; while (getline(ss, number, ' ')) numbers[n++] = stoi(number); // execute opearation if (n == 2) { // query cout << rmq(numbers[0], numbers[1]) << endl; } else { // update inc(numbers[0], numbers[1], numbers[2]); } } }<file_sep>/14-firing-employees/firings.cpp #include <iostream> #include <vector> #include <math.h> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } struct Node { int rank; int parent; vector<int> children; int depth; }; bool is_prime(int num) { // simple cases if (num < 2 || (num > 2 && num % 2 == 0)) return false; else if (num==2) return true; // test it for (int i = 2; i <= sqrt(num); ++i) if((num % i) == 0) return false; return true; } int compute_n_black_list(vector<Node> * nodes, Node * node, int depth) { int counter = 0; node->depth = depth; if (node->depth != 0 && is_prime(node->depth + node->rank)) { counter++; } for (int i = 0; i < node->children.size(); ++i) { int child = node->children.at(i); Node next = nodes->at(child); counter += compute_n_black_list(nodes, &next, depth + 1); } return counter; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; Node * root; vector<Node> nodes (n); vector<int> numbers = get_input_sequence<int>(n); for (int j = 0; j < n; ++j) { nodes[j].rank = j+1; nodes[j].parent = numbers[j]; if (numbers[j] == 0) { root = &nodes[j]; } else { nodes[numbers[j]-1].children.emplace_back(j); } } cout << compute_n_black_list(&nodes, root, 0) << endl; } return 0; }<file_sep>/02-kadane/kadane.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); int current = numbers[0]; int best = numbers[0]; for (int j = 1; j < n; ++j) { current = max(numbers[j], numbers[j] + current); best = max(best, current); } cout << best << endl; } }<file_sep>/39-magic-number/magicnumber.cpp #include <iostream> #include <vector> using namespace std; string is_magic(string number) { if (number.length() == 0) return "YES"; int n = number.length(); if (number[n-1] == '1') return is_magic(number.substr(0, n-1)); if (number[n-2] == '1' && number[n-1] == '4') return is_magic(number.substr(0, n-2)); if (number[n-3] == '1' && number[n-2] == '4' && number[n-1] == '4') return is_magic(number.substr(0, n-3)); return "NO"; } int main() { std::ios_base::sync_with_stdio(false); string number; getline(cin, number); cout << is_magic(number) << endl; return 0; }<file_sep>/11-two-heaps/heaps.cpp #include <iostream> #include <vector> #include <algorithm> #include <queue> #include <math.h> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } struct Number { int id; int value; }; bool heap[201]; int main() { std::ios_base::sync_with_stdio(false); uint64_t n; cin >> n; vector<int> values = get_input_sequence<int>(2 * n); vector<Number> numbers (2 * n); for (int i = 0; i < 2 * n; ++i) { Number number; number.value = values[i]; number.id = i; numbers[i] = number; } // sort according to numbers values sort(numbers.begin(), numbers.end(), [](Number a, Number b) {return a.value < b.value;}); // first heap assignment int c1 = 1; int c2 = 1; queue<int> repeated; int heapID = false; heap[numbers[0].id] = false; heap[numbers[1].id] = true; for (int i = 2; i < 2 * n; ++i) { if (numbers[i].value == numbers[i-2].value) { repeated.push(numbers[i].id); continue; } if (heapID) c1++; else c2++; heap[numbers[i].id] = heapID; heapID = !heapID; } cout << c1 * c2 << endl; // second heap assignment while (!repeated.empty()) { heap[repeated.front()] = heapID; heapID = !heapID; repeated.pop(); } for (int i = 0; i < 2 * n; ++i) cout << (heap[i] ? 2 : 1) << " "; cout << endl; }<file_sep>/10-find-pair/pairs.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); uint64_t n, k; cin >> n; cin >> k; vector<int> numbers = get_input_sequence<int>(n); sort(numbers.begin(), numbers.end()); uint64_t i = (k-1) / n; uint64_t l = 0; for (; l < n; l++) if (numbers[l] == numbers[i]) break; uint64_t r = count(numbers.begin(), numbers.end(), numbers[i]); uint64_t j = ((k-1) - (l * n)) / r; cout << numbers[i] << " " << numbers[j] << endl; }<file_sep>/22-update-array/update.cpp #include <iostream> #include <vector> using namespace std; int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n, u; cin >> n >> u; // process updates vector<int64_t> v (n); for (int j = 0; j < u; ++j) { int l, r, val; cin >> l >> r >> val; v[l] += val; if (r < n-1) v[r+1] -= val; } // inclusive prefix sum for (int j = 1; j < n; ++j) v[j] += v[j-1]; // process queries int q; cin >> q; while (q-- > 0) { int j; cin >> j; cout << v[j] << " "; } cout << endl; } return 0; }<file_sep>/43-woodcutters/woodcutters.cpp #include <iostream> #include <vector> using namespace std; #define LEFT 0 #define RIGHT 1 struct Tree { int pos; // position int hgt; // height bool cut; int side; }; int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; vector<Tree> trees (n); for (int i = 0; i < n; ++i) cin >> trees[i].pos >> trees[i].hgt; int counter = 0; for (int i = 0; i < n; ++i) { // special cases if (i == 0 || i == n-1) { trees[i].cut = true; trees[i].side = (i == 0) ? LEFT : RIGHT; counter++; continue; } if (trees[i-1].pos < trees[i].pos - trees[i].hgt) { if (trees[i-1].side == LEFT || !trees[i-1].cut || ((trees[i-1].pos + trees[i-1].hgt) < (trees[i].pos - trees[i].hgt))) { trees[i].cut = true; trees[i].side = LEFT; counter++; continue; } } if (trees[i+1].pos > trees[i].pos + trees[i].hgt) { trees[i].cut = true; trees[i].side = RIGHT; counter++; continue; } } cout << counter << endl; return 0; }<file_sep>/42-lex-max-subsequence/lexmax.cpp #include <iostream> #include <deque> using namespace std; int main() { std::ios_base::sync_with_stdio(false); string sequence; getline(cin, sequence); deque<char> letters; for (int i = 0; i < sequence.length(); ++i) { while (!letters.empty() && letters.front() < sequence[i]) letters.pop_front(); letters.push_front(sequence[i]); } while (!letters.empty()) { cout << letters.back(); letters.pop_back(); } cout << endl; return 0; }<file_sep>/48-longest-increasing-subsequence/lis.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int lis(vector<int> numbers, int n) { if (n == 0) return 0; vector<int> M (n,1); int m = -1; for (int i = 1; i < n; ++i) { for (int j = 0; j < i; ++j) if (numbers[j] < numbers[i]) M[i] = max(M[i], 1 + M[j]); m = max(m, M[i]); } return m; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); cout << lis(numbers, n) << endl; } return 0; }<file_sep>/20-3-ways/3ways.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; vector<int64_t> numbers = get_input_sequence<int64_t>(n); int64_t sum = 0; for (int i = 0; i < n; ++i) { sum += numbers[i]; } if (n < 3 || sum % 3 != 0) { cout << 0 << endl; return 0; } sum = sum / 3; // compute number of suffixes that sum to target value vector<int64_t> n_suffs (n); int64_t acc = 0; uint64_t counter = 0; for (int i = n-1; i > -1; --i) { n_suffs[i] = (numbers[i] + acc == sum) ? ++counter : counter; acc += numbers[i]; } // computer the three ways acc = 0; counter = 0; for (int i = 0; i < n-2; ++i) { counter = (numbers[i] + acc == sum) ? n_suffs[i+2]+counter : counter; acc += numbers[i]; } cout << counter << endl; return 0; }<file_sep>/54-longest-palindromic-sequence/lps.cpp #include <iostream> #include <vector> using namespace std; int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; cin.ignore(); while (t-- > 0) { string str; getline(cin, str); int n = str.length(); int M [n+1][n+1]; for (int i = 0; i <= n; ++i) { for (int j = 0; j <= n; ++j) M[i][j] = -1; M[i][i] = 1; if (i > 0) M[i][i-1] = 0; } for (int i = n-1; i > 0; --i) { for (int j = i+1; j <= n; ++j) { if (str[i-1] == str[j-1]) M[i][j] = 2 + M[i+1][j-1]; M[i][j] = max(M[i][j], max(M[i+1][j], M[i][j-1])); } } cout << M[1][n] << endl; } return 0; } <file_sep>/27-nested-segments-seg-tree/nested.cpp #include <iostream> #include <vector> #include <algorithm> #include <math.h> #define lft(i) (2*i+1) #define rgt(i) (2*i+2) #define par(i) ((i-1)/2) using namespace std; class SegmentTree { public: SegmentTree(uint64_t _n) { // nearest greater or equal power of two size = pow(2, ceil(log2(_n))) * 2 - 1; seg_tree = new int64_t[size]; for (int i = 0; i < size; ++i) seg_tree[i] = 0; n = _n; } ~SegmentTree() { delete [] seg_tree; } void increment(uint64_t pos) { pos += ((size + 1) / 2) - 1; while (1) { seg_tree[pos]++; if (pos == 0) break; pos = par(pos); } } uint64_t count(uint64_t i) { return rec_count(0, i, 0, ((size+1) / 2) - 1, 0); } private: uint64_t size; uint64_t n; int64_t * seg_tree; uint64_t rec_count(uint64_t qlow, uint64_t qhigh, uint64_t low, uint64_t high, uint64_t pos) { // total overlap if (qlow <= low && qhigh >= high) return seg_tree[pos]; // no overlap if (qlow > high || qhigh < low) return 0; uint64_t mid = (low + high) / 2; return rec_count(qlow, qhigh, low, mid, lft(pos)) + rec_count(qlow, qhigh, mid+1, high, rgt(pos)); } }; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } struct Segment { int64_t id; int64_t i; int64_t j; int64_t includes; }; int main() { std::ios_base::sync_with_stdio(false); int64_t n; cin >> n; vector<Segment> segments (n); for (int64_t id = 0; id < n; ++id) { segments[id].id = id; cin >> segments[id].i >> segments[id].j; segments[id].includes = 0; } // make all ends positive so we can use it in BIT O(nlogn) sort(segments.begin(), segments.end(), [](Segment a, Segment b) {return a.j < b.j;}); for (int i = 0; i < n; ++i) segments[i].j = i; // sort according to starts in descending order sort(segments.begin(), segments.end(), [](Segment a, Segment b) {return a.i > b.i;}); SegmentTree segment_tree (n); for (int64_t i = 0; i < n; ++i) { Segment * s = &segments[i]; s->includes = segment_tree.count(s->j); segment_tree.increment(s->j); } sort(segments.begin(), segments.end(), [](Segment a, Segment b) {return a.id < b.id;}); for (int64_t i = 0; i < n; ++i) cout << segments[i].includes << endl; return 0; }<file_sep>/52-subset-sum/subset.cpp #include <iostream> #include <vector> using namespace std; int numbers [101]; bool knapsack(int c, int n) { bool M [n+1][c+1]; // init for (int i = 0; i <= c; ++i) M[0][i] = false; for (int i = 0; i <= n; ++i) M[i][0] = true; for (int i = 1; i <= n; ++i) for (int j = 1; j <= c; ++j) M[i][j] = (M[i-1][j] || (j >= numbers[i-1] && M[i-1][j-numbers[i-1]])); return M[n][c]; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; for(int i = 0; i < n; ++i) cin >> numbers[i]; int sum = 0; for (int i = 0; i < n; i++) sum += numbers[i]; if (sum % 2 != 0) { cout << "NO" << endl; continue; } int target = sum / 2; if (knapsack(target, n) == 0) cout << "NO" << endl; else cout << "YES" << endl; } return 0; } <file_sep>/56-longest-prefix-suffix/lps.cpp #include <iostream> #include <string> using namespace std; int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; cin.ignore(); while (t--) { string str; getline(cin, str); int pp [str.length()]; pp[0] = 0; int i = 1, j = 0; while (i < str.length()) if (str[j] == str[i]) pp[i++] = ++j; else if (j == 0) pp[i++] = 0; else j = pp[j-1]; cout << pp[str.length()-1] << endl; } return 0; }<file_sep>/README.md # cp-course Competitive Programming. University of Pisa. C++ programming<file_sep>/28-pashmak-pirmida-seg-tree/pashmak.cpp #include <iostream> #include <vector> #include <algorithm> #include <unordered_map> #include <math.h> #define lft(i) (2*i+1) #define rgt(i) (2*i+2) #define par(i) ((i-1)/2) using namespace std; class SegmentTree { public: SegmentTree(uint64_t _n) { // nearest greater or equal power of two size = pow(2, ceil(log2(_n))) * 2 - 1; seg_tree = new int64_t[size]; for (int i = 0; i < size; ++i) seg_tree[i] = 0; n = _n; } ~SegmentTree() { delete [] seg_tree; } void increment(uint64_t pos) { pos += ((size + 1) / 2) - 1; while (1) { seg_tree[pos]++; if (pos == 0) { break; } pos = par(pos); } } uint64_t count(uint64_t i) { return rec_count(0, i, 0, ((size+1) / 2) - 1, 0); } void print() { for (int i = 0; i < size; ++i) cout << seg_tree[i] << " "; cout << endl; } private: uint64_t size; uint64_t n; int64_t * seg_tree; uint64_t rec_count(uint64_t qlow, uint64_t qhigh, uint64_t low, uint64_t high, uint64_t pos) { // total overlap if (qlow <= low && qhigh >= high) return seg_tree[pos]; // no overlap if (qlow > high || qhigh < low) return 0; uint64_t mid = (low + high) / 2; return rec_count(qlow, qhigh, low, mid, lft(pos)) + rec_count(qlow, qhigh, mid+1, high, rgt(pos)); } }; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); unordered_map<int,int> map; vector<int> left (n); for (int i = 0; i < n; ++i) { map[numbers[i]]++; left[i] = map[numbers[i]]; } map.clear(); vector<int> right (n); for (int i = n-1; i > -1; --i) { map[numbers[i]]++; right[i] = map[numbers[i]]; } int max = -1; for (int i = 0; i < n; ++i) { if (max < left[i]) max = left[i]; if (max < right[i]) max = right[i]; } SegmentTree segment_tree (max+1); uint64_t counter = 0; for (int i = n-1; i > 0; --i) { segment_tree.increment(right[i]); counter += segment_tree.count(left[i-1]-1); } cout << counter << endl; return 0; }<file_sep>/15-is-bst/is-bst.cpp #include <stddef.h> #include <vector> using namespace std; // struct Node { // int data; // struct Node * left; // struct Node * right; // }; void traversal(Node * node, vector<int> * numbers) { if (node != NULL) { traversal(node->left, numbers); numbers->emplace_back(node->data); traversal(node->right, numbers); } } bool isBST(Node * root) { vector<int> numbers; traversal(root, &numbers); for (int i = 1; i < numbers.size(); ++i) if (numbers[i] < numbers[i-1]) return false; return true; }<file_sep>/38-chat-room/chatroom.cpp #include <iostream> #include <vector> using namespace std; int main() { std::ios_base::sync_with_stdio(false); string hello = "hello"; string s; getline(cin, s); int i = 0; int j = 0; while (i < s.length() && j < hello.length()) if (s[i++] == hello[j]) j++; cout << (j == hello.length() ? "YES" : "NO") << endl; return 0; }<file_sep>/04-trapping-rain/trapping.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int counter(vector<int> numbers) { int to_count = 0; int i = 0; int j = 1; int n = numbers.size(); while (i < n && j < n) { int to_cut = 0; while (j < n && numbers[i] > numbers[j]) to_cut += numbers[j++]; if (j == n) { vector<int> tmp (n-i); for (int k = tmp.size()-1; k > -1; --k) tmp[k] = numbers[n-k-1]; to_count += counter(tmp); return to_count; } to_count += (j-i-1) * numbers[i] - to_cut; i = j++; } return to_count; } int main() { int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); cout << counter(numbers) << endl; } return 0; }<file_sep>/32-fox-names/foxnames.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; #define I(X) X-'a' #define WHITE 0 #define GREY 1 #define BLACK 2 int G[26][26]; vector<int> letters (26); string output; bool dfs(int i) { if (letters[i] == BLACK) return true; if (letters[i] == GREY) return false; letters[i] = GREY; for (int j = 0; j < 26; ++j) if (G[i][j] == 1 && !dfs(j)) return false; letters[i] = BLACK; output = char(i+'a') + output; return true; } int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; cin.ignore(); vector<string> names (n); for (int i = 0; i < n; ++i) getline(cin, names[i]); for (int k = 0; k < n-1; k++) { string current = names[k]; string next = names[k+1]; // find leftmost position where chars differ int i = 0; while (i < current.length() && i < next.length() && current[i] == next[i]) i++; // if the first string has been processed // then it is okay and we just move forward if (i == current.length()) continue; // no cases like: // rivest // rives if (i == next.length()) { cout << "Impossible" << endl; return 0; } G[I(current[i])][I(next[i])] = 1; } for (int i = 0; i < 26; ++i) { if (letters[i] == WHITE && !dfs(i)) { cout << "Impossible" << endl; return 0; } } cout << output << endl; return 0; }<file_sep>/06-next-larger/larger.cpp #include <iostream> #include <vector> #include <stack> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } void print_next_larger(vector<int> * numbers, int n) { stack<int> stack; stack.push(numbers->at(n-1)); numbers->at(n-1) = -1; for (int i = n - 2; i >= 0; --i) { while (!stack.empty() && numbers->at(i) >= stack.top()) stack.pop(); int elem = numbers->at(i); numbers->at(i) = stack.empty() ? -1 : stack.top(); stack.push(elem); } for (int i = 0; i < n; ++i) cout << numbers->at(i) << " "; cout << endl; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); print_next_larger(&numbers, n); } return 0; }<file_sep>/13-largest-even/largest-even.cpp #include <iostream> #include <vector> using namespace std; int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; cin.ignore(); while (t-- > 0) { string number; cin >> number; vector<int> counters (10); int minEven = 10; for (int i = 0; i < number.length(); ++i) { int n = number[i] - '0'; if (n % 2 == 0 && minEven > n) minEven = n; counters[n]++; } // if no even numbers if (minEven < 10) counters[minEven]--; for (int i = 9; i >= 0; --i) while (counters[i]-- > 0) cout << i; if (minEven < 10) cout << minEven; cout << endl; } return 0; } <file_sep>/41-alternative-thinking/alternative.cpp #include <iostream> using namespace std; #define ZERO(x) ((x-'0')==1) int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; cin.ignore(); string sequence; getline(cin, sequence); bool last = ZERO(sequence[0]); int counter = 1; for (int i = 1; i < n; ++i) { if (ZERO(sequence[i]) != last) { last = !last; counter++; } } cout << min(n, counter + 2) << endl; return 0; }<file_sep>/24-pashmak-parmida/pashmak.cpp #include <iostream> #include <vector> #include <algorithm> #include <unordered_map> using namespace std; class BIT { public: BIT(uint64_t _size) { if (_size < 1) _size = 10; size = _size + 1; A = new uint64_t[size]; fill_n(A, size, 0); } ~BIT() { delete [] A; } void add(uint64_t i, uint64_t qty) { if (i < 1 || i >= size) return; while (i < size) { A[i] += qty; i += i & (-i); } } uint64_t sum(uint64_t i) { if (i < 1 || i >= size) return 0; uint64_t sum = 0; while (i > 0) { sum += A[i]; i -= i & (-i); } return sum; } private: uint64_t size; uint64_t * A; }; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); unordered_map<int,int> map; vector<int> left (n); for (int i = 0; i < n; ++i) { map[numbers[i]]++; left[i] = map[numbers[i]]; } map.clear(); vector<int> right (n); for (int i = n-1; i > -1; --i) { map[numbers[i]]++; right[i] = map[numbers[i]]; } int max = -1; for (int i = 0; i < n; ++i) { if (max < left[i]) max = left[i]; if (max < right[i]) max = right[i]; } BIT bit (max); uint64_t counter = 0; for (int i = n-1; i > -1; --i) { bit.add(right[i], 1); counter += bit.sum(left[i-1]-1); } cout << counter << endl; return 0; }<file_sep>/19-alice-bob/alice-bob.cpp #include <iostream> #include <vector> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; if (n == 1) { cout << "1 0" << endl; return 0; } vector<int> a = get_input_sequence<int>(n); int i = 0; int j = n-1; int alice = 1; int bob = 1; while (j - i > 1) { if (a[i] > a[j]) { a[i] -= a[j--]; bob++; continue; } if (a[j] > a[i]) { a[j] -= a[i++]; alice++; continue; } i++; j--; // gentlment step if (i < j) bob++; alice++; } cout << alice << " " << bob << endl; return 0; }<file_sep>/45-iwgbs/iwgbs.cpp #include <iostream> #include <algorithm> using namespace std; class BigInteger { private: string integer; public: BigInteger(string integer); void setInteger(unsigned int integer); void setInteger(string integer); unsigned int getIntValue() const; string toString() const; BigInteger addInteger(const BigInteger& integer_to_add) const; BigInteger addInteger(const string& integer_to_add) const; static size_t getTrimIndex(const string& integer); BigInteger operator+(const BigInteger& integer) const; }; BigInteger::BigInteger(string integer) { for (int i = 0; i < (int)integer.size() && integer[i] >= '0' && integer[i] <= '9'; i++) { this->integer += integer[i]; } if (this->integer.size() == 0) { this->integer = "0"; } else { this->integer = integer.substr(getTrimIndex(integer)); } } void BigInteger::setInteger(string integer) { this->integer = integer; } unsigned int BigInteger::getIntValue() const { unsigned int ret = 0; unsigned int biggest = 0xFFFFFFFF; for (int i = 0; i < (int)integer.size(); i++) { int unit = integer[i] - '0'; if (ret > (biggest - unit) / 10.0) return 0; ret = ret * 10 + unit; } return ret; } string BigInteger::toString() const { return integer; } BigInteger BigInteger::addInteger(const BigInteger& integer_to_add) const { int a_n = max((int)(integer_to_add.toString().size() - toString().size()), 0); int b_n = max((int)(toString().size() - integer_to_add.toString().size()), 0); string a = string(a_n, '0') + toString(); string b = string(b_n, '0') + integer_to_add.toString(); reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); string result; int carry = 0; for (int i = 0; i < (int)a.size(); i++) { int sum = (a[i] - '0') + (b[i] - '0') + carry; result += ((char)(sum % 10 + '0')); carry = sum / 10; } if (carry != 0) result += ((char)(carry + '0')); reverse(result.begin(), result.end()); return BigInteger(result.substr(getTrimIndex(result))); } BigInteger BigInteger::addInteger(const string& integer_to_add) const { return addInteger(BigInteger(integer_to_add)); } size_t BigInteger::getTrimIndex(const string& integer) { size_t index = 0; while (integer[index] == '0' && index < integer.size() - 1) index++; return index; } BigInteger BigInteger::operator+(const BigInteger& integer) const { return addInteger(integer); } int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; BigInteger fibX ("2"); BigInteger fibY ("3"); if (n <= 2) { cout << n+1 << endl; return 0; } for (int i = 2; i < n; ++i) { BigInteger tmp = fibX; fibX = fibY; fibY = fibY + tmp; } cout << fibY.toString() << endl; return 0; } <file_sep>/53-vertex-cover/vc.cpp #include <iostream> #include <vector> #define WHITE 0 #define BLACK 1 using namespace std; struct Node { vector<Node*> children; int when_taken; int when_not_taken; int state; }; void vcover(Node * root) { root->state = BLACK; // compute if needed something root->when_taken = 1; for (int i = 0; i < root->children.size(); ++i) { Node * child = root->children[i]; if (child->state == BLACK) continue; vcover(child); root->when_not_taken += child->when_taken; root->when_taken += min(child->when_not_taken, child->when_taken); } } int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; if (n == 1) { cout << 1 << endl; return 0; } vector<Node> nodes (n); for(int i = 0; i < n; ++i) nodes[i].state = WHITE; for (int i = 0; i < n-1; ++i) { int u,v; cin >> u >> v; nodes[u-1].children.push_back(&nodes[v-1]); nodes[v-1].children.push_back(&nodes[u-1]); } vcover(&nodes[0]); cout << min(nodes[0].when_taken, nodes[0].when_not_taken) << endl; return 0; } <file_sep>/55-misha-and-forest/misha.cpp #include <iostream> #include <vector> #include <queue> using namespace std; struct Node { int degree; int xsum; }; int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; vector<Node> nodes (n); queue<int> leaves; int counter = 0; for (int i = 0; i < n; ++i) { cin >> nodes[i].degree >> nodes[i].xsum; if (nodes[i].degree == 1) leaves.push(i); counter += nodes[i].degree; } cout << counter / 2 << endl; while (!leaves.empty()) { int id = leaves.front(); leaves.pop(); if (nodes[id].degree < 1) { continue; } nodes[nodes[id].xsum].xsum ^= id; nodes[nodes[id].xsum].degree--; if (nodes[nodes[id].xsum].degree == 1) leaves.push(nodes[id].xsum); cout << id << " " << nodes[id].xsum << endl; } return 0; }<file_sep>/25-powerful-array/powerful.cpp #include <iostream> #include <vector> #include <algorithm> #include <math.h> using namespace std; struct Query { int id; int i; int j; }; int table[1000001]; uint64_t answer[200000]; uint64_t power = 0; long long numbers[200000]; int main() { std::ios_base::sync_with_stdio(false); int n, t; scanf("%I64d %I64d", &n, &t); for(int i = 0; i < n; i++) scanf("%I64d", &numbers[i]); Query queries[t]; for(int i = 0; i < t; i++) { queries[i].id = i; scanf("%I64d %I64d", &queries[i].i, &queries[i].j); } int p = sqrt(n); sort(queries, queries+t, [p](Query a, Query b) { if (a.i / p == b.i / p) return a.j < b.j; return a.i < b.i; }); int current_i = 0; int current_j = 0; int v = table[numbers[0]]; power -= numbers[0] * v * v; table[numbers[0]]++; v++; power += numbers[0] * v * v; for (int q = 0; q < t; ++q) { while (current_i < queries[q].i-1) { v = table[numbers[current_i]]; power -= numbers[current_i] * v * v; table[numbers[current_i]]--; v--; power += numbers[current_i] * v * v; current_i++; } while (current_i > queries[q].i-1) { current_i--; v = table[numbers[current_i]]; power -= numbers[current_i] * v * v; table[numbers[current_i]]++; v++; power += numbers[current_i] * v * v; } while (current_j < queries[q].j-1){ current_j++; v = table[numbers[current_j]]; power -= numbers[current_j] * v * v; table[numbers[current_j]]++; v++; power += numbers[current_j] * v * v; } while (current_j > queries[q].j-1) { v = table[numbers[current_j]]; power -= numbers[current_j] * v * v; table[numbers[current_j]]--; v--; power += numbers[current_j] * v * v; current_j--; } answer[queries[q].id] = power; } for (int i = 0; i < t; ++i) printf("%I64d\n", answer[i]); return 0; }<file_sep>/49-jumps/jumps.cpp #include <iostream> #include <vector> using namespace std; #define MAX 101 template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int jumps(vector<int> * numbers, vector<int> * dp, int i, int n) { if (i >= n-1) return 0; if (numbers->at(i) == 0) return MAX; if (dp->at(i) != MAX) return dp->at(i); for (int j = 1; j <= numbers->at(i); ++j) dp->at(i) = min(dp->at(i), 1 + jumps(numbers, dp, i+j, n)); return dp->at(i); } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); vector<int> dp (n, MAX); int j = jumps(&numbers, &dp, 0, n); if (j == MAX) cout << -1 << endl; else cout << j << endl; } return 0; } <file_sep>/17-max-path-sum/maxpath.cpp pair<int,int> maxPathSumRec(struct Node * node) { if (node->left == NULL && node->right == NULL) { pair<int,int> p; p.first = node->data; p.second = node->data; return p; } pair<int,int> leftPair, rightPair; if (node->left == NULL) { rightPair = maxPathSumRec(node->right); rightPair.first += node->data; return rightPair; } if (node->right == NULL) { leftPair = maxPathSumRec(node->left); leftPair.first += node->data; return leftPair; } leftPair = maxPathSumRec(node->left); rightPair = maxPathSumRec(node->right); int bridge = leftPair.first + rightPair.first + node->data; if (bridge > leftPair.second && bridge > rightPair.second) { pair<int,int> newPair; newPair.second = bridge; newPair.first = max(leftPair.first, rightPair.first) + node->data; return newPair; } if (leftPair.second > rightPair.second) { leftPair.first += node->data; return leftPair; } else { rightPair.first += node->data; return rightPair; } } int maxPathSum(struct Node *root) { return maxPathSumRec(root).second; } <file_sep>/08-team-member/member.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } struct Pair { int strength; int i; int j; }; int main() { std::ios_base::sync_with_stdio(false); int n; cin >> n; vector<Pair> pairs; // read pairs for (int i = 2; i <= n << 1; ++i) { vector<int> numbers = get_input_sequence<int>(i-1); for (int j = 1; j <= i-1; ++j) { Pair p; p.i = i; p.j = j; p.strength = numbers[j-1]; pairs.push_back(p); } } sort(pairs.begin(), pairs.end(), [](Pair a, Pair b) {return a.strength > b.strength;}); // compute members vector<int> members (2 * n, 0); for (int i = 0; i < pairs.size(); ++i) { Pair p = pairs[i]; if (members[p.i-1] == 0 && members[p.j-1] == 0) { members[p.i-1] = p.j; members[p.j-1] = p.i; } } for (int i = 0; i < n << 1; i++) cout << members[i] << " "; cout << endl; return 0; }<file_sep>/50-edit/edit.cpp #include <iostream> #include <vector> using namespace std; int edit(string a, string b, int n, int m) { int M [n+1][m+1]; // init for (int i = 0; i <= n; ++i) M[i][0] = i; for (int i = 0; i <= m; ++i) M[0][i] = i; for (int i = 1; i <= n; ++i) for (int j = 1; j <= m; ++j) M[i][j] = min(min(M[i-1][j] + 1, M[i][j-1] + 1), M[i-1][j-1] + ((a[i-1] == b[j-1]) ? 0 : 1)); return M[n][m]; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n, m; cin >> n >> m; string a, b; cin >> a >> b; cout << edit(a,b,n,m) << endl; } return 0; }<file_sep>/16-preorder/preorder.cpp #include <iostream> #include <vector> #include <stack> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int t; cin >> t; while (t-- > 0) { int n; cin >> n; vector<int> numbers = get_input_sequence<int>(n); stack<int> s; int root = 0; int i = 0; for (; i < n; ++i) { if (numbers[i] < root) break; while (!s.empty() && s.top() < numbers[i]) { root = s.top(); s.pop(); } s.push(numbers[i]); } cout << ((i == n) ? 1 : 0) << endl; } return 0; }<file_sep>/34-checkposts/checkposts.cpp #include <iostream> #include <vector> #include <algorithm> #include <stack> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } struct Node { int index; int lowlink; int cost; int sccID; bool onStack; vector<int> neighbors; }; int nSCC = 0; int IDX = 0; stack<int> s; vector<Node> nodes; void scc(int i) { nodes[i].index = IDX; nodes[i].lowlink = IDX; IDX++; s.push(i); nodes[i].onStack = true; for (int j = 0; j < nodes[i].neighbors.size(); j++) { int next = nodes[i].neighbors[j]; if (nodes[next].index == -1) { scc(next); nodes[i].lowlink = min(nodes[i].lowlink, nodes[next].lowlink); } else if (nodes[next].onStack) { nodes[i].lowlink = min(nodes[i].lowlink, nodes[next].index); } } // if node is the root of scc if (nodes[i].index == nodes[i].lowlink) { int next; do { next = s.top(); s.pop(); nodes[next].onStack = false; nodes[next].sccID = nSCC; } while (nodes[i].index != nodes[next].index); nSCC++; } } void tarjan() { for (int i = 0; i < nodes.size(); ++i) if (nodes[i].index == -1) // not yet discovered scc(i); } int main() { std::ios_base::sync_with_stdio(false); // read nodes int n; cin >> n; vector<int> costs = get_input_sequence<int>(n); for (int i = 0; i < n; i++) { Node n; n.cost = costs[i]; n.index = -1; nodes.push_back(n); } // read edges int m; cin >> m; for (int i = 0; i < m; i++) { int x, y; cin >> x >> y; nodes[x-1].neighbors.push_back(y-1); } // find strongly connected components tarjan(); // pay for each scc the minimum cost vector<int> min (nSCC, 1e9); for (int i = 0; i < n; ++i) { Node n = nodes[i]; if (n.cost < min[n.sccID]) min[n.sccID] = n.cost; } // total cost uint64_t sum = 0; for (int i = 0; i < nSCC; ++i) sum += min[i]; // compute number of ways vector<int> ways (nSCC, 0); for (int i = 0; i < n; ++i) { Node n = nodes[i]; if (n.cost == min[n.sccID]) ways[n.sccID]++; } // total number of ways uint64_t totWays = 1; for (int i = 0; i < nSCC; ++i) totWays *= ways[i]; cout << sum << " " << (totWays % 1000000007) << endl; return 0; }<file_sep>/35-minimum-spanning-tree/minimumtree.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> class UnionFind { public: struct Node { T data; int rank; int forestIndex; Node* parent; Node(T _data, int _forestIndex) { data = _data; rank = 0; forestIndex = _forestIndex; parent = this; } }; UnionFind() { } Node* MakeSet(T data) { Node* newNode = new Node(data, forest.size()); forest.push_back(newNode); return newNode; } // Union by Rank, if equal y becomes root void Union(Node* x, Node* y) { Node* rootX = Find(x); Node* rootY = Find(y); if (rootX == rootY) { return; } if (rootX->rank > rootY->rank) { rootY->parent = rootX; return; } rootX->parent = rootY; if (rootX->rank == rootY->rank) rootY->rank++; } // Find with Path Compression Node* Find(Node* x) { if (x->parent != x) x->parent = Find(x->parent); return x->parent; } vector<Node*> Forest() { return forest; } private: vector<Node*> forest; }; struct Edge { int i; int j; int w; Edge(int _i, int _j, int _w) { i = _i; j = _j; w = _w; } }; int main() { std::ios_base::sync_with_stdio(false); int n, m; cin >> n >> m; vector<Edge*> edges; for (int e = 0; e < m; e++) { int i, j, w; cin >> i >> j >> w; edges.push_back(new Edge(i,j,w)); } sort(edges.begin(), edges.end(), [](Edge* e1, Edge* e2) {return e1->w < e2->w;}); UnionFind<int> uf; vector<UnionFind<int>::Node*> nodes; for (int i = 0; i < n; i++) { nodes.push_back(uf.MakeSet(i)); } uint64_t sum = 0; for (int i = 0; i < m; i++) { Edge* e = edges[i]; UnionFind<int>::Node* u = nodes[e->i-1]; UnionFind<int>::Node* v = nodes[e->j-1]; if (uf.Find(u)->data != uf.Find(v)->data) { uf.Union(u,v); sum += e->w; } } cout << sum << endl; return 0; }<file_sep>/57-shift-string/shift.cpp #include <iostream> #include <string> using namespace std; int kmp(string p, string t) { // pattern preprocessing int pp [p.length()]; pp[0] = 0; int i = 1, j = 0; while (i < p.length()) { if (p[j] == p[i]) pp[i++] = ++j; else if (j == 0) pp[i++] = 0; else j = pp[j-1]; } // kmp i = 0; j = 0; int shifts = -1; int best_j = -1; while(i < t.length() && j < p.length()) { if (t[i] != p[j]) { if (j == 0) i++; else j = pp[j-1]; } else { if (t[i] == p[j]) i++, j++; if (j > best_j) { best_j = j; shifts = i-j; } } } return shifts; } int main() { std::ios_base::sync_with_stdio(false); int n; string A; string B; cin >> n; cin >> A >> B; B = B + B; cout << kmp(A,B) << endl; return 0; }<file_sep>/21-little-girl/little.cpp #include <iostream> #include <vector> #include <algorithm> using namespace std; template<typename T> vector<T> get_input_sequence(size_t n) { vector<T> sequence(n); for(size_t i = 0; i < n; ++i) cin >> sequence[i]; return sequence; } int main() { std::ios_base::sync_with_stdio(false); int n, q; cin >> n >> q; vector<int> numbers = get_input_sequence<int>(n); sort(numbers.begin(), numbers.end(), [](int a, int b) {return a > b;}); // count frequencies vector<int64_t> freqs (n); for (int i = 0; i < q; ++i) { int l, r; cin >> l >> r; freqs[l-1]++; if (r < n) freqs[r]--; } // inclusive prefix sum for (int i = 1; i < n; ++i) freqs[i] += freqs[i-1]; sort(freqs.begin(), freqs.end(), [](int a, int b) {return a > b;}); uint64_t sum = 0; for (int i = 0; i < freqs.size() && freqs[i] != 0; ++i) sum += freqs[i] * numbers[i]; cout << sum << endl; return 0; }
585f2bf941324e2c2586a272be10321575b058aa
[ "Markdown", "C++" ]
56
C++
ig92/cp-course
9e52788e8f6a76752149b74d06d0272e16c3b528
18581f2bdd15a1700fc60d4a7bebea759360632e
refs/heads/master
<file_sep>package com.lambdaschool.african_market_place.services; import com.lambdaschool.african_market_place.AfricanMarketPlaceApplicationTest; import com.lambdaschool.african_market_place.exceptions.ResourceNotFoundException; import com.lambdaschool.african_market_place.models.Listing; import com.lambdaschool.african_market_place.models.User; import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.MethodSorters; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest(classes = AfricanMarketPlaceApplicationTest.class) @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ListingServiceImplTest { @Autowired private ListingService listingService; @Autowired private UserService userService; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); List<Listing> initList = new ArrayList<>(); listingService.findAll().iterator().forEachRemaining(initList :: add); for( Listing l : initList){ System.out.println(l.getListingid() + " " + l.getListingname()); } } @After public void tearDown() throws Exception { } @Test public void a_findAll() { assertEquals(2, listingService.findAll().size()); } @Test public void findById() { assertEquals("Beef Stew", listingService.findById(10).getListingname()); } @Test public void b_findListingsByUser() { assertEquals(2, listingService.findListingsByUser(6).size()); } @Test public void save() { Listing newListing = new Listing("listingname", "test success", 6.90, 420, "deviances", userService.findUserById(6), "https://localhost:69"); Listing saveListing = listingService.save(newListing); assertEquals(3, listingService.findAll().size()); } @Test(expected = NullPointerException.class) public void y_delete() { listingService.delete(11); assertEquals(null, listingService.findById(11)); } @Test public void z_deleteAllListings() { listingService.deleteAllListings(); assertEquals(0, listingService.findAll().size()); } }<file_sep>package com.lambdaschool.african_market_place.models; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import javax.persistence.*; import java.util.HashSet; import java.util.Set; @Entity /*** table of fields ID,locations(one-to many), Country(many-to-one), */ @Table(name = "cities") public class City { //#region fields/constructors @Id @GeneratedValue(strategy = GenerationType.AUTO) private long citycode; @ManyToOne @JoinColumn(name = "countrycode", nullable = false) @JsonIgnoreProperties(value = "cities", allowSetters = true) private Country country; // @Column(nullable = false) private String cityname; @OneToMany(mappedBy = "city", cascade = CascadeType.ALL, orphanRemoval = true) @JsonIgnoreProperties(value = "city", allowSetters = true) private Set<Location> locations = new HashSet<>(); public City() { } public City(String cityname) { this.cityname = cityname; } public City(Country country, String cityname) { this.country = country; this.cityname = cityname; } //#endregion //#region getters/setters public long getCitycode() { return citycode; } public void setCitycode(long citycode) { this.citycode = citycode; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public Set<Location> getLocations() { return locations; } public void setLocations(Set<Location> locations) { this.locations = locations; } public String getCityname() { return cityname; } public void setCityname(String cityname) { this.cityname = cityname; } //#endregion } <file_sep>package com.lambdaschool.african_market_place.repositories; import com.lambdaschool.african_market_place.models.City; import org.springframework.data.repository.CrudRepository; public interface CityRepository extends CrudRepository<City, Long> { } <file_sep>package com.lambdaschool.african_market_place.repositories; import com.lambdaschool.african_market_place.models.Order; import com.lambdaschool.african_market_place.models.User; import org.springframework.data.repository.CrudRepository; public interface OrderRepository extends CrudRepository<Order, Long> { // User FindUserByOrderId(Long orderid); // // Order FindOrderById(Long orderid); } <file_sep>package com.lambdaschool.african_market_place.services; import com.lambdaschool.african_market_place.models.Country; import java.util.List; public interface CountryService { Country findCountryById(long countrycode); List<Country> findAllCountries(); Country save(Country country); } <file_sep>package com.lambdaschool.african_market_place.services; import com.lambdaschool.african_market_place.models.Listing; import java.util.List; public interface ListingService { List<Listing> findAll(); Listing findById(long listingid); Listing save(Listing newListing); List<Listing> findListingsByUser(long userid); Listing update(long listingid, Listing updateListing); void delete(long listingid); void deleteAllListings(); } <file_sep>package com.lambdaschool.african_market_place.services; import com.lambdaschool.african_market_place.models.City; import java.util.List; public interface CityService { City findCityById(long cityCode); List<City> findAllCities(); City save(City city); } <file_sep>package com.lambdaschool.african_market_place.services; import com.lambdaschool.african_market_place.models.OrderItem; public interface OrderItemService { OrderItem save(OrderItem oi1); } <file_sep>package com.lambdaschool.african_market_place.repositories; import com.lambdaschool.african_market_place.models.Listing; import org.springframework.data.repository.CrudRepository; public interface ListingRepository extends CrudRepository<Listing, Long> { } <file_sep>package com.lambdaschool.african_market_place.controllers; import com.lambdaschool.african_market_place.models.Order; import com.lambdaschool.african_market_place.services.HelperFunctions; import com.lambdaschool.african_market_place.services.ListingService; import com.lambdaschool.african_market_place.services.OrderService; import com.lambdaschool.african_market_place.services.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping("/orders") public class OrderController { @Autowired OrderService orderService; @Autowired UserService userService; @Autowired ListingService listingService; @Autowired HelperFunctions helperFunctions; @PreAuthorize("hasAnyRole('ADMIN')") @GetMapping(value = "/orders", produces = "application/json") public ResponseEntity<?> getAllOrders() { List<Order> allOrders = orderService.findAllOrders(); return new ResponseEntity<>(allOrders, HttpStatus.OK); } @GetMapping(value = "/order/{orderid}", produces = "application/json") public ResponseEntity<?> getOrderById(@PathVariable Long orderid) { Order order = orderService.findOrderById(orderid); return new ResponseEntity<>(order, HttpStatus.OK); } //post /orders/order @PostMapping(value = "/order", consumes = "application/json", produces = "application/json") public ResponseEntity<?> postOrder(@Valid @RequestBody Order newOrder) { newOrder.setOrdercode(0); newOrder.setUser(helperFunctions.getCurrentUser()); newOrder = orderService.save(newOrder); HttpHeaders responseHeaders = new HttpHeaders(); URI newOrderURI = ServletUriComponentsBuilder.fromCurrentRequest() .path("/{ordercode}") .buildAndExpand(newOrder.getOrdercode()) .toUri(); responseHeaders.setLocation(newOrderURI); return new ResponseEntity<>(null, responseHeaders, HttpStatus.CREATED); } //get /orders/orders/:userid //put /orders/order/:orderid //delete /orders/order/:orderid } <file_sep>package com.lambdaschool.african_market_place; import com.github.javafaker.Faker; import com.lambdaschool.african_market_place.models.*; import com.lambdaschool.african_market_place.repositories.CityRepository; import com.lambdaschool.african_market_place.services.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import javax.transaction.Transactional; import java.util.*; /** * SeedData puts both known and random data into the database. It implements CommandLineRunner. * <p> * CoomandLineRunner: Spring Boot automatically runs the run method once and only once * after the application context has been loaded. */ @Transactional @Component public class SeedData implements CommandLineRunner { /** * Connects the Restaurant Service to this process */ @Autowired private ListingService listingService; @Autowired private UserService userService; @Autowired private RoleService roleService; @Autowired private LocationService locationService; @Autowired private OrderService orderService; @Autowired private CityService cityService; @Autowired private CityRepository cityRepository; @Autowired private CountryService countryService; @Autowired private OrderItemService orderItemService; /** * A Random generator is needed to randomly generate faker data. */ private Random random = new Random(); /** * Generates test, seed data for our application * First a set of known data is seeded into our database. * Second a random set of data using Java Faker is seeded into our database. * Note this process does not remove data from the database. So if data exists in the database * prior to running this process, that data remains in the database. * * @param args The parameter is required by the parent interface but is not used in this process. */ @Transactional @Override public void run(String[] args) throws Exception { listingService.deleteAllListings(); userService.deleteAll(); roleService.deleteAll(); locationService.deleteAllLocations(); /** ROLES */ Role r1 = new Role("admin"); Role r2 = new Role("user"); Role r3 = new Role("merchant"); r1 = roleService.save(r1); r2 = roleService.save(r2); r3 = roleService.save(r3); /**COUNTRIES */ Country country1 = new Country("Rwanda"); country1 = countryService.save(country1); City c1 = new City(country1, "Wakanda"); c1 = cityService.save(c1); country1.getCities().add(c1); /** CITIES */ //Country country, // City c1 = new City(country1, "Wakanda"); // country1.getCities().add(c1); // country1 = countryService.save(country1); // City c2 = new City(country1, "My City"); // country1.getCities().add(c2); // c2 = cityService.save(c2); /** LOCATIONS */ //City city, String zip, String address Location loc1 = new Location(c1, "123 Example St.", "12345 address"); // loc1 = locationService.save(loc1); c1.getLocations().add(loc1); User admin = new User("username", null, null, null, null, "<PASSWORD>", loc1); admin.getListings().add(new Listing("New listingasdf", "Listing description", 6.99, 14, "more food", admin, "https://pmcvariety.files.wordpress.com/2020/07/kanye-west-1-e1599269208476.jpg")); admin.getRoles().add(new UserRoles(admin, r1)); admin = userService.save(admin); User vendor = new User("usernamer", null, null, null, null, "<PASSWORD>", loc1); vendor.getRoles().add(new UserRoles(vendor, r3)); vendor = userService.save(vendor); Listing l1 = new Listing("Eggs Benedict", "Listing description", 6.99, 14, "food", admin, "https://pmcvariety.files.wordpress.com/2020/07/kanye-west-1-e1599269208476.jpg"); admin.getListings().add(l1); Listing l2 = new Listing("Beef Stew", "Listing description", 6.99, 14, "other food", admin, "https://pmcvariety.files.wordpress.com/2020/07/kanye-west-1-e1599269208476.jpg"); admin.getListings().add(l2); User user = new User("ultimateuser", null, null, null, null, "password", loc1); user.getRoles().add(new UserRoles(user, r2)); // // Order o1 = new Order(loc1); //// OrderItem oi1 = new OrderItem(o1, l1, 5); //// oi1 = orderItemService.save(oi1); // o1.setUser(user); // o1.getOrderItems().add(new OrderItem(o1, l1, 5)); // o1 = orderService.save(o1); // user.getOrders().add(o1); // o1 = orderService.save(o1); user = userService.save(user); // listingService.save(l1); // listingService.save(l2); /** using JavaFaker create a bunch of regular restaurants https://www.baeldung.com/java-faker https://www.baeldung.com/regular-expressions-java */ Faker nameFaker = new Faker(new Locale("en-US")); // this section gets a unique list of namesry Set<String> countryNamesSet = new HashSet<>(); for (int i = 0; i < 2; i++) { countryNamesSet.add(nameFaker.country().name()); } Set<Country> countrySet = new HashSet<>(); for (String countryName : countryNamesSet) { Country fakeCountry = new Country(countryName); fakeCountry = countryService.save(fakeCountry); int randomNumber = random.nextInt(3) + 1; // random number 1 through 10 for (int j = 0; j < randomNumber; j++) { fakeCountry.getCities() .add(new City(fakeCountry, nameFaker.gameOfThrones() .city())); for (City c : fakeCountry.getCities()) { int randomLocNumber = random.nextInt(3) + 1; // random number 1 through 10 for (int k = 0; k < randomLocNumber; k++) { c.getLocations().add(new Location(c, nameFaker.address().zipCode(), nameFaker.address().streetAddress())); for (Location l : c.getLocations()) { int randomUserNumber = random.nextInt(3) + 1; // random number 1 through 10 for (int z = 0; z < randomUserNumber; z++) ; { User fakeUser = new User( nameFaker.company().name(), nameFaker.phoneNumber().phoneNumber(), nameFaker.internet().emailAddress(), nameFaker.name().firstName(), nameFaker.name().lastName(), "<PASSWORD>", l); fakeUser = userService.save(fakeUser); } } } } } } List<String> categories = new ArrayList<>(); categories.add("Animal Products"); categories.add("Beans"); categories.add("Cereals - Maize"); categories.add("Cereals - Maize"); categories.add("Cereals - OtherCereals - Rice"); categories.add("Fruits"); categories.add("Other"); categories.add("Peas"); categories.add("Roots & Tubers"); categories.add("Seeds & Nuts"); categories.add("Vegetables"); List<String> commodityList = new ArrayList<>(); commodityList.add("Eggs"); commodityList.add("Exotic Eggs"); commodityList.add("Local Eggs"); commodityList.add("Milk"); commodityList.add("Nile Perch"); commodityList.add("Processed Honey"); commodityList.add("Tilapia"); commodityList.add("Unprocessed Honey"); commodityList.add("Beef"); commodityList.add("Goat Meat"); commodityList.add("Pork"); commodityList.add("Exotic Chicken"); commodityList.add("Local Chicken"); commodityList.add("Turkey"); commodityList.add("Agwedde Beans"); commodityList.add("Beans"); commodityList.add("Beans (K132)"); commodityList.add("Beans Canadian"); commodityList.add("Beans Mwitemania"); commodityList.add("Beans Rosecoco"); commodityList.add("Black Beans (Dolichos)"); commodityList.add("Dolichos (Njahi)"); commodityList.add("Green Gram"); commodityList.add("Kidney Beans"); commodityList.add("Mixed Beans"); commodityList.add("Mwezi Moja"); commodityList.add("Nambale Beans"); commodityList.add("Old Beans"); commodityList.add("Red Beans"); commodityList.add("Soya Beans"); commodityList.add("White Beans"); commodityList.add("Yellow Beans"); commodityList.add("Dry Maize"); commodityList.add("Green Maize"); commodityList.add("Maize"); commodityList.add("Maize Bran"); commodityList.add("Maize Flour"); commodityList.add("Barley"); commodityList.add("Bulrush Millet"); commodityList.add("Finger Millet"); commodityList.add( "Millet Flour"); commodityList.add("Millet Grain"); commodityList.add("Pearl Millet"); commodityList.add("White Millet"); commodityList.add("Red Sorghum"); commodityList.add("Sorghum"); commodityList.add("Sorghum Flour"); commodityList.add("Sorghum Grain"); commodityList.add("White Sorghum"); commodityList.add("Wheat"); commodityList.add("Wheat Bran"); commodityList.add("Wheat Flour"); commodityList.add("Imported Rice"); commodityList.add("Kahama Rice"); commodityList.add("Kayiso Rice"); commodityList.add("Kilombero Rice"); commodityList.add("Mbeya Rice"); commodityList.add("Morogoro Rice"); commodityList.add("Paddy Rice"); commodityList.add("Rice"); commodityList.add("Rice Bran"); commodityList.add("Super Rice"); commodityList.add("Unprocessed/husked rice"); commodityList.add("Upland Rice"); commodityList.add("Avocado"); commodityList.add("Apple Bananas"); commodityList.add("Cavendish (Bogoya)"); commodityList.add("Cooking Bananas"); commodityList.add("Ripe Bananas"); commodityList.add("Passion Fruits"); commodityList.add("Lemons"); commodityList.add("Limes"); commodityList.add("Mangoes Local"); commodityList.add("Pawpaw"); commodityList.add("Mangoes Ngowe"); commodityList.add("Oranges"); commodityList.add("Pineapples"); commodityList.add("Coffee (Arabica)"); commodityList.add("Coffee (Robusta)"); commodityList.add("Unprocessed Cotton"); commodityList.add("Unprocessed Tea"); commodityList.add("Tobacco"); commodityList.add("Unprocessed Vanilla"); commodityList.add("Chic Pea"); commodityList.add("Cowpeas"); commodityList.add("Dry Peas"); commodityList.add( "Fresh Peas"); commodityList.add("Green Peas"); commodityList.add( "Peas"); commodityList.add("Pigeon Peas"); commodityList.add("Cassava Chips"); commodityList.add("Cassava Flour"); commodityList.add("Cassava Fresh"); commodityList.add( "Dry Fermented Cassava"); commodityList.add("Sun Dried Cassava"); commodityList.add( "Red Irish Potatoes"); commodityList.add("Round Potatoes"); commodityList.add("Sweet Potatoes"); commodityList.add("White Fleshed Sweet Potatoes"); commodityList.add("White Irish Potatoes"); commodityList.add( "Ground Nuts"); commodityList.add("Simsim"); commodityList.add("Sunflower Seed"); commodityList.add("Sunflower Seed Cake"); commodityList.add("Brinjal/Eggplant"); commodityList.add("Cabbages"); commodityList.add( "Capsicums"); commodityList.add("Carrots"); commodityList.add("Cauliflower"); commodityList.add("Chillies"); commodityList.add("Cucumber"); commodityList.add("Ginger"); commodityList.add("Kales"); commodityList.add("Lettuce"); commodityList.add("Onions Dry"); commodityList.add("Spring Onions"); commodityList.add("Tomatoes"); List<User> userList = userService.findAll(); for (User u : userList) { int randomListingNumber = random.nextInt(3) + 1; // random number 1 through 3 for (int y = 0; y < randomListingNumber; y++){ Listing newListing = new Listing(nameFaker.options().nextElement(commodityList), nameFaker.lorem().sentence(), nameFaker.number().randomDouble(2, 1, 100), nameFaker.number().randomDigitNotZero(), nameFaker.options().nextElement(categories), u, "https://ca.slack-edge.com/ESZCHB482-W015P677M1T-d9f28327bb26-512"); newListing = listingService.save(newListing); } } } } <file_sep>package com.lambdaschool.african_market_place.controllers; import com.fasterxml.jackson.databind.ObjectMapper; import com.lambdaschool.african_market_place.AfricanMarketPlaceApplication; import com.lambdaschool.african_market_place.AfricanMarketPlaceApplicationTest; import com.lambdaschool.african_market_place.models.*; import com.lambdaschool.african_market_place.services.ListingService; import com.lambdaschool.african_market_place.services.UserService; import io.restassured.module.mockmvc.RestAssuredMockMvc; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.RequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.any; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; //@ContextConfiguration(locations = "classpath*:/spring/applicationContext*.xml") @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = AfricanMarketPlaceApplicationTest.class) @AutoConfigureMockMvc @WithMockUser(username = "admin", roles = {"USER", "ADMIN"}) public class UserControllerTest { @Autowired private WebApplicationContext webApplicationContext; @Autowired private MockMvc mockMvc; @MockBean private UserService userService; private List<User> userList; private List<Listing> listingList; @Before public void setUp() throws Exception { userList = new ArrayList<>(); listingList = new ArrayList<>(); RestAssuredMockMvc.webAppContextSetup(webApplicationContext); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext) .apply(SecurityMockMvcConfigurers.springSecurity()) .build(); Role r1 = new Role("admin"); Role r2 = new Role("user"); Role r3 = new Role("merchant"); Country country1 = new Country("Rwanda"); City c1 = new City(country1, "Wakanda"); Location loc1 = new Location(c1, "12345", "example Test Lane"); User u1 = new User("username", "111-1111", "<EMAIL>", "Boris", "Yeltsin", "RussiaRules", loc1); u1.setUserid(5); userList.add(u1); u1.getRoles().add(new UserRoles(u1, r1)); u1.getRoles().add(new UserRoles(u1, r2)); u1.getRoles().add(new UserRoles(u1, r3)); Listing listing1 = new Listing("Listy Listy", "I could really use a list right now", 600.0, 6, "Rap song", u1, "exampleabc.com/coolshit.jpg"); listing1.setListingid(50); Listing listing2 = new Listing("Uzbekistan", "Poor and white", 600.0, 6, "Nation State", u1, "exampleabc.com/coolshit.jpg"); listing1.setListingid(51); u1.getListings().add(listing1); u1.getListings().add(listing2); listingList.add(listing1); listingList.add(listing2); } @After public void tearDown() throws Exception { } @Test public void listAllUsers() throws Exception{ String apiUrl = "/users/users"; Mockito.when(userService.findAll()) .thenReturn(userList); RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) .accept(MediaType.APPLICATION_JSON); // the following actually performs a real controller call MvcResult r = mockMvc.perform(rb) .andReturn(); // this could throw an exception String tr = r.getResponse() .getContentAsString(); ObjectMapper mapper = new ObjectMapper(); String er = mapper.writeValueAsString(userList); System.out.println("Expect: " + er); System.out.println("Actual: " + tr); assertEquals("Rest API Returns List", er, tr); } @Test public void getUserById() throws Exception{ String apiUrl = "/users/user/5"; Mockito.when(userService.findUserById(5)) .thenReturn(userList.get(0)); RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) .accept(MediaType.APPLICATION_JSON); MvcResult r = mockMvc.perform(rb) .andReturn(); // this could throw an exception String tr = r.getResponse() .getContentAsString(); ObjectMapper mapper = new ObjectMapper(); String er = mapper.writeValueAsString(userList.get(0)); System.out.println("Expect: " + er); System.out.println("Actual: " + tr); assertEquals("Rest API Returns List", er, tr); } @Test public void getUserByName() throws Exception { String apiUrl = "/users/user/name/username"; Mockito.when(userService.findByName("username")) .thenReturn(userList.get(0)); RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) .accept(MediaType.APPLICATION_JSON); MvcResult r = mockMvc.perform(rb) .andReturn(); // this could throw an exception String tr = r.getResponse() .getContentAsString(); ObjectMapper mapper = new ObjectMapper(); String er = mapper.writeValueAsString(userList.get(0)); System.out.println("Expect: " + er); System.out.println("Actual: " + tr); assertEquals("Rest API Returns List", er, tr); } @Test public void getUserLikeName() throws Exception{ String apiUrl = "/users/user/name/like/user"; Mockito.when(userService.findByNameContaining(any(String.class))) .thenReturn(userList); RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) .accept(MediaType.APPLICATION_JSON); // the following actually performs a real controller call MvcResult r = mockMvc.perform(rb) .andReturn(); // this could throw an exception String tr = r.getResponse() .getContentAsString(); ObjectMapper mapper = new ObjectMapper(); String er = mapper.writeValueAsString(userList); System.out.println("Expect: " + er); System.out.println("Actual: " + tr); assertEquals("Rest API Returns List", er, tr); } @Test public void addNewUser() throws Exception{ String apiUrl = "/users/register"; // build a user User u1 = new User("derp", "<PASSWORD>"); u1.setUserid(100); // u1.setUsername("derp"); // u1.setPassword("<PASSWORD>!"); ObjectMapper mapper = new ObjectMapper(); String userString = mapper.writeValueAsString(u1); Mockito.when(userService.save(any(User.class))) .thenReturn(u1); RequestBuilder rb = MockMvcRequestBuilders.post(apiUrl) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(userString); mockMvc.perform(rb) .andExpect(status().isCreated()) .andDo(MockMvcResultHandlers.print()); } @Test public void updateFullUser() throws Exception{ String apiUrl = "/users/user/{userid}"; // build a user User u1 = new User(); u1.setUserid(100); u1.setUsername("tigerUpdated"); u1.setPassword("<PASSWORD>!"); Mockito.when(userService.update(u1, 100)) .thenReturn(userList.get(0)); ObjectMapper mapper = new ObjectMapper(); String userString = mapper.writeValueAsString(u1); RequestBuilder rb = MockMvcRequestBuilders.put(apiUrl, 100L) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(userString); mockMvc.perform(rb) .andExpect(status().is2xxSuccessful()) .andDo(MockMvcResultHandlers.print()); } @Test public void updateUser() throws Exception { String apiUrl = "/users/user/{userid}"; // build a user User u1 = new User(); u1.setUserid(100); u1.setUsername("tigerUpdated"); u1.setPassword("<PASSWORD>!"); Mockito.when(userService.update(u1, 100)) .thenReturn(userList.get(0)); ObjectMapper mapper = new ObjectMapper(); String userString = mapper.writeValueAsString(u1); RequestBuilder rb = MockMvcRequestBuilders.put(apiUrl, 100L) .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON) .content(userString); mockMvc.perform(rb) .andExpect(status().is2xxSuccessful()) .andDo(MockMvcResultHandlers.print()); } @Test public void deleteUserById() throws Exception{ String apiUrl = "/users/user/{userid}"; RequestBuilder rb = MockMvcRequestBuilders.delete(apiUrl, "5") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON); mockMvc.perform(rb) .andExpect(status().is2xxSuccessful()) .andDo(MockMvcResultHandlers.print()); } @Test public void deleteUserSelf() throws Exception{ String apiUrl = "/users/user/{userid}"; RequestBuilder rb = MockMvcRequestBuilders.delete(apiUrl, "100") .contentType(MediaType.APPLICATION_JSON) .accept(MediaType.APPLICATION_JSON); mockMvc.perform(rb) .andExpect(status().is2xxSuccessful()) .andDo(MockMvcResultHandlers.print()); } // @Test // public void getCurrentUserInfo() throws Exception{ // String apiUrl = "/users/getuserinfo"; // // RequestBuilder rb = MockMvcRequestBuilders.get(apiUrl) // .accept(MediaType.APPLICATION_JSON); // MvcResult r = mockMvc.perform(rb) // .andReturn(); // this could throw an exception // String tr = r.getResponse() // .getContentAsString(); // // ObjectMapper mapper = new ObjectMapper(); // String er = mapper.writeValueAsString(userList.get(0)); // // System.out.println("Expect: " + er); // System.out.println("Actual: " + tr); // // assertEquals("Rest API Returns List", er, tr); // } // @Test // public void changeRole() { // } }
796f4a346cdb2a752dfc933f02156ea1d408408c
[ "Java" ]
12
Java
schroeder-g/agora-marketplace
9249071a61e8f3fe1694ff75d173bab6a2f0e27d
74c2503f88e6129a1e59a707cbb8f5f258e771a0
refs/heads/master
<repo_name>elanpr01/Cucumber-Project<file_sep>/src/test/java/modules/LogInAction.java package modules; import java.util.HashMap; import com.cucumber.listener.Reporter; import helper.Log; import pageObjects.LoginPage; public class LogInAction { public static void execute(HashMap<String,String> map) { Log.startTestCase(); Log.info("Login Action perfomed"); LoginPage.userName.sendKeys(map.get("username")); LoginPage.Password.sendKeys(map.get("<PASSWORD>")); LoginPage.submitButton.click(); Reporter.addStepLog("Logged In successfully"); Log.endTestCase(); } } <file_sep>/target/classes/META-INF/maven/com.gbig.feature/Cucumber/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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.gbig.feature</groupId> <artifactId>Cucumber</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>Cucumber</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/log4j/log4j --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-java</artifactId> <version>1.2.0</version> </dependency> <!-- <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-testng</artifactId> <version>1.2.0</version> </dependency> --> <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-junit</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.11.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.11-beta3</version> </dependency> <dependency> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>xerces</groupId> <artifactId>xercesImpl</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.vimalselvam</groupId> <artifactId>cucumber-extentsreport</artifactId> <version>3.0.2</version> </dependency> <dependency> <groupId>com.aventstack</groupId> <artifactId>extentreports</artifactId> <version>3.1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version> </dependency> <!-- <dependency> <groupId>info.cukes</groupId> <artifactId>cucumber-picocontainer</artifactId> <version>1.1.3</version> <scope>test</scope> </dependency> https://mvnrepository.com/artifact/org.springframework/spring-test <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.12.RELEASE</version> <scope>test</scope> </dependency> <dependency> <groupId>io.cucumber</groupId> <artifactId>cucumber-spring</artifactId> <version>3.0.0</version> </dependency> --> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.6.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.19.1</version> <configuration> <includes> <include>MyRunner.java</include> </includes> </configuration> </plugin> </plugins> </build> <reporting> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-report-plugin</artifactId> <version>2.19.1</version> </plugin> </plugins> </reporting> </project> <file_sep>/src/test/java/stepDefinations/GuruDemoSite.java package stepDefinations; import java.util.HashMap; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; import modules.LogInAction; import pageObjects.LoginPage; public class GuruDemoSite { public WebDriver driver; public HashMap<String, String> data = Hooks.data; @Given("^I want to write a step with Launch the URLs$") public void i_want_to_write_a_step_with_Launch_the_URLs() throws Throwable { driver = Hooks.driver; driver.get("http://demo.guru99.com/V4/"); } @When("^Login the site with Username$") public void login_the_site_with_USername() throws Throwable { PageFactory.initElements(driver, LoginPage.class); //driver.findElement(By.id("dfd")); LogInAction.execute(data); } @Then("^verify the status$") public void verify_the_status() throws Throwable { driver.switchTo().alert().accept(); driver.close(); } } <file_sep>/README.md # Cucumber-Project Cucumber Project with Extended Report
fe05e6fb8f4c0ac5346db18c158058d7c1b8fa70
[ "Markdown", "Java", "Maven POM" ]
4
Java
elanpr01/Cucumber-Project
d852369b1e06ad0eac6dc122362f248d2194b06f
fd275cf852c14b306f70ec8b7dd286990ad2db58
refs/heads/master
<repo_name>adershmanoj/flight-booking-java<file_sep>/src/main/java/com/nissan/training/advancedjava/assignment/model/Details.java package com.nissan.training.advancedjava.assignment.model; public class Details { private String firstName; private String lastName; private String mobile; private int flightId; private String email; public int getFlightId() { return flightId; } public void setFlightId(int flightId2) { this.flightId = flightId2; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } } <file_sep>/README.md <h3 align="center">Flight Booking</h3> <p align="center"> Spring MVC app for flight booking demo <br> </p> --- ## About Demo flight booking app built with Spring MVC. Uses MySQL db and Hibernate ORM. <div align="center"><img src="https://raw.githubusercontent.com/adershmanoj/flight-booking-java/master/media/home.png" alt="Home" /></div> ## Screenshots Application screenshots<br> **Login** <div align="center"><img src="https://raw.githubusercontent.com/adershmanoj/flight-booking-java/master/media/login.png" alt="Login" /></div> **Search** <div align="center"><img src="https://raw.githubusercontent.com/adershmanoj/flight-booking-java/master/media/search.png" alt="Search" /></div> **Itinerary** <div align="center"><img src="https://raw.githubusercontent.com/adershmanoj/flight-booking-java/master/media/itinerary.png" alt="Itinerary" /></div> **Book** <div align="center"><img src="https://raw.githubusercontent.com/adershmanoj/flight-booking-java/master/media/book.png" alt="Book" /></div> **Cancel** <div align="center"><img src="https://raw.githubusercontent.com/adershmanoj/flight-booking-java/master/media/cancel.png" alt="Cancel" /></div><file_sep>/src/main/java/com/nissan/training/advancedjava/assignment/model/Insurance.java package com.nissan.training.advancedjava.assignment.model; public class Insurance { private int age; private String ownership; private String property; private String city; private long sum; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getOwnership() { return ownership; } public void setOwnership(String ownership) { this.ownership = ownership; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public long getSum() { return sum; } public void setSum(long sum) { this.sum = sum; } } <file_sep>/src/main/java/com/nissan/training/advancedjava/assignment/dao/FlightDAO.java package com.nissan.training.advancedjava.assignment.dao; import java.util.List; import com.nissan.training.advancedjava.assignment.model.Flight; import com.nissan.training.advancedjava.assignment.model.Search; public interface FlightDAO { public List<Flight> getFlights(Search search); public Flight getFlight(int id); public void reduceFlightCapacity(int flightId); }
e124d13232ca0d98b2e0eb5fb1bd99a9c544fe98
[ "Markdown", "Java" ]
4
Java
adershmanoj/flight-booking-java
632c9cc1b0e1f8215f976f5e04927214d08dc766
4d96d32b4effd52bf32f34dc3cbebd85ee79dddf
refs/heads/master
<repo_name>RoshanRane/active_vision_prednet<file_sep>/prednet-smth-smth/preprocess_data.py ########################################## Importing libraries ######################################################### import os import sys import glob from time import sleep import json from tqdm import tqdm import pandas as pd import matplotlib.pyplot as plt ######################################################################################################################## def split_data(data_dir, train_json_name="something-something-v2-train.json", test_json_name="something-something-v2-test.json", val_json_name="something-something-v2-validation.json", split_flag=True): ''' Input : Directory of the data to be processed (dtype: String) Description : Splits the videos into train, val, test folders. Turn off the split_flag to disable the functionality. Convention : data_dir should contain the raw videos in a 'raw' folder and the train, test and val json files. ''' print("Pre-processing step 1: Splitting videos into train, test, and val datasets.") if split_flag: # Getting the files train_json = os.path.join(data_dir, train_json_name) test_json = os.path.join(data_dir, test_json_name) val_json = os.path.join(data_dir, val_json_name) # Checking if the file exists assert os.path.isfile(train_json) assert os.path.isfile(test_json) assert os.path.isfile(val_json) # Dividing files into train, test, and validation dataset train_data = json.load(train_json) train_data = [entries["id"] for entries in train_data] test_data = json.load(test_json) test_data = [entries["id"] for entries in test_data] val_data = json.load(val_json) val_data = [entries["id"] for entries in val_data] # Creating the necessary directories os.system("mkdir -p {}/preprocessed".format(data_dir)) os.system("mkdir -p {}/preprocessed/train".format(data_dir)) os.system("mkdir -p {}/preprocessed/test".format(data_dir)) os.system("mkdir -p {}/preprocessed/val".format(data_dir)) videos = [video for video in os.listdir(os.path.join(data_dir, "raw"))] print("Total number of videos:", len(videos)) with tqdm(total=100, file=sys.stdout) as pbar: for files in tqdm(videos): ids = files.split(".")[0] if ids in test_data: os.system("cp -u {} {}".format(os.path.join(data_dir, "raw", files), os.path.join(data_dir, "preprocessed/test/", files))) elif ids in train_data: os.system("cp -u {} {}".format(os.path.join(data_dir, "raw", files), os.path.join(data_dir, "preprocessed/train/", files))) elif ids in val_data: os.system("cp -u {} {}".format(os.path.join(data_dir, "raw", files), os.path.join(data_dir, "preprocessed/val/", files))) else: print("{} is listed neither in test, train nor val data.".format(files)) pbar.update(1) sleep(1) else: pass def extract_videos(raw_vids, dest_dir, fps=None, extract_flag=True): ''' Input : raw_vids - dest_dir - The dir in which the final extracted and processed videos will be placed. (dtype: String) Description : Converts .webm to image sequences. Turn off the extract_flag to disable the functionality. ''' print("Pre-processing step 2: Converting videos from .webm to image sequences.") if extract_flag: with tqdm(total=100, file=sys.stdout) as pbar: for raw_vid in raw_vids: # create a folder for each video with it's unique ID v_name = raw_vid.split("/")[-1].split(".")[0] split = raw_vid.split("/")[-2] os.system("mkdir -p {}/{}/{}".format(dest_dir, split, v_name)) # check if this folder is already extracted if (not os.path.isfile("{}/{}/{}/image-001.png".format(dest_dir, split, v_name))): # run the ffmpeg software to extract the videos based on the fps provided if fps is not None: os.system("ffmpeg -framerate {} -i {} {}/{}/{}/image-%03d.png".format( fps, raw_vid, dest_dir, split, v_name)) else: os.system("ffmpeg -i {} {}/{}/{}/image-%03d.png".format( raw_vid, dest_dir, split, v_name)) print(raw_vid, " has been converted..") else: pass pbar.update(1) sleep(1) else: pass def create_dataframe(vid_list,create_flag=True): """ :input: :return : pandas dataframe Description : creates dataframe Turn off the create_flag to disable functionality """ print("Pre-processing step 3 : Creating dataframe.") if create_flag: df = pd.DataFrame({"path": vid_list}) with tqdm(total=100, file=sys.stdout) as pbar: for i, vid_path in enumerate(df['path']): # read the first frame of the video im = plt.imread(vid_path + "/image-001.png") # add split information df.loc[i, 'split'] = vid_path.split("/")[-2] # add frame resolution information df.loc[i, 'height'] = int(im.shape[0]) df.loc[i, 'width'] = int(im.shape[1]) df.loc[i, 'aspect_ratio'] = im.shape[0] / im.shape[1] df.loc[i, 'num_of_frames'] = int(len(os.listdir(vid_path))) # image statistics arr = im.flatten() df.loc[i, 'first_frame_mean'] = np.mean(arr) df.loc[i, 'first_frame_std'] = np.std(arr) df.loc[i, 'first_frame_min'] = np.min(arr) df.loc[i, 'first_frame_max'] = np.max(arr) pbar.update(1) sleep(1) # decide crop group (see dataset_smthsmth_analysis.ipynb point(2) for analysis) df = df.drop(df[df.width < 300].index) df['crop_group'] = 1 df.loc[df.width >= 420, 'crop_group'] = 2 # reject extreme frame lengths # df = df.drop(df[z<(z.mean()-3*z.std())].index) # df = df.drop(df[z<(z.mean()+3*z.std())].index) return df else: pass def _chunks(l, n): """ Input : l (dtype : int) n (dtype : int) Description : Yield successive n-sized chunks from l. """ for i in range(0, len(l), n): yield l[i:i + n]<file_sep>/prednet-smth-smth/viz_utils.py from collections import defaultdict import glob import imageio from matplotlib.backends.backend_pdf import PdfPages import matplotlib.pyplot as plt import numpy as np import os import pandas as pd from skimage.transform import rescale import sys import time # Please don't remove this function - <NAME> (Thanks and Regards, <NAME>) def plot_loss_curves(history, evaluation_method, model, result_dir): # plots the accuracy and loss curve for the mentioned evaluation method """ history: fitted model evaluation_method: categorical_crossentropy, threshold_score etc(dtype:string) model: neural network architecture(dtype:string) result_dir : directory in which results are stored(dtype:string) """ plot_dir = os.path.join(result_dir, "plots") if not os.path.exists(plot_dir): os.makedirs(plot_dir) fig = plt.figure() plt.plot(history.history['loss'], 'r', linewidth=3.0) plt.plot(history.history['val_loss'], 'b', linewidth=3.0) plt.legend(['Training loss', 'Validation Loss'], fontsize=18) plt.xlabel('Epochs ', fontsize=16) plt.ylabel('Reconstruction Loss', fontsize=16) plt.title("Loss Curves :" + model + "_for_" + evaluation_method, fontsize=16) fig.savefig(os.path.join(plot_dir, "loss_" + model + "_" + evaluation_method + ".png")) # Please don't remove this function - <NAME> (Thanks and Regards, <NAME>) def plot_accuracy_curves(history, evaluation_method, model, result_dir): # plots the accuracy and loss curve for the mentioned evaluation method """ history: fitted model evaluation_method: categorical_crossentropy, threshold_score etc(dtype:string) model: neural network architecture(dtype:string) result_dir : directory in which results are stored(dtype:string) """ plot_dir = os.path.join(result_dir, "plots") if not os.path.exists(plot_dir): os.makedirs(plot_dir) fig = plt.figure() plt.plot(history.history['accuracy'], 'r', linewidth=3.0) plt.plot(history.history['val_accuracy'], 'b', linewidth=3.0) plt.legend(['Training Accuracy', 'Validation Accuracy'], fontsize=18) plt.xlabel('Epochs ', fontsize=16) plt.ylabel('Accuracy', fontsize=16) plt.title("Accuracy Curves :" + model + "_for_" + evaluation_method, fontsize=16) fig.savefig(os.path.join(plot_dir, "accuracy_" + model + "_" + evaluation_method + ".png")) def plot_video(video=None, stats=False, save_pdf=False, RESULTS_SAVE_DIR='plots', vid_path=None): ''' plotting function that shows or saves a video as a sequence of frames on a grid can optionally show stats index of the frame is on the x label either video or path has to be given Arguments: video: an array of (n_frames, size_x, size_y) set to None by default in case path is given stats: False by default if True then it will output statistics for each frame (by index) frame.shape, np.min(frame), np.mean(frame), np.max(frame) save_pdf: False by default, it will show the plot only if True, it saves plot to RESULTS_SAVE_DIR the name of the file is current date and time RESULTS_SAVE_DIR: \plots by default folder to save plots into, gets created if doesn't exist vid_path: None by default if given it has to be in the form as seen in data.csv['path'] e.g.'/data/videos/something-something-v2/preprocessed/train/51646' ''' assert type(video) == np.ndarray or vid_path, "Please specify a video to plot as an array or path." assert not (type(video) == np.ndarray and vid_path), "Please only speficy either a video or a path." if vid_path != None: files = [] vid_list = [] for im_path in glob.glob(vid_path + '/*.png'): files.append(im_path) for file in sorted(files): im = (imageio.imread(file)) vid_list.append(im) video = np.array(vid_list) timestr = time.strftime("%Y%m%d-%H%M%S") if not os.path.exists(RESULTS_SAVE_DIR): os.mkdir(RESULTS_SAVE_DIR) height_of_plot = np.shape(video)[0] / 8 if np.shape(video)[0] % 8 == 0 else np.shape(video)[0] // 8 + 1 figs = [] fig1 = plt.figure(figsize=((np.shape(video)[2] + 20) / 80 * 8, (np.shape(video)[1] + 50) / 80 * height_of_plot)) for ind in range(np.shape(video)[0]): plt.subplot(height_of_plot, 8, ind + 1) plt.imshow(video[ind]) plt.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) plt.xlabel(ind, fontsize=15) plt.subplots_adjust(wspace=0.05, hspace=0.2) plt.show() figs.append(fig1) if stats: data = [] for ind, frame in enumerate(video): data.append([(ind), (frame.shape), (np.min(frame)), (np.mean(frame)), (np.max(frame))]) fig2 = plt.figure(figsize=((np.shape(video)[2] + 20) / 80 * 8, len(video))) the_table = plt.table(cellText=data, colLabels=["Index", "Frame shape", "Frame min", "Frame mean", "Frame max"], bbox=[0, 1, 1, 0.8]) the_table.set_fontsize(15) plt.xticks([]) plt.yticks([]) for spine in plt.gca().spines.values(): spine.set_visible(False) figs.append(fig2) if save_pdf: with PdfPages(RESULTS_SAVE_DIR + '/' + timestr + '.pdf') as pdf: for fig in figs: pdf.savefig(fig, bbox_inches='tight') else: plt.show() def plot_errors(error_outputs, X_test, ind=0): ''' function used to produce error_matrices for the evaluation mode in the pipeline ''' layer_error = [] matrices = [] for layer in range(len(error_outputs)): matrices.append([]) layer_error = error_outputs[layer][0] vid_error = layer_error[ind] for frame in vid_error: frame = np.transpose(frame, (2,0,1)) frame_matrix = np.sum([mat for mat in frame], axis=0) frame_matrix_rescaled = rescale(frame_matrix, (2**layer, 2**layer)) matrices[layer].append(frame_matrix_rescaled) return matrices def plot_changes_in_r(X_hats, ind, std_param=0.5): ''' funtion used to produce the values needed for R plots in the evaluation mode in the pipeline ''' results = [] vid = [(x_hat[0][ind], x_hat[1]) for x_hat in X_hats] frames = defaultdict(lambda : defaultdict(float)) for channel in range(len(vid)): for ind, frame in enumerate(vid[channel][0]): frames[channel][ind] = (np.average(np.abs(frame)), np.std(np.abs(frame))) results.append([]) y = [tup[0] for tup in frames[channel].values()] x = [n for n in range(len(y))] std = [tup[1] for tup in frames[channel].values()] results[channel].append((y, x, std)) return results <file_sep>/prednet-smth-smth/pipeline.py ######################################### Importing libraries ########################################################## import os import sys import time import glob import argparse import json from multiprocessing import Pool from functools import partial from six.moves import cPickle import numpy as np import pandas as pd import keras from keras import backend as K from keras.models import Model, model_from_json from keras.layers import Input, Dense, Flatten from keras.layers import TimeDistributed from keras.callbacks import LearningRateScheduler, ModelCheckpoint from keras.optimizers import Adam from keras.callbacks import EarlyStopping import tensorflow as tf tf.logging.set_verbosity(tf.logging.ERROR) import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from mpl_toolkits.axes_grid1 import make_axes_locatable # Custom imports from preprocess_data import split_data, extract_videos, create_dataframe, _chunks from data_utils import SmthSmthSequenceGenerator from viz_utils import plot_loss_curves, plot_errors, plot_changes_in_r from prednet import PredNet ######################################################################################################################## ########################################## Setting up the Parser ####################################################### parser = argparse.ArgumentParser(description="Prednet Pipeline") parser.add_argument('--csv_path', type=str, default="/data/videos/something-something-v2/preprocessed/data.csv") parser.add_argument("--preprocess_data_flag", default=False, action="store_true", help="Perform pre-processing") parser.add_argument("--train_model_flag", default=False, action="store_true", help="Train the model") parser.add_argument("--evaluate_model_flag", default=False, action="store_true", help="Evaluate the model") parser.add_argument("--finetune_extrapolate_model_flag", default=False,action="store_true", help="Extrapolate the model.") parser.add_argument("--extra_plots_flag", default=False, action="store_true", help="Evaluate the model and show error and R plots") # arguments needed for training and evaluation parser.add_argument('--weight_dir', type=str, default=os.path.join(os.getcwd(), "model"), help="Directory for saving trained weights and model") parser.add_argument('--result_dir', type=str, default=os.path.join(os.getcwd(), "results"), help="Directory for saving the results") parser.add_argument("--nb_epochs", type=int, default=150, help="Number of epochs") parser.add_argument("--batch_size", type=int, default=32, help="batch size to use for training, testing and validation") parser.add_argument("--n_channels", type=int, default=3, help="number of channels - RGB") parser.add_argument("--n_chan_layer", type=list, default=[48, 96, 192], help="number of channels for layer 1,2,3 and so " "on depending upon the length of the list.") parser.add_argument("--layer_loss", type=list, default=[1., 0., 0., 0.], help='Weightage of each layer in final loss.') parser.add_argument("--loss", type=str, default='mean_absolute_error', help="Loss function") parser.add_argument("--optimizer", type=str, default='adam', help="Model Optimizer") parser.add_argument("--lr", type=float, default=0.001, help="the learning rate during training.") parser.add_argument("--lr_reduce_epoch", type=int, default=200, help="the epoch after which the learning rate is devided by 10" "By default the whole val_data is used.") parser.add_argument("--horizontal_flip", default=False, action="store_true", help="Perform horizontal flipping when training") parser.add_argument("--samples_per_epoch", type=int, default=None, help="defines the number of samples that are considered as one epoch during training. " "By default it is len(train_data).") parser.add_argument("--samples_per_epoch_val", type=int, default=None, help="defines the number of samples from val_data to use for validation. " "By default the whole val_data is used.") parser.add_argument("--samples_test", type=int, default=None, help="defines the number of samples from test_data to use for Testing. " "By default the whole test_data is used in the evaluation phase.") parser.add_argument("--model_checkpoint", type=int, default=None, help="Saves model after mentioned amount of epochs. If not mentioned, " "saves the best model on val dataset") parser.add_argument("--early_stopping", default=False, action="store_true", help="enable early-stopping when training") parser.add_argument("--early_stopping_patience", type=int, default=10, help="number of epochs with no improvement after which training will be stopped") parser.add_argument("--plots_per_grp", type=int, default=2, help="Evaluation_mode. Produces 'n' plots per each sub-grps of videos. ") parser.add_argument("--std_param", type=float, default=0.5, help="parameter for the plotting R function: how many times the STD should we shaded") # arguments needed for SmthsmthGenerator() parser.add_argument("--fps", type=int, default=12, help="fps of the videos. Allowed values are [1,2,3,6,12]") parser.add_argument("--data_split_ratio", type=float, default=1.0, help="Splits the dataset for use in the mentioned ratio") parser.add_argument("--im_height", type=int, default=64, help="Image height") parser.add_argument("--im_width", type=int, default=80, help="Image width") parser.add_argument("--nframes", type=int, default=None, help="number of frames") parser.add_argument("--seed", type=int, default=None, help="seed") # arguments needed by PredNet model parser.add_argument("--a_filt_sizes", type=tuple, default=(3, 3, 3), help="A_filt_sizes") parser.add_argument("--ahat_filt_sizes", type=tuple, default=(3, 3, 3, 3), help="Ahat_filt_sizes") parser.add_argument("--r_filt_sizes", type=tuple, default=(3, 3, 3, 3), help="R_filt_sizes") parser.add_argument("--frame_selection", type=str, default="smth-smth-baseline-method", help="n frame selection method for sequence generator") # Extrapolation attributes parser.add_argument('--extrap_start_time', type=int, default=None, help="starting at this time step, the prediction from " "the previous time step will be treated as the " "actual input") args = parser.parse_args() ######################################################################################################################## ############################################# Common globals for all modes ############################################# json_file = os.path.join(args.weight_dir, 'model.json') history_file = os.path.join(args.weight_dir, 'training_history.json') start_time = time.time() # check if fps given is in valid values assert args.fps in [1, 2, 3, 6, 12], "allowed values for fps are [1,2,3,6,12] for this dataset. But given {}".format( args.fps) # if nframes is None then SmthsmthGenerator automatically calculates it using the fps if (args.nframes is None): fps_to_nframes = {12: 36, 6: 20, 3: 10, 2: 8, 1: 5} # dict taken from SmthsmthGenerator() time_steps = fps_to_nframes[args.fps] else: time_steps = args.nframes assert args.plots_per_grp > 0, "plots_per_grp cannot be 0 or negative." ######################################################################################################################## ############################################### Loading data ########################################################### df = pd.read_csv(os.path.join(args.csv_path), low_memory=False) train_data = df[df.split == 'train'] val_data = df[df.split == 'val'] test_data = df[df.split == 'holdout'] train_data = train_data[:int(len(train_data) * args.data_split_ratio)] val_data = val_data[:int(len(val_data) * args.data_split_ratio)] test_data = test_data[:int(len(test_data) * args.data_split_ratio)] print("num of training videos= ", len(train_data)) print("num of val videos= ", len(val_data)) print("num of test videos= ", len(test_data)) ######################################################################################################################## ############################################ Training model ############################################################ if args.train_model_flag: print("########################################## Training Model #################################################") # create weight directory if it does not exist if not os.path.exists(args.weight_dir): os.makedirs(args.weight_dir) # Data files # train_data = os.path.join(args.dest_dir, "train") # val_data = os.path.join(args.dest_dir, "val") input_shape = (args.n_channels, args.im_height, args.im_width) if K.image_data_format() == 'channels_first' else ( args.im_height, args.im_width, args.n_channels) stack_sizes = tuple([args.n_channels] + args.n_chan_layer) # weighting for each layer in final loss; "L_0" model: [1, 0, 0, 0], "L_all": [1, 0.1, 0.1, 0.1] # Checking if all the values in layer_loss are between 0.0 and 1.0 # Checking if the length of all layer loss list is equal to the number of prednet layers assert all(1.0 >= i >= 0.0 for i in args.layer_loss) and len(args.layer_loss) == len(stack_sizes) layer_loss_weights = np.array(args.layer_loss) layer_loss_weights = np.expand_dims(layer_loss_weights, 1) # equally weight all timesteps except the first time_loss_weights = 1. / (time_steps - 1) * np.ones((time_steps, 1)) time_loss_weights[0] = 0 r_stack_sizes = stack_sizes # Configuring the model prednet = PredNet(stack_sizes, r_stack_sizes, args.a_filt_sizes, args.ahat_filt_sizes, args.r_filt_sizes, output_mode='error', return_sequences=True) inputs = Input(shape=(time_steps,) + input_shape) errors = prednet(inputs) # errors will be (batch_size, nt, nb_layers) errors_by_time = TimeDistributed(Dense(1, trainable=False), weights=[layer_loss_weights, np.zeros(1)], trainable=False)(errors) # calculate weighted error by layer errors_by_time = Flatten()(errors_by_time) # will be (batch_size, nt) final_errors = Dense(1, weights=[time_loss_weights, np.zeros(1)], trainable=False)( errors_by_time) # weight errors by time model = Model(inputs=inputs, outputs=final_errors) model.compile(loss=args.loss, optimizer=args.optimizer) train_generator = SmthSmthSequenceGenerator(train_data , nframes=args.nframes , fps=args.fps , target_im_size=(args.im_height, args.im_width) , batch_size=args.batch_size , horizontal_flip=args.horizontal_flip , shuffle=True, seed=args.seed , nframes_selection_mode=args.frame_selection ) val_generator = SmthSmthSequenceGenerator(val_data , nframes=args.nframes , fps=args.fps , target_im_size=(args.im_height, args.im_width) , batch_size=args.batch_size , horizontal_flip=False , shuffle=True, seed=args.seed , nframes_selection_mode=args.frame_selection ) # start with lr of 0.001 and then drop to 0.0001 after 75 epochs lr_schedule = lambda epoch: args.lr if epoch < args.lr_reduce_epoch else args.lr/10 callbacks = [LearningRateScheduler(lr_schedule)] # Model checkpoint callback if args.model_checkpoint is None: period = 1 weights_file = os.path.join(args.weight_dir, 'checkpoint-best.hdf5') # where weights will be saved else: assert args.model_checkpoint <= args.nb_epochs, "'model_checkpoint' arg must be less than 'nb_epochs' arg" period = args.model_checkpoint weights_file = os.path.join(args.weight_dir, "checkpoint-{epoch:03d}-loss{val_loss:.5f}.hdf5") callbacks.append(ModelCheckpoint(filepath=weights_file, monitor='val_loss', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=period)) # Early stopping callback if (args.early_stopping == True): callbacks.append( EarlyStopping(monitor='val_loss', min_delta=0.00001, patience=args.early_stopping_patience, verbose=1, mode='auto')) if (args.samples_per_epoch): steps_per_epoch = args.samples_per_epoch // args.batch_size else: steps_per_epoch = len(train_generator) if (args.samples_per_epoch_val): steps_per_epoch_val = args.samples_per_epoch_val // args.batch_size else: steps_per_epoch_val = len(val_generator) # print out model summary and save model json model.summary() json_string = model.to_json() with open(json_file, "w") as f: f.write(json_string) history = model.fit_generator(train_generator , steps_per_epoch=steps_per_epoch , epochs=args.nb_epochs , callbacks=callbacks , validation_data=val_generator , validation_steps=steps_per_epoch_val ) # save training history to a file with open(history_file, 'w') as f: json.dump(history.history, f, sort_keys=True, indent=4) plot_loss_curves(history, "MSE", "Prednet", args.weight_dir) else: pass ######################################################################################################################## ########################################### Extrapolate the model ###################################################### if args.finetune_extrapolate_model_flag: print("###################################### Extrapolating the model ############################################") # Define loss as MAE of frame predictions after t=0 # It doesn't make sense to compute loss on error representation, since the error isn't wrt ground truth when # extrapolating. def extrap_loss(y_true, y_hat): y_true = y_true[:, 1:] y_hat = y_hat[:, 1:] return 0.5 * K.mean(K.abs(y_true - y_hat), axis=-1) # 0.5 to match scale of loss when trained in error mode (positive and negative errors split) nt = time_steps extrap_json_file = os.path.join(args.weight_dir, 'prednet_model-extrapfinetuned.json') # Throw an exception if the weight directory is empty if not os.listdir(args.weight_dir): sys.exit('Weight directory is empty. Please Train the model for t+1 prediction before extrapolating it.') # Getting all the filenames in the weight directory file_name,valid_loss_value = ([] for i in range(2)) for weights_file in glob.glob(args.weight_dir + "/*.hdf5"): file_name.append(weights_file) if len(file_name) > 1: # For models saved at every n epochs # Getting the weight file with lowest reconstruction loss. valid_loss_value = [float(values.split("-")[-1].split(".hdf5")[0][4:]) for values in file_name] min_loss_file_index = np.argmin(valid_loss_value) file = file_name[min_loss_file_index] filename = file.split("/")[-1].split(".hdf5")[0] else: filename = file_name[0].split("/")[-1].split(".hdf5")[0] if args.extrap_start_time is None: extrap_start_time = time_steps/2 else: extrap_start_time = args.extrap_start_time # Load trained model f = open(json_file, 'r') json_string = f.read() f.close() train_model = model_from_json(json_string, custom_objects={'PredNet': PredNet}) train_model.load_weights(weights_file) layer_config = train_model.layers[1].get_config() layer_config['output_mode'] = 'prediction' layer_config['extrap_start_time'] = extrap_start_time data_format = layer_config['data_format'] if 'data_format' in layer_config else layer_config['dim_ordering'] prednet = PredNet(weights=train_model.layers[1].get_weights(), **layer_config) input_shape = list(train_model.layers[0].batch_input_shape[1:]) input_shape[0] = time_steps inputs = Input(input_shape) predictions = prednet(inputs) model = Model(inputs=inputs, outputs=predictions) model.compile(loss=extrap_loss, optimizer='adam') train_generator = SmthSmthSequenceGenerator(train_data , nframes=args.nframes , fps=args.fps , target_im_size=(args.im_height, args.im_width) , batch_size=args.batch_size , horizontal_flip=args.horizontal_flip , shuffle=True, seed=args.seed , nframes_selection_mode=args.frame_selection , output_mode="prediction" ) val_generator = SmthSmthSequenceGenerator(val_data , nframes=args.nframes , fps=args.fps , target_im_size=(args.im_height, args.im_width) , batch_size=args.batch_size , horizontal_flip=args.horizontal_flip , shuffle=True, seed=args.seed , nframes_selection_mode=args.frame_selection , output_mode='prediction' ) # start with lr of 0.001 and then drop to 0.0001 after half number of epochs # lr_schedule = lambda epoch: 0.001 if epoch < args.lr_reduce_epoch else 0.0001 # callbacks = [LearningRateScheduler(lr_schedule)] callbacks = [] # where weights will be saved extrap_weights_file = os.path.join(args.weight_dir, filename + '-extrapolate.hdf5') callbacks.append(ModelCheckpoint(filepath=extrap_weights_file, monitor='val_loss', verbose=1, save_best_only=True)) if (args.samples_per_epoch): steps_per_epoch = args.samples_per_epoch // args.batch_size else: steps_per_epoch = len(train_generator) if (args.samples_per_epoch_val): steps_per_epoch_val = args.samples_per_epoch_val // args.batch_size else: steps_per_epoch_val = len(val_generator) history = model.fit_generator(train_generator, steps_per_epoch=steps_per_epoch, callbacks=callbacks, validation_data=val_generator, validation_steps=steps_per_epoch_val) json_string = model.to_json() with open(extrap_json_file, "w") as f: f.write(json_string) ######################################################################################################################## ############################################## Evaluate model ########################################################## if args.evaluate_model_flag: print("########################################### Evaluating data ###############################################") if not os.path.exists(args.result_dir): os.mkdir(args.result_dir) for weights_file in glob.glob(args.weight_dir + "/*.hdf5"): filename = weights_file.split("/")[-1].split(".hdf5")[0] # Load trained model f = open(json_file, 'r') json_string = f.read() f.close() train_model = model_from_json(json_string, custom_objects={'PredNet': PredNet}) train_model.load_weights(weights_file) # Create testing model (to output predictions) layer_config = train_model.layers[1].get_config() layer_config['output_mode'] = 'prediction' data_format = layer_config['data_format'] if 'data_format' in layer_config else layer_config['dim_ordering'] test_prednet = PredNet(weights=train_model.layers[1].get_weights(), **layer_config) input_shape = list(train_model.layers[0].batch_input_shape[1:]) input_shape[0] = time_steps inputs = Input(shape=tuple(input_shape)) predictions = test_prednet(inputs) test_model = Model(inputs=inputs, outputs=predictions) test_generator = SmthSmthSequenceGenerator(test_data , nframes=args.nframes , fps=args.fps , target_im_size=(args.im_height, args.im_width) , batch_size=args.batch_size , horizontal_flip=False , shuffle=True, seed=args.seed , nframes_selection_mode=args.frame_selection ) if (args.samples_test): max_test_batches = args.samples_test // args.batch_size else: max_test_batches = len(test_generator) mse_model_list, mse_prev_list = ([] for i in range(2)) for index, data in enumerate(test_generator): # Only consider steps_test number of steps if index > max_test_batches: break # X_test = test_generator.next()[0] X_test = data[0] X_hat = test_model.predict(X_test, args.batch_size) if data_format == 'channels_first': X_test = np.transpose(X_test, (0, 1, 3, 4, 2)) X_hat = np.transpose(X_hat, (0, 1, 3, 4, 2)) # Compare MSE of PredNet predictions vs. using last frame. Write results to prediction_scores.txt mse_model_list.append( np.mean((X_test[:, 1:] - X_hat[:, 1:]) ** 2)) # look at all timesteps except the first mse_prev_list.append(np.mean((X_test[:, :-1] - X_test[:, 1:]) ** 2)) # save in a dict and limit the size of float decimals to max 6 results_dict = { "MSE_mean": float("{:.6f}".format(np.mean(mse_model_list))), "MSE_std":float(("{:.6f}".format(np.std(mse_model_list)))), "MSE_mean_prev_frame_copy":float("{:.6f}".format(np.mean(mse_prev_list))), "MSE_std_prev_frame_copy":float("{:.6f}".format(np.std(mse_prev_list))) } with open(os.path.join(args.result_dir, 'scores_' + filename + '.json'), 'w') as f: json.dump(results_dict, f, sort_keys=True, indent=4) # Select specific sub-groups of the data to plot predictions # 1) group 1 - varying freq of labels in dataset # a) (> 200 videos) 3 labels with (putting + down) hand movement # b) (< 70 videos) 3 labels with (putting + down) hand movement # 2) group 2 - different hand movements (same freq) # a) showing to the camera # b) digging # 3) group 3 - different objects and background # a) throwning [something1] # b) throwning [something2] # 4) group 4 - ego motion and no ego motion # a) turning camera / moving camera closer # b) folding / unfolding sub_grps = [ # tuples containing (grp_name, templates) ("1a_freq_putting_", ["Putting [something] on a surface"]), ("1b_infreq_putting_", ["Putting [something] onto a slanted surface but it doesn't glide down"]), ("2a_no_hand_motion_showing_", ["Showing [something] to the camera"]), ("2b_hand_motion_digging_", ["Digging [something] out of [something]"]), ("3a_throwing_object1_", ["Throwing [something]"]), ("3b_throwing_object2_", ["Throwing [something]"]), ("4a_camera_motion_", ["Turning the camera left while filming [something]", "Turning the camera downwards while filming [something]", "Approaching [something] with your camera"]), ("4b_no_camera_motion_folding_", ["Folding [something]", "Unfolding [something]"]) ] total_vids_to_plt = args.plots_per_grp * len(sub_grps) total_grps = len(sub_grps) # sample 'plots_per_grp' videos from each sub-group test_data_for_plt = pd.DataFrame() for name, lbls in sub_grps: test_data_for_plt = test_data_for_plt.append( test_data[test_data.template.isin(lbls)].sample(n=args.plots_per_grp, random_state=args.seed) , ignore_index=True) X_test = SmthSmthSequenceGenerator(test_data_for_plt , nframes=args.nframes , fps=args.fps , target_im_size=(args.im_height, args.im_width) , batch_size=total_vids_to_plt , shuffle=False, seed=args.seed , nframes_selection_mode=args.frame_selection ).next()[0] X_hat = test_model.predict(X_test, total_vids_to_plt) ############################################## Extra plots ############################################## if args.extra_plots_flag: #Create models for error and R plots extra_test_models = [] extra_output_modes = ['E0', 'E1', 'E2', 'E3', 'A0', 'A1', 'A2', 'A3', 'Ahat0', 'Ahat1', 'Ahat2', 'Ahat3', 'R0', 'R1', 'R2', 'R3'] for output_mode in extra_output_modes: layer_config['output_mode'] = output_mode data_format = (layer_config['data_format'] if 'data_format' in layer_config else layer_config['dim_ordering']) extra_test_prednet = PredNet(weights=train_model.layers[1].get_weights(), **layer_config) input_shape = list(train_model.layers[0].batch_input_shape[1:]) input_shape[0] = args.nframes inputs = Input(shape=tuple(input_shape)) extra_predictions = extra_test_prednet(inputs) extra_test_model = Model(inputs=inputs, outputs=extra_predictions) extra_test_models.append((extra_test_model, output_mode)) #Create outputs for extra plots error_X_hats = [] for test_model, output_mode in extra_test_models: if output_mode[0]=='E': error_X_hat = test_model.predict(X_test, total_grps) error_X_hats.append((error_X_hat, output_mode)) R_X_hats = [] for test_model, output_mode in extra_test_models: if output_mode[0]=='R': R_X_hat = test_model.predict(X_test, total_grps) R_X_hats.append((R_X_hat, output_mode)) A_X_hats = [] Ahat_X_hats = [] for test_model, output_mode in extra_test_models: if output_mode[0]=='A': if output_mode[1]!='h': A_X_hat = test_model.predict(X_test, total_grps) A_X_hats.append((A_X_hat, output_mode)) else: Ahat_X_hat = test_model.predict(X_test, total_grps) Ahat_X_hats.append((Ahat_X_hat, output_mode)) ###################################################################################################################### plot_save_dir = os.path.join(args.result_dir, 'predictions/' + filename) if not os.path.exists(plot_save_dir): os.makedirs(plot_save_dir) aspect_ratio = float(X_hat.shape[2]) / X_hat.shape[3] for i in range(total_vids_to_plt): if args.extra_plots_flag: fig, ax = plt.subplots(ncols=1, nrows=20, sharex=True, figsize=(time_steps, 25 * aspect_ratio), gridspec_kw={'height_ratios':[1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,3,3]}) else: fig, ax = plt.subplots(ncols=1, nrows=2, sharex=True, figsize=(time_steps, 2 * aspect_ratio)) # set the title of the plot as the label and the video ID for reference fig.suptitle("ID {}: {}".format(test_data_for_plt.loc[i,'id'], test_data_for_plt.loc[i,'label'])) #Plot video ax = plt.subplot() ax.imshow(np.concatenate([t for t in X_test[i]], axis=1), interpolation='none', aspect="auto") ax.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) ax.set_ylabel(r'Actual', fontsize=10) ax.set_xlim(0,time_steps*args.im_width) #Plot predictions divider = make_axes_locatable(ax) ax = divider.append_axes("bottom", size="100%", pad=0.0) ax.imshow(np.concatenate([t for t in X_hat[i]], axis=1), interpolation='none', aspect="auto") ax.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) ax.set_ylabel(r'Prediction', fontsize=10) ax.set_xlim(0,time_steps*args.im_width) ######################################### Extra plot ############################################# if args.extra_plots_flag: #Create values for R plots results = plot_changes_in_r(R_X_hats, i, std_param=args.std_param) ax = divider.append_axes("bottom", size="300%", pad=0.2) #Plot R plots for layer in results: (y,x,std) = layer[0] x = [args.im_width/2+item*args.im_width for item in x] ax.fill_between(x, [(val-args.std_param*dev) for val,dev in zip(y,std)], [(val+args.std_param*dev) for val,dev in zip(y,std)], alpha=0.1) ax.plot(x, y) ax.set_xlim(0,time_steps*args.im_width) ax.set_xticks(np.arange(args.im_width/2, time_steps*args.im_width, step=args.im_width)) ax.set_xticklabels(np.arange(1,time_steps+1)) ax.grid(True) ax.set_ylabel(r"Mean R activations", fontsize=10) ax.xaxis.set_label_position('top') ax.legend(['R0','R1','R2','R3']) #Create values for E plots results = plot_changes_in_r(error_X_hats, i, std_param=args.std_param) ax = divider.append_axes("bottom", size="300%", pad=0.2) #Plot E plots for layer in results: (y,x,std) = layer[0] x = [args.im_width/2+item*args.im_width for item in x] ax.fill_between(x, [(val-args.std_param*dev) for val,dev in zip(y,std)], [(val+args.std_param*dev) for val,dev in zip(y,std)], alpha=0.1) ax.plot(x, y) ax.set_xlim(0,time_steps*args.im_width) ax.set_xticks(np.arange(args.im_width/2, time_steps*args.im_width, step=args.im_width)) ax.set_xticklabels(np.arange(1,time_steps+1)) ax.grid(True) ax.set_ylabel(r"Mean E activations", fontsize=10) ax.xaxis.set_label_position('top') ax.legend(['E0','E1','E2','E3']) #Create error output matrices to plot inside the next loop R_matrices = plot_errors(R_X_hats, X_test, ind=i) A_matrices = plot_errors(A_X_hats, X_test, ind=i) Ahat_matrices = plot_errors(Ahat_X_hats, X_test, ind=i) error_matrices = plot_errors(error_X_hats, X_test, ind=i) #Plot R, A, Ahat and errors for each layer for layer in range(len(error_matrices)): ##R ax = divider.append_axes("bottom", size="100%", pad=0.2) ax.imshow(np.concatenate([t for t in R_matrices[layer]], axis=1), interpolation='nearest', cmap='gray', aspect="auto") ax.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) ax.set_ylabel(r"R" + str(layer), fontsize=10) ax.set_xlabel(r"Layer " + str(layer), fontsize=10) ax.xaxis.set_label_position('top') ax.set_xlim(0,time_steps*args.im_width) ##A ax = divider.append_axes("bottom", size="100%", pad=0.0) ax.imshow(np.concatenate([t for t in Ahat_matrices[layer]], axis=1), interpolation='nearest', cmap='gray', aspect="auto") ax.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) ax.set_ylabel(r"Ahat" + str(layer), fontsize=10) ax.set_xlim(0,time_steps*args.im_width) ##Ahat ax = divider.append_axes("bottom", size="100%", pad=0.0) ax.imshow(np.concatenate([t for t in A_matrices[layer]], axis=1), interpolation='nearest', cmap='gray', aspect="auto") ax.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) ax.set_ylabel(r"A" + str(layer), fontsize=10) ax.set_xlim(0,time_steps*args.im_width) ##E ax = divider.append_axes("bottom", size="100%", pad=0.0) ax.imshow(np.concatenate([t for t in error_matrices[layer]], axis=1), interpolation='nearest', cmap='gray', aspect="auto") ax.tick_params(axis='both', which='both', bottom=False, top=False, left=False, right=False, labelbottom=False, labelleft=False) ax.set_ylabel(r"E" + str(layer), fontsize=10) ax.set_xlim(0,time_steps*args.im_width) ##################################################################################################################### grp_i = i // args.plots_per_grp plt.subplots_adjust(hspace=0., wspace=0., top=0.97) plt.savefig(plot_save_dir + "/" + sub_grps[grp_i][0] + str(test_data_for_plt.loc[i,'id']) + '.png') plt.clf() else: pass ######################################################################################################################## time_elapsed = time.time() - start_time print("Time elapsed for complete pipeline: {:.0f}h:{:.0f}m:{:.0f}s".format( time_elapsed // 3600, (time_elapsed // 60) % 60, time_elapsed % 60)) <file_sep>/prednet-smth-smth/requirements.txt numpy == 1.15.4 matplotlib == 3.0.2 scipy == 1.1.0 pandas == 0.23.4 keras == 2.0.6 theano==0.9.0 tensorflow-gpu == 1.2.1<file_sep>/prednet-smth-smth/run.bash # HOW TO USE #$1=output_files_suffix to prevent overwriting #$2=gpu Ex: can be 0, "1,2" etc. #$3=number of epochs # EXAMPLE #./run.bash test 0 ---> runs on gpu 0 for 50 epochs by default. saves results and models folders with '_test'suffix # tail -f nohup_test.out ---> to see the live output of the pipeline on the display #./run.bash fpstest "2,3" 5 ---> runs on gpu 2 and 3, for 5 epochs. saves results and models folders with '_fpstest' suffix epochs=${3-500} export CUDA_VISIBLE_DEVICES=$2 echo "========================================= SETTINGS =============================================" > nohup_$1.out cmd="python3 pipeline.py --batch_size 64 --nframes 12 --fps 3 --im_height 48 --im_width 56 --weight_dir model_fps3_n12_img48_56_750k --evaluate_model_flag --result_dir results_$1 --samples_test 100 --extra_plots_flag" echo $cmd >> nohup_$1.out echo "=================================================================================================" >> nohup_$1.out nohup $cmd &>> nohup_$1.out & #--train_model_flag --nb_epochs $epochs --samples_per_epoch 1500 --samples_per_epoch_val 1000 --model_checkpoint 5 #--samples_per_epoch 100 --data_split_ratio 0.002 --frame_selection "dynamic-fps" --model_checkpoint 1 # parser.add_argument("--preprocess_data_flag", type=bool, default=False, help="Perform pre-processing") # parser.add_argument("--train_model_flag", type=bool, default=False, help="Train the model") # parser.add_argument("--evaluate_model_flag", type=bool, default=False, help="Evaluate the model") # arguments needed for training and evaluation # parser.add_argument('--weight_dir', type=str, default=os.path.join(os.getcwd(), "model"), # help="Directory for saving trained weights and model") # parser.add_argument('--result_dir', type=str, default=os.path.join(os.getcwd(), "results"), # help="Directory for saving the results") # parser.add_argument("--nb_epochs", type=int, default=150, help="Number of epochs") # parser.add_argument("--train_batch_size", type=int, default=32, help="Train batch size") # parser.add_argument("--test_batch_size", type=int, default=32, help="Test batch size") # parser.add_argument("--n_channels", type=int, default=3, help="number of channels") # parser.add_argument("--loss", type=str, default='mean_absolute_error', help="Loss function") # parser.add_argument("--optimizer", type=str, default='adam', help="Model Optimizer") # parser.add_argument("--samples_per_epoch", type=int, default=None, # help="defines the number of samples that are considered as one epoch during training. By default it is len(train_data).") # parser.add_argument("--samples_per_epoch_val", type=int, default=None, # help="defines the number of samples from val_data to use for validation. By default the whole val_data is used.") # parser.add_argument("--model_checkpoint",type=int, default=None, # help="Saves model after mentioned amount of epochs. If not mentioned, saves the best model on val dataset") # parser.add_argument("--early_stopping", type=bool, default=True, # help="enable early-stopping when training") # parser.add_argument("--early_stopping_patience", type=int, default=10, # help="number of epochs with no improvement after which training will be stopped") # # arguments needed for SmthsmthGenerator() # parser.add_argument("--fps", type=int, default=12, # help="fps of the videos. Allowed values are [1,2,3,6,12]") # parser.add_argument("--data_split_ratio", type=float, default=1.0, # help="Splits the dataset for use in the mentioned ratio") # parser.add_argument("--im_height", type=int, default=64, help="Image height") # parser.add_argument("--im_width", type=int, default=80, help="Image width") # parser.add_argument("--nframes", type=int, default=None, help="number of frames") # parser.add_argument("--seed", type=int, default=None, help="seed") # # arguments needed by PredNet model # parser.add_argument("--a_filt_sizes", type=tuple, default=(3, 3, 3), help="A_filt_sizes") # parser.add_argument("--ahat_filt_sizes", type=tuple, default=(3, 3, 3, 3), help="Ahat_filt_sizes") # parser.add_argument("--r_filt_sizes", type=tuple, default=(3, 3, 3, 3), help="R_filt_sizes") # parser.add_argument("--frame_selection", type=str, default="smth-smth-baseline-method", # help="n frame selection method for sequence generator") # # arguments needed when preprocess_data_flag is True # parser.add_argument('--data_dir', type=str, help="Data directory", # default="/data/videos/something-something-v2") # parser.add_argument('--dest_dir', type=str, help="Destination directory", # default="/data/videos/something-something-v2/preprocessed") # parser.add_argument("--multithread_off", help="switch off multithread operation. By default it is on", # action="store_true") # parser.add_argument("--fps_dir", type=str, default=None, help="Frame per seconds directory")<file_sep>/prednet-smth-smth/data_utils.py #!/usr/bin/env python # coding: utf-8 ########################################## Importing libraries #####################################################import os, glob, sys import os, glob, sys import numpy as np import pandas as pd from matplotlib import pyplot as plt from PIL import Image, ImageOps from keras import backend as K from keras_preprocessing.image import Iterator # , load_img, img_to_array import threading ######################################################################################################################## class SmthSmthSequenceGenerator(Iterator): ''' Data generator that creates batched sequences from the smth-smth dataset for input into PredNet. info: to generate the data_csv, run the extract_20bn.py script first on the raw smth-smth videos. Args: dataframe : Can either be the path to the csv file generated by the extract_20bn.py or be a pandas df of the same csv nframes (optional): number of frames to use per video. If unspecified, the default is calculated from the fps as {fps:nframes} - {12:36, 6:20, 3:10, 2:8, 1:5} The policy for selection of these frames can be further modified using the 'nframes_selection_mode' and 'reject_extremes'parameters. fps (optional): Allowed values are [1,2,3,6,12]. Default fps of the videos is 12. split (optional): The split to use for training. Can be one of 'train', 'val', 'test'. target_im_size (optional): Provide a tuple of format (height,width). All video frames are resized to this shape. Default value is (128, 160). The height or width cannot be greater than this output_mode (optional): Used to control what is returned in y (label): if set to 'label' returns the label's template ID. if set to 'prediction' simply returns y = X. if set to 'error' returns a np.zeros() of same shape as x. nframes_selection_mode (optional): Can be one of "smth-smth-baseline-method" or "dynamic-fps" if set as "smth-smth-baseline-method", a) For num_of_frames < nframes : replicate the first and last frames. b) For num_of_frames > nframes : sample consecutive 'nframes' such that the sampled videos segments are mostly in the center of the whole video if set as "dynamic-fps", a) For num_of_frames < nframes : Artificially increase fps - Duplicate frames at the begining, end and in between the video to make it equal to nframes. b) For num_of_frames > nframes : Artificially decrease fps - Sample non-consecutive frames from the videos such that the total number of frames equal nframes. reject_extremes (optional): A tuple which says (reject-videos-with-nframes-lower-than-this, reject-videos-with-nframes-higher-than-this) Recommended to set to (12,84) that corresponds to 3 std. dev. for the smth-smth dataset and will rejects outliers in the dataset. img_interpolation (optional): PIL interpolation to use while resizing. allowed values are {'nearest', 'bicubic', 'bilinear', 'LANCZOS'} random_crop (optional): Data-augumentation. Flag to enable 'random-crop' by the width of the frames. The crop width is decided using a binomial distribution with max probability at the center of the frame. horizontal_flip (optional): Data-augumentation. Flag to enable random 'horizontal_flip' of videos. the labels are also changed appropriately. Ex. 'Pulling [something] from right to left' -> 'Pulling [something] from left to right' after flipping ''' def __init__(self, dataframe , nframes=None , fps=12 , split='' , batch_size=32 , target_im_size=(64, 80) , img_interpolation='nearest' , output_mode='error' , nframes_selection_mode="smth-smth-baseline-method" , reject_extremes=(None, None) , random_crop=True , horizontal_flip=False , shuffle=True, seed=None , data_format='channels_last' , debug=False ): if seed is not None: np.random.seed(seed) if (isinstance(dataframe, str)): df = pd.read_csv(dataframe) else: df = dataframe # select the split subset if (split): assert split in set(df['split']), "split can be one of ({}) only".format(set(df['split'])) # select the split subset df = df[df['split'] == split] # select the subset of videos with nframes >= min_nframes and <= max_nframes min_nframes, max_nframes = reject_extremes if (min_nframes is not None): df_subset = df[df.num_of_frames >= min_nframes] if (len(df_subset) < 0.7 * len(df)): # if more than 30% rejected then raise a WARNING print( "SmthsmthGenerator WARNING: Rejecting videos less than {}-frames resulted in {:.0f}% of the videos({}) to be discarded.".format( min_nframes, float(len(df_subset)) * 100 / len(df), len(df_subset))) df = df_subset if (max_nframes is not None): df_subset = df[df.num_of_frames <= max_nframes] if (len(df_subset) < 0.7 * len(df)): # if more than 30% rejected then raise a WARNING print( "SmthsmthGenerator WARNING: Rejecting videos more than {}-frames resulted in {:.0f}% of the videos({}) to be discarded.".format( max_nframes, float(len(df_subset)) * 100 / len(df), len(df_subset))) df = df_subset assert output_mode in {'error', 'prediction', 'label'}, 'output_mode must be in {error, prediction, label}' self.output_mode = output_mode assert len(target_im_size) == 2, "Invalid 'target_im_size'. It should be a tuple of format (height, width)" assert (target_im_size[0] <= min(df.height)) and (target_im_size[1] <= min(df.width)), "Invalid 'target_im_size'.\ (height, width) cannot be greater than the ({:.0f},{:.0f}) which is the minimum in the dataset".format(min(df.height), min(df.width)) self.df = df.reset_index(drop=True) self.target_im_size = target_im_size self.batch_size = batch_size assert nframes_selection_mode in { "smth-smth-baseline-method", "dynamic-fps" }, 'nframes_selection_mode must be one of {"smth-smth-baseline-method", "dynamic-fps"}' self.nframes_selection_mode = nframes_selection_mode if(fps!=12 and nframes_selection_mode=="dynamic-fps"): print("SmthsmthGenerator WARNING. Value passed to fps is ignored when 'nframes_selection_mode' is set as 'dynamic-fps'") assert nframes_selection_mode!="dynamic-fps" or nframes is not None,"when 'nframes_selection_mode' is set as 'dynamic-fps' then nframes must be specified and cannot be 'None'. " assert fps in [1,2,3,6,12], "allowed values for fps are [1,3,6,12] for this dataset. But given {}".format(fps) self.fps_ratio = 12//fps if(nframes is None): fps_to_nframes = {12:36, 6:20, 3:10, 2:8, 1:5} nframes = fps_to_nframes[fps] print("{} nframes/video set by default.".format(nframes)) self.nframes = nframes _PIL_INTERPOLATION_METHODS = { 'LANCZOS': Image.LANCZOS, 'nearest': Image.NEAREST, 'bilinear': Image.BILINEAR, 'bicubic': Image.BICUBIC } assert img_interpolation in _PIL_INTERPOLATION_METHODS.keys(), "Allowed values for 'img_interpolation' are {}".format( set(_PIL_INTERPOLATION_METHODS.keys())) self.img_interpolation = _PIL_INTERPOLATION_METHODS[img_interpolation] self.horizontal_flip = horizontal_flip if (self.horizontal_flip): # if we flip, some labels need to be remapped which contain these orientation information self.some_label_remaps = {166: 167, 167: 166, 93: 94, 94: 93, 86: 87, 87: 86} self.random_crop = random_crop self.shuffle = shuffle self.seed = seed self.debug = debug if (data_format != 'channels_last'): raise NotImplementedError("Only 'channels_last' data_format is currently supported.\ {} option is not supported".format(data_format)) super(SmthSmthSequenceGenerator, self).__init__(n=len(self.df), batch_size=batch_size, shuffle=shuffle, seed=seed) def _get_batches_of_transformed_samples(self, index_array): batch_x = np.empty(((len(index_array),) + (self.nframes,) + self.target_im_size + (3,)) , dtype=np.float32) # to store which videos have been horizontally flipped. Needed for output mode 'label' hor_flipped = np.empty(len(index_array), ) for i, idx in enumerate(index_array): # read the video dir vid_dir = self.df.loc[idx, 'path'] batch_x[i], hor_flipped[i] = self.fetch_and_preprocess(vid_dir, self.target_im_size) if self.output_mode == 'error': # model outputs errors, so y should be zeros batch_y = np.zeros(self.batch_size, np.float32) elif self.output_mode == 'prediction': # output actual pixels batch_y = batch_x elif self.output_mode == 'label': batch_y = np.asarray(self.df.loc[index_array, "template_id"]) if (self.horizontal_flip): # remap the effected horizontally flipped labels for i in range(len(batch_y)): if (hor_flipped[i]) and (batch_y[i] in self.some_label_remaps.keys()): if (self.debug): print("idx {}: label {} replaced with {}".format(i, batch_y[i], self.some_label_remaps[ batch_y[i]])) batch_y[i] = self.some_label_remaps[batch_y[i]] else: raise NotImplementedError return batch_x, batch_y def fetch_and_preprocess(self, vid_dir, target_im_size): #read the fps if specified frames = sorted(glob.glob(vid_dir + "/*.png"))[::self.fps_ratio] total_frames = len(frames) # select exactly 'nframes' from each video dir... preprocessing (4) if (self.nframes_selection_mode == "smth-smth-baseline-method"): if (total_frames > self.nframes): # sample the start frame using a binomial distribution highest probability at the center of the video start_frame_idx = np.random.binomial((total_frames - self.nframes), p=0.5) frames_out = frames[start_frame_idx: start_frame_idx + self.nframes] elif (total_frames < self.nframes): # replicate the first frame and last frame at the ends to match self.nframes rep_begin = np.random.binomial((self.nframes - total_frames), p=0.5) rep_end = (self.nframes - (total_frames + rep_begin)) frames_out = [frames[0]] * (rep_begin) + frames + [frames[-1]] * (rep_end) else: # total_frames == self.nframes frames_out = frames else: # (self.nframes_selection_mode == "dynamic-fps"): if (total_frames > self.nframes): # delete frames at regular intervals until exactly nframes are left if (self.debug): print("total_frames=", total_frames, "frames_excess=", (total_frames - self.nframes)) frames_out = frames delete_rate = (total_frames // (total_frames - self.nframes)) deleted = 0 i = 0 # start by first replicating the 0th frame while (len(frames_out) > self.nframes): del_idx = i * delete_rate - deleted if (self.debug): print("removing frame at idx", del_idx) del frames_out[del_idx] i += 1 deleted += 1 elif (total_frames < self.nframes): # duplicate frames at regular intervals until exactly nframes are left if (self.debug): print("total_frames=", total_frames, "frames_shortage=", (self.nframes - total_frames)) frames_out = frames insert_rate = (total_frames // (self.nframes - total_frames)) inserted = 0 i = 0 # start by first replicating the 0th frame while (len(frames_out) < self.nframes): dup_idx = i * insert_rate + inserted if (self.debug): print("duplicating frame at idx", dup_idx) frames_out.insert(dup_idx, frames[dup_idx]) i += 1 inserted += 1 else: # total_frames == self.nframes frames_out = frames ### load_vid using keras built-in function # X = np.empty(((self.nframes,) + target_im_size + (3,)), dtype=np.float32) # for i,frame in enumerate(frames_out): # X[i] = img_to_array(load_img(frame, target_size=target_im_size)) X, hor_flip = self.load_vid(frames_out, target_im_size) # rescale X = X / 255. return X, hor_flip def load_vid(self, frames, target_im_size): X = np.empty(((self.nframes,) + target_im_size + (3,)), dtype=np.float32) target_h, target_w = target_im_size if (self.horizontal_flip): # flip coin to randomly perform horizontal flipping flip = np.random.randint(0, 2) else: flip = False if (self.debug): debug_print_once = True else: debug_print_once = False w_crop_flag = True # calculate the width crop edges only once for i, frame in enumerate(frames): im = Image.open(frame) if (debug_print_once): print("original im shape (W X H)=", im.size) if (self.random_crop): w_same_aspect = int((target_h / im.height) * im.width) # resize such that the aspect ratio is conserved for later random cropping if (w_same_aspect > target_w): im = im.resize((w_same_aspect, target_h), self.img_interpolation) # width-cropping if (w_crop_flag): w_crop = np.random.binomial((im.width - target_w), p=0.5) w_crop_flag = False if (debug_print_once): print( "({},{}) width cropped on left and right resp.".format(w_crop, im.width - w_crop - target_w)) im = im.crop((w_crop, 0, target_w + w_crop, im.height)) else: im = im.resize((target_w, target_h), self.img_interpolation) else: im = im.resize((target_w, target_h), self.img_interpolation) if (flip): if (debug_print_once): print("Horizontal flipping performed") im = ImageOps.mirror(im) if (debug_print_once): print("im resized shape", im.size) debug_print_once = False # turn off for this video's remaining frames # move axis and store the array in X X[i] = np.asarray(im, dtype=np.float32) return X, flip def next(self): """For python 2.x. # Returns The next batch. info : function taken directly from keras_preprocessing.DataFrameIterator class """ # Keeps under lock only the mechanism which advances # the indexing of each batch. with self.lock: index_array = next(self.index_generator) # A bug in keras.Iterator class causes it to sometimes return index_array of size < batch_size # This occurs at the end of the entire dataset if(len(index_array)!=self.batch_size ): index_array = next(self.index_generator) # The transformation of images is not under thread lock # so it can be done in parallel return self._get_batches_of_transformed_samples(index_array) def __len__(self): return len(self.df)//self.batch_size # In[71]: if __name__ == '__main__': # TEST : runs the generator 10 times and prints out the output dimension of the batches returned # GUIDE : how to use the class data_csv = "/data/videos/something-something-v2/preprocessed/data.csv" val_gen = SmthSmthSequenceGenerator(data_csv , nframes=48 , split="val" , batch_size=8 , target_im_size=(64, 80) , shuffle=True, seed=42 # , reject_extremes = (16, 80) , output_mode="label" , random_crop=False , horizontal_flip=True , img_interpolation='bilinear' # , debug = True # , nframes_selection_mode = "dynamic-fps" ) print("shape of the next 10 generator outputs:") for i in range(5): batch, label = next(val_gen) print("Batch shape =", batch.shape) print("label shape =", label.shape) from viz_utils import plot_video # visualize one video plot_video(next(val_gen)[0][0], save_pdf=True, stats=True)<file_sep>/extract_20bn.py import glob, os import sys import argparse import json from multiprocessing import Pool from functools import partial import numpy as np import pandas as pd from PIL import Image, ImageStat def split_20bn_dataset(data_dir, train_json_name="something-something-v2-train.json", test_json_name="something-something-v2-test.json", val_json_name="something-something-v2-validation.json" ): ''' Script to split the videos into train, val, test folders. data_dir should contain the raw videos in a 'raw' folder and the train, test and val json files. ''' with open(data_dir+train_json_name) as f: data = json.load(f) train_list = [v["id"] for v in data] with open(data_dir+val_json_name) as f: data = json.load(f) val_list = [v["id"] for v in data] with open(data_dir+test_json_name) as f: data = json.load(f) test_list = [v["id"] for v in data] os.system("mkdir {}/preprocessed".format(data_dir)) os.system("mkdir {}/preprocessed/train".format(data_dir)) os.system("mkdir {}/preprocessed/test".format(data_dir)) os.system("mkdir {}/preprocessed/val".format(data_dir)) # videos = [video for video in os.listdir(data_dir+"raw")] # print(len(videos)) for v in videos: v_id = v.split(".")[0] if(v_id in test_list): os.system("cp -u {} {}".format(data_dir+"raw/"+v, data_dir+"preprocessed/test/"+v)) elif(v_id in train_list): os.system("cp -u {} {}".format(data_dir+"raw/"+v, data_dir+"preprocessed/train/"+v)) elif(v_id in val_list): os.system("cp -u {} {}".format(data_dir+"raw/"+v, data_dir+"preprocessed/val/"+v)) else: print("{} is not listed in either test, train nor val lists".format(v)) def extract_videos(raw_vids, dest_dir, fps=None): '''Script to convert .webm to image sequences''' for raw_vid in raw_vids: # create a folder for each video with it's unique ID v_name = raw_vid.split("/")[-1].split(".")[0] split = raw_vid.split("/")[-2] os.system("mkdir -p {}/{}/{}".format(dest_dir, split, v_name)) # check if this folder is already extracted if (not os.path.isfile("{}/{}/{}/image-001.png".format(dest_dir, split, v_name))): # run the ffmpeg software to extract the videos based on the fps provided if fps is not None: os.system("ffmpeg -framerate {} -i {} {}/{}/{}/image-%03d.png".format( fps, raw_vid, dest_dir, split, v_name) ) else: os.system("ffmpeg -i {} {}/{}/{}/image-%03d.png".format( raw_vid, dest_dir, split, v_name)) print(raw_vid, "converted..") def create_dataframe(vid_list, labels_dir): df = pd.DataFrame({"path":vid_list}) for i, vid_path in enumerate(df['path']): # read the first frame of the video im = Image.open(vid_path + "/image-001.png") #add video name df.loc[i,'id'] = vid_path.split("/")[-1] #add frame resolution information df.loc[i,'height'] = int(im.height) df.loc[i,'width'] = int(im.width) df.loc[i,'aspect_ratio'] = im.height/im.width df.loc[i, 'num_of_frames'] = int(len(os.listdir(vid_path))) # image statistics im_stat = ImageStat.Stat(im) df.loc[i, 'first_frame_mean'] = np.mean(im_stat.mean) df.loc[i, 'first_frame_var'] = np.mean(im_stat.var) df.loc[i, 'first_frame_min'] = im_stat.extrema[0][0] df.loc[i, 'first_frame_max'] = im_stat.extrema[0][1] im.close() #decide crop group (see dataset_smthsmth_analysis.ipynb point(2) for analysis) df = df.drop(df[df.width < 300].index) df['crop_group'] = 1 df.loc[df.width >= 420,'crop_group'] = 2 # add label information train_json_name = "/something-something-v2-train.json" val_json_name = "/something-something-v2-validation.json" labels_json_name = "/something-something-v2-labels.json" test_json_name = "/something-something-v2-test.json" with open(labels_dir + train_json_name) as f: train_df = pd.DataFrame(json.load(f)) train_df['split'] = ['train']*len(train_df) with open(labels_dir + val_json_name) as f: val_df = pd.DataFrame(json.load(f)) val_df['split'] = ['val']*len(val_df) with open(labels_dir + test_json_name) as f: test_df = pd.DataFrame(json.load(f)) test_df['split'] = ['test']*len(test_df) with open(labels_dir + labels_json_name) as f: templates = json.load(f) labels_df = train_df.append([val_df, test_df], sort=False) df = df.join(labels_df.set_index('id'), on='id') # map the label ID defined in the templates f = lambda x: templates[x.replace('[','').replace(']','')] if(isinstance(x,str)) else x df['template_id'] = df.template.map(f) return df def _chunks(l, n): """Yield successive n-sized chunks from l.""" for i in range(0, len(l), n): yield l[i:i + n] if __name__ == '__main__': ''' script usage example - python3 extract_20bn.py /data/videos/something-something-v2/raw /data/videos/something-something-v2/preprocessed ''' parser = argparse.ArgumentParser(description="Extracts the 20bn-something-something dataset raw videos from 'data_dir' to 'dest_dir' and performs some pre-processing on the video frames") parser.add_argument('--data_dir', type=str, help="The dir containing the raw 20bn dataset categorized into 'train', 'val' and 'test' folders.", default = "/data/videos/something-something-v2/raw") parser.add_argument('--dest_dir', type=str, help="The dir in which the final extracted and processed videos will be placed.", default = "/data/videos/something-something-v2/preprocessed") parser.add_argument("--multithread_off", help="switch off multithread operation. By default it is on", action="store_true") parser.add_argument("--fps", type=str, help="Extract videos with a fps other than the default. should now be higher than the max fps of the video.") args = parser.parse_args() assert os.path.isdir(args.data_dir), "arg 'data_dir' must be a valid directory" assert os.path.isdir(args.dest_dir), "arg 'dest_dir' must be a valid directory" if args.fps is not None: # create a new folder for the fps and append it to the dest_dir os.system("mkdir -p {}/fps{}".format(args.dest_dir, args.fps)) args.dest_dir = args.dest_dir+"/fps"+args.fps #step 0 - divide into train, test and val splits os.system("mkdir -p {}/train".format(args.dest_dir)) os.system("mkdir -p {}/test".format(args.dest_dir)) os.system("mkdir -p {}/val".format(args.dest_dir)) #step 1 - extract the videos to frames (details in dataset_smthsmth_analysis.ipynb) videos = glob.glob(args.data_dir+"/*/*") # videos = [ # v for v in glob.glob(args.data_dir+"/*/*") if not os.path.isfile( # "{}/{}/{}/image-001.png".format( # args.dest_dir, v.split("/")[-2], v.split("/")[-1].split(".")[0] # ) # ) # ] if not (args.multithread_off): #split the videos into sets of 10000 videos and create a thread for each videos_list = list(_chunks(videos, 10000)) print("starting {} parallel threads..".format(len(videos_list))) # fix the dest_dir and fps parameter before starting parallel processing extract_videos_1 = partial(extract_videos, dest_dir=args.dest_dir, fps=args.fps) pool = Pool(processes=len(videos_list)) pool.map(extract_videos_1, videos_list) else: extract_videos(videos) #step 2 - define frames-resize categories in a pandas df (details in dataset_smthsmth_analysis.ipynb) videos = [vid for vid in glob.glob(args.dest_dir+"/*/*")] df = create_dataframe(videos, os.path.abspath(os.path.join(args.data_dir,".."))) #step3 - randomly set 20k videos as holdout from the train 'split' train_idxs = df[df.split == 'train'].index holdout_idxs = np.random.choice(train_idxs, size=20000,replace=False) df.loc[holdout_idxs,'split'] = 'holdout' df.to_csv(args.dest_dir+"/data.csv", index=False)<file_sep>/README.md # Active vision in PredNet ### Introduction : In this project, we will study different way to implement an "Active vision" technique on the PredNet architecture (https://coxlab.github.io/prednet/) The PredNet model is a deep learning model that is inspired by the neuroscientific theory of Predictive coding. The model is trained to predict the next frame in videos. We will use the following video action-classification datasets : https://20bn.com/datasets/something-something/v2 ### Motivation : Working with videos is very computationally expensive and using active vision techniques to 'actively' select and process smaller portions of the video at a time could turnout to be very useful. Also we believe that 'actively' deciding the sample of the video through the course of learning would result in the model learning a richer representation of the video as a whole. ### Sub-tasks : There are a bunch of possible working directions in this project : (1) Study the different techniques of implementing Active Vision in PredNet. I could think of the following techniques - saccadic vision-like, fovea-like, using probabilistic saliency filters, soft attention layers, controlling dropout/dropconnect, control inception layer. (2) Try to implement saccadic-vision-like system in the PredNet's top-down. (3) Try to implement probabilistic saliency filters in the PredNet's top-down. (4) Try using soft-attention in the PredNet's top-down. (5) Study this problem as a Reinforcement learning problem and argue if the problems faced by today's RL techniques are also applicable here ? It goes something like this - the top-down makes a series of choices /actions through the time span of the video. These actions could be, for example, selecting the next region to focus on in a saccadic-based model or fovea-based model. Each action is selected conditional on the previous sequence of actions and inputs just like any other RL problem. At the end of the video the model predicts the action class of the video. A policy gradient then helps the model to learn the right policy (the sequence of actions that lead to correct action classification of the video) from the wrong ones. ### Architecture : Vanilla PredNet | Active PredNet :-------------------------:|:-------------------------: <img src="https://github.com/RoshanRane/active_vision_prednet/blob/master/PredNet_Vanilla.jpg" height="450" width="400"/> | <img src="https://github.com/RoshanRane/active_vision_prednet/blob/master/PredNet_active.png" height="450" width="400" align="right"/>
f5adb43b8858270f4d7b42e10a6dd89b2a399a32
[ "Markdown", "Python", "Text", "Shell" ]
8
Python
RoshanRane/active_vision_prednet
9fa52c01a1ea46b69a1677fa431fec236ca728ce
a8238b40d80b5d94280f1f7c25b64c1da1f7abc5
refs/heads/master
<file_sep>require 'rails_helper' RSpec.describe 'as a visitor', type: :feature do before :each do @shelter1 = Shelter.create( name: '<NAME>', address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202' ) @pet1 = Pet.create( image: 'https://www.talenthounds.ca/wp-content/uploads/2014/02/1010297_10151682411488254_1369748570_n.jpg', name: 'Athena', description: 'butthead', age: '1', sex: 'female', status: false, shelter_id: @shelter1.id ) end it 'can update a pet from index' do visit '/pets' expect(page).to have_button("Update Pet") click_button "Update Pet" expect(current_path).to eq("/pets/#{@pet1.id}/edit") end it 'can delete a pet from index' do visit '/pets' expect(page).to have_button("Delete #{@pet1.name}") click_button "Delete #{@pet1.name}" expect(current_path).to eq('/pets') expect(page).to have_no_content(@pet1.name) end end <file_sep>require 'rails_helper' RSpec.describe 'shelters show page feature', type: :feature do context 'as a user' do it 'can see all data pertaining to shelters' do shelter1 = Shelter.create(name: "<NAME>", address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202') visit "/shelters/#{shelter1.id}" expect(page).to have_content(shelter1.name) expect(page).to have_content(shelter1.address) expect(page).to have_content(shelter1.city) expect(page).to have_content(shelter1.state) expect(page).to have_content(shelter1.zip) end it 'can delete a shelter' do shelter1 = Shelter.create(name: "<NAME>", address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202') visit "/shelters/#{shelter1.id}" click_button('Delete Shelter') expect(page).to have_no_content(shelter1.name) end end end RSpec.describe 'shelter show page links' do context 'as a page' do it 'has an edit button' do shelter1 = Shelter.create(name: "<NAME>", address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202') visit "/shelters/#{shelter1.id}" click_button 'Update Shelter' expect(current_path).to eq("/shelters/#{shelter1.id}/edit") end end end <file_sep>require 'rails_helper' RSpec.describe 'editing a shelter' do context 'as a user' do it 'can edit parameters of a shelter' do shelter1 = Shelter.create(name: "<NAME>", address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202') visit "/shelters/#{shelter1.id}" expect(page).to have_content("Mike's Shelter") click_on 'Update Shelter' expect(current_path).to eq("/shelters/#{shelter1.id}/edit") fill_in 'Name', with: '<NAME> Shop Name' fill_in 'Address', with: '1234 Address Road' fill_in 'City', with: 'Denver' fill_in 'State', with: 'CO' fill_in 'Zip', with: '12345' click_on 'Update Shelter' expect(current_path).to eq("/shelters/#{shelter1.id}") expect(page).to have_content('New Pet Shop Name') expect(page).to_not have_content("Mike's Shelter") end end end <file_sep>require 'rails_helper' RSpec.describe 'editing a pet', type: :feature do context 'as a visitor' do before :each do @shelter1 = Shelter.create( name: '<NAME>', address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202' ) @pet1 = Pet.create!( image: 'https://www.talenthounds.ca/wp-content/uploads/2014/02/1010297_10151682411488254_1369748570_n.jpg', name: 'Athena', description: 'butthead', age: '1', sex: 'female', status: false, shelter_id: @shelter1.id ) end it 'can edit parameters of a pet' do visit "/pets/#{@pet1.id}" click_on 'Update Pet' expect(current_path).to eq("/pets/#{@pet1.id}/edit") fill_in 'name', with: 'Oscar' fill_in 'image', with: 'https://i.ytimg.com/vi/DgdMV3IczYY/hqdefault.jpg' fill_in 'description', with: 'Edited desc' fill_in 'age', with: '1' fill_in 'sex', with: 'female' click_on 'Update' expect(current_path).to eq("/pets/#{@pet1.id}") expect(page).to have_content('Oscar') expect(page).to have_content('F') end end end <file_sep>require 'rails_helper' RSpec.describe 'pet show page', type: :feature do context 'as a visitor' do before :each do @shelter1 = Shelter.create!( name: '<NAME>', address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202' ) @pet1 = Pet.create!( image: 'https://www.talenthounds.ca/wp-content/uploads/2014/02/1010297_10151682411488254_1369748570_n.jpg', name: 'Athena', description: 'butthead', age: '1', sex: 'female', status: false, shelter_id: @shelter1.id ) end it 'can see an individual pets information' do visit "/pets/#{@pet1.id}" expect(page).to have_css("img[src*='#{@pet1.image}']") expect(page).to have_content(@pet1.name) expect(page).to have_content(@pet1.description.capitalize) expect(page).to have_content(@pet1.age) expect(page).to have_content('F') expect(page).to have_content(@pet1.status) end end end <file_sep>require 'rails_helper' RSpec.describe 'As a visitor', type: :feature do before :each do @shelter1 = Shelter.create( name: '<NAME>', address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202' ) @shelter2 = Shelter.create( name: '<NAME>', address: '150 Main Street', city: 'Hershey', state: 'PA', zip: '17033' ) end it 'can edit a shelter from index' do visit '/shelters' expect(page).to have_button("Update #{@shelter1.name}") expect(page).to have_button("Update #{@shelter2.name}") click_button "Update #{@shelter1.name}" expect(current_path).to eq("/shelters/#{@shelter1.id}/edit") end it 'can delete a shelter from index' do visit '/shelters' expect(page).to have_button("Delete #{@shelter1.name}") expect(page).to have_button("Delete #{@shelter2.name}") click_button "Delete #{@shelter1.name}" expect(current_path).to eq('/shelters') expect(page).to have_no_content(@shelter1.name) end end <file_sep>require 'rails_helper' RSpec.describe 'new shelter creation', type: :feature do context 'as a user' do it 'can create a new shelter' do visit '/shelters/new' fill_in 'name', with: '<NAME>' fill_in 'address', with: '999 E. Road' fill_in 'city', with: 'City Name' fill_in 'state', with: 'State Abbrev' fill_in 'zip', with: 'Zip Code' click_button('Create Shelter') expect(current_path).to eq('/shelters') expect(page).to have_content('New Shelter Name') end end end <file_sep>require 'rails_helper' RSpec.describe 'shelters index page', type: :feature do context 'as a user' do it 'can see names of shelters' do shelter1 = Shelter.create(name: '<NAME>', address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202') shelter2 = Shelter.create(name: '<NAME>', address: '150 Main Street', city: 'Hershey', state: 'PA', zip: '17033') visit '/shelters' expect(page).to have_content(shelter1.name) expect(page).to have_content(shelter2.name) end end end <file_sep>require 'rails_helper' RSpec.describe 'as a visitor', type: :feature do before :each do @shelter1 = Shelter.create( name: '<NAME>', address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202' ) end it 'can create a pet for a shelter' do visit "/shelters/#{@shelter1.id}/pets" click_button 'Create Pet' expect(current_path).to eq("/shelters/#{@shelter1.id}/pets/new") fill_in 'image', with: 'https://images-na.ssl-images-amazon.com/images/I/41c%2BPPhJGkL._AC_.jpg' fill_in 'name', with: 'Octavius' fill_in 'description', with: 'Derpy' fill_in 'age', with: '1' fill_in 'sex', with: 'male' click_button 'Create Pet' expect(current_path).to eq("/shelters/#{@shelter1.id}/pets") expect(page).to have_content('Octavius') end end <file_sep>class Pet < ApplicationRecord validates_presence_of :image, :name, :description, :age, :sex, :status, :shelter_id belongs_to :shelter end <file_sep>require 'rails_helper' RSpec.describe 'shelters index page', type: :feature do context 'as a user' do before :each do @shelter1 = Shelter.create( name: '<NAME>', address: '1331 17th Street', city: 'Denver', state: 'CO', zip: '80202' ) @shelter2 = Shelter.create( name: '<NAME>', address: '150 Main Street', city: 'Hershey', state: 'PA', zip: '17033' ) @pet1 = Pet.create( image: 'https://www.talenthounds.ca/wp-content/uploads/2014/02/1010297_10151682411488254_1369748570_n.jpg', name: 'Athena', description: 'butthead', age: '1', sex: 'female', status: false, shelter_id: @shelter1.id ) @pet2 = Pet.create!( image: 'https://qph.fs.quoracdn.net/main-qimg-93bfd510cdebb550b6d46a2455d3c39a', name: 'Odell', description: 'good dog', age: '4', sex: 'male', status: false, shelter_id: @shelter2.id ) end it 'can see names of shelters' do visit '/pets' expect(page).to have_css("img[src*='#{@pet1.image}']") expect(page).to have_content(@pet1.name) expect(page).to have_content(@pet2.name) expect(page).to have_content(@pet1.age) expect(page).to have_content(@pet2.age) expect(page).to have_content('F') expect(page).to have_content('M') expect(page).to have_content(@shelter1.name) expect(page).to have_content(@shelter2.name) end end end
f92ad0adf7a7ef51b27354aa799434ad7fc5858e
[ "Ruby" ]
11
Ruby
alerrian/adopt_dont_shop
7c2d77c02767b6f25882c4182717e45b552de9b9
4958e3ef8d1c47d8b1af1129a30d4aa73a729d98
refs/heads/master
<repo_name>bug00r/color<file_sep>/crgb_array.h #ifndef CRGB_ARRAY_H #define CRGB_ARRAY_H #include "color.h" #include "array.h" void assoc_crgb_value(void * array_entry, int newidx ,void * init_value); void assoc_crgb_ref(void * array_entry, int newidx ,void * init_value); array_t * crgb_array_new(int cnt_i); array_t * crgb_array2D_new(int cnt_i, int cnt_j); void crgb_array_init(array_t * array, cRGB_t * init_value); array_error_t crgb_array_get(array_t * array, int index,cRGB_t * result); array_error_t crgb_array_get_ref(array_t * array, int index,cRGB_t ** result); array_error_t crgb_array2D_get(array_t * array, int i, int j, cRGB_t * result); array_error_t crgb_array2D_get_ref(array_t * array, int i, int j, cRGB_t ** result); array_error_t crgb_array_set(array_t * array, int index, cRGB_t * value); array_error_t crgb_array2D_set(array_t * array, int i, int j, cRGB_t * value); #if 0 /** additional for color_t */ #endif void assoc_color_value(void * array_entry, int newidx ,void * init_value); void assoc_color_ref(void * array_entry, int newidx ,void * init_value); array_t * color_array_new(int cnt_i); array_t * color_array2D_new(int cnt_i, int cnt_j); void color_array_init(array_t * array, color_t * init_value); array_error_t color_array_get(array_t * array, int index,color_t * result); array_error_t color_array_get_ref(array_t * array, int index,color_t ** result); array_error_t color_array2D_get(array_t * array, int i, int j, color_t * result); array_error_t color_array2D_get_ref(array_t * array, int i, int j, color_t ** result); array_error_t color_array_set(array_t * array, int index, color_t * value); array_error_t color_array2D_set(array_t * array, int i, int j, color_t * value); #endif <file_sep>/color.c #include "color.h" static const size_t cRGB_size = sizeof(cRGB_t); cRGB_t * create_crgb(const float r, const float g, const float b) { cRGB_t * newcolor = malloc(cRGB_size); newcolor->r = r; newcolor->g = g; newcolor->b = b; return newcolor; } void crgb_crgb_copy(cRGB_t * color, const cRGB_t * color2) { color->r = color2->r; color->g = color2->g; color->b = color2->b; } void crgb_crgb_set(cRGB_t *color, const float r, const float g, const float b) { color->r = r; color->g = g; color->b = b; } void crgb_crgb_set_ptr(cRGB_t *color, const float *r, const float *g, const float *b) { color->r = *r; color->g = *g; color->b = *b; } void crgb_crgb_add(cRGB_t * color, const cRGB_t * color2) { color->r += color2->r; color->g += color2->g; color->b += color2->b; } void crgb_add(cRGB_t * color, const float add) { color->r += add; color->g += add; color->b += add; } void color_add(color_t * color, const int add) { *color = COL_CREATE_RGBA( (COL_GET_R(*color) + add), (COL_GET_G(*color) + add), (COL_GET_B(*color) + add), (COL_GET_A(*color) + add)); } void color_add_dest(color_t * dest, const color_t * color, const int add) { *dest = COL_CREATE_RGBA( (COL_GET_R(*color) + add), (COL_GET_G(*color) + add), (COL_GET_B(*color) + add), (COL_GET_A(*color) + add)); } void crgb_mul(cRGB_t * color, const float mul) { color->r *= mul; color->g *= mul; color->b *= mul; } void color_mul(color_t * color, const int mul) { *color = COL_CREATE_RGBA( (COL_GET_R(*color) * mul), (COL_GET_G(*color) * mul), (COL_GET_B(*color) * mul), (COL_GET_A(*color) * mul)); } void color_mul_dest(color_t * dest, const color_t * color, const int mul) { *dest = COL_CREATE_RGBA( (COL_GET_R(*color) * mul), (COL_GET_G(*color) * mul), (COL_GET_B(*color) * mul), (COL_GET_A(*color) * mul)); } void color_mulf(color_t * color, const float mul) { *color = COL_CREATE_RGBA( (int)((float)COL_GET_R(*color) * mul), (int)((float)COL_GET_G(*color) * mul), (int)((float)COL_GET_B(*color) * mul), (int)((float)COL_GET_A(*color) * mul)); } void color_mulf_dest(color_t * dest, const color_t * color, const float mul) { *dest = COL_CREATE_RGBA( (int)((float)COL_GET_R(*color) * mul), (int)((float)COL_GET_G(*color) * mul), (int)((float)COL_GET_B(*color) * mul), (int)((float)COL_GET_A(*color) * mul)); } void crgb_print(const cRGB_t * color) { printf("R,G,B=%f,%f,%f\n", color->r, color->g, color->b); } void color_print(const color_t * color) { printf("R,G,B,A=%ld,%ld,%ld,%ld\n", COL_GET_R(*color), COL_GET_G(*color), COL_GET_B(*color), COL_GET_A(*color)); } void color_truncate(int * value) { int * val = value; int _val = *val; if ( _val > 255 ) *val = 255; else if (_val < 0) *val = 0; } void color_brightness_255_dest(color_t * dest, const color_t * color, const int brightness) { *dest = *color; int r = COL_GET_R(*dest) + brightness, g = COL_GET_G(*dest) + brightness, b = COL_GET_B(*dest) + brightness; color_truncate(&r); color_truncate(&g); color_truncate(&b); COL_SET_R(*dest,r); COL_SET_G(*dest,g); COL_SET_B(*dest,b); } void crgb_truncate(float * value) { float * val = value; float _val = *val; if ( _val > 255.f ) *val = 255.f; else if (_val < 0.f) *val = 0.f; } void crgb_brightness_255_dest(cRGB_t * dest, const cRGB_t * color, const float brightness) { crgb_crgb_copy(dest, color); crgb_add(dest, brightness); crgb_truncate(&dest->r); crgb_truncate(&dest->g); crgb_truncate(&dest->b); } float crgb_contrast_factor_255(const float contrast) { float usedcontrast = contrast; if(usedcontrast > 255.f) usedcontrast = 255.f; else if(usedcontrast < -255.f) usedcontrast = -255.f; return (259.f*(usedcontrast + 255.f)) / (255.f*(259.f - usedcontrast)) ; } float color_contrast_factor_255(const int contrast) { float usedcontrast = (float)contrast; if(usedcontrast > 255.f) usedcontrast = 255.f; else if(usedcontrast < -255.f) usedcontrast = -255.f; return (259.f*(usedcontrast + 255.f)) / (255.f*(259.f - usedcontrast)) ; } void crgb_contrast_255_dest(cRGB_t * dest, const cRGB_t * color, const float contrast_factor) { crgb_crgb_copy(dest, color); dest->r = (contrast_factor * (dest->r - 128.f)) + 128.f; dest->g = (contrast_factor * (dest->g - 128.f)) + 128.f; dest->b = (contrast_factor * (dest->b - 128.f)) + 128.f; crgb_truncate(&dest->r); crgb_truncate(&dest->g); crgb_truncate(&dest->b); } void color_contrast_255_dest(color_t * dest, const color_t * color, const float contrast_factor) { *dest = *color; int r = (int)((contrast_factor * ((float)(COL_GET_R(*color)) - 128.f)) + 128.f), g = (int)((contrast_factor * ((float)(COL_GET_G(*color)) - 128.f)) + 128.f), b = (int)((contrast_factor * ((float)(COL_GET_B(*color)) - 128.f)) + 128.f); color_truncate(&r); color_truncate(&g); color_truncate(&b); COL_SET_R(*dest,r); COL_SET_G(*dest,g); COL_SET_B(*dest,b); }<file_sep>/test_color.c #if 0 /** This is a Test programm for the color lib */ #endif #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "color.h" #define TEST_COLOR_COLOR(_color, _color2) \ do {\ assert(_color.r == _color2.r);\ assert(_color.g == _color2.g);\ assert(_color.b == _color2.b);\ } while(0) #define TEST_COLOR_RGB(_color, _r, _g, _b) \ do {\ assert(_color.r == _r);\ assert(_color.g == _g);\ assert(_color.b == _b);\ } while(0) int main() { cRGB_t color = {255.f,255.f,255.f}; TEST_COLOR_RGB(color, 255.f,255.f,255.f); color.r = 12.f; color.g = 12.f; color.b = 12.f; crgb_add(&color, 8.f); TEST_COLOR_RGB(color, 20.f, 20.f, 20.f); cRGB_t color2 = {0.f,0.f,0.f}; crgb_crgb_copy(&color2,&color); TEST_COLOR_COLOR(color2, color); crgb_add(&color2, 10.f); TEST_COLOR_RGB(color2, 30.f, 30.f, 30.f); crgb_mul(&color, 2.f); TEST_COLOR_RGB(color, 40.f, 40.f, 40.f); crgb_crgb_copy(&color2,&color); crgb_mul(&color2, 3.f); TEST_COLOR_RGB(color2, 120.f, 120.f, 120.f); crgb_crgb_copy(&color2,&color); crgb_mul(&color2, .5f); TEST_COLOR_RGB(color2, 20.f, 20.f, 20.f); crgb_crgb_copy(&color2,&color); crgb_mul(&color2, .5f); TEST_COLOR_RGB(color2, 20.f, 20.f, 20.f); crgb_crgb_set(&color2, 1.f, 2.f, 3.f); TEST_COLOR_RGB(color2, 1.f, 2.f, 3.f); crgb_crgb_set_ptr(&color2, &color.r , &color.g, &color.b); TEST_COLOR_RGB(color2, 40.f, 40.f, 40.f); return 0; }<file_sep>/color.h #if 0 /** This is a simple color class. */ #endif #ifndef COLOR_H #define COLOR_H #include <stdlib.h> #include <stdio.h> #include <math.h> #define COL_MAX 255 #define COL_BIT_R 24 #define COL_BIT_G 16 #define COL_BIT_B 8 #define COL_BIT_A 0 #define COL_MASK_R (COL_MAX << COL_BIT_R) #define COL_MASK_G (COL_MAX << COL_BIT_G) #define COL_MASK_B (COL_MAX << COL_BIT_B) #define COL_MASK_A 255 #define COL_MASK_R_NOT (~(COL_MAX << COL_BIT_R)) #define COL_MASK_G_NOT (~(COL_MAX << COL_BIT_G)) #define COL_MASK_B_NOT (~(COL_MAX << COL_BIT_B)) #define COL_MASK_A_NOT (~(COL_MAX)) #define COL_MASK 255 #define COL_MASK_NOT ~255 #define COL_MOVE_R(r) ((r&COL_MASK) << COL_BIT_R) #define COL_MOVE_G(g) ((g&COL_MASK) << COL_BIT_G) #define COL_MOVE_B(b) ((b&COL_MASK) << COL_BIT_B) #define COL_MOVE_A(a) ((a&COL_MASK) << COL_BIT_A) #define COL_MOVE_ALL(r,g,b,a) (COL_MOVE_R(r) | COL_MOVE_G(g) | COL_MOVE_B(b) | COL_MOVE_A(a)) #define COL_TRUNC_R(color) (color & COL_MASK_R_NOT) #define COL_TRUNC_G(color) (color & COL_MASK_G_NOT) #define COL_TRUNC_B(color) (color & COL_MASK_B_NOT) #define COL_TRUNC_A(color) (color & COL_MASK_A_NOT) #define COL_GET_R(color) ((color >> COL_BIT_R) & COL_MASK) #define COL_GET_G(color) ((color >> COL_BIT_G) & COL_MASK) #define COL_GET_B(color) ((color >> COL_BIT_B) & COL_MASK) #define COL_GET_A(color) ((color >> COL_BIT_A) & COL_MASK) #define COL_SET_R(color, r) (color = (COL_TRUNC_R(color) | COL_MOVE_R(r))) #define COL_SET_G(color, g) (color = (COL_TRUNC_G(color) | COL_MOVE_G(g))) #define COL_SET_B(color, b) (color = (COL_TRUNC_B(color) | COL_MOVE_B(b))) #define COL_SET_A(color, a) (color = (COL_TRUNC_A(color) | COL_MOVE_A(a))) #define COL_CREATE_RGBA(r,g,b,a) ((color_t) COL_MOVE_ALL(r,g,b,a)) typedef unsigned long int color_t; typedef struct { float r, g, b; } cRGB_t; #if 0 /** Creates new color object */ #endif cRGB_t * create_crgb( const float r, const float g, const float b); #if 0 /** copy values from color2 into color. */ #endif void crgb_crgb_copy(cRGB_t * color, const cRGB_t * color2); void crgb_crgb_set(cRGB_t * color, const float r, const float g, const float b); void crgb_crgb_set_ptr(cRGB_t * color, const float *r, const float *g, const float *b); #if 0 /** Add two colors and store result in color. */ #endif void crgb_crgb_add(cRGB_t * color, const cRGB_t * color2); //no need for color_t its only color1 += color2 #if 0 /** Add color value to each value of rgba. If you want to sub then add negative number */ #endif void crgb_add(cRGB_t * color, const float add); void color_add(color_t * color, const int add); void color_add_dest(color_t * dest, const color_t * color, const int add); #if 0 /** Multiplies color value to each value of rgba. If you want to divife then multiply antivalent number */ #endif void crgb_mul(cRGB_t * color, const float mul); void color_mul(color_t * color, const int mul); void color_mul_dest(color_t * dest, const color_t * color, const int mul); void color_mulf(color_t * color, const float mul); void color_mulf_dest(color_t * dest, const color_t * color, const float mul); #if 0 /** prints color value */ #endif void crgb_print(const cRGB_t * color); void color_print(const color_t * color); #if 0 /** calculates color with new brightness for color range 0 to 255. Result is stored in dest. */ #endif void crgb_brightness_255_dest(cRGB_t * dest, const cRGB_t * color, const float brightness); void color_brightness_255_dest(/** cRGB_t*/color_t * dest, /** cRGB_t*/const color_t * color, const int brightness); #if 0 /** calculates color with new contrast_factor for wanted contrast for color range 0 to 255. Result is stored in dest. */ #endif float crgb_contrast_factor_255(const float contrast); float color_contrast_factor_255(const int contrast); #if 0 /** calculates color with new contrast for color range 0 to 255. Result is stored in dest. */ #endif void crgb_contrast_255_dest(cRGB_t * dest, const cRGB_t * color, const float contrast_factor); void color_contrast_255_dest(/** cRGB_t*/color_t * dest, /** cRGB_t*/const color_t * color, const float contrast_factor); #endif <file_sep>/test_crgb_array.c #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include "crgb_array.h" int main() { #ifdef debug printf("test collections color array:\n"); #endif array_t * oneD = crgb_array_new(10); array_t * twoD = crgb_array2D_new(5,5); cRGB_t blue = { 0.f , 0.f, 1.f}; cRGB_t red = { 1.f , 0.f, 0.f}; crgb_array_init(oneD, &blue); crgb_array_init(twoD, &red); array_error_t farray_res; cRGB_t black = { 0.f , 0.f, 0.f}; cRGB_t white = { 1.f , 1.f, 1.f}; farray_res = crgb_array_set(oneD, 8, &black); assert(farray_res == ARRAY_ERR_OK); farray_res = crgb_array2D_set(twoD, 3, 3, &white); assert(farray_res == ARRAY_ERR_OK); cRGB_t result_value; cRGB_t * result_ref; farray_res = crgb_array_get(oneD, 2, &result_value); assert(farray_res == ARRAY_ERR_OK); assert(&result_value != &blue); assert(result_value.r == 0.f); assert(result_value.g == 0.f); assert(result_value.b == 1.f); farray_res = crgb_array2D_get(twoD, 1, 3, &result_value); assert(farray_res == ARRAY_ERR_OK); assert(&result_value != &red); assert(result_value.r == 1.f); assert(result_value.g == 0.f); assert(result_value.b == 0.f); farray_res = crgb_array_get(oneD, 8, &result_value); assert(farray_res == ARRAY_ERR_OK); assert(&result_value != &black); assert(result_value.r == 0.f); assert(result_value.g == 0.f); assert(result_value.b == 0.f); farray_res = crgb_array2D_get(twoD, 3, 3, &result_value); assert(farray_res == ARRAY_ERR_OK); assert(&result_value != &white); assert(result_value.r == 1.f); assert(result_value.g == 1.f); assert(result_value.b == 1.f); cRGB_t * carray = (cRGB_t *)oneD->entries; carray[4].r = 47.f; carray[4].g = 1.f; carray[4].b = 1.f; farray_res = crgb_array_get_ref(oneD, 4, &result_ref); assert(farray_res == ARRAY_ERR_OK); assert(result_ref == &carray[4]); assert(result_ref->r == 47.f); assert(result_ref->g == 1.f); assert(result_ref->b == 1.f); carray = (cRGB_t *)twoD->entries; farray_res = crgb_array2D_get_ref(twoD, 2, 3, &result_ref); assert(farray_res == ARRAY_ERR_OK); assert(result_ref == &carray[17]); assert(result_ref->r == 1.f); assert(result_ref->g == 0.f); assert(result_ref->b == 0.f); farray_res = crgb_array_get(oneD, 44, &result_value); assert(farray_res == ARRAY_ERR_OVERFLOW); farray_res = crgb_array2D_get(twoD, 34, 3, &result_value); assert(farray_res == ARRAY_ERR_OVERFLOW); farray_res = crgb_array_get_ref(oneD, 44, &result_ref); assert(farray_res == ARRAY_ERR_OVERFLOW); farray_res = crgb_array2D_get_ref(twoD, 34, 3, &result_ref); assert(farray_res == ARRAY_ERR_OVERFLOW); farray_res = crgb_array_get(oneD, -44, &result_value); assert(farray_res == ARRAY_ERR_UNDERFLOW); farray_res = crgb_array2D_get(twoD, -34, 3, &result_value); assert(farray_res == ARRAY_ERR_UNDERFLOW); farray_res = crgb_array_get_ref(oneD, -44, &result_ref); assert(farray_res == ARRAY_ERR_UNDERFLOW); farray_res = crgb_array2D_get_ref(twoD, -34, 3, &result_ref); assert(farray_res == ARRAY_ERR_UNDERFLOW); array_free(oneD); array_free(twoD); #ifdef debug printf("EO test collections color array:\n"); #endif return 0; } <file_sep>/crgb_array.c #include "crgb_array.h" #include <stdio.h> #include <stdlib.h> #include <stddef.h> void assoc_crgb_value(void * array_entry, int newidx ,void * init_value){ crgb_crgb_copy(((cRGB_t*)array_entry+newidx), ((cRGB_t*)init_value)); } void assoc_crgb_ref(void * array_entry, int newidx ,void * init_value){ *((cRGB_t **)array_entry+newidx) = ((cRGB_t *)init_value); } array_t * crgb_array_new(int cnt_i){ return array1D_new(cnt_i, sizeof(cRGB_t)); } array_t * crgb_array2D_new(int cnt_i, int cnt_j){ return array2D_new(cnt_i, cnt_j, sizeof(cRGB_t)); } void crgb_array_init(array_t * array, cRGB_t * init_value){ array_init(array, init_value, assoc_crgb_value); } array_error_t crgb_array_get(array_t * array, int index, cRGB_t * result){ return array_get(array, index, assoc_crgb_value, result); } array_error_t crgb_array2D_get(array_t * array, int i, int j, cRGB_t * result){ return array2D_get(array, i, j, assoc_crgb_value, result); } array_error_t crgb_array_get_ref(array_t * array, int index, cRGB_t ** result){ return array_get(array, index, assoc_crgb_ref, result); } array_error_t crgb_array2D_get_ref(array_t * array, int i, int j, cRGB_t ** result){ return array2D_get(array, i, j, assoc_crgb_ref, result); } array_error_t crgb_array_set(array_t * array, int index, cRGB_t * value){ return array_set(array, index, value, assoc_crgb_value); } array_error_t crgb_array2D_set(array_t * array, int i, int j, cRGB_t * value){ return array2D_set(array, i, j, value, assoc_crgb_value); } #if 0 //implementation for color_t #endif void assoc_color_value(void * array_entry, int newidx ,void * init_value){ *((color_t*)array_entry+newidx) = *((color_t*)init_value); } void assoc_color_ref(void * array_entry, int newidx ,void * init_value){ *((color_t **)array_entry+newidx) = ((color_t *)init_value); } array_t * color_array_new(int cnt_i){ return array1D_new(cnt_i, sizeof(color_t)); } array_t * color_array2D_new(int cnt_i, int cnt_j){ return array2D_new(cnt_i, cnt_j, sizeof(color_t)); } void color_array_init(array_t * array, color_t * init_value){ array_init(array, init_value, assoc_color_value); } array_error_t color_array_get(array_t * array, int index, color_t * result){ return array_get(array, index, assoc_color_value, result); } array_error_t color_array2D_get(array_t * array, int i, int j, color_t * result){ return array2D_get(array, i, j, assoc_color_value, result); } array_error_t color_array_get_ref(array_t * array, int index, color_t ** result){ return array_get(array, index, assoc_color_ref, result); } array_error_t color_array2D_get_ref(array_t * array, int i, int j, color_t ** result){ return array2D_get(array, i, j, assoc_color_ref, result); } array_error_t color_array_set(array_t * array, int index, color_t * value){ return array_set(array, index, value, assoc_color_value); } array_error_t color_array2D_set(array_t * array, int i, int j, color_t * value){ return array2D_set(array, i, j, value, assoc_color_value); } <file_sep>/Makefile all: $(MAKE) -f Makefile_color $(MAKE) -f Makefile_crgb_array install: $(MAKE) -f Makefile_color install $(MAKE) -f Makefile_crgb_array install test: $(MAKE) -f Makefile_color test $(MAKE) -f Makefile_crgb_array test clean: $(MAKE) -f Makefile_color clean $(MAKE) -f Makefile_crgb_array clean .PHONY: clean install test <file_sep>/test_color_t.c #if 0 /** This is a Test programm for the color lib */ #endif #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "color.h" int main() { #ifdef debug printf("Start testing color_t lib:\n"); color_t color = COL_CREATE_RGBA(255,255,255,255); color_print(&color); color = COL_CREATE_RGBA(0,0,0,0); COL_SET_R(color, 12); COL_SET_G(color, 12); COL_SET_B(color, 12); COL_SET_A(color, 12); printf("col1 with 12: "); color_print(&color); color_add(&color, 8); printf("col1 + 8: "); color_print(&color); color_t color2 = COL_CREATE_RGBA(0,0,0,0); color_add_dest(&color2,&color, 10); printf("col2: col1 + 10: "); color_print(&color2); color_mul(&color, 2); printf("col1 * 2: "); color_print(&color); color_mul_dest(&color2,&color, 3); printf("col2 = col1 * 3: "); COL_SET_A(color2, 66); color_print(&color2); color_mulf_dest(&color2,&color, 0.5f); printf("col2 = col1 / 2: "); color_print(&color2); color_mulf(&color2, 0.5f); printf("col2 / 2: "); color_print(&color2); color_t color3 = COL_CREATE_RGBA(0,0,0,0); color_t color4 = COL_CREATE_RGBA(0,0,0,0); int twof = 2.f; float half = .5f; for(unsigned int r = 0; r < 255; r++){ COL_SET_R(color3,0); for(unsigned int g = 0; g < 255; g++){ COL_SET_G(color3,0); for(unsigned int b = 0; b < 255; b++){ COL_SET_R(color3,(int)((float)r * 1.f)); COL_SET_G(color3,(int)((float)g * 1.f)); COL_SET_B(color3,(int)((float)b * 1.f)); color_add(&color3, 2); color2 = color; color4 = color2; color_mul(&color2,twof); color_mulf(&color4,half); } } } printf("End testing color_t lib:\n"); #endif return 0; }
4882b6957d8f47ec28e7945104b9622a3e5e28a9
[ "C", "Makefile" ]
8
C
bug00r/color
a5da0a2be31e0ed553d7be7e8d809b2d7ad8ba74
5656fad49f7beee1ca2446a8058c2530626b27b5
refs/heads/master
<file_sep>package Minesweeper; import java.util.Date; public class CheckVitory { //Check condition of win or lose public static void checkWinStatus() { if(GUI.Lose == false ) { for(int i = 0; i < 16; i++) { for(int j = 0; j < 9; j ++) { if(GUI.revealed[i][j] == true && GUI.mines[i][j] == 1) { GUI.Lose = true; GUI.happy = false; GUI.endDate = new Date(); for(int k = 0; k < 16; k++) { for(int l = 0; l < 9; l ++) { if(GUI.flagged[k][l] == false) { GUI.revealed[k][l] = true;} } } } } } } if ((totalBoxRevealed()) >= 144 - totalMines() && GUI.Win == false && GUI.Lose == false) { GUI.Win = true; GUI.endDate = new Date(); } } //Total of mines public static int totalMines() { int total = 0; for(int i = 0; i < 16; i++) { for(int j = 0; j < 9; j ++) { if(GUI.mines[i][j] == 1) { total ++; } } } return total; } //total Box revealed public static int totalBoxRevealed() { int total = 0; for(int i = 0; i < 16; i++) { for(int j = 0; j < 9; j ++) { if(GUI.revealed[i][j] == true) { total++; } } } return total; } } <file_sep>package Minesweeper; public class Button { public static boolean inFlagger() { int dif = (int) Math.sqrt(Math.abs(GUI.mx-GUI.flaggerCenterX)*Math.abs(GUI.mx-GUI.flaggerCenterX)+Math.abs(GUI.my-GUI.flaggerCenterY)*Math.abs(GUI.my-GUI.flaggerCenterY)); if(dif < 35) { return true; } else if(dif >= 35) { return false; } return false; } public static boolean inSmile() { int dif = (int) Math.sqrt(Math.abs(GUI.mx-GUI.smileCenter_X)*Math.abs(GUI.mx-GUI.smileCenter_X)+Math.abs(GUI.my-GUI.smileCenter_Y)*Math.abs(GUI.my-GUI.smileCenter_Y)); if(dif < 35) { return true; } else if(dif >= 35) { return false; } return false; } } <file_sep>package Minesweeper; public class Explore { public static int checkMinesW() { if(GUI.mines[Box.BoxX()-1][Box.BoxY()] == 1 && GUI.revealed[Box.BoxX()-1][Box.BoxY()] == false) return 1; else if(GUI.mines[Box.BoxX()-1][Box.BoxY()] == 0) return 0; return -1; } public static int checkMinesN() { if(GUI.mines[Box.BoxX()][Box.BoxY()-1] == 1 && GUI.revealed[Box.BoxX()][Box.BoxY()-1] == false) return 1; else if(GUI.mines[Box.BoxX()][Box.BoxY()-1] == 0) return 0; return -1; } public static int checkMinesE() { if(GUI.mines[Box.BoxX()+1][Box.BoxY()] == 1 && GUI.revealed[Box.BoxX()+1][Box.BoxY()] == false) return 1; else if(GUI.mines[Box.BoxX()+1][Box.BoxY()] == 0) return 0; return -1; } public static int checkMinesS() { if(GUI.mines[Box.BoxX()][Box.BoxY()+1] == 1 && GUI.revealed[Box.BoxX()][Box.BoxY()+1] == false) return 1; else if(GUI.mines[Box.BoxX()][Box.BoxY()+1]== 0 ) return 0; return -1; } // public static int checkMinesNE() { if(GUI.mines[Box.BoxX()+1][Box.BoxY()-1] == 1 && GUI.revealed[Box.BoxX()+1][Box.BoxY()-1] == false) return 1; else if(GUI.mines[Box.BoxX()+1][Box.BoxY()-1] == 0) return 0; return -1; } public static int checkMinesNW() { if(GUI.mines[Box.BoxX()-1][Box.BoxY()-1] == 1 && GUI.revealed[Box.BoxX()-1][Box.BoxY()-1] == false) return 1; else if(GUI.mines[Box.BoxX()-1][Box.BoxY()-1] == 0) return 0; return -1; } public static int checkMinesSE() { if(GUI.mines[Box.BoxX()+1][Box.BoxY()+1] == 1 && GUI.revealed[Box.BoxX()+1][Box.BoxY()+1] == false) return 1; else if(GUI.mines[Box.BoxX()+1][Box.BoxY()+1] == 0) return 0; return -1; } public static int checkMinesSW() { if(GUI.mines[Box.BoxX()-1][Box.BoxY()+1] == 1 && GUI.revealed[Box.BoxX()-1][Box.BoxY()+1] == false) return 1; else if(GUI.mines[Box.BoxX()-1][Box.BoxY()+1] == 0) return 0; return -1; } ////////////////////////////////////////////////////////////// //Open cell East,West,North,South. public static boolean openW() { if(checkMinesW() == 1 ) { return false; }else return true; } public static boolean openN() { if(checkMinesN() == 1) { return false; }else return true; } public static boolean openE() { if(checkMinesE() == 1) { return false; }else return true; } public static boolean openS() { if(checkMinesS() == 1) { return false; }else return true; } public static boolean openNW() { if(checkMinesNW() == 1) { return false; }else return true; } public static boolean openNE() { if(checkMinesNE() == 1) { return false; }else return true; } public static boolean openSW() { if(checkMinesSW() == 1) { return false; }else return true; } public static boolean openSE() { if(checkMinesSE() == 1) { return false; }else return true; } } <file_sep>package Minesweeper; public class Box { public static int BoxX() { for(int i = 0; i < 16; i++) { for(int j = 0; j < 9; j ++) { if(GUI.mx >= GUI.scaping +i*80 && GUI.mx < GUI.scaping+i*80 + 80-2* GUI.scaping && GUI.my >= GUI.scaping+j*80+80+26 && GUI.my < GUI.scaping+j*80+26+80+80-2*GUI.scaping) { return i; } } } return -1; } public static int BoxY() { for(int i = 0; i < 16; i++) { for(int j = 0; j < 9; j ++) { if(GUI.mx >= GUI.scaping+i*80 && GUI.mx < GUI.scaping+i*80 + 80-2*GUI.scaping && GUI.my >= GUI.scaping+j*80+80+26 && GUI.my < GUI.scaping+j*80+26+80+80-2*GUI.scaping) { return j; } } } return -1; } public static boolean isN(int mX, int mY, int cX, int cY){ if(mX - cX <2 && mX - cX > -2 && mY - cY <2 && mY - cY > -2 && GUI.mines[cX][cY] == 1) { return true; } return false; } } <file_sep>package Minesweeper; import java.util.Date; public class ResetAll { public static void resetAll() { GUI.resetter = true; GUI.flagger = false; GUI.startDate = new Date(); GUI.vicMes_Y = -50; String vicMess = "Win!!"; GUI.happy = true; GUI.Win = false; GUI.Lose = false; //Mines for(int i = 0; i < 16; i++) { for(int j = 0; j < 9; j ++) { if(GUI.rand.nextInt(144) < 20) { GUI.mines[i][j] = 1; }else { GUI.mines[i][j] = 0; } GUI.revealed[i][j] = false; GUI.flagged[i][j] = false; } } //count neighbours where to explore number. for(int i = 0; i < 16; i++) { for(int j = 0; j < 9; j ++) { GUI.neighs = 0; for(int m = 0; m < 16; m++) { for(int n = 0; n < 9; n ++) { if(!(m == i && n == j)) { if(Box.isN(i,j,m,n) == true) GUI.neighs ++; } } } GUI.neighbours[i][j] = GUI.neighs; } } GUI.resetter = false; } }
abbb363159fd61588dfa4c1e7af82955e4b80782
[ "Java" ]
5
Java
TH-Thedevelop/Final_Minesweeper
0863ffe460f2f4be821a109d31b19e0ccd3d6c88
e689c2c5bd8b54cee55e0038906e74fd57b3f044
refs/heads/master
<repo_name>JJakubowskiCenveo/SmartLincEICustomers<file_sep>/SmartLincEINew/Service.svc.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using SmartLincInterface; using CMS; using Lexis; using LexisGlobal; using SAP; namespace SmartLincServiceTemplate { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging. public class SmartLincContractImplementation : IExpressInterface { #region IExpressInterface Members public string DoSimpleOperation(string strApplicationIdentifier, string strOperationParameter) { return string.Empty; } public EntityShipment SimplePullMethod(EntityShipment objRequest) { switch (objRequest.ToolKit.ID.ToUpper()) { case "LEXIS": LexisInterface objLexis = new LexisInterface(); objRequest = objLexis.Pull(objRequest); break; case "LEXISGLOBAL": LexisGlobalInterface objLexisGlobal = new LexisGlobalInterface(); objRequest = objLexisGlobal.Pull(objRequest); break; case "CMS": CMSInterface objCMS = new CMSInterface(); objRequest = objCMS.Pull(objRequest); break; case "SAP": SAPInterface objSAP = new SAPInterface(); objRequest = objSAP.Pull(objRequest); break; } return objRequest; } public EntityShipment SimplePutbackMethod(EntityShipment objRequest) { switch (objRequest.ToolKit.ID.ToUpper()) { case "LEXIS": LexisInterface objLexis = new LexisInterface(); objRequest = objLexis.Putback(objRequest); break; case "LEXISGLOBAL": LexisGlobalInterface objLexisGlobal = new LexisGlobalInterface(); objRequest = objLexisGlobal.Putback(objRequest); break; case "CMS": CMSInterface objCMS = new CMSInterface(); objRequest = objCMS.Putback(objRequest); break; case "SAP": SAPInterface objSAP = new SAPInterface(); objRequest = objSAP.Putback(objRequest); break; } return objRequest; } public EntityShipment SimpleVoidMethod(EntityShipment objRequest) { switch (objRequest.ToolKit.ID.ToUpper()) { case "LEXIS": LexisInterface objLexis = new LexisInterface(); objRequest = objLexis.Void(objRequest); break; case "LEXISGLOBAL": LexisGlobalInterface objLexisGlobal = new LexisGlobalInterface(); objRequest = objLexisGlobal.Void(objRequest); break; case "CMS": CMSInterface objCMS = new CMSInterface(); objRequest = objCMS.Void(objRequest); break; case "SAP": SAPInterface objSAP = new SAPInterface(); objRequest = objSAP.Void(objRequest); break; } return objRequest; } #endregion public EntityShipment GetRates(EntityShipment request) { throw new NotImplementedException(); //Not Used at this time. } public string GetEncryption(string strPassword) { throw new NotImplementedException(); //Not used at this time. } public List<EntityOrderSelector> SimpleOrderSelectorPullMethod(EntityOrderSelector objOS) { throw new NotImplementedException(); //Not used at this time. } } } <file_sep>/Class2.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExploringDataTypes { class Program { static void Main(string[] args) { int integerTest = 0; decimal usedForCurrency = 0; float aDifferentNumberFormat = 0.01234567890F; double andYetAnotherOne = 0.01234567890D; bool boolTest = true; int aDifferentInteger = 1 + 3; bool aDifferentBool = (usedForCurrency == integerTest); string aTextTest = "Hi everyone!"; int myStringLen = aTextTest.Length; string aDifferentString = "Learning C# is fun!"; Console.WriteLine("integerTest's value is " + integerTest + ", usedForCurrency holds " + usedForCurrency + ", aDifferentNumberFormat's value is " + aDifferentNumberFormat + ", while andYetAnotherOne stores " + andYetAnotherOne); Console.WriteLine(); Console.WriteLine(aTextTest); Console.WriteLine(aTextTest.ToUpper()); Console.WriteLine(aTextTest.Substring(0, 2)); Console.WriteLine("The first 'e' in '" + aTextTest + "' is in position " + aTextTest.IndexOf("e")); Console.WriteLine("The last 'e' in '" + aTextTest + "' is in position " + aTextTest.LastIndexOf("e")); Console.WriteLine("The total length of the string is " + myStringLen); // Inserting text on an existing string, just for output Console.WriteLine("Using the Insert method to add some text results in: " + aDifferentString.Insert(15, "easy and ")); // But it doesn't affect the original string Console.WriteLine("But the original string remains untouched: " + aDifferentString); // Now let's change the value, by assigning the function output to the original variable aDifferentString = aDifferentString.Insert(15, "easy and "); Console.WriteLine("Now aDifferentString has a different value: " + aDifferentString); // Append some text aDifferentStringOnSteroids.Append(" But sometimes is quirky..."); Console.WriteLine(); Console.WriteLine("aDifferentStringOnSteroids after the Append:\n" + aDifferentStringOnSteroids); // Insert some text aDifferentStringOnSteroids.Insert(46, "very "); Console.WriteLine(); Console.WriteLine("aDifferentStringOnSteroids after the Insert:\n" + aDifferentStringOnSteroids); // Replace some text aDifferentStringOnSteroids.Replace("very", "extremely"); Console.WriteLine(); Console.WriteLine("aDifferentStringOnSteroids after the Replace:\n" + aDifferentStringOnSteroids); // Remove some text aDifferentStringOnSteroids.Remove(28, 37); Console.WriteLine(); Console.WriteLine("aDifferentStringOnSteroids after the Remove:\n" + aDifferentStringOnSteroids); Console.ReadKey(); } } } <file_sep>/SmartLincEINew/IService.cs using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; using SmartLincInterface; namespace SmartLincServiceTemplate { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. [ServiceContract] public interface IService { [OperationContract] EntityShipment SimplePullMethod(EntityShipment objRequest); [OperationContract] string DoSimpleOperation(string strApplicationIdentifier, string strOperationParameter); [OperationContract] EntityShipment SimplePutbackMethod(EntityShipment objShipment); [OperationContract] EntityShipment SimpleVoidMethod(EntityShipment objShipment); [OperationContract] EntityShipment GetRates(EntityShipment request); [OperationContract] string GetEncryption(string strPassword); [OperationContract] List<EntityOrderSelector> SimpleOrderSelectorPullMethod(EntityOrderSelector objOrderSelector); // TODO: Add your service operations here } } <file_sep>/Sample/SampleInterface.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using SmartLincInterface; namespace Sample { public class SampleInterface { private List<EntityResponseStatus> lstResponse = new List<EntityResponseStatus>(); public EntityShipment Pull(EntityShipment objES) { try { objES.objShipTo = GetShipTo(); objES.objDetails.strPONumber = "PONumber"; objES.objDetails.strInvoiceNumber = "InvNumber"; objES.objShipMethod = new EntityShipMethod(); objES.objShipMethod.strShipViaCode = "100"; objES.lstContainer = new List<EntityContainer>(); //If line items are needed... objES.lstContainer.Add(FillLineItems()); } catch (Exception ex) { lstResponse.Add(SetResponse(ex.Message + " - IE - " + ex.InnerException.Message + " - GE", ResponseStatusType.ERROR)); } objES.lstEntityResponseStatus = lstResponse; return objES; } private EntityAddress GetShipTo() { EntityAddress objEA = new EntityAddress(); objEA.strCompanyName = "ShipToCompany"; objEA.strContactName = "ShipToContact"; objEA.strAddressLine1 = "ShipToAdd1"; objEA.strAddressLine2 = "ShipToAdd2"; objEA.strAddressLine3 = "ShipToAdd3"; objEA.strCity = "Milwaukee"; objEA.strState = "WI"; objEA.strPostalCode = "53203"; objEA.strCountryCode = "US"; return objEA; } private EntityResponseStatus SetResponse(string strMessage, ResponseStatusType eResponseType) { EntityResponseStatus objResponse = new EntityResponseStatus(); objResponse.Message = strMessage; objResponse.StatusType = eResponseType; return objResponse; } private EntityContainer FillLineItems() { EntityContainer EC = new EntityContainer(); EC.lstPackageGroup = new List<EntityPackageGroup>(); EntityPackageGroup EPG = new EntityPackageGroup(); List<EntityLineItem> lstELI = new List<EntityLineItem>(); EntityLineItem objELI = new EntityLineItem(); objELI.strItemNumber = "ABC123"; objELI.intOrderedQuantity = 20; objELI.strItemDescription = "Sample Line Item"; lstELI.Add(objELI); EPG.lstLineItem = lstELI; EC.lstPackageGroup.Add(EPG); return EC; } public EntityShipment Putback(EntityShipment objES) { try { } catch (Exception ex) { lstResponse.Add(SetResponse(ex.Message, ResponseStatusType.ERROR)); } objES.lstEntityResponseStatus = lstResponse; return objES; } public EntityShipment Void(EntityShipment objES) { try { } catch (Exception ex) { lstResponse.Add(SetResponse(ex.Message, ResponseStatusType.ERROR)); } return objES; } } } <file_sep>/TestHarness/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using SmartLincInterface; using System.Xml.Serialization; using System.Xml; using CMS; using Lexis; using LexisGlobal; using SAP; using System.IO; namespace TestHarness { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Button1_Click(object sender, EventArgs e) { string strInterface = lstInterface.SelectedItem.ToString().Trim(); EntityShipment objES = new EntityShipment { objDetails = new EntityShipmentDetails { strDeliveryDocNumber = txtOrder.Text } }; EntityConnection objConnection = new EntityConnection(); if (radioButtonDev.Checked == true) { switch (strInterface.ToUpper()) { case "CMS": objConnection.strDSNName = "Systema"; objConnection.strServer = "SystemA.cadmus.com"; objConnection.strDatabase = "SHLIB"; objConnection.strUserID = "CENPROUSER"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "LEXIS": objConnection.strDSNName = @"dvsqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "LEXISGLOBAL": objConnection.strDSNName = @"dvsqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "SAP": objConnection.strDSNName = @"dvsqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; default: MessageBox.Show("Interface was not selected"); break; } } if (radioButtonQA.Checked == true) { switch (strInterface.ToUpper()) { case "CMS": objConnection.strDSNName = "Sysatr"; objConnection.strServer = "Sysatr.cadmus.com"; objConnection.strDatabase = "SHLIB"; objConnection.strUserID = "ODBCUSER"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "LEXIS": objConnection.strDSNName = @"qasqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "LEXISGLOBAL": objConnection.strDSNName = @"qasqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "SAP": objConnection.strDSNName = @"qasqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; default: MessageBox.Show("Interface was not selected"); break; } } if (radioButtonPD.Checked == true) { switch (strInterface.ToUpper()) { case "CMS": objConnection.strDSNName = "Systemb"; objConnection.strServer = "SystemB.cadmus.com"; objConnection.strDatabase = "SHLIB"; objConnection.strUserID = "ODBCUSER"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "LEXIS": objConnection.strDSNName = @"pdsqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "LEXISGLOBAL": objConnection.strDSNName = @"pdsqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; case "SAP": objConnection.strDSNName = @"pdsqlmonarch.cenveo.cvo.net"; objConnection.strDatabase = "PSIntegration"; objConnection.strUserID = "service.ps"; objConnection.strPassword = "<PASSWORD>"; objES.ToolKit = new EntityToolKit(); break; default: MessageBox.Show("Interface was not selected"); break; } } objES.ToolKit.objConnection = objConnection; switch (strInterface.ToUpper()) { case "CMS": break; case "LEXIS": LexisInterface objSample = new LexisInterface(); objSample.Pull(objES); break; case "LEXISGLOBAL": LexisGlobalInterface objSampleLG = new LexisGlobalInterface(); objSampleLG.Pull(objES); break; case "SAP": SAPInterface objSampleSAP = new SAPInterface(); objSampleSAP.Pull(objES); break; default: MessageBox.Show("Interface was not selected"); break; } } private void Button2_Click(object sender, EventArgs e) { string strInterface = lstInterface.SelectedItem.ToString().Trim(); EntityShipment objES = new EntityShipment(); //This to debug the code through xml XmlSerializer serializer = new XmlSerializer(typeof(EntityShipment)); using (TextReader reader = new StringReader(txtXML.Text)) { objES = (EntityShipment)serializer.Deserialize(reader); } switch (strInterface.ToUpper()) { case "CMS": CMSInterface objCMS = new CMSInterface(); objCMS.Putback(objES); break; case "LEXIS": LexisInterface objLexis = new LexisInterface(); objLexis.Putback(objES); break; case "LEXISGLOBAL": LexisGlobalInterface objLexisGlobal = new LexisGlobalInterface(); objLexisGlobal.Putback(objES); break; case "SAP": SAPInterface objSAP = new SAPInterface(); objSAP.Putback(objES); break; default: MessageBox.Show("Interface was not selected"); break; } } private void Button3_Click(object sender, EventArgs e) { string strInterface = lstInterface.SelectedItem.ToString().Trim(); EntityShipment objES = new EntityShipment(); //This to debug the code through xml XmlSerializer serializer = new XmlSerializer(typeof(EntityShipment)); //objEIShipment = (EntityShipment)serializer.Deserialize(new XmlTextReader(txtXML.Text)); using (TextReader reader = new StringReader(txtXML.Text)) { objES = (EntityShipment)serializer.Deserialize(reader); } switch (strInterface.ToUpper()) { case "CMS": CMSInterface objCMS = new CMSInterface(); objCMS.Void(objES); break; case "LEXIS": LexisInterface objLexis = new LexisInterface(); objLexis.Void(objES); break; case "LEXISGLOBAL": LexisGlobalInterface objLexisGlobal = new LexisGlobalInterface(); objLexisGlobal.Void(objES); break; case "SAP": SAPInterface objSAP = new SAPInterface(); objSAP.Void(objES); break; default: MessageBox.Show("Interface was not selected"); break; } } } } <file_sep>/CMSInterface.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; using SmartLincInterface; namespace CMS { public class CMSInterface { private List<EntityResponseStatus> lstResponse = new List<EntityResponseStatus>(); private SqlConnection objSQLCon; public EntityShipment Pull(EntityShipment objES) { objSQLCon = GetSqlConnection(objES.ToolKit.objConnection); if (ContinueCheck() == false) { objES.lstEntityResponseStatus = lstResponse; return objES; } objES = FillShipment(objES); objES.lstEntityResponseStatus = lstResponse; return objES; } public EntityShipment Putback(EntityShipment objES) { objSQLCon = GetSqlConnection(objES.ToolKit.objConnection); if (ContinueCheck() == false) { objES.lstEntityResponseStatus = lstResponse; return objES; } if (InsertData(objES) == false) lstResponse.Add(SetResponse("Error - During Putback!", "Error - During Putback! Contact System Administrator!", ResponseStatusType.CRITICAL)); objES.lstEntityResponseStatus = lstResponse; return objES; } public EntityShipment Void(EntityShipment objES) { objSQLCon = GetSqlConnection(objES.ToolKit.objConnection); if (UpdateData(objES) == false) lstResponse.Add(SetResponse("Error - During Void!", "Error - During Void! Contact System Administrator!", ResponseStatusType.CRITICAL)); objES.lstEntityResponseStatus = lstResponse; return objES; } private bool InsertData(EntityShipment objES) { DataTable dtHeader; dtHeader = GetShipmentInformation(objES.objDetails.strDeliveryDocNumber); string str = "update solink set trknum = '" + objES.lstContainer[0].strTrackingNumber.Trim() + "', shipdate = '" + objES.dtShipDate.ToString("MM-dd-yyyy H:mm:ss") + "', shpcharge = '" + TotalFreightCosts(objES.lstContainer, dtHeader) + "' where shipid = '" + objES.objDetails.strDeliveryDocNumber.Trim() + "'"; return ExecuteQuery(str); } private bool UpdateData(EntityShipment objES) { string str = "update solink set trknum = 'VOID' where shipid = '" + objES.objDetails.strDeliveryDocNumber.Trim() + "'"; return ExecuteQuery(str); } private double TotalFreightCosts(List<EntityContainer> lstEC, DataTable dtHeader) { double dblFreight = 0.00; if (dtHeader.Rows[0]["frtprepay"] != DBNull.Value && dtHeader.Rows[0]["frtprepay"].ToString().ToUpper() == "TRUE") return dblFreight; dblFreight = (from c in lstEC select c.objRates.dblTotalPublishedPrice).Sum(); return Math.Round(dblFreight, 2); } private bool ExecuteQuery(string strQuery) { try { lstResponse.Add(SetResponse(strQuery, string.Empty, ResponseStatusType.LOG)); SqlCommand sqlCMD = new SqlCommand(strQuery, objSQLCon); if (objSQLCon.State == ConnectionState.Closed) objSQLCon.Open(); sqlCMD.ExecuteNonQuery(); if (objSQLCon.State == ConnectionState.Open) objSQLCon.Close(); return true; } catch (SqlException ex) { if (objSQLCon.State == ConnectionState.Open) objSQLCon.Close(); lstResponse.Add(SetResponse(strQuery, ex.Message, ResponseStatusType.CRITICAL)); return false; } catch (Exception ex) { if (objSQLCon.State == ConnectionState.Open) objSQLCon.Close(); lstResponse.Add(SetResponse(strQuery, ex.Message, ResponseStatusType.CRITICAL)); return false; } } private SqlConnection GetSqlConnection(EntityConnection objEC) { try { objSQLCon = new SqlConnection(); objSQLCon.ConnectionString = "Data Source=" + objEC.strServer + ";" + "Initial Catalog=" + objEC.strDatabase + ";" + "User ID=" + objEC.strUserID + ";" + "Password=" + objEC.strPassword + ";"; } catch (Exception ex) { lstResponse.Add(SetResponse("Getting SQL Connection String", ex.Message, ResponseStatusType.CRITICAL)); } return objSQLCon; } private EntityResponseStatus SetResponse(string strMessage, string strError, ResponseStatusType eResponseType) { EntityResponseStatus objResponse = new EntityResponseStatus(); objResponse.Message = strMessage; objResponse.StatusType = eResponseType; objResponse.Error = strError; return objResponse; } private bool ContinueCheck() { var objError = (from p in lstResponse where p.StatusType == ResponseStatusType.CRITICAL || p.StatusType == ResponseStatusType.ERROR select p); if (objError == null || objError.Count() == 0) return true; else return false; } private EntityShipment FillShipment(EntityShipment objES) { DataTable dtHeader; dtHeader = GetShipmentInformation(objES.objDetails.strDeliveryDocNumber); if (ContinueCheck() == false) { return objES; } if (dtHeader != null && dtHeader.Rows.Count > 0) { if (dtHeader.Rows[0]["trknum"] != null && dtHeader.Rows[0]["trknum"].ToString().Trim() != "" && dtHeader.Rows[0]["trknum"].ToString().Trim() != "VOID") { lstResponse.Add(SetResponse("Record Already Shipped", "Record Already Shipped", ResponseStatusType.WARNING)); return objES; } else { objES.objShipTo = FillShipTo(dtHeader.Rows[0]); objES.objDetails = FillDetails(dtHeader.Rows[0], objES.objDetails); objES.objShipMethod = GetShipViaCode(dtHeader.Rows[0]); } } else lstResponse.Add(SetResponse("No Shipment Information Found!", "No Shipment Information Found!", ResponseStatusType.CRITICAL)); return objES; } private EntityShipMethod GetShipViaCode(DataRow dr) { EntityShipMethod objSM = new EntityShipMethod(); String strPaymentTerms = ""; if (dr["shipvia"] != null) objSM.strShipViaCode = dr["shipvia"].ToString().Trim(); if (dr["shpbillopt"] != null) strPaymentTerms = dr["shpbillopt"].ToString().Trim(); switch (strPaymentTerms.ToUpper()) { case "SENDER": objSM.PaymentTermType = ePaymentTerms.Shipper; break; case "RECIPIENT": objSM.PaymentTermType = ePaymentTerms.Recipient; break; case "THIRD PARTY": objSM.PaymentTermType = ePaymentTerms.ThirdParty; break; case "CONSIGNEE": objSM.PaymentTermType = ePaymentTerms.Consignee; break; case "FREIGHT COLLECT": objSM.PaymentTermType = ePaymentTerms.FreightCollect; break; default: objSM.PaymentTermType = ePaymentTerms.Shipper; break; } return objSM; } private DataTable GetShipmentInformation(string strDeliveryDocNumber) { StringBuilder sb = new StringBuilder(); sb.Append("Select * from solink where shipid = '" + strDeliveryDocNumber.Trim() + "'"); return ExecuteSelectQuery(sb.ToString()); } private DataTable ExecuteSelectQuery(string strStatement) { try { lstResponse.Add(SetResponse(strStatement, string.Empty, ResponseStatusType.LOG)); DataTable dtSelect = new DataTable(); if (objSQLCon.State == ConnectionState.Closed) objSQLCon.Open(); SqlDataAdapter daSelect = new SqlDataAdapter(strStatement, objSQLCon); daSelect.Fill(dtSelect); if (objSQLCon.State == ConnectionState.Open) objSQLCon.Close(); return dtSelect; } catch (SqlException ex) { lstResponse.Add(SetResponse(strStatement, ex.Message, ResponseStatusType.CRITICAL)); } catch (Exception ex) { lstResponse.Add(SetResponse(strStatement, ex.Message, ResponseStatusType.CRITICAL)); } finally { if (objSQLCon.State == ConnectionState.Open) objSQLCon.Close(); } return null; } private EntityAddress FillShipTo(DataRow dr) { EntityAddress objEntityAddress = new EntityAddress(); try { if (dr["CompanyName"] != DBNull.Value) objEntityAddress.strCompanyName = dr["CompanyName"].ToString().Trim(); if (dr["Address1"] != DBNull.Value) objEntityAddress.strAddressLine1 = dr["Address1"].ToString().Trim(); if (dr["Address2"] != DBNull.Value) objEntityAddress.strAddressLine2 = dr["Address2"].ToString().Trim(); if (dr["Address3"] != DBNull.Value) objEntityAddress.strAddressLine3 = dr["Address3"].ToString().Trim(); if (dr["City"] != DBNull.Value) objEntityAddress.strCity = dr["City"].ToString().Trim(); if (dr["ShipState"] != DBNull.Value) objEntityAddress.strState = dr["ShipState"].ToString().Trim(); if (dr["ZipCode"] != DBNull.Value) objEntityAddress.strPostalCode = dr["ZipCode"].ToString().Trim(); if (dr["PhoneNumber"] != DBNull.Value) objEntityAddress.strPhoneNumber = dr["PhoneNumber"].ToString().Trim(); if (dr["AttentionTo"] != DBNull.Value) objEntityAddress.strContactName = dr["AttentionTo"].ToString().Trim(); if (dr["SenderEmailAddress1"] != DBNull.Value) objEntityAddress.strEmailAddress = dr["SenderEmailAddress1"].ToString().Trim(); if (dr["Country"] != DBNull.Value) objEntityAddress.strCountryCode = dr["Country"].ToString().Trim(); } catch (Exception ex) { lstResponse.Add(SetResponse("Error Filling In Ship To Details!", ex.Message, ResponseStatusType.WARNING)); } return objEntityAddress; } private EntityShipmentDetails FillDetails(DataRow dr, EntityShipmentDetails objSD) { try { if (dr["sono"] != DBNull.Value) objSD.strPONumber = dr["sono"].ToString().Trim(); if (dr["invno"] != DBNull.Value) objSD.strInvoiceNumber = dr["invno"].ToString().Trim(); } catch (Exception ex) { lstResponse.Add(SetResponse("Error Filling In Shipment Details!", ex.Message, ResponseStatusType.WARNING)); } return objSD; } } }
254b62a22119d7ba667ce8836ebc97f00fdd3867
[ "C#" ]
6
C#
JJakubowskiCenveo/SmartLincEICustomers
12d60277e164d8fdd0926d2755f00dd313eb9be2
d352d390bf927f93a69f92ce80df4b65a1a4f0d1
refs/heads/master
<repo_name>raj-savaj/water<file_sep>/app/src/main/java/com/rj/watersupply/modal/ResponseLogin.java package com.rj.watersupply.modal; import java.util.ArrayList; public class ResponseLogin { private float status; private String msg; ArrayList<Data> data = new ArrayList<Data>(); public float getStatus() { return status; } public String getMsg() { return msg; } public void setStatus( float status ) { this.status = status; } public void setMsg( String msg ) { this.msg = msg; } public ArrayList<Data> getData() { return data; } public void setData(ArrayList<Data> data) { this.data = data; } public class Data { private int id; private String name; private String email; private String pass; public void setId(int id){ this.id = id; } public int getId(){ return this.id; } public void setName(String name){ this.name = name; } public String getName(){ return this.name; } public void setEmail(String email){ this.email = email; } public String getEmail(){ return this.email; } public void setPass(String pass){ this.pass = pass; } public String getPass(){ return this.pass; } } } <file_sep>/app/src/main/java/com/rj/watersupply/AddBottle.java package com.rj.watersupply; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearSmoothScroller; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.TextView; import com.google.android.material.button.MaterialButton; import com.google.android.material.snackbar.Snackbar; import com.google.android.material.textfield.TextInputLayout; import com.rj.watersupply.WebApi.API; import com.rj.watersupply.WebApi.Builder; import com.rj.watersupply.modal.Product; import com.rj.watersupply.modal.ResponseLogin; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class AddBottle extends AppCompatActivity { List<Product> products; Product product=null; AutoCompleteTextView edtAutocomplete; TextInputLayout txtQty,txtBasePrice,txtDescription; MaterialButton btnSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_addbottle); edtAutocomplete = findViewById(R.id.filled_exposed_dropdown); txtQty=findViewById(R.id.txtQty); txtBasePrice=findViewById(R.id.txtBasePrice); txtDescription=findViewById(R.id.txtDescription); btnSave=findViewById(R.id.btnSaveBottle); setProduct(); edtAutocomplete.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { product=products.get(position); txtBasePrice.getEditText().setText(""+products.get(position).getBase_price()); } }); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Validation()){ HashMap<String, String> hashFields=new HashMap<>(); hashFields.put("pid",""+product.getPID()); hashFields.put("qty",txtQty.getEditText().getText().toString()); hashFields.put("price",txtBasePrice.getEditText().getText().toString()); hashFields.put("desc",txtDescription.getEditText().getText().toString()); API api=Builder.getClient(); Call<ResponseLogin> call=api.addBottle(hashFields); call.enqueue(new Callback<ResponseLogin>() { @Override public void onResponse(Call<ResponseLogin> call, Response<ResponseLogin> response) { if(response.isSuccessful()){ Snackbar.make(getView(), "Bottle successfully saved", Snackbar.LENGTH_LONG).show(); txtQty.getEditText().setText(null); txtBasePrice.getEditText().setText(null); txtDescription.getEditText().setText(null); } else{ Snackbar.make(getView(), "Please fill the detail", Snackbar.LENGTH_LONG).show(); } } @Override public void onFailure(Call<ResponseLogin> call, Throwable t) { Snackbar.make(getView(), "Page not found", Snackbar.LENGTH_LONG).setAction("RETRY", new View.OnClickListener() { @Override public void onClick(View v) { setProduct(); } }).show(); } }); } } }); } private void setProduct() { API api= Builder.getClient(); Call<List<Product>> call=api.getAllProduct(); call.enqueue(new Callback<List<Product>>() { @Override public void onResponse(Call<List<Product>> call, Response<List<Product>> response) { if(response.isSuccessful()){ products=response.body(); setAdapater(); } else { Snackbar.make(getView(), "Internal server error", Snackbar.LENGTH_LONG).show(); } } @Override public void onFailure(Call<List<Product>> call, Throwable t) { Snackbar.make(getView(), "Page not found", Snackbar.LENGTH_LONG).setAction("RETRY", new View.OnClickListener() { @Override public void onClick(View v) { setProduct(); } }).show(); } }); } public void setAdapater(){ ArrayList<String> pname= new ArrayList<>(); int i=0; for(Product p:products){ pname.add(p.getPname()); } ArrayAdapter<String> adapter =new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,pname); edtAutocomplete.setAdapter(adapter); } public View getView() { return findViewById(android.R.id.content); } public boolean Validation(){ boolean check=true; if(product==null){ Snackbar.make(getView(), "Please fill the detail", Snackbar.LENGTH_LONG).show(); check=false; } if(txtQty.getEditText().getText().toString().isEmpty()){ txtQty.setError("Please fill the qty"); check=false; } else{ txtQty.setErrorEnabled(false); } return check; } } <file_sep>/app/src/main/java/com/rj/watersupply/modal/CustomerData.java package com.rj.watersupply.modal; public class CustomerData { private String c_id; private String name; private String address; private String phone; private int cBottle; private int hBottle; private int cBottlePrice; private int hBottlePrice; private int cBottleRet; private int hBottleRet; private int credit; private int debit; private int total; private String status; private String date; public String getC_id() { return c_id; } public String getName() { return name; } public String getAddress() { return address; } public String getPhone() { return phone; } public int getCBottle() { return cBottle; } public int getHBottle() { return hBottle; } public int getCBottlePrice() { return cBottlePrice; } public int getHBottlePrice() { return hBottlePrice; } public int getCBottleRet() { return cBottleRet; } public int getHBottleRet() { return hBottleRet; } public int getCredit() { return credit; } public int getDebit() { return debit; } public int getTotal() { return total; } public String getStatus() { return status; } public String getDate() { return date; } // Setter Methods public void setC_id( String c_id ) { this.c_id = c_id; } public void setName( String name ) { this.name = name; } public void setAddress( String address ) { this.address = address; } public void setPhone( String phone ) { this.phone = phone; } public void setCBottle( int cBottle ) { this.cBottle = cBottle; } public void setHBottle( int hBottle ) { this.hBottle = hBottle; } public void setCBottlePrice( int cBottlePrice ) { this.cBottlePrice = cBottlePrice; } public void setHBottlePrice( int hBottlePrice ) { this.hBottlePrice = hBottlePrice; } public void setCBottleRet( int cBottleRet ) { this.cBottleRet = cBottleRet; } public void setHBottleRet( int hBottleRet ) { this.hBottleRet = hBottleRet; } public void setCredit( int credit ) { this.credit = credit; } public void setDebit( int debit ) { this.debit = debit; } public void setTotal( int total ) { this.total = total; } public void setStatus( String status ) { this.status = status; } public void setDate( String date ) { this.date = date; } } <file_sep>/app/src/main/java/com/rj/watersupply/AddCustomer.java package com.rj.watersupply; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Intent; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TimePicker; import android.widget.Toast; import com.google.android.material.button.MaterialButton; import com.google.android.material.datepicker.MaterialDatePicker; import com.google.android.material.datepicker.MaterialPickerOnPositiveButtonClickListener; import com.google.android.material.textfield.TextInputLayout; import com.rj.watersupply.Util.InputValidatorHelper; import com.rj.watersupply.WebApi.API; import com.rj.watersupply.WebApi.Builder; import com.rj.watersupply.modal.ResponseLogin; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Objects; import java.util.TimeZone; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class AddCustomer extends AppCompatActivity { TextInputLayout txtName, txtaddress, txtmno; TextInputLayout txtColdQty, txtHotQty, txtColdPrice, txtHotPrice, txtReturnCold, txtReturnHot; TextInputLayout txtDebit, txtCredit, txtTotal; MaterialButton btnSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_customer); init(); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(validation()){ HashMap<String, String> hashMap=new HashMap<>(); hashMap.put("name",txtName.getEditText().getText().toString()); hashMap.put("add",txtaddress.getEditText().getText().toString()); hashMap.put("phone",txtmno.getEditText().getText().toString()); hashMap.put("cBottle",txtColdQty.getEditText().getText().toString()); hashMap.put("hBottle",txtHotQty.getEditText().getText().toString()); hashMap.put("cBottlePr",txtColdPrice.getEditText().getText().toString()); hashMap.put("hBottlePr",txtHotPrice.getEditText().getText().toString()); hashMap.put("cBottleRt",txtReturnCold.getEditText().getText().toString()); hashMap.put("hBottleRt",txtReturnHot.getEditText().getText().toString()); hashMap.put("credit",txtCredit.getEditText().getText().toString()); hashMap.put("debit",txtDebit.getEditText().getText().toString()); hashMap.put("total",txtTotal.getEditText().getText().toString()); btnSave.setEnabled(false); API api= Builder.getClient(); Call<ResponseLogin> call=api.InsertCustomer(hashMap); call.enqueue(new Callback<ResponseLogin>() { @Override public void onResponse(Call<ResponseLogin> call, Response<ResponseLogin> response) { btnSave.setEnabled(true); if(response.isSuccessful()) { if(response.body().getStatus()==200){ Toast.makeText(AddCustomer.this, ""+response.body().getMsg(), Toast.LENGTH_SHORT).show(); Intent i=new Intent(getApplicationContext(),Customer.class); startActivity(i); } if(response.body().getStatus()==401){ txtmno.setError(response.body().getMsg()); } }else{ Toast.makeText(AddCustomer.this, "Server Error", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<ResponseLogin> call, Throwable t) { btnSave.setEnabled(true); Toast.makeText(AddCustomer.this, "Page Not Found ", Toast.LENGTH_SHORT).show(); } }); } } }); } private void init() { txtName = findViewById(R.id.txtName); txtaddress = findViewById(R.id.txtaddress); txtmno = findViewById(R.id.txtmno); txtColdQty = findViewById(R.id.txtColdQty); txtHotQty = findViewById(R.id.txtHotQty); txtColdPrice = findViewById(R.id.txtColdPrice); txtHotPrice = findViewById(R.id.txtHotPrice); txtReturnCold = findViewById(R.id.txtReturnCold); txtReturnHot = findViewById(R.id.txtReturnHot); txtDebit = findViewById(R.id.txtDebit); txtCredit = findViewById(R.id.txtCredit); txtTotal = findViewById(R.id.txtTotal); btnSave = findViewById(R.id.btnSave); } public boolean validation(){ boolean status=true; InputValidatorHelper v=new InputValidatorHelper(); if(v.isNullOrEmpty(txtName.getEditText().getText().toString())){ status=false; txtName.setError("Please Enter Name"); } else{ txtName.setErrorEnabled(false); } if(v.isNullOrEmpty(txtaddress.getEditText().getText().toString())){ status=false; txtaddress.setError("Please Enter Address"); } else{ txtaddress.setErrorEnabled(false); } if(v.isNullOrEmpty(txtmno.getEditText().getText().toString())){ status=false; txtmno.setError("Please Enter Mobile No"); } else{ txtmno.setErrorEnabled(false); } if(v.isNullOrEmpty(txtColdQty.getEditText().getText().toString())){ status=false; txtColdQty.setError("Please Enter Cold Qty"); } else{ txtColdQty.setErrorEnabled(false); } if(v.isNullOrEmpty(txtHotQty.getEditText().getText().toString())){ status=false; txtHotQty.setError("Please Enter Hot Qty"); } else{ txtHotQty.setErrorEnabled(false); } if(v.isNullOrEmpty(txtColdPrice.getEditText().getText().toString())){ status=false; txtColdPrice.setError("Please Enter Cold Price"); } else{ txtColdPrice.setErrorEnabled(false); } if(v.isNullOrEmpty(txtHotPrice.getEditText().getText().toString())){ status=false; txtHotPrice.setError("Please Enter Hot Price"); } else{ txtHotPrice.setErrorEnabled(false); } if(v.isNullOrEmpty(txtDebit.getEditText().getText().toString())){ status=false; txtDebit.setError("Please Enter Debit Amount"); } else{ txtDebit.setErrorEnabled(false); } if(v.isNullOrEmpty(txtCredit.getEditText().getText().toString())){ status=false; txtCredit.setError("Please Enter Credit Amount"); } else{ txtCredit.setErrorEnabled(false); } return status; } } <file_sep>/app/src/main/java/com/rj/watersupply/Login.java package com.rj.watersupply; import androidx.appcompat.app.AppCompatActivity; import android.app.Dialog; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.rj.watersupply.WebApi.API; import com.rj.watersupply.WebApi.Builder; import com.rj.watersupply.modal.ResponseLogin; import org.w3c.dom.Text; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Login extends AppCompatActivity { EditText uname,pass; TextView btnlogin; Dialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); uname=findViewById(R.id.uname); pass=findViewById(R.id.pass); btnlogin=findViewById(R.id.btnlogin); btnlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { doLogin(); } }); } private void doLogin() { btnlogin.setEnabled(false); API api= Builder.getClient(); Call<ResponseLogin> call=api.checkLogin(uname.getText().toString(),pass.getText().toString()); call.enqueue(new Callback<ResponseLogin>() { @Override public void onResponse(Call<ResponseLogin> call, Response<ResponseLogin> response) { btnlogin.setEnabled(true); if(response.isSuccessful()) { if(response.body().getStatus()==200){ Toast.makeText(Login.this, ""+response.body().getMsg(), Toast.LENGTH_SHORT).show(); Intent i=new Intent(getApplicationContext(),MainActivity.class); startActivity(i); finish(); } else{ ShowDialog(); } } else{ Toast.makeText(Login.this, "Server Error", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<ResponseLogin> call, Throwable t) { Toast.makeText(Login.this, "Page Not Found ", Toast.LENGTH_SHORT).show(); Log.e("MSG",""+t.getMessage()); btnlogin.setEnabled(true); } }); } public void ShowDialog() { dialog = new Dialog(Login.this); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setCancelable(true); dialog.setContentView(R.layout.popup_cancel); dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); dialog.show(); Window window = dialog.getWindow(); window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT); TextView t = (TextView) dialog.findViewById(R.id.btnok); t.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); pass.setText(null); } }); } } <file_sep>/app/src/main/java/com/rj/watersupply/modal/Product.java package com.rj.watersupply.modal; public class Product { private int PID; private String pname; private String pcode; private int base_price; // Getter Methods public int getPID() { return PID; } public String getPname() { return pname; } public String getPcode() { return pcode; } public int getBase_price() { return base_price; } // Setter Methods public void setPID(int PID) { this.PID = PID; } public void setPname(String pname) { this.pname = pname; } public void setPcode(String pcode) { this.pcode = pcode; } public void setBase_price(int base_price) { this.base_price = base_price; } }
5a2358dfe33c14b0ec3ca11f26b8548d496cdcc9
[ "Java" ]
6
Java
raj-savaj/water
51fc90367902f8eda3a07c7dc4a617d3dbc998d4
ca2cfd94f628967fcfeb22f4bec8df43c4cc75b5
refs/heads/master
<repo_name>AndriiBruk/Horoshop_migration<file_sep>/src/main.js import './main.scss'; const regSite = /.+/i; const regEmail = /.+@.+\..+/i; let inputs = document.querySelectorAll('input'); for (let input of inputs) { input.addEventListener('blur', function(){ let inputClasses = this.classList; let inputValue = this.value; let check; for (let className of inputClasses){ switch (className) { case 'url-field': check = regSite.test(inputValue); break; case 'email-field': check = regEmail.test(inputValue); break; } if (check) { this.classList.remove('invalid') this.classList.add('valid') } else { this.classList.remove('valid') this.classList.add('invalid') } } }) } <file_sep>/webpack.config.js const path = require('path'); const HTMLWebpackPlugin = require('html-webpack-plugin'); const {CleanWebpackPlugin} = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const CssMinimizerPlugin = require('css-minimizer-webpack-plugin'); const TerserWebpackPlugin = require("terser-webpack-plugin"); const isDev = process.env.NODE_ENV === 'development'; const isProd = !isDev; const optimization = () => { const config = {} if(isProd) { config.minimizer = [ new CssMinimizerPlugin(), new TerserWebpackPlugin() ] } return config } module.exports = { context: path.resolve(__dirname, 'src'), mode: 'development', entry: './main.js', output: { filename: `main.[contenthash].js`, path: path.resolve(__dirname, 'app'), }, optimization: optimization(), devServer: { historyApiFallback: true, contentBase: path.resolve(__dirname, 'app'), open: true, compress: true, port:3000 }, plugins: [ new HTMLWebpackPlugin({ template: './index.html', inject: 'body', minify: { collapseWhitespace: isProd } }), new CleanWebpackPlugin(), new MiniCssExtractPlugin({ filename:'style.[contenthash].css' }), new CopyWebpackPlugin({ patterns: [ {from: path.resolve(__dirname, 'src/img'), to: path.resolve(__dirname, 'app/img')} ] }) ], module: { rules: [ { test: /\.s[ac]ss$/, use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"], }, { test: /\.(png|svg|jpg|jpeg|gif)$/, use: ['file-loader'] }, { test: /\.(ttf|woff|woff2)$/, loader: 'file-loader', options: { outputPath: 'fonts' } } ] } }
731085bb5aebfb0e4d6941d0936ce9f95f3191c4
[ "JavaScript" ]
2
JavaScript
AndriiBruk/Horoshop_migration
46ef6c334bd9c2e38f05d5fbac0eb6f8b0e46971
5756d806c805038c21d1f7ac3eceb1f05c3c93bf
refs/heads/master
<repo_name>FranciscodaMVP/keep-angular<file_sep>/notebook.js angular .module ('notebook', []) .controller('notebookController', notebookController) .factory('NoteService', NoteService); // function notebookController($scope, NoteService) { // $scope.notes = NoteService.notes; // $scope.addNote = function () { // let newNote = { // 'text' : $scope.newNote, // 'id' : new Date(), // 'modified' : '',} // NoteService.notes.push(newNote); // $scope.newNote = {}; // } // } function startNotes() { if (localStorage.getItem('oldNotes')){ NoteService.notes = (JSON.parse(localStorage.getItem('oldNotes'))); } } function Note (text) { let Note = { 'id' : setId(), 'date' : new Date (), 'note' : text.text, 'modified' : '', }; return Note; } function notebookController($scope, NoteService) { $scope.notes = NoteService.notes; $scope.onBlur = function () { if ($scope.newNote && $scope.newNote.id) { console.log ($scope.newNote.id); updateNote($scope, $scope.newNote.id, $scope.newNote)} if ($scope.newNote && typeof $scope.newNote.text != 'undefined' ) { let note = Note($scope.newNote); NoteService.notes.push(note); $scope.newNote = {}; localStorage.setItem('oldNotes', JSON.stringify($scope.notes)); }} $scope.updateNewNote = function (text, id) { $scope.newNote = {text}; $scope.newNote.id = id;} $scope.deleteNote = function (id) {killNote ($scope, id)} } function NoteService() { if (localStorage.getItem('oldNotes')){ var notebook = { notes : (JSON.parse(localStorage.getItem('oldNotes'))) } //console.log(notebook); } else {var notebook = { notes: [] } } return notebook; } function updateNote ($scope, id, note) { for (var a in $scope.notes) { if ($scope.notes[a].id === id) { $scope.notes[a].note = note.text; $scope.notes[a].modified = new Date (); localStorage.setItem('oldNotes', JSON.stringify($scope.notes)); $scope.newNote = {}; } } } function setId() { return new Date().getTime(); } function killNote ($scope, id) { for (var a in $scope.notes) { if ($scope.notes[a].id === id) { //console.log($scope.notes[a]); $scope.notes.splice(a,1); } } }
96adbcb293c3e708b00cfed9e787b8c6d163eef8
[ "JavaScript" ]
1
JavaScript
FranciscodaMVP/keep-angular
e35c7829a0f098013e562266474572545020e3dc
ad120efb22a47fac48a7a0ec8dbc5a87a16eaeb0
refs/heads/master
<file_sep>'use strict' /** @typedef {import('@adonisjs/framework/src/Request')} Request */ /** @typedef {import('@adonisjs/framework/src/Response')} Response */ /** @typedef {import('@adonisjs/framework/src/View')} View */ /** * Resourceful controller for interacting with todos */ const Todo = use('App/Models/Todo') class TodoController { /** * Show a list of all todos. * GET todos * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async index ({ auth }) { const todo = await Todo.query().where('user_id', auth.user.id).fetch() return todo } /** * Create/save a new todo. * POST todos * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async store ({ request, auth, params }) { const data = request.only(['title']) const todo = Todo.create({ ...data, user_id: auth.user.id, category_id: params.id}) return todo } /** * Display a single todo. * GET todos/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async show ({ params, auth, response }) { const { id } = params const todo = await Todo.findOrFail(id) if(todo.user_id !== auth.user.id) { return response.status(401).json({ error: 'not authorized' }) } return todo } /** * Update todo details. * PUT or PATCH todos/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update ({ params, request, response, auth }) { const data = request.only(['title', 'status']) const todo = await Todo.find(params.id) if(todo.user_id !== auth.user.id) { return response.status(401).json({ error: "Not authorized" }) } todo.merge(data) await todo.save() return todo } /** * Delete a todo with id. * DELETE todos/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy ({ params, response, auth }) { const todo = await Todo.findOrFail(params.id) if(todo.user_id !== auth.user.id) { return response.status(401).json({ error: "Not authorized" }) } await todo.delete() } } module.exports = TodoController <file_sep>'use strict' /** @typedef {import('@adonisjs/framework/src/Request')} Request */ /** @typedef {import('@adonisjs/framework/src/Response')} Response */ /** @typedef {import('@adonisjs/framework/src/View')} View */ /** * Resourceful controller for interacting with categories */ const Category = use('App/Models/Category') class CategoryController { /** * Show a list of all categories. * GET categories * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async index ({auth}) { const categories = await Category.query().where('user_id', auth.user.id).fetch() return categories } /** * Create/save a new category. * POST categories * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async store ({auth, request }) { const { id } = auth.user const data = request.only(['title']) const category = await Category.create({...data, user_id: id}) return category } /** * Display a single category. * GET categories/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response * @param {View} ctx.view */ async show ({ params, auth, response }) { const { id } = params; const category = await Category.findOrFail(id) await category.load('todos') if(category.user_id !== auth.user.id) { return response.status(401).json({ error: 'not authorized' }) } return category } /** * Update category details. * PUT or PATCH categories/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async update ({ params, request, response, auth }) { const data = request.only(['title']) const category = await Category.find(params.id) if(category.user_id !== auth.user.id) { return response.status(401).json({ error: "Not authorized" }) } category.merge(data) await category.save() return category } /** * Delete a category with id. * DELETE categories/:id * * @param {object} ctx * @param {Request} ctx.request * @param {Response} ctx.response */ async destroy ({ params, auth, response }) { const category = await Category.findOrFail(params.id) if(category.user_id !== auth.user.id) { return response.status(401).json({ error: "Not authorized" }) } await category.delete() } } module.exports = CategoryController
dd4a4d78e01d2a974ccbf4229dd9a0c75e52484f
[ "JavaScript" ]
2
JavaScript
alissin4444/todo-adonis-materialui-paper
f301ec24050af5ecebba0163c85f3ea29381b561
6795da135fa44e87a0ef1a6eda66cb6735f857a3
refs/heads/master
<repo_name>VashingMachine/rotating-cube<file_sep>/camera_matrix/CameraMatrixProjection.py import numpy as np import tkinter import index class CameraProjection: def __init__(self, f): self.f = f self.camera_matrix = None self.x_angle = 0 self.y_angle = 0 self.z_angle = 0 self.transposition = np.array([0, 0, 0]) self.rotation = np.matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.setF(f) self.camera_pos = np.array([0, 0, 0]) def setF(self, f): self.f = f self.camera_matrix = np.column_stack( [np.array([f, 0, 0]), np.array([0, f, 0]), np.array([0, 0, 1]), np.array([0, 0, 0])]) def rotation_matrix(self): x = self.x_angle y = self.y_angle z = self.z_angle x_rotation = np.matrix([[1, 0, 0], [0, np.cos(x), -np.sin(x)], [0, np.sin(x), np.cos(x)]]) y_rotation = np.matrix([[np.cos(y), 0, np.sin(y)], [0, 1, 0], [-np.sin(y), 0, np.cos(y)]]) z_rotation = np.matrix([[np.cos(z), -np.sin(z), 0], [np.sin(z), np.cos(z), 0], [0, 0, 1]]) rotation = x_rotation.dot(y_rotation.dot(z_rotation)) return rotation def m_matrix(self): t = self.transposition rotation = self.rotation_matrix() output = np.block([ [rotation, t.reshape((3, 1))], [0, 0, 0, 1] ]) self.rotation = rotation self.camera_pos = np.squeeze(np.asarray(-np.linalg.inv(rotation).dot(np.squeeze(np.asarray(t))))) return output def localise(self, x): x = np.append(x, [1]) m = self.m_matrix() c = np.append(self.transposition, [1]) # l = self.get_lookup_vector() # l = np.squeeze(np.asarray(l)) # c = np.append(l, [1]) h = m.dot(x - c) h = np.squeeze(np.asarray(h)) y = self.camera_matrix.dot(h) y = y / y[2] return y def get_lookup_vector(self): u, w, v = self.rotation[:, 0], self.rotation[:, 1], self.rotation[:, 2] n = u + w + v norm = np.linalg.norm(n) return n / norm <file_sep>/camera_matrix/CameraController.py import numpy as np class Controller: def __init__(self, camera, drawer): self.camera = camera self.drawer = drawer self.drawer.register_binding("<Up>", self.key_up) self.drawer.register_binding("<Down>", self.key_down) self.drawer.register_binding("<Left>", self.key_left) self.drawer.register_binding("<Right>", self.key_right) self.drawer.register_binding("<Key>", self.key) # self.drawer.register_binding("<Motion>", self.motion) def key_up(self, event): self.camera.transposition += np.array([0, 0, 1]) def key_down(self, event): self.camera.transposition += np.array([0, 0, -1]) def key_left(self, event): self.camera.transposition += np.array([-1, 0, 0]) def key_right(self, event): self.camera.transposition += np.array([1, 0, 0]) def key(self, event): camera = self.camera if event.char == 'f': camera.setF(camera.f + 10) elif event.char == 'g': camera.setF(camera.f - 10) elif event.char == 'q': camera.z_angle += 0.1 elif event.char == 'w': camera.z_angle -= 0.1 elif event.char == 'a': camera.y_angle += 0.1 elif event.char == 's': camera.y_angle -= 0.1 elif event.char == 'z': camera.x_angle += 0.1 elif event.char == 'x': camera.x_angle -= 0.1 elif event.char == 'y': camera.transposition += np.array([0, 1, 0]) elif event.char == 'u': camera.transposition += np.array([0, -1, 0]) mouse_previous_point = None <file_sep>/index.py import tkinter import numpy as np cube = [np.array([0, 0, 0]), np.array([0, 0, 1]), np.array([0, 1, 0]), np.array([0, 1, 1]), np.array([1, 0, 0]), np.array([1, 0, 1]), np.array([1, 1, 0]), np.array([1, 1, 1])] clear_cube = [200 * (v + np.array([1, 1, 1])) for v in cube] cube = [200 * (v + np.array([-0.5, -0.5, -0.5])) for v in cube] def draw_segment_projected(A, B, projection, canvas): offset = [300, 300] a = projection.localise(A) b = projection.localise(B) canvas.create_line(a[0] + offset[0], a[1] + offset[1], b[0] + offset[0], b[1] + offset[1]) def draw_cube(cube, projection, canvas): draw_segment_projected(cube[0], cube[1], projection, canvas) draw_segment_projected(cube[0], cube[2], projection, canvas) draw_segment_projected(cube[0], cube[4], projection, canvas) draw_segment_projected(cube[1], cube[3], projection, canvas) draw_segment_projected(cube[1], cube[5], projection, canvas) draw_segment_projected(cube[2], cube[3], projection, canvas) draw_segment_projected(cube[2], cube[6], projection, canvas) draw_segment_projected(cube[3], cube[7], projection, canvas) draw_segment_projected(cube[4], cube[5], projection, canvas) draw_segment_projected(cube[4], cube[6], projection, canvas) draw_segment_projected(cube[5], cube[7], projection, canvas) draw_segment_projected(cube[6], cube[7], projection, canvas) <file_sep>/pointy_projection.py import tkinter import numpy as np from PointyProjection import PointyProjection as Projection from OrtogonalProjection import Base from index import draw_cube, cube u1 = np.array([1, 0, 0]) u2 = np.array([0, 1, 0]) u3 = np.array([0, 0, 1]) base = Base(u1, u2, u3) p = Projection(50, np.array([200.0, -60.0, -400.0]), base) def key_up(event): p.near -= 1 def key_down(event): p.near += 1 mouse_previous_point = None def motion(event): global mouse_previous_point if mouse_previous_point is not None: move = event.x - mouse_previous_point[0], event.y - mouse_previous_point[1] print(move) base.rotate_x(move[1] * 0.001) base.rotate_y(move[0] * 0.001) mouse_previous_point = event.x, event.y def key(event): if event.char == 'd': p.pv += base.base[:, 0] * 10 elif event.char == 'a': p.pv -= base.base[:, 0] * 10 elif event.char == 'w': p.pv += base.base[:, 2] * 20 elif event.char == 's': p.pv -= base.base[:, 2] * 20 top = tkinter.Tk() C = tkinter.Canvas(top, bg="white", height=1080, width=1920) top.bind("<Up>", key_up) top.bind("<Down>", key_down) top.bind("<Key>", key) top.bind("<Motion>", motion) def main_loop(): C.delete("all") C.pack() draw_cube(cube, p, C) top.after(17, main_loop) top.after(0, main_loop) top.mainloop() <file_sep>/camera_matrix/cmp_index.py from camera_matrix.CameraMatrixProjection import CameraProjection from camera_matrix.Drawer import Drawer from camera_matrix.solids.Cuboid import Cuboid from camera_matrix.CameraController import Controller from camera_matrix.CameraGui import Gui import numpy as np projection = CameraProjection(400) drawer = Drawer(projection) controller = Controller(projection, drawer) gui = Gui(projection, drawer) drawer.add_solid(Cuboid(np.array([0, 0, 200]), 100, 100, 100)) drawer.add_solid(Cuboid(np.array([0, 0, 300]), 100, 100, 100)) drawer.add_solid(Cuboid(np.array([200, 0, 300]), 50, 80, 100)) drawer.add_solid(Cuboid(np.array([200, 200, 300]), 100, 100, 100)) drawer.init() <file_sep>/PointyProjection.py import numpy as np class PointyProjection: def __init__(self, near, pv, base): self.near = near self.pv = pv self.base = base def localise(self, p): p = self.base.localise(p) pv = self.base.localise(self.pv) x = pv[0] - p[0] y = pv[1] - p[1] h = pv[2] - p[2] - self.near f = h / (h + self.near) return np.array([x * f, y * f]) <file_sep>/camera_matrix/Drawer.py import tkinter from camera_matrix.SolidDraw import SolidDraw class Drawer: frameTime = 30 offset = (400, 300) def __init__(self, projection, height=600, width=800): self.projection = projection self.topLayer = tkinter.Tk() self.canvas = tkinter.Canvas(self.topLayer, bg="white", height=height, width=width) self.solidDrawer = SolidDraw(self) self.funcs = [] self.solids = [] def add_to_loop(self, func): self.funcs.append(func) def add_solid(self, solid): self.solids.append(solid) def main_loop(self): self.canvas.delete("all") self.canvas.pack() for func in self.funcs: func() for solid in self.solids: self.solidDrawer.draw(solid) self.topLayer.after(self.frameTime, self.main_loop) def register_binding(self, key, func): self.topLayer.bind(key, func) def init(self): self.topLayer.after(0, self.main_loop) self.topLayer.mainloop() <file_sep>/main.py import tkinter import numpy as np import scipy.linalg as la class Base: def __init__(self, v, w): self.base = np.column_stack([v, w]) self.normalize() pass def normalize(self): # self.base = la.orth(self.base) # Gram - Schmitd ortonormalization u1 = self.base[:, 0] u2 = self.base[:, 1] u2 = u2 - u2.dot(u1) / u1.dot(u1) * u1 u1 = u1 / np.linalg.norm(u1) u2 = u2 / np.linalg.norm(u2) self.base = np.column_stack([u1, u2]) pass def rotate_z(self, a): rotation_matrix = np.matrix([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]]) self.base = rotation_matrix.dot(self.base) self.base = np.squeeze(np.asarray(self.base)) pass def rotate_x(self, a): rotation_matrix = np.matrix([[1, 0, 0], [0, np.cos(a), -np.sin(a)], [0, np.sin(a), np.cos(a)]]) self.base = rotation_matrix.dot(self.base) self.base = np.squeeze(np.asarray(self.base)) def localise(self, v): return v.dot(self.base[:, 0]), v.dot(self.base[:, 1]) def __str__(self): return self.base.__str__() def draw_segment_projected(A, B, base, canvas): offset = [300, 300] a = base.localise(A) b = base.localise(B) canvas.create_line(a[0] + offset[0], a[1] + offset[1], b[0] + offset[0], b[1] + offset[1]) def draw_cube(cube, base, canvas): draw_segment_projected(cube[0], cube[1], base, canvas) draw_segment_projected(cube[0], cube[2], base, canvas) draw_segment_projected(cube[0], cube[4], base, canvas) draw_segment_projected(cube[1], cube[3], base, canvas) draw_segment_projected(cube[1], cube[5], base, canvas) draw_segment_projected(cube[2], cube[3], base, canvas) draw_segment_projected(cube[2], cube[6], base, canvas) draw_segment_projected(cube[3], cube[7], base, canvas) draw_segment_projected(cube[4], cube[5], base, canvas) draw_segment_projected(cube[4], cube[6], base, canvas) draw_segment_projected(cube[5], cube[7], base, canvas) draw_segment_projected(cube[6], cube[7], base, canvas) u1 = np.array([0, 0, 1]) u2 = np.array([1, 0, 0]) base = Base(u1, u2) cube = [np.array([0, 0, 0]), np.array([0, 0, 1]), np.array([0, 1, 0]), np.array([0, 1, 1]), np.array([1, 0, 0]), np.array([1, 0, 1]), np.array([1, 1, 0]), np.array([1, 1, 1])] cube = [200 * (v + np.array([-0.5, -0.5, -0.5])) for v in cube] base.rotate_z(0.2) mouse_event_start = None def button_start(event): global mouse_event_start mouse_event_start = event def button_click(event): global mouse_event_start base.rotate_x(-(event.x - mouse_event_start.x) * 0.01) base.rotate_z((event.y - mouse_event_start.y) * 0.01) mouse_event_start = event top = tkinter.Tk() C = tkinter.Canvas(top, bg="white", height=600, width=800) C.bind("<B1-Motion>", button_click) C.bind("<Button-1>", button_start) def main_loop(): C.delete("all") draw_cube(cube, base, C) C.pack() top.after(17, main_loop) top.after(0, main_loop) top.mainloop() <file_sep>/camera_matrix/solids/Cuboid.py import numpy as np class Cuboid: def __init__(self, position, depth, height, width): self.position = position self.coords = [np.array([0, 0, 0]), np.array([0, 0, depth]), np.array([0, height, 0]), np.array([0, height, depth]), np.array([width, 0, 0]), np.array([width, 0, depth]), np.array([width, height, 0]), np.array([width, height, depth])] self.coords = [v + position for v in self.coords] self.edges = [(0, 1), (0, 2), (0, 4), (1, 3), (1, 5), (2, 3), (2, 6), (3, 7), (4, 5), (4, 6), (5, 7), (6, 7)] <file_sep>/camera_matrix/SolidDraw.py class SolidDraw: def __init__(self, drawer): self.drawer = drawer def draw(self, solid): for edge in solid.edges: self.draw_segment_projected(solid.coords[edge[0]], solid.coords[edge[1]]) def draw_segment_projected(self, A, B): offset = self.drawer.offset a = self.drawer.projection.localise(A) b = self.drawer.projection.localise(B) self.drawer.canvas.create_line(a[0] + offset[0], a[1] + offset[1], b[0] + offset[0], b[1] + offset[1]) <file_sep>/OrtogonalProjection.py import numpy as np class Base: def __init__(self, v, w, u): self.base = np.column_stack([v, w, u]) self.normalize() pass def normalize(self): # self.base = la.orth(self.base) # Gram - Schmitd ortonormalization u1 = self.base[:, 0] u2 = self.base[:, 1] u3 = self.base[:, 2] u2 = u2 - u2.dot(u1) / u1.dot(u1) * u1 u3 = u3 - u3.dot(u1) / u1.dot(u1) * u1 - u3.dot(u2) / u2.dot(u2) * u2 u1 = u1 / np.linalg.norm(u1) u2 = u2 / np.linalg.norm(u2) u3 = u3 / np.linalg.norm(u3) self.base = np.column_stack([u1, u2, u3]) pass def rotate_z(self, a): rotation_matrix = np.matrix([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]]) self.base = rotation_matrix.dot(self.base) self.base = np.squeeze(np.asarray(self.base)) pass def rotate_x(self, a): rotation_matrix = np.matrix([[1, 0, 0], [0, np.cos(a), -np.sin(a)], [0, np.sin(a), np.cos(a)]]) self.base = rotation_matrix.dot(self.base) self.base = np.squeeze(np.asarray(self.base)) def rotate_y(self, a): rotation_matrix = np.matrix([[np.cos(a), 0, np.sin(a)], [0, 1, 0], [-np.sin(a), 0, np.cos(a)]]) self.base = rotation_matrix.dot(self.base) self.base = np.squeeze(np.asarray(self.base)) def localise(self, v): # change later to matrix multiplication return v.dot(self.base[:, 0]), v.dot(self.base[:, 1]), v.dot(self.base[:, 2]) def __str__(self): return self.base.__str__() <file_sep>/camera_matrix/CameraGui.py class Gui: def __init__(self, camera, drawer): self.camera = camera self.drawer = drawer self.drawer.add_to_loop(self.draw_gui) def draw_gui(self): self.draw_text(str(self.camera.rotation), 200, 30) self.draw_text(str(self.camera.transposition), 200, 100) self.draw_text(str(self.camera.f), 200, 130) def draw_text(self, text, x, y): self.drawer.canvas.create_text(x, y, fill="darkblue", font="Times 12 italic bold", text=text)
fcdb4dcfa01d46ee5e970bc47312b0fd67f5bef3
[ "Python" ]
12
Python
VashingMachine/rotating-cube
66189848c27cea83fdbed6e7d7400f770dee9e2e
b4a660761062c46c57348262c89ee73391dbcb01
refs/heads/main
<repo_name>tord-s/currency_predictor<file_sep>/app.py import requests import tensorflow from flask import Flask import json from flask_cors import CORS # Import the libraries import math import numpy as np from sklearn.preprocessing import MinMaxScaler from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, LSTM, Dropout app = Flask(__name__) CORS(app) @app.before_first_request def _run_on_start(): print("hi there") @app.route("/", methods=["GET"]) def get_100_preds(): return get_100_preds() def get_100_preds(): response = requests.get( "https://data.norges-bank.no/api/data/EXR/B.USD", params={"format": "sdmx-json", "lastNObservations": "50", "locale": "no"}, ) json_response = response.json() observations = json_response["data"]["dataSets"][0]["series"]["0:0:0:0"][ "observations" ] print("Raw data collected") raw_data = [] for o in observations.items(): raw_data.append(o[1]) # import matplotlib.pyplot as plt # plt.style.use("fivethirtyeight") use_current_model = True model = None training_dataset_length = math.ceil(len(raw_data) * 0.75) # print(training_dataset_length) # Scale the all of the data to be values between 0 and 1 scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(raw_data) train_data = scaled_data[0:training_dataset_length, :] # Splitting the data x_train = [] y_train = [] for i in range(10, len(train_data)): x_train.append(train_data[i - 10 : i, 0]) y_train.append(train_data[i, 0]) # Convert to numpy arrays x_train, y_train = np.array(x_train), np.array(y_train) # Reshape the data into 3-D array x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1)) print("Data is ready") if use_current_model: from tensorflow.keras.models import model_from_json json_file = open("model.json", "r") loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) model.load_weights("model.h5") # tensorflow.keras.backend.clear_session() # model = tensorflow.keras.models.load_model("models", compile=False) else: # Initialising the RNN model = Sequential() model.add( LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)) ) model.add(Dropout(0.2)) # Adding a second LSTM layer and Dropout layer model.add(LSTM(units=50, return_sequences=True)) model.add(Dropout(0.2)) # Adding a third LSTM layer and Dropout layer model.add(LSTM(units=50, return_sequences=True)) model.add(Dropout(0.2)) # Adding a fourth LSTM layer and and Dropout layer model.add(LSTM(units=50)) model.add(Dropout(0.2)) # Adding the output layer # For Full connection layer we use dense # As the output is 1D so we use unit=1 model.add(Dense(units=1)) # compile and fit the model on 30 epochs model.compile(optimizer="adam", loss="mean_squared_error") model.fit(x_train, y_train, epochs=30, batch_size=50) # model.save("models") model.save_weights("model.h5") model_json = model.to_json() with open("model.json", "w") as json_file: json_file.write(model_json) json_file.close() print("Model is ready") # Test data set test_data = scaled_data # splitting the x_test and y_test data sets x_test = [] # y_test = raw_data for i in range(10, len(test_data)): x_test.append(test_data[i - 10 : i, 0]) # Convert x_test to a numpy array x_test = np.array(x_test) # Reshape the data into 3-D array x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1)) # check predicted values print("X_test: ------------------------------------") print(x_test) predictions = model.predict(x_test) # Undo scaling predictions = scaler.inverse_transform(predictions) print("Predictions done") # plt.plot(predictions) # plt.show() # convert nympy array to JSON json_str = json.dumps(predictions.tolist()) return json_str
f10ec0928f800d2f755a47d60eca54d1308703b4
[ "Python" ]
1
Python
tord-s/currency_predictor
72abddd8766986f3ffc8b0c12449fb76208bf306
d0a3a6fa36890da9dd2e2115cece3166488de3fa
refs/heads/master
<file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Adapter; use League\Uri\Schemes\Data; use Psr\Http\Message\UriInterface; class DataUriAdapter extends Data implements UriInterface { } <file_sep><?php declare(strict_types=1); namespace Tests\UriParser; use K911\UriBuilder\Adapter\UriParserAdapter; use K911\UriBuilder\Contracts\UriParserInterface; use PHPUnit\Framework\TestCase; class UriParserTest extends TestCase { private const EMPTY_COMPONENTS = [ 'scheme' => null, 'user' => null, 'pass' => null, 'host' => null, 'port' => null, 'path' => '', 'query' => null, 'fragment' => null, ]; /** * @var UriParserInterface */ private $parser; protected function setUp() { $this->parser = new UriParserAdapter(); } public function validUriProvider(): array { return [ 'http' => [ [ 'scheme' => 'http', 'host' => 'example.com', 'port' => 80, 'path' => '/foo/bar', 'query' => 'foo=bar', 'fragment' => 'content', ], 'http://example.com:80/foo/bar?foo=bar#content', ], 'https' => [ [ 'scheme' => 'https', 'host' => 'example.com', 'path' => '/foo/bar', 'query' => 'foo=bar', ], 'https://example.com/foo/bar?foo=bar', ], 'ftp' => [ [ 'scheme' => 'ftp', 'host' => 'example.com', 'port' => 21, 'user' => 'user', 'pass' => '<PASSWORD>', ], 'ftp://user:password@example.com:21', ], 'ftps' => [ [ 'scheme' => 'sftp', 'host' => 'example.com', 'user' => 'user', 'port' => 27015, 'path' => '/foo/bar', ], 'sftp://user@example.com:27015/foo/bar', ], 'ws' => [ [ 'scheme' => 'ws', 'host' => 'example.com', 'port' => 80, 'path' => '/foo/bar', 'query' => 'foo=bar', ], 'ws://example.com:80/foo/bar?foo=bar', ], 'wss' => [ [ 'scheme' => 'wss', 'host' => 'example.com', 'port' => 443, 'path' => '/foo/bar', 'query' => 'foo=bar', ], 'wss://example.com:443/foo/bar?foo=bar', ], 'file' => [ [ 'scheme' => 'file', 'host' => 'cdn.example.com', 'path' => '/foo/bar', ], 'file://cdn.example.com/foo/bar', ], 'file relative w/o host' => [ [ 'scheme' => 'file', 'host' => '', 'path' => '/../foo/bar', ], 'file:///../foo/bar', ], 'file relative w/ host' => [ [ 'scheme' => 'file', 'host' => 'example.com', 'path' => '/../foo/bar', ], 'file://example.com/../foo/bar', ], 'data' => [ [ 'scheme' => 'data', 'path' => 'text/plain;charset=utf-8,FooBarWithSpecialChars%20%20%C4%85%C4%87%C4%99%C5%82', ], 'data:text/plain;charset=utf-8,FooBarWithSpecialChars%20%20%C4%85%C4%87%C4%99%C5%82', ], ]; } /** * @dataProvider validUriProvider * * @param array $expected * @param string $uri */ public function testUriToComponents(array $expected, string $uri) { $expectedComponents = array_merge(self::EMPTY_COMPONENTS, $expected); $parsedComponents = $this->parser->parse($uri); $this->assertEquals(true, ksort($expectedComponents)); $this->assertEquals(true, ksort($parsedComponents)); $this->assertSame($expectedComponents, $parsedComponents); } } <file_sep><?php declare(strict_types=1); namespace Tests\UriBuilder; use K911\UriBuilder\Adapter\UriParserAdapter; use K911\UriBuilder\Facade\UriBuilder as UriBuilderFacade; use K911\UriBuilder\UriBuilder; use K911\UriBuilder\UriFactory; use PHPUnit\Framework\TestCase; use Psr\Http\Message\UriInterface; class UriBuilderTest extends TestCase { /** * Not used host in valid uri providers */ private const UNUSED_HOST = 'unused.host.com'; /** * @var \K911\UriBuilder\UriBuilder */ private $builder; /** * @var \K911\UriBuilder\Contracts\UriFactoryInterface */ private $factory; /** * @var \K911\UriBuilder\Contracts\UriParserInterface */ private $parser; protected function setUp(): void { $this->parser = new UriParserAdapter(); $this->factory = new UriFactory($this->parser); $this->builder = new UriBuilder($this->factory); } public function validUriProvider(): array { return array_merge([ 'file' => [ 'file://localhost/../foo/bar', 'file:///../foo/bar', ], 'file relative' => [ 'file://localhost/./../foo/bar', 'file:///./../foo/bar', ], 'data' => [ 'data:text/plain;charset=utf-8,FooBarWithSpecialChars%20%20%C4%85%C4%87%C4%99%C5%82', 'data:text/plain;charset=utf-8,FooBarWithSpecialChars%20%20%C4%85%C4%87%C4%99%C5%82', ], ], $this->validUriWithHostProvider()); } public function validUriWithHostProvider(): array { return [ 'http' => [ 'http://example.com/foo/bar?foo=bar#content', 'http://example.com:80/foo/bar?foo=bar#content', ], 'https' => [ 'https://example.com/foo/bar?foo=bar', 'https://example.com:443/foo/bar?foo=bar', ], 'ftp' => [ 'ftp://user:<EMAIL>', 'ftp://user:password@example.com:21', ], 'ftps' => [ 'sftp://user@<EMAIL>/foo/bar', 'sftp://user@example.com:22/foo/bar', ], 'ws' => [ 'ws://example.com/foo/bar?foo=bar', 'Ws://eXamPLE.cOm:80/foo/bar?foo=bar', ], 'wss' => [ 'wss://example.com/foo/bar?foo=bar', 'WsS://eXamPLE.cOm:443/foo/bar?foo=bar', ], 'file' => [ 'file://cdn.example.com/foo/bar', 'file://cdn.eXamPLE.cOm/foo/bar', ], ]; } /** * @dataProvider validUriProvider * * @param string $expected * @param string $uri */ public function testSetUpFrom(string $expected, string $uri) { $uriObject = $this->builder->from($uri)->getUri(); $this->assertInstanceOf(UriInterface::class, $uriObject); $this->assertSame($expected, (string) $uriObject); } /** * @dataProvider validUriWithHostProvider * * @param string $expected * @param string $uri */ public function testSetUpFromComponents(string $expected, string $uri) { // TODO: Use Parser() instead $components = parse_url($uri); $this->assertNotEquals(false, $components); $uriObject = $this->builder->fromComponents($components)->getUri(); $this->assertInstanceOf(UriInterface::class, $uriObject); $this->assertSame($expected, (string) $uriObject); } /** * @dataProvider validUriWithHostProvider * * @param string $expected * @param string $uri */ public function testImmutability(string $expected, string $uri) { $uriObject = $this->builder->from($uri)->getUri(); $newUri = $this->builder->fromUri($uriObject) ->setHost(self::UNUSED_HOST) ->getUri(); $this->assertInstanceOf(UriInterface::class, $newUri); $this->assertNotSame($uri, $newUri); $this->assertNotEquals((string) $uriObject, (string) $newUri); $this->assertNotEquals($expected, (string) $newUri); $expectedUri = $this->builder->from($expected) ->setHost(self::UNUSED_HOST) ->getUri(); $this->assertSame((string) $expectedUri, (string) $newUri); } /** * @expectedException \K911\UriBuilder\Exception\UriBuilderException * @expectedExceptionMessage UriBuilder is not initialized with any Uri instance. */ public function testGetUriOnEmptyBuilder() { $this->builder->getUri(); } /** * @dataProvider validUriWithHostProvider * * @param string $expected * @param string $uri */ public function testFacade(string $expected, string $uri) { $newUri = UriBuilderFacade::from($uri)->getUri(); $this->assertSame($expected, (string) $newUri); // TODO: Use Parser() instead $components = parse_url($uri); $newUri = UriBuilderFacade::fromComponents($components)->getUri(); $this->assertSame($expected, (string) $newUri); $newUri = UriBuilderFacade::fromUri($newUri)->getUri(); $this->assertSame($expected, (string) $newUri); } /** * @expectedException \K911\UriBuilder\Exception\UriBuilderException * @expectedExceptionMessage UriBuilder Facade object cannot be constructed. */ public function testFacadeConstructFail() { $reflection = new \ReflectionClass(UriBuilderFacade::class); $constructor = $reflection->getConstructor(); $constructor->setAccessible(true); $object = $reflection->newInstanceWithoutConstructor(); $constructor->invoke($object); } } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Extensions; use K911\UriBuilder\Contracts\UriFactoryInterface; use K911\UriBuilder\Contracts\UriParserInterface; use K911\UriBuilder\Exception\NotSupportedSchemeException; use Psr\Http\Message\UriInterface; abstract class AbstractUriFactory implements UriFactoryInterface { /** * Supported schemes and corresponding Uri instance classes * @var array Key => string, Value => UriInterface::class */ protected const SUPPORTED_SCHEMES = []; /** * @var \K911\UriBuilder\Contracts\UriParserInterface */ protected $parser; /** * AbstractUriFactory constructor. * * @param \K911\UriBuilder\Contracts\UriParserInterface $parser */ public function __construct(UriParserInterface $parser) { $this->parser = $parser; } /** * @inheritdoc */ public function create(string $uri): UriInterface { return $this->createFromComponents($this->parser->parse($uri)); } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\NotSupportedSchemeException * @throws \InvalidArgumentException */ public function transform(UriInterface $uri, string $scheme): UriInterface { $schemeNormalized = $this->normalizeString($scheme); if ($this->isSchemeCompatible($scheme, $uri)) { return $uri->withScheme($schemeNormalized); } $components = $this->parser->parse((string) $uri); $components['scheme'] = $schemeNormalized; return $this->createFromComponents($components); } /** * Gets fully qualified class name of UriInstance that support scheme provided * * @param string $scheme An supported by UriFactory URI scheme * * @return string UriInterface::class * * @throws \K911\UriBuilder\Exception\NotSupportedSchemeException */ public function getSchemeClass(string $scheme): string { if (!$this->isSchemeSupported($scheme)) { throw new NotSupportedSchemeException($scheme); } return static::SUPPORTED_SCHEMES[$this->normalizeString($scheme)]; } /** * @inheritdoc */ public function isSchemeSupported(string $scheme): bool { return array_key_exists($this->normalizeString($scheme), static::SUPPORTED_SCHEMES); } /** * @inheritdoc */ public function getSupportedSchemes(): array { return array_keys(static::SUPPORTED_SCHEMES); } /** * Determines whether provided Uri instance is compatible with provided URI scheme * Remarks: When URI scheme is compatible it means that an Uri instance does not need * to be transformed to support this scheme * * @param string $scheme An URI scheme * @param UriInterface $uri An Uri instance * * @return bool * * @throws \K911\UriBuilder\Exception\NotSupportedSchemeException */ protected function isSchemeCompatible(string $scheme, UriInterface $uri): bool { return $this->getSchemeClass($scheme) === $this->getSchemeClass($uri->getScheme()); } /** * Helper: Lowercase and trim string * * @param string $input * * @return string */ protected function normalizeString(string $input): string { return mb_strtolower(trim($input)); } } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Contracts; /** * Interface UriParser describes behaviour of parsing and validating an URI string */ interface UriParserInterface { /** * Parses an URI string and creates array of URI components. * * @param string $uri An URI string to be parsed * * @return string[] Array of URI components which MUST contain all possible components: * - `scheme` => string|null URI scheme (e.g: http) * - `host` => string|null Full URI host (e.g: www.foo.bar) * - `user` => string|null URI UserInfo: Username (before ':' after scheme) * - `pass` => string|null URI UserInfo: Password (after ':' before '@' and host) * - `path` => string URI path (after host and '/' or directly after scheme) * - `port` => int|null URI port (after ':' after host) * - `query` => string|null URI query (after '?' after path) * - `fragment` => string|null URI fragment (after '#') * */ public function parse(string $uri): array; } <file_sep>FROM php:7.1-cli RUN echo "deb http://ppa.launchpad.net/ondrej/php/ubuntu xenial main" > /etc/apt/sources.list.d/ondrej-php.list \ && echo "deb http://ppa.launchpad.net/ondrej/php-qa/ubuntu xenial main" > /etc/apt/sources.list.d/ondrej-php-qa.list \ && apt-key adv --keyserver keyserver.ubuntu.com --recv-keys <KEY> \ && apt-get -q update \ && apt-get -y --no-install-recommends install \ git openssh-client ca-certificates tar gzip \ libicu-dev unzip php7.1-mbstring RUN pecl -q install xdebug RUN docker-php-ext-enable xdebug RUN docker-php-ext-configure intl RUN docker-php-ext-install intl RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && \ php -r "if (hash_file('SHA384', 'composer-setup.php') === '669656bab3166a7aff8a7506b8cb2d1c292f042046c5a994c43155c0be6190fa0355160742ab2e1c88d40d5be660b410') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;" && \ php composer-setup.php && \ php -r "unlink('composer-setup.php');" && \ mv composer.phar /usr/local/bin/composer <file_sep><?php declare(strict_types=1); namespace Tests\Examples; use PHPUnit\Framework\TestCase; class ExamplesTest extends TestCase { protected const EXAMPLES_PATH = __DIR__ . '/../../examples'; /** * Examples and theirs expected output * @return array */ public function validExampleProvider(): array { return [ 'UriBuilder facade usage' => [ 'facade', 'https://user:password@api.foo.bar/v1?api_token=<PASSWORD>', ], 'Readme' => [ 'readme', 'https://user:password@api.foo.bar/v1?api_token=Qwerty<PASSWORD>', ], ]; } /** * @dataProvider validExampleProvider * * @param string $example */ public function testExamplesExists(string $example) { $this->assertFileExists(sprintf('%s/%s.php', self::EXAMPLES_PATH, $example)); } /** * @depends testExamplesExists * @dataProvider validExampleProvider * * @param string $example * @param string $expected */ public function testExamples(string $example, string $expected) { $this->assertEquals(true, ob_start()); require sprintf('%s/%s.php', self::EXAMPLES_PATH, $example); $output = trim(ob_get_clean()); $this->assertEquals($expected, $output); } } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Adapter; use K911\UriBuilder\Contracts\UriParserInterface; use League\Uri\Parser; class UriParserAdapter extends Parser implements UriParserInterface { /** * {@inheritdoc} * * @throws \League\Uri\Exception */ public function parse(string $uri): array { return $this->__invoke($uri); } } <file_sep># UriBuilder [![CircleCI](https://circleci.com/gh/k911/uri-builder.svg?style=svg)](https://circleci.com/gh/k911/uri-builder) Simplifies manipulation of URI value objects compatible with PSR-7. Under the hood, it utilizes `League\Uri` powerful [library](http://uri.thephpleague.com/). [![Code Climate](https://codeclimate.com/github/k911/uri-builder/badges/gpa.svg)](https://codeclimate.com/github/k911/uri-builder) [![Test Coverage](https://codeclimate.com/github/k911/uri-builder/badges/coverage.svg)](https://codeclimate.com/github/k911/uri-builder/coverage) [![Issue Count](https://codeclimate.com/github/k911/uri-builder/badges/issue_count.svg)](https://codeclimate.com/github/k911/uri-builder) - [Installation](#installation) - [Supported Schemes](#supported-schemes) - [Usage](#Usage) ## Installation ``` $ composer require k911/uri-builder ``` ## Supported Schemes Currently supported, tested, URI schemes that UriBuilder can manage and parse from bare URI string or URI components. - http/https - ftp/sftp - ws/wss - file - data ## Usage **Full public interface is available [here](src/UriBuilderInterface.php).** Usage example: ```php // Simple URI string $uri = 'wss://foo.bar:9999'; // Create UriBuilder and its dependencies // ..you should either use DI container to manage it // ..or use UriBuilder facade $parser = new K911\UriBuilder\Adapter\UriParserAdapter(); $factory = new K911\UriBuilder\UriFactory($parser); $builder = new K911\UriBuilder\UriBuilder($factory); // Intiliaze UriBuilder with URI string $builder->from($uri); // or $builder->fromUri(UriInterface $uri); // or $builder->fromComponents(array $components); // UriBuilder is mutable, and allows method chaining $builder // under the hood, it automatically transforms Uri object ->setScheme('https') // simple setters ->setHost('api.foo.bar') ->setFragment('foobar') // setting DEFAULT port for https scheme ->setPort(443) // domain-related paths must always start with forward slash '/' ->setPath('/v1') // query string is generated safely from pairs according to RFC3986 ->setQuery([ 'api_token' => '<PASSWORD>', ]) // set user info (password can be omitted) ->setUserInfo('user', 'password'); // Print result echo (string) $builder->getUri(); // https://user:password@api.foo.bar/v1?api_token=<PASSWORD>%20%40%23%24TYu#foobar ``` <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Contracts; use Psr\Http\Message\UriInterface; interface UriBuilderInterface { /** * Create a new Uri instance from an URI string in UriBuilderInterface * * @param string $uri URI string * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public function from(string $uri): self; /** * Clones an Uri instance and assigns to an UriBuilderInterface * * @param UriInterface $uri * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public function fromUri(UriInterface $uri): self; /** * Create a new Uri instance from a hash of parse_url parts in UriBuilderInterface * * @param array $components a hash representation of the URI similar * to PHP parse_url function result * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public function fromComponents(array $components): self; /** * Set the scheme component of the URI. * * @param string $scheme The URI scheme * * @return \K911\UriBuilder\Contracts\UriBuilderInterface * * @see https://tools.ietf.org/html/rfc3986#section-3.1 */ public function setScheme(string $scheme): self; /** * Sets the specified user information for Uri instance. * * Password is optional, but the user information MUST include the * user; an empty string for the user is equivalent to removing user * information. * * @param string $user The user name to use for authority. * @param null|string $password The password associated with $user. * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public function setUserInfo(string $user, string $password = null): self; /** * Sets the specified host to an Uri instance. * * An empty host value is equivalent to removing the host. * * @param string $host The hostname to use with the new instance. * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public function setHost(string $host): self; /** * Sets the specified port to an Uri instance. * * Implementations MUST raise an exception for ports outside the * established TCP and UDP port ranges. * * A null value provided for the port is equivalent to removing the port * information. * * @param int|null $port The port to use with the new instance; a null value * removes the port information. * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public function setPort(int $port = null): self; /** * Sets the specified path to an Uri instance. * * The path can either be empty or absolute (starting with a slash) or * rootless (not starting with a slash). Implementations MUST support all * three syntaxes. * * If the path is intended to be domain-relative rather than path relative then * it must begin with a slash ("/"). Paths not starting with a slash ("/") * are assumed to be relative to some base path known to the application or * consumer. * * Users can provide both encoded and decoded path characters. * Implementations ensure the correct encoding as outlined in getPath(). * * @param string $path The path to use with the new instance. * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public function setPath(string $path): self; /** * Sets the specified query pairs to an Uri instance. * * The query pairs are number of pairs of "key=value" represented in URI * as string between '?' and '#' characters, separated by '&' character * * Users can provide both encoded and decoded query pair characters. * * The value MUST be percent-encoded, but MUST NOT double-encode * any characters. To determine what characters to encode, please refer to * RFC 3986, Sections 2 and 3.4. * * An empty array is equivalent to removing the query pairs. * * @param string[] $pairs Pairs of "key=value" represented in URI as query * * @return \K911\UriBuilder\Contracts\UriBuilderInterface * * @see https://tools.ietf.org/html/rfc3986#section-2 * @see https://tools.ietf.org/html/rfc3986#section-3.4 */ public function setQuery(array $pairs): self; /** * Set the specified URI fragment to an Uri instance. * * Users can provide both encoded and decoded fragment characters. * Implementations ensure the correct encoding as outlined in UriInterface::getFragment(). * * An empty fragment value is equivalent to removing the fragment. * * @param string $fragment The fragment to use with the new instance. * * @return \K911\UriBuilder\Contracts\UriBuilderInterface * * @see https://tools.ietf.org/html/rfc3986#section-2 * @see https://tools.ietf.org/html/rfc3986#section-3.5 */ public function setFragment(string $fragment): self; /** * Return clone of internal value object representing an URI. * * @return \Psr\Http\Message\UriInterface * * @see http://www.php-fig.org/psr/psr-7/ (UriInterface specification) * @see http://tools.ietf.org/html/rfc3986 (the URI specification) */ public function getUri(): UriInterface; } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Exception; use Throwable; /** * Exception thrown if user provides not supported Uri scheme anywhere in library */ class NotSupportedSchemeException extends InvalidArgumentException { /** * @param string $scheme * @param \Throwable $previous [optional] The previous throwable used for the exception chaining. */ public function __construct(string $scheme, Throwable $previous = null) { parent::__construct(sprintf('Scheme `%s` has not yet been supported by the library.', $scheme), 501, $previous); } } <file_sep><?php declare(strict_types=1); use K911\UriBuilder\Facade\UriBuilder; require __DIR__ . '/../vendor/autoload.php'; // Simple URI string $uri = 'wss://foo.bar:9999'; // Intiliaze UriBuilder with URI string using facade // Facade takes care of managing UriBuilder dependencies $builder = UriBuilder::from($uri); // or UriBuilder::fromUri(UriInterface $uri); // or UriBuilder::fromComponents(array $components); // UriBuilder is mutable, and allows method chaining $builder // under the hood, it automatically transforms Uri object ->setScheme('https') // simple setters ->setHost('api.foo.bar') ->setFragment('foobar') // setting DEFAULT port for https scheme ->setPort(443) // domain-related paths must always start with forward slash '/' ->setPath('/v1') // query string is generated safely from pairs according to RFC3986 ->setQuery([ 'api_token' => '<PASSWORD>', ]) // password can be null ->setUserInfo('user', 'password'); // Print result echo (string) $builder->getUri() . PHP_EOL; // https://user:password@api.foo.bar/v1?api_token=<PASSWORD>%21%20%40%23%24TYu#foobar <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Exception; use RuntimeException; class UriBuilderException extends RuntimeException implements UriBuilderExceptionInterface { } <file_sep><?php declare(strict_types=1); use K911\UriBuilder\UriBuilder; use K911\UriBuilder\UriFactory; use K911\UriBuilder\Adapter\UriParserAdapter; require __DIR__ . '/../vendor/autoload.php'; // Simple URI string $uri = 'wss://foo.bar:9999'; // Create UriBuilder and its dependencies // ..you should either use DI container to manage it // ..or use UriBuilder facade $parser = new UriParserAdapter(); $factory = new UriFactory($parser); $builder = new UriBuilder($factory); // Intiliaze UriBuilder with URI string $builder->from($uri); // or $builder->fromUri(UriInterface $uri); // or $builder->fromComponents(array $components); // UriBuilder is mutable, and allows method chaining $builder // under the hood, it automatically transforms Uri object ->setScheme('https') // simple setters ->setHost('api.foo.bar') ->setFragment('foobar') // setting DEFAULT port for https scheme ->setPort(443) // domain-related paths must always start with forward slash '/' ->setPath('/v1') // query string is generated safely from pairs according to RFC3986 ->setQuery([ 'api_token' => '<PASSWORD>', ]) // set user info (password can be omitted) ->setUserInfo('user', 'password'); // Print result echo (string) $builder->getUri() . PHP_EOL; // https://user:password@api.foo.bar/v1?api_token=<PASSWORD>%21%20%40%23%24TYu#foobar <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Exception; /** * Interface used for all types of exceptions thrown by the UriBuilder library. */ interface UriBuilderExceptionInterface { } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder; use K911\UriBuilder\Contracts\UriBuilderInterface; use K911\UriBuilder\Contracts\UriFactoryInterface; use K911\UriBuilder\Exception\UriBuilderException; use Psr\Http\Message\UriInterface; class UriBuilder implements UriBuilderInterface { /** * Message of UriBuilderException thrown when trying to use UriBuilder without prior initialization. */ protected const MESSAGE_NOT_INITIALIZED = 'UriBuilder is not initialized with any Uri instance. Please initialize it by using `from` methods.'; /** * Separator character of query pairs in URI string */ protected const URI_QUERY_SEPARATOR = '&'; /** * RFC used when building query string * @link http://php.net/manual/pl/function.http-build-query.php#refsect1-function.http-build-query-parameters */ protected const PHP_QUERY_RFC = PHP_QUERY_RFC3986; /** * @var \Psr\Http\Message\UriInterface The internal value object representing an URI */ protected $uri; /** * @var \K911\UriBuilder\Contracts\UriFactoryInterface */ protected $factory; /** * UriBuilder constructor. * * @param UriFactoryInterface $factory */ public function __construct(UriFactoryInterface $factory) { $this->factory = $factory; } /** * @inheritdoc */ public function from(string $uri): UriBuilderInterface { $this->uri = $this->factory->create($uri); return $this; } /** * @inheritdoc */ public function fromUri(UriInterface $uri): UriBuilderInterface { $this->uri = clone $uri; return $this; } /** * @inheritdoc */ public function fromComponents(array $components): UriBuilderInterface { $this->uri = $this->factory->createFromComponents($components); return $this; } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\UriBuilderException */ public function setScheme(string $scheme): UriBuilderInterface { $this->validateState(); $this->uri = $this->factory->transform($this->uri, $scheme); return $this; } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\UriBuilderException */ public function setUserInfo(string $user, string $password = null): UriBuilderInterface { $this->validateState(); $this->uri = $this->uri->withUserInfo($user, $password); return $this; } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\UriBuilderException * @throws \InvalidArgumentException */ public function setHost(string $host): UriBuilderInterface { $this->validateState(); $this->uri = $this->uri->withHost($host); return $this; } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\UriBuilderException * @throws \InvalidArgumentException */ public function setPort(int $port = null): UriBuilderInterface { $this->validateState(); $this->uri = $this->uri->withPort($port); return $this; } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\UriBuilderException * @throws \InvalidArgumentException */ public function setPath(string $path): UriBuilderInterface { $this->validateState(); $this->uri = $this->uri->withPath($path); return $this; } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\UriBuilderException * @throws \InvalidArgumentException */ public function setQuery(array $pairs): UriBuilderInterface { $this->validateState(); $query = http_build_query($pairs, '', static::URI_QUERY_SEPARATOR, static::PHP_QUERY_RFC); $this->uri = $this->uri->withQuery($query); return $this; } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\UriBuilderException */ public function setFragment(string $fragment): UriBuilderInterface { $this->validateState(); $this->uri = $this->uri->withFragment($fragment); return $this; } /** * {@inheritdoc} * * @throws \K911\UriBuilder\Exception\UriBuilderException */ public function getUri(): UriInterface { $this->validateState(); return clone $this->uri; } /** * Validates state of Uri Builder. Throws exception if builder is not ready to use. * * @throws UriBuilderException */ protected function validateState(): void { if (null === $this->uri) { throw new UriBuilderException(static::MESSAGE_NOT_INITIALIZED, 500); } } } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Exception; use InvalidArgumentException as BaseException; /** * Exception thrown if an argument does not match with the expected value * used in the UriBuilder library. */ class InvalidArgumentException extends BaseException implements UriBuilderExceptionInterface { } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder; use K911\UriBuilder\Adapter\DataUriAdapter; use K911\UriBuilder\Adapter\FileUriAdapter; use K911\UriBuilder\Adapter\FtpUriAdapter; use K911\UriBuilder\Adapter\WsUriAdapter; use K911\UriBuilder\Exception\InvalidArgumentException; use K911\UriBuilder\Exception\NotSupportedSchemeException; use K911\UriBuilder\Extensions\AbstractUriFactory; use League\Uri\Schemes\AbstractUri; use League\Uri\Schemes\Http; use Psr\Http\Message\UriInterface; /** * The UriFactory utilizes powerful library League\Uri to create new Uri instances */ class UriFactory extends AbstractUriFactory { /** * Supported schemes and corresponding Uri instance classes * Array<string, string UriInterface::class> */ protected const SUPPORTED_SCHEMES = [ 'data' => DataUriAdapter::class, 'file' => FileUriAdapter::class, 'ftp' => FtpUriAdapter::class, 'sftp' => FtpUriAdapter::class, 'ftps' => FtpUriAdapter::class, 'https' => Http::class, 'http' => Http::class, 'ws' => WsUriAdapter::class, 'wss' => WsUriAdapter::class, ]; /** * Create a new Uri instance from a hash of parse_url parts * Remarks: Scheme part is required. * * @param array $components a hash representation of the URI similar * to PHP parse_url function result * * @return UriInterface|AbstractUri Newly created URI value object * * @throws InvalidArgumentException * @throws NotSupportedSchemeException * * @see http://php.net/manual/en/function.parse-url.php */ public function createFromComponents(array $components): UriInterface { if (empty($components['scheme'])) { throw new InvalidArgumentException('Part URI scheme from components array cannot be empty.'); } /** * @var static|AbstractUri $abstractUri Class name of instance of AbstractUri; */ $abstractUri = $this->getSchemeClass($components['scheme']); return $abstractUri::createFromComponents($components); } } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Adapter; use League\Uri\Schemes\File; use Psr\Http\Message\UriInterface; class FileUriAdapter extends File implements UriInterface { } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Facade; use K911\UriBuilder\Adapter\UriParserAdapter; use K911\UriBuilder\Contracts\UriBuilderInterface; use K911\UriBuilder\Contracts\UriFactoryInterface; use K911\UriBuilder\Exception\UriBuilderException; use K911\UriBuilder\UriBuilder as UriBuilderInstance; use K911\UriBuilder\UriFactory; use Psr\Http\Message\UriInterface; final class UriBuilder { /** * Single UriFactory instance * * @var \K911\UriBuilder\Contracts\UriFactoryInterface */ private static $factory; /** * Remarks: This is static class. * * @throws \K911\UriBuilder\Exception\UriBuilderException */ private function __construct() { throw new UriBuilderException('UriBuilder Facade object cannot be constructed.'); } /** * Create a new UriBuilder instance * Initializing it from an URI string * * @param string $uri URI string * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public static function from(string $uri): UriBuilderInterface { $factory = self::getFactory(); return (new UriBuilderInstance($factory))->from($uri); } /** * Create a new UriBuilder instance * Initializing it from an actual Uri instance * * @param UriInterface $uri * * @return UriBuilderInterface */ public static function fromUri(UriInterface $uri): UriBuilderInterface { $factory = self::getFactory(); return (new UriBuilderInstance($factory))->fromUri($uri); } /** * Create a new UriBuilder instance * Initializing it from a hash of parse_url parts * * @param array $components a hash representation of the URI similar * to PHP parse_url function result * * @return \K911\UriBuilder\Contracts\UriBuilderInterface */ public static function fromComponents(array $components): UriBuilderInterface { $factory = self::getFactory(); return (new UriBuilderInstance($factory))->fromComponents($components); } /** * Gets factory instance (always the same) * * @return \K911\UriBuilder\Contracts\UriFactoryInterface */ private static function getFactory(): UriFactoryInterface { if (null === self::$factory) { self::$factory = new UriFactory(new UriParserAdapter()); } return self::$factory; } } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Adapter; use League\Uri\Schemes\Ws; use Psr\Http\Message\UriInterface; class WsUriAdapter extends Ws implements UriInterface { } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Adapter; use League\Uri\Schemes\Ftp; use Psr\Http\Message\UriInterface; class FtpUriAdapter extends Ftp implements UriInterface { /** * @inheritdoc */ protected static $supported_schemes = [ 'ftp' => 21, 'sftp' => 22, 'ftps' => 990, ]; } <file_sep><?php declare(strict_types=1); namespace Tests\UriFactory; use K911\UriBuilder\Adapter\DataUriAdapter; use K911\UriBuilder\Adapter\FileUriAdapter; use K911\UriBuilder\Adapter\FtpUriAdapter; use K911\UriBuilder\Adapter\WsUriAdapter; use K911\UriBuilder\Contracts\UriParserInterface; use K911\UriBuilder\UriFactory; use League\Uri\Schemes\Http; use PHPUnit\Framework\TestCase; use Psr\Http\Message\UriInterface; class UriFactoryTest extends TestCase { private const EMPTY_COMPONENTS = [ 'scheme' => null, 'user' => null, 'pass' => null, 'host' => null, 'port' => null, 'path' => '', 'query' => null, 'fragment' => null, ]; /** * @var \K911\UriBuilder\UriFactory */ private $factory; /** * @var \K911\UriBuilder\Contracts\UriParserInterface|\PHPUnit_Framework_MockObject_MockObject */ private $parser; protected function setUp() { $this->parser = $this->getMockBuilder(UriParserInterface::class) ->setMethods(['parse']) ->getMock(); $this->factory = new UriFactory($this->parser); } public function supportedSchemesProvider(): array { return [ 'data uris' => [ 'class' => DataUriAdapter::class, 'schemes' => ['data'], ], 'file uris' => [ 'class' => FileUriAdapter::class, 'schemes' => ['file'], ], 'file transfer protocol uris' => [ 'class' => FtpUriAdapter::class, 'schemes' => ['ftp', 'sftp', 'ftps'], ], 'hypertext transfer protocol uris' => [ 'class' => Http::class, 'schemes' => ['http', 'https'], ], 'web sockets uris' => [ 'class' => WsUriAdapter::class, 'schemes' => ['ws', 'wss'], ], ]; } public function testSupportedSchemesProviderRegression() { $providerSupportedSchemes = []; foreach ($this->supportedSchemesProvider() as ['schemes' => $schemes]) { /** @var array $schemes */ foreach ($schemes as $scheme) { $supportedSchemes[] = $scheme; } } $supportedSchemes = $this->factory->getSupportedSchemes(); $this->assertSame(sort($providerSupportedSchemes, SORT_STRING), sort($supportedSchemes, SORT_STRING)); } public function validUriProvider(): array { return [ 'data scheme adapter' => [ [ 'scheme' => 'data', 'path' => 'text/plain;charset=utf-8,FooBarWithSpecialChars%20%20%C4%85%C4%87%C4%99%C5%82', ], DataUriAdapter::class, 'data:text/plain;charset=utf-8,FooBarWithSpecialChars%20%20%C4%85%C4%87%C4%99%C5%82', ], 'file scheme adapter' => [ [ 'scheme' => 'file', 'host' => 'example.com', 'path' => '/../foo/bar', ], FileUriAdapter::class, 'file://example.com/../foo/bar', ], 'ftp schemes adapter' => [ [ 'scheme' => 'sftp', 'host' => 'example.com', 'user' => 'user', 'port' => 27015, 'path' => '/foo/bar', ], FtpUriAdapter::class, 'sftp://user@example.com:27015/foo/bar', ], 'ws schemes adapter' => [ [ 'scheme' => 'wss', 'host' => 'example.com', 'path' => '/foo/bar', 'query' => 'foo=bar', ], WsUriAdapter::class, 'wss://example.com/foo/bar?foo=bar', ], 'http schemes' => [ [ 'scheme' => 'http', 'host' => 'example.com', 'path' => '/foo/bar', 'query' => 'foo=bar', 'fragment' => 'content', ], Http::class, 'http://example.com/foo/bar?foo=bar#content', ], ]; } /** * @dataProvider validUriProvider * * @param array $components * @param string $class * @param string $uri */ public function testCreateUriFromString(array $components, string $class, string $uri) { $this->parser->expects($this->atLeast(2)) ->method('parse') ->with($this->equalTo($uri)) ->will($this->returnValue(array_merge(self::EMPTY_COMPONENTS, $components))); $uriObject = $this->factory->create($uri); $this->assertEquals($uri, (string) $uriObject); $this->assertInstanceOf(UriInterface::class, $uriObject); $this->assertInstanceOf($class, $uriObject); $this->assertNotSame($uriObject, $this->factory->create($uri)); } /** * @dataProvider validUriProvider * * @param array $components * @param string $class * @param string $uri */ public function testCreateUriFromComponents(array $components, string $class, string $uri) { $this->parser->expects($this->never()) ->method('parse'); $uriObject = $this->factory->createFromComponents($components); $this->assertEquals($uri, (string) $uriObject); $this->assertInstanceOf(UriInterface::class, $uriObject); $this->assertInstanceOf($class, $uriObject); $this->assertNotSame($uriObject, $this->factory->createFromComponents($components)); } /** * @dataProvider supportedSchemesProvider * * @param string $class * @param string[] $supportedSchemes */ public function testSupportedSchemes(string $class, array $supportedSchemes) { $this->parser->expects($this->never()) ->method('parse'); foreach ($supportedSchemes as $supportedScheme) { $this->assertContains($supportedScheme, $this->factory->getSupportedSchemes()); $this->assertTrue($this->factory->isSchemeSupported($supportedScheme)); $this->assertSame($class, $this->factory->getSchemeClass($supportedScheme)); } } /** * @dataProvider validUriProvider * * @param array $components */ public function testCreateWithoutScheme(array $components) { $this->parser->expects($this->never()) ->method('parse'); $this->expectException(\InvalidArgumentException::class); unset($components['scheme']); $this->factory->createFromComponents($components); } public function testSimpleTransform() { $httpUri = $this->factory->createFromComponents(parse_url('http://google.com')); $httpsUri = $this->factory->createFromComponents(parse_url('https://google.com')); $this->assertNotSame((string) $httpUri, (string) $httpsUri); $transformedUri = $this->factory->transform($httpUri, 'https'); $this->assertSame((string) $httpsUri, (string) $transformedUri); } /** * @expectedException \K911\UriBuilder\Exception\NotSupportedSchemeException */ public function testGetUnsupportedSchemeClass() { $this->factory->getSchemeClass('git'); } } <file_sep><?php declare(strict_types=1); namespace K911\UriBuilder\Contracts; use Psr\Http\Message\UriInterface; /** * Interface for UriFactory that creates and manages * URI value objects that implements UriInterface * * @see http://www.php-fig.org/psr/psr-7/ UriInterface specification */ interface UriFactoryInterface { /** * Create a new Uri instance from an URI string * Remarks: URI string must be valid and therefore consist of URI scheme. * * @param string $uri URI string * * @return \Psr\Http\Message\UriInterface Newly created URI value object */ public function create(string $uri): UriInterface; /** * Create a new Uri instance from a hash of parse_url parts * Remarks: Scheme part is required. * * @param array $components a hash representation of the URI similar * to PHP parse_url function result * * @return \Psr\Http\Message\UriInterface Newly created URI value object * * @see http://php.net/manual/en/function.parse-url.php */ public function createFromComponents(array $components): UriInterface; /** * Transforms an existing Uri instance into new Uri instance * with support for different URI scheme and optionally adjusted URI components. * Scheme must be supported by UriFactory. * * @param \Psr\Http\Message\UriInterface $uri An Uri instance to be transformed * @param string $scheme New URI scheme * * @return \Psr\Http\Message\UriInterface New, transformed Uri instance compatible with provided scheme */ public function transform(UriInterface $uri, string $scheme): UriInterface; /** * Determines whether provided URI scheme is supported by the UriFactory * * @param string $scheme An URI scheme * * @return bool */ public function isSchemeSupported(string $scheme): bool; /** * Gets normalized scheme names (in lowercase) that are supported by UriFactory. * * @return string[] */ public function getSupportedSchemes(): array; }
433f49b940f00c48f21870ffb3ef14ff822eedd5
[ "Markdown", "Dockerfile", "PHP" ]
24
PHP
k911/uri-builder
8efb51684f77ea1985c4d6ec93be4a5499cb923b
821064494236f85b131b0be0a6afe40954f02ae4
refs/heads/master
<file_sep>using Bsuir.Retinex.UI.Command; using Microsoft.Win32; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using System.Windows.Media.Imaging; namespace Bsuir.Retinex.UI.Model { public class ProcessAreaViewModel { public event PropertyChangedEventHandler PropertyChanged; private string _imagePath; private ICommand _addImageCommand; public string ImagePath { get { return _imagePath; } set { _imagePath = value; OnPropertyChanged(() => ImagePath); } } public List<string> ProcessTypes { get; set; } public string SelectedProcessType { get; set; } public ICommand AddImageCommand => _addImageCommand ?? (_addImageCommand = new RelayCommand(AddImage)); public ProcessAreaViewModel() { ProcessTypes = new List<string> { "SSR", "MSR", "MSRCR" }; SelectedProcessType = ProcessTypes.First(); } private void AddImage(object obj) { var dlg = new OpenFileDialog(); dlg.DefaultExt = ".jpg"; dlg.Filter = "Images|*.jpg;*.png;*.gif"; if (dlg.ShowDialog() != true) return; try { ImagePath = dlg.FileName; } catch (NotSupportedException) { Debug.WriteLine("not supported conversion"); } } public void OnPropertyChanged<T>(Expression<Func<T>> property) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property.Name)); } } } <file_sep>using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Bsuir.Retinex.Web.Controllers { [Route("api/[controller]")] [ApiController] public class ImageController : ControllerBase { [HttpGet] public IActionResult Index() { return Content("Working..."); } } } <file_sep>using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Bsuir.SSR.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Bsuir.SSR.Tests")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("9ea5605c-d312-4728-897d-133003d2af3d")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] <file_sep>using Bsuir.Retinex.UI.Model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Bsuir.Retinex.UI.ViewModel { public class MainWindowViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public ObservableCollection<ProcessAreaViewModel> Areas { get; set; } public MainWindowViewModel() { var areas = new List<ProcessAreaViewModel> { new ProcessAreaViewModel(), new ProcessAreaViewModel(), new ProcessAreaViewModel(), new ProcessAreaViewModel(), new ProcessAreaViewModel(), new ProcessAreaViewModel() }; Areas = new ObservableCollection<ProcessAreaViewModel>(areas); } public void OnPropertyChanged<T>(Expression<Func<T>> property) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(property.Name)); } } }
c44c9f6dd2805dbf3a98beebc31d7c71a9ed819d
[ "C#" ]
4
C#
cb150971720/retinex
a2c1b1053cb1039637a864f1dc0cc46b7ef5f4b1
f13e8ae98245ec270e544d6528efd4c08dc81f28
refs/heads/master
<repo_name>mastergage11/ShapeyShapes<file_sep>/src/Game.java import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.image.BufferedImage; import java.awt.event.KeyListener; public class Game extends JFrame implements KeyListener { Board board; int positionX, positionY; long moment; boolean mouseClicked = false; boolean pPressed; public Game(){ setTitle("Don't feed the dog!"); setVisible(true); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); setResizable(false); board = new Board(this); add(board); addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { super.mouseEntered(e); setCursor(getToolkit().createCustomCursor(new BufferedImage(3, 3, 2), new Point(0, 0), "null")); } }); addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseMoved(MouseEvent e) { super.mouseMoved(e); positionX = e.getX(); positionY = e.getY(); } }); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { super.mouseClicked(e); mouseClicked = true; moment = System.currentTimeMillis(); } }); pack(); board.setup(); setLocationRelativeTo(null); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_P){ pPressed = true; System.out.println("ssssssssssssssssssss"); } } public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_P){ pPressed = false; System.out.println("SSSSSSSSSSSSSSSSSSSS"); } } public boolean ispPressed(){ return pPressed; } public int getPositionX(){ return positionX; } public int getPositionY(){ return positionY; } public boolean getIsClicked(){ return mouseClicked; } public void notClicked(){ mouseClicked = false; } public long getMoment(){ return moment; } public static void main(String[] args){ Game game = new Game(); game.board.setup(); } }
2d25036dd8e9909b5c9529b7c2c8a87a852668b4
[ "Java" ]
1
Java
mastergage11/ShapeyShapes
6258555095360ab9249016947a23b84154e9f9b2
e9b56451d9eff767b7bf1e303f734bf85856e611
refs/heads/master
<repo_name>jawadsa007/AppBalittra<file_sep>/app/Analisa.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Analisa extends Model { public function kategori() { return $this->belongsTo('App\Kategori'); } public function permintaan() { return $this->belongsToMany('App\Permintaan'); } } <file_sep>/database/migrations/2020_01_08_235917_create_analisa_permintaan_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateAnalisaPermintaanTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('analisa_permintaan', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('analisa_id'); $table->unsignedBigInteger('permintaan_id'); $table->timestamps(); $table->foreign('analisa_id')->references('id')->on('analisas'); $table->foreign('permintaan_id')->references('id')->on('permintaans'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('analisa_permintaan'); } } <file_sep>/app/Pelanggan.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Pelanggan extends Model { protected $fillable = ['nama_pelanggan', 'nama_instansi', 'alamat', 'no_telp']; public function permintaan() { return $this->hasMany('App\Permintaan'); } } <file_sep>/database/seeds/KategorisTableSeeder.php <?php use Illuminate\Database\Seeder; class KategorisTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('kategoris')->insert([ [ 'nama_kategori' => 'tanah' ], [ 'nama_kategori' => 'jaringan' ], [ 'nama_kategori' => 'pupuk' ], [ 'nama_kategori' => 'air' ], [ 'nama_kategori' => 'gas' ], ]); } } <file_sep>/app/Http/Controllers/PendapatanController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Permintaan; use Carbon\Carbon; use DB; class PendapatanController extends Controller { public function index() { $pendapatan = Permintaan::where('bayar', '>', 0)->paginate(10); $total = $pendapatan->sum('bayar'); $tgl = Carbon::now('Asia/Kuala_Lumpur'); return view('pendapatan.data', compact('pendapatan', 'total', 'tgl')); } public function filter(Request $request) { $pendapatan = Permintaan::whereBetween('updated_at',[$request->start, $request->end])->paginate(10); $total = $pendapatan->sum('bayar'); $tgl = Carbon::now('Asia/Kuala_Lumpur'); return view('pendapatan.data', compact('pendapatan', 'total', 'tgl')); } public function laporan(Request $request) { $pendapatan = Permintaan::where('bayar', '>', 0)->get(); $total = $pendapatan->sum('bayar'); $tgl = Carbon::now('Asia/Kuala_Lumpur'); return view('pendapatan.laporan', compact('pendapatan', 'total', 'tgl')); } } <file_sep>/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('auth.login'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); //Pelanggan Route::get('/data-pelanggan', 'PelangganController@index')->name('pelanggan.index'); Route::get('/tambah-pelanggan', 'PelangganController@create')->name('pelanggan.create'); Route::post('/tambah-pelanggan', 'PelangganController@store')->name('pelanggan.store'); Route::get('/edit-data-pelanggan/{pelanggan}', 'PelangganController@edit')->name('pelanggan.edit'); Route::patch('/edit-data-pelanggan/{pelanggan}', 'PelangganController@update')->name('pelanggan.update'); Route::delete('/hapus-data-pelanggan/{pelanggan}', 'PelangganController@destroy')->name('pelanggan.destroy'); Route::get('/laporan-pelanggan/{pelanggan}', 'PelangganController@laporan')->name('pelanggan.laporan'); //Permintaan Route::get('/data-permintaan', 'PermintaanController@index')->name('permintaan.index'); Route::get('/tambah-permintaan', 'PermintaanController@create')->name('permintaan.create'); Route::post('/tambah-permintaan', 'PermintaanController@store')->name('permintaan.store'); Route::get('/edit-data-permintaan/{permintaan}', 'PermintaanController@edit')->name('permintaan.edit'); Route::patch('/edit-data-permintaan/{permintaan}', 'PermintaanController@update')->name('permintaan.update'); Route::delete('/hapus-data-permintaan/{permintaan}', 'PermintaanController@destroy')->name('permintaan.destroy'); Route::get('/pembayaran/{permintaan}', 'PermintaanController@pembayaran')->name('permintaan.pembayaran'); Route::patch('/pembayaran/{permintaan}', 'PermintaanController@bayar')->name('permintaan.bayar'); Route::get('/cetak-nota/{permintaan}', 'PermintaanController@nota')->name('permintaan.nota'); Route::get('/cetak-permintaan-belum-dikerjakan', 'PermintaanController@belum')->name('permintaan.belum'); Route::get('/cetak--permintaan-sedang-dikerjakan', 'PermintaanController@sedang')->name('permintaan.sedang'); Route::get('/cetak-permintaan-selesai', 'PermintaanController@selesai')->name('permintaan.selesai'); Route::get('/detail-permintaan/{permintaan}', 'PermintaanController@detail')->name('permintaan.detail'); Route::get('/proses-permintaan/{permintaan}', 'PermintaanController@proses')->name('permintaan.proses'); Route::patch('/proses-permintaan/{permintaan}', 'PermintaanController@kerjakan')->name('permintaan.kerjakan'); Route::patch('/proses-selesai-permintaan/{permintaan}', 'PermintaanController@done')->name('permintaan.done'); //pendapatan Route::get('/pendapatan', 'PendapatanController@index')->name('pendapatan.index'); Route::get('/pendapatan/filter', 'PendapatanController@filter')->name('pendapatan.filter'); Route::get('/pendapatan/laporan', 'PendapatanController@laporan')->name('pendapatan.laporan');<file_sep>/app/Permintaan.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Permintaan extends Model { protected $fillable = ['pelanggan_id', 'judul_penelitian','kategori_id', 'jumlah_contoh', 'asal_contoh']; public function analisa() { return $this->belongsToMany('App\Analisa'); } public function kategori() { return $this->belongsTo('App\Kategori'); } public function pelanggan() { return $this->belongsTo('App\Pelanggan'); } public function analis() { return $this->hasOne('App\Analis'); } } <file_sep>/database/seeds/AnalisasTableSeeder.php <?php use Illuminate\Database\Seeder; class AnalisasTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('analisas')->insert([ [ 'nama_analisa' => 'Persiapan Contoh + Kadar Air', 'kategori_id' => '1', 'harga' => '18000', ], [ 'nama_analisa' => 'Kadar Abu', 'kategori_id' => '1', 'harga' => '20000', ], [ 'nama_analisa' => 'Tekstur 3 Fraksi', 'kategori_id' => '1', 'harga' => '30000', ], [ 'nama_analisa' => 'BD dan PD', 'kategori_id' => '1', 'harga' => '50000', ], [ 'nama_analisa' => 'pH (pH H2O + pH KCL)', 'kategori_id' => '1', 'harga' => '24000', ], [ 'nama_analisa' => 'DHL', 'kategori_id' => '1', 'harga' => '12000', ], [ 'nama_analisa' => 'C-Organik (Walkey)', 'kategori_id' => '1', 'harga' => '24000', ], [ 'nama_analisa' => 'C-Organik (Muffle)', 'kategori_id' => '1', 'harga' => '20000', ], [ 'nama_analisa' => 'N Total', 'kategori_id' => '1', 'harga' => '30000', ], [ 'nama_analisa' => 'C/N Ratio (C-org + N-total', 'kategori_id' => '1', 'harga' => '5000', ], ]); } } <file_sep>/app/Http/Controllers/PelangganController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Pelanggan; use PDF; class PelangganController extends Controller { public function index() { $pelanggans = Pelanggan::all(); return view('pelanggan.index', compact('pelanggans')); } public function create() { return view('pelanggan.create'); } public function store(Request $request) { $pelanggan = new Pelanggan; $pelanggan->nama_pelanggan = $request->nama_pelanggan; $pelanggan->nama_instansi = $request->nama_instansi; $pelanggan->alamat = $request->alamat; $pelanggan->no_telp = $request->no_telp; $pelanggan->save(); return redirect()->route('pelanggan.index'); } public function edit(Pelanggan $pelanggan) { return view('pelanggan.edit', compact('pelanggan')); } public function update(Request $request, Pelanggan $pelanggan) { $pelanggan->nama_pelanggan = $request->nama_pelanggan; $pelanggan->nama_instansi = $request->nama_instansi; $pelanggan->alamat = $request->alamat; $pelanggan->no_telp = $request->no_telp; $pelanggan->save(); return redirect()->route('pelanggan.index'); } public function delete(Pelanggan $pelanggan) { $pelanggan->delete(); return redirect()->route('pelanggan.index'); } public function laporan(Pelanggan $pelanggan) { $total = $pelanggan->permintaan->count(); return view('pelanggan.laporan', compact('pelanggan', 'total')); } } <file_sep>/app/Http/Controllers/PermintaanController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Permintaan; use App\Pelanggan; use App\Kategori; use App\Analisa; use App\Analis; use PDF; use Carbon\Carbon; class PermintaanController extends Controller { public function index() { $permintaans =Permintaan::all(); return view('permintaan.index', compact('permintaans')); } public function create() { $kategoris = Kategori::all(); $analisas =Analisa::all(); $pelanggans = Pelanggan::all(); return view('permintaan.create', compact('pelanggans', 'analisas', 'kategoris')); } public function store(Request $request) { $permintaan = new Permintaan; $permintaan->pelanggan_id = $request->pelanggan_id; $permintaan->judul_penelitian = $request->judul_penelitian; $permintaan->kategori_id = $request->kategori_id; $permintaan->jumlah_contoh = $request->jumlah_contoh; $permintaan->asal_contoh = $request->asal_contoh; $permintaan->save(); $permintaan->analisa()->sync($request->analisas, false); return redirect()->route('permintaan.index'); } public function edit() { } public function update() { } public function destroy(Permintaan $permintaan) { $permintaan->analisa()->detach(); $permintaan->delete(); return redirect()->route('permintaan.index'); } public function pembayaran(Permintaan $permintaan) { $subtotal = $permintaan->analisa->sum('harga'); $pajak = ($subtotal*5)/100; $total = $subtotal + $pajak; return view('permintaan.bayar', compact('permintaan', 'subtotal', 'total', 'pajak')); } public function bayar(Request $request, Permintaan $permintaan) { $subtotal = $permintaan->analisa->sum('harga'); $pajak = ($subtotal*5)/100; $total = $subtotal + $pajak; $permintaan->bayar = $total; $permintaan->save(); return redirect()->route('permintaan.index'); } public function nota(Permintaan $permintaan) { $subtotal = $permintaan->analisa->sum('harga'); $pajak = ($subtotal*5)/100; $total = $subtotal + $pajak; $tgl = Carbon::now()->locale("id_ID"); return view('permintaan.nota', compact('permintaan', 'subtotal', 'pajak', 'total', 'tgl')); } public function belum() { $permintaans = Permintaan::where('status_proses', 0)->get(); return view('permintaan.belum', compact('permintaans')); } public function sedang() { $permintaans = Permintaan::where('status_proses', 1)->get(); return view('permintaan.sedang', compact('permintaans')); } public function selesai() { $permintaans = Permintaan::where('status_proses', 2)->get(); return view('permintaan.selesai', compact('permintaans')); } public function detail(Permintaan $permintaan) { return view('permintaan.detail', compact('permintaan')); } public function proses(Permintaan $permintaan) { $analis = Analis::all(); return view('permintaan.proses', compact('permintaan', 'analis')); } public function kerjakan(Request $request, Permintaan $permintaan) { $permintaan->status_proses = 1; $permintaan->analis_id = $request->analis_id; $permintaan->save(); return redirect()->route('permintaan.index'); } public function done(Permintaan $permintaan) { $permintaan->status_proses = 2; $permintaan->save(); return redirect()->route('permintaan.index'); } } <file_sep>/app/Kategori.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Kategori extends Model { public function analisa() { return $this->hasOne('App\Analisa'); } public function permintaan() { return $this->hasMany('App\Permintaan'); } } <file_sep>/database/migrations/2020_01_08_235522_create_permintaans_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePermintaansTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('permintaans', function (Blueprint $table) { $table->bigIncrements('id'); $table->unsignedBigInteger('pelanggan_id'); $table->string('judul_penelitian'); $table->unsignedBigInteger('kategori_id'); $table->string('jumlah_contoh'); $table->string('asal_contoh'); $table->unsignedBigInteger('analis_id')->nullable(); $table->tinyInteger('status_proses')->default('0'); $table->integer('bayar')->default('0'); $table->timestamps(); $table->foreign('pelanggan_id')->references('id')->on('pelanggans'); $table->foreign('kategori_id')->references('id')->on('kategoris'); $table->foreign('analis_id')->references('id')->on('analis'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('permintaans'); } } <file_sep>/app/Analis.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Analis extends Model { public function permintaan() { return $this->belongsTo('App\Permintaan'); } }
2f48743b1db332b730baf5f23626ed1a0eb6cd75
[ "PHP" ]
13
PHP
jawadsa007/AppBalittra
60e93b1c756b27e8c3ccd855f479f8c846421334
b3756064251e4524ee598b715c0552387a7400fd
refs/heads/master
<repo_name>TeeJet/rt-mis<file_sep>/src/tests/CalculatorTest.php <?php use classes\calculator\Calculator; use classes\numbers\NumberArray; use classes\numbers\NumberInteger; use classes\numbers\NumberString; use PHPUnit\Framework\TestCase; class CalculatorTest extends TestCase { public function testEmpty() { $calculator = new Calculator(); $this->assertEmpty($calculator->getNumbers()); return $calculator; } /** * @param Calculator $calculator * @throws Exception * @depends testEmpty */ public function testAppendAndClear(Calculator $calculator) { $number1 = new NumberString("123"); $number2 = new NumberInteger(456); $number3 = new NumberArray(['7', '8', '9']); $calculator->append($number1); $this->assertSame([$number1], $calculator->getNumbers()); $calculator->append($number2); $this->assertSame([$number1, $number2], $calculator->getNumbers()); $calculator->append($number3); $this->assertSame([$number1, $number2, $number3], $calculator->getNumbers()); $calculator->clear(); $this->assertEmpty($calculator->getNumbers()); } /** * @depends testEmpty * @param Calculator $calculator */ public function testFailWhenAppendIsIncorrect(Calculator $calculator) { $this->expectException(TypeError::class); $calculator->append(123); } /** * @param Calculator $calculator * @throws Exception * @depends testEmpty */ public function testSum(Calculator $calculator) { $number1 = new NumberString("1000000000000000000000000000000000000"); $number2 = new NumberString("2000000000000000000000000000000000000"); $number3 = new NumberString("7000000000000000000000000000000000000"); $calculator->append($number1); $calculator->append($number2); $calculator->append($number3); $this->assertSame("10000000000000000000000000000000000000", $calculator->sum()); } }<file_sep>/src/tests/NumberStringTest.php <?php use classes\numbers\NumberString; use classes\numbers\NumberStringIterator; use PHPUnit\Framework\TestCase; class NumberStringTest extends TestCase { public function valueProvider() { return [ ["0", 1, "0", ['0']], ["1", 1, "1", ['1']], ["1234567890", 10, "1234567890", ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']], ["0987654321", 10, "987654321", ['0', '9', '8', '7', '6', '5', '4', '3', '2', '1']], ["1234567890123456789012345678901234567890", 40, "1234567890123456789012345678901234567890", ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0']], ]; } /** * @dataProvider valueProvider * @param $expected * @param $size * @param $text * @param $iterator * @throws Exception */ public function testValueAndProperties($expected, $size, $text, $iterator) { $number = new NumberString($expected); $this->assertSame($expected, $number->getValue()); $this->assertSame($size, $number->getSize()); $this->assertSame($text, $number->getTextValue()); $this->assertEquals(new NumberStringIterator($number), $number->getIterator()); $this->assertEquals($iterator, iterator_to_array($number->getIterator())); } /** * @throws Exception */ public function testFailWhenInitValueIsIncorrect() { $this->expectExceptionMessage("В числе задан недопустимый символ"); new NumberString("-123"); } }<file_sep>/src/tests/SumCommandTest.php <?php use classes\numbers\NumberArray; use classes\numbers\NumberInteger; use classes\numbers\NumberString; use classes\calculator\SumCommand; use PHPUnit\Framework\TestCase; class SumCommandTest extends TestCase { /** * @return array * @throws Exception */ public function valueProvider() { $number1 = new NumberString("0"); $number2 = new NumberString("1"); $number3 = new NumberString("9"); $number4 = new NumberString("100000000000000000000000000000000000000000000000"); $number5 = new NumberString("999999999999999999999999999999999999999999999999"); $number6 = new NumberInteger(10000000000000); $number7 = new NumberArray([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); $number8 = new NumberString("10000000000000"); return [ [[$number1], "0"], [[$number1, $number1], "0"], [[$number1, $number2], "1"], [[$number2, $number3], "10"], [[$number3, $number4], "100000000000000000000000000000000000000000000009"], [[$number4, $number5], "1099999999999999999999999999999999999999999999999"], [[$number5, $number4], "1099999999999999999999999999999999999999999999999"], [[$number2, $number5], "1000000000000000000000000000000000000000000000000"], [[$number5, $number2], "1000000000000000000000000000000000000000000000000"], [[$number1, $number2, $number3], "10"], [[$number4, $number4, $number4, $number4], "400000000000000000000000000000000000000000000000"], [[$number6, $number7], "20000000000000"], [[$number6, $number8], "20000000000000"], [[$number7, $number8], "20000000000000"], [[$number6, $number7, $number8], "30000000000000"], ]; } /** * @dataProvider valueProvider * @param $numbers * @param $excepted * @throws Exception */ public function testExecute($numbers, $excepted) { $command = new SumCommand($numbers); $this->assertSame($excepted, $command->execute()); } /** * @throws Exception */ public function testFailWhenSumEmpty() { $this->expectExceptionMessage("Для сложения, добавьте числа"); new SumCommand([]); } }<file_sep>/src/tests/NumberIntegerTest.php <?php use classes\numbers\NumberInteger; use classes\numbers\NumberIntegerIterator; use PHPUnit\Framework\TestCase; class NumberIntegerTest extends TestCase { public function valueProvider() { return [ [0, 1, "0", [1 => 0]], [1, 1, "1", [1 => 1]], [1234567890, 10, "1234567890", [1 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 0]], [987654321, 9, "987654321", [1 => 9, 8, 7, 6, 5, 4, 3, 2, 1]], ]; } /** * @dataProvider valueProvider * @param $expected * @param $size * @param $text * @param $iterator * @throws Exception */ public function testValueAndProperties($expected, $size, $text, $iterator) { $number = new NumberInteger($expected); $this->assertSame($expected, $number->getValue()); $this->assertSame($size, $number->getSize()); $this->assertSame($text, $number->getTextValue()); $this->assertEquals(new NumberIntegerIterator($number), $number->getIterator()); $this->assertEquals($iterator, iterator_to_array($number->getIterator())); } /** * @throws Exception */ public function testFailWhenInitValueIsIncorrect() { $max = PHP_INT_MAX; $min = PHP_INT_MIN; $this->expectExceptionMessage("Для числового формата максимальное значение составляет {$max}"); new NumberInteger($max * 2); $this->expectExceptionMessage("Можно использовать только положительные числа"); new NumberInteger(-1); $this->expectExceptionMessage("Можно использовать только положительные числа"); new NumberInteger($min * 2); $this->expectExceptionMessage("Можно использовать только положительные числа"); new NumberInteger($min - 1); $this->expectExceptionMessage("Введено число неверного типа или превышено максимальное значение"); new NumberInteger($max + 1); $this->expectExceptionMessage("Введено число неверного типа или превышено максимальное значение"); new NumberInteger("1234567890"); } }<file_sep>/src/classes/numbers/Number.php <?php namespace classes\numbers; use Exception; use IteratorAggregate; abstract class Number implements IteratorAggregate, NumberInterface { protected $value; /** * Number constructor. * @param $value * @throws Exception */ public function __construct($value) { $this->setValue($value); } public function getValue() { return $this->value; } /** * @param $value * @throws Exception */ public function setValue($value) { $this->value = $value; $this->guardValue(); } abstract public function getIterator(): NumberIterator; abstract public function getSize(): int; abstract protected function guardValue(); }<file_sep>/examples.php <?php require_once 'vendor/autoload.php'; use classes\calculator\Calculator; use classes\numbers\NumberArray; use classes\numbers\NumberInteger; use classes\numbers\NumberString; try { $calculator = new Calculator(); $calculator->append(new NumberString("123")); $calculator->append(new NumberArray([1, 2, 3])); $calculator->append(new NumberInteger(123)); echo $calculator->sum() . PHP_EOL; } catch (Exception $exception) { echo "Ошибка: {$exception->getMessage()}"; } <file_sep>/src/classes/numbers/NumberIntegerIterator.php <?php namespace classes\numbers; use DivisionByZeroError; class NumberIntegerIterator extends NumberIterator { /** * @inheritDoc */ public function current() { return $this->getDigitByPosition(); } /** * @inheritDoc */ public function next() { $this->position--; } /** * @inheritDoc */ public function key(): int { return $this->position; } /** * @inheritDoc */ public function valid(): bool { try { return $this->position >= 1; } catch (DivisionByZeroError $exception) { return false; } } /** * @inheritDoc */ public function rewind() { $this->position = strlen($this->number->getValue()); } private function getDigitByPosition(): int { $temp = pow(10, $this->number->getSize() - $this->position); return intdiv($this->number->getValue(), $temp) % 10; } }<file_sep>/src/classes/calculator/Calculator.php <?php namespace classes\calculator; use classes\numbers\NumberInterface; use Exception; class Calculator { private $numbers = []; public function append(NumberInterface $number) { $this->numbers[] = $number; } public function getNumbers(): array { return $this->numbers; } public function clear() { $this->numbers = []; } /** * @return mixed * @throws Exception */ public function sum(): string { $command = new SumCommand($this->numbers); return $command->execute(); } }<file_sep>/src/classes/numbers/NumberString.php <?php namespace classes\numbers; use Exception; class NumberString extends Number { /** * @inheritDoc */ public function getIterator(): NumberIterator { return new NumberStringIterator($this); } public function getSize(): int { return strlen($this->getValue()); } public function getTextValue(): string { $value = (string)$this->getValue(); if ($this->getSize() > 1) { $value = ltrim($value, 0); } return $value; } /** * @throws Exception */ protected function guardValue() { if(preg_match("/[^0-9]/", $this->getValue())) { throw new Exception("В числе задан недопустимый символ"); } } }<file_sep>/src/classes/numbers/NumberArray.php <?php namespace classes\numbers; use Exception; class NumberArray extends Number { /** * @inheritDoc */ public function getIterator(): NumberIterator { return new NumberArrayIterator($this); } public function getSize(): int { return count($this->getValue()); } public function getTextValue(): string { $value = implode('', $this->getValue()); if ($this->getSize() > 1) { $value = ltrim($value, 0); } return $value; } /** * @throws Exception */ protected function guardValue() { if ($this->getSize() == 0) { throw new Exception("Должен быть хотя бы 1 элемент массива"); } foreach ($this->getIterator() as $digit) { if (!is_string($digit) && !is_int($digit)) { throw new Exception("Элементы массива должен быть строкового или числового типа"); } if (strlen($digit) > 1) { throw new Exception("Элементы массива должны содержать только один символ"); } if(preg_match("/[^0-9]/", $digit)) { throw new Exception("Элементы массива должны содержать только числова значения"); } } } }<file_sep>/src/classes/calculator/SumCommand.php <?php namespace classes\calculator; use classes\numbers\Number; use classes\numbers\NumberString; use Exception; class SumCommand implements CommandInterface { private $numbers; private $result; private $tempResult = ""; private $remains = 0; /** * SumCommand constructor. * @param array $numbers * @throws Exception */ public function __construct(array $numbers) { if (!$numbers) { throw new Exception("Для сложения, добавьте числа"); } $this->numbers = $numbers; $this->result = new NumberString("0"); } /** * @return string * @throws Exception */ public function execute(): string { foreach ($this->numbers as $number) { $this->add($number); } return $this->result->getTextValue(); } /** * @param Number $number * @throws Exception */ private function add(Number $number) { $number1 = $number->getSize() > $this->result->getSize() ? $number : $this->result; $number2 = $number->getSize() <= $this->result->getSize() ? $number : $this->result; $iterator = $number2->getIterator(); $iterator->rewind(); $this->tempResult = ""; $this->remains = 0; foreach ($number1->getIterator() as $digit1) { $digit2 = $iterator->valid() ? $iterator->current() : 0; $this->operateDigits($digit1, $digit2); $iterator->next(); } $this->tempResult .= $this->remains > 0 ? $this->remains : ''; $this->result->setValue(strrev($this->tempResult)); } private function operateDigits($digit1, $digit2) { $digit = $this->sumDigits((int)$digit1, (int)$digit2, $this->remains); $this->tempResult .= $digit % 10; $this->remains = intdiv($digit, 10); } private function sumDigits(...$digits): int { return array_sum($digits); } }<file_sep>/src/classes/numbers/NumberInteger.php <?php namespace classes\numbers; use Exception; class NumberInteger extends Number { /** * @inheritDoc */ public function getIterator(): NumberIterator { return new NumberIntegerIterator($this); } public function getSize(): int { return strlen($this->getValue()); } public function getTextValue(): string { $value = (string)$this->getValue(); if ($this->getSize() > 1) { $value = ltrim($value, 0); } return $value; } /** * @param int $max * @throws Exception */ protected function guardValue(int $max = PHP_INT_MAX) { if ($this->getValue() > $max) { throw new Exception("Для числового формата максимальное значение составляет {$max}"); } if ($this->getValue() < 0) { throw new Exception("Можно использовать только положительные числа"); } if (!is_int($this->getValue())) { throw new Exception("Введено число неверного типа или превышено максимальное значение"); } } }<file_sep>/src/classes/numbers/NumberStringIterator.php <?php namespace classes\numbers; class NumberStringIterator extends NumberIterator { /** * @inheritDoc */ public function current() { return $this->number->getValue()[$this->position]; } /** * @inheritDoc */ public function next() { $this->position--; } /** * @inheritDoc */ public function key(): int { return $this->position; } /** * @inheritDoc */ public function valid(): bool { return $this->position >= 0 && isset($this->number->getValue()[$this->position]); } /** * @inheritDoc */ public function rewind() { $this->position = strlen($this->number->getValue()) - 1; } }<file_sep>/src/classes/calculator/CommandInterface.php <?php namespace classes\calculator; interface CommandInterface { public function execute(): string; }<file_sep>/src/classes/numbers/NumberInterface.php <?php namespace classes\numbers; interface NumberInterface { public function getValue(); public function getTextValue(): string; public function getSize(): int; }<file_sep>/src/classes/numbers/NumberIterator.php <?php namespace classes\numbers; use Iterator; abstract class NumberIterator implements Iterator { public $number; public $position = 0; public function __construct(NumberInterface $number) { $this->number = $number; } }
5e4dc0b9ad92bb874a25b66c8ce1d6dae58d4be7
[ "PHP" ]
16
PHP
TeeJet/rt-mis
745846070d9bf2495feb5299898abc7d56bd98d6
c0b09dbcc7c0b5856a005c9991adfd83e510e391
refs/heads/master
<file_sep>module.exports = function override(config, env) { config.plugins=config.plugins || [] const chalk = require("chalk") const PreloadPlugin = require('preload-webpack-plugin') //config.plugins = config.plugins.concat([new PreloadPlugin({})]) config.plugins = config.plugins.concat([ new require("progress-bar-webpack-plugin")({ format: ` [:current/:total] :percent :elapsed seconds [${chalk.green.bold(":bar")}] :msg `, clear:true }) ]) return config; } <file_sep># TF-TD Browser Tower Defense game with Team Fortress 2 characters
8c572564d3faad16e11276a7095da9a1f3b5b0dd
[ "JavaScript", "Markdown" ]
2
JavaScript
SupinePandora43/TF-TD
6532cd9165a2bdb294d4620dda6ecb5eaa3985c8
ae03bc40b36a78cbb165b7573d64f5ae6e392dea
refs/heads/master
<repo_name>Winaway/particle_filter_localization<file_sep>/src/particle_filter.cpp /* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: <NAME> */ #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include "particle_filter.h" using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and others in this file). std::cout << "/* init_start */" << '\n'; num_particles = 50; default_random_engine gen; normal_distribution<double> dist_x(x,std[0]); normal_distribution<double> dist_y(y,std[1]); normal_distribution<double> dist_theta(theta,std[2]); // std::cout << "/* init_1 */" << '\n'; Particle p1; // std::cout << "/* init_2 */" << '\n'; for(int i = 0;i<num_particles;i++){ p1.x = dist_x(gen); p1.y = dist_y(gen); p1.theta = dist_theta(gen); p1.weight = 1.0; p1.id = i; particles.push_back(p1); weights.push_back(p1.weight); is_initialized = true; } std::cout << "/* init_end */" << '\n'; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ std::cout << "/* predict_start */" << '\n'; default_random_engine gen; // std::cout <<"p1_x="<<particles[0].x<<"p1_y="<<particles[0].y<<"p1_theta="<<particles[0].theta<< '\n'; // std::cout<<"yaw_rate="<<yaw_rate<<'\n'; for(int i=0;i<num_particles;i++){ Particle p = particles[i]; if(yaw_rate==0){ p.x = p.x+velocity*delta_t*cos(p.theta); p.y = p.y +velocity*delta_t*sin(p.theta);; p.theta = p.theta; }else{ p.x = p.x+(velocity/yaw_rate)*(sin(p.theta+yaw_rate*delta_t)-sin(p.theta)); p.y = p.y +(velocity/yaw_rate)*(cos(p.theta)-cos(p.theta+yaw_rate*delta_t)); p.theta = p.theta+yaw_rate*delta_t; } // std::cout <<"x="<<p.x<<"y="<<p.y<<"theta="<<p.theta<< '\n'; normal_distribution<double> dist_x(p.x,std_pos[0]); normal_distribution<double> dist_y(p.y,std_pos[1]); normal_distribution<double> dist_theta(p.theta,std_pos[2]); p.x = dist_x(gen); p.y = dist_y(gen); p.theta = dist_theta(gen); particles[i] = p; } std::cout << "/* predict_end */" << '\n'; } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to // implement this method and use it as a helper during the updateWeights phase. for(int i=0;i<observations.size();i++){ double distance = 0.0; // int id =0; for(int j=0;j<predicted.size();j++){ double temp_dist =dist(predicted[j].x,predicted[j].y,observations[i].x,observations[i].y); // std::cout << "/* temp_dist */"<<temp_dist << '\n'; if(temp_dist<distance||distance==0.0){ distance = temp_dist; observations[i].id = predicted[j].id; } } } } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { // TODO: Update the weights of each particle using a mult-variate Gaussian distribution. You can read // more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution // NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located // according to the MAP'S coordinate system. You will need to transform between the two systems. // Keep in mind that this transformation requires both rotation AND translation (but no scaling). // The following is a good resource for the theory: // https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm // and the following is a good resource for the actual equation to implement (look at equation // 3.33 // http://planning.cs.uiuc.edu/node99.html std::cout << "/* update_weights_start */" << '\n'; for(int p=0;p<num_particles;p++){ Particle p1 = particles[p]; std::vector<LandmarkObs> obs_tran; // std::cout << "/* tramsform */"<<"x="<<observations[0].x<<"y="<<observations[0].y<< '\n'; // std::cout <<"p1_x="<<particles[0].x<<"p1_y="<<particles[0].y<<"p1_theta="<<particles[0].theta<< '\n'; //transform the observations to MAP's coordinate. for(int i=0;i<observations.size();i++){ LandmarkObs obs; obs.x = p1.x+(cos(p1.theta)*observations[i].x)-(sin(p1.theta)*observations[i].y); obs.y = p1.y+(sin(p1.theta)*observations[i].x)+(cos(p1.theta)*observations[i].y); // std::cout << "obs_x="<<obs.x<<"obs_y="<<obs.y<< '\n'; obs_tran.push_back(obs); } // std::cout << "/* find */"<< obs_tran[0].id<<"x="<<obs_tran[0].x <<"y="<<obs_tran[0].y<< '\n'; //find the possible avaliable map_landmark std::vector<LandmarkObs> predicted; for(int j=0;j<map_landmarks.landmark_list.size();j++){ double distance = dist(map_landmarks.landmark_list[j].x_f,map_landmarks.landmark_list[j].y_f,p1.x,p1.y); if(distance <= sensor_range){ LandmarkObs predict_mark; predict_mark.id = map_landmarks.landmark_list[j].id_i; predict_mark.x = map_landmarks.landmark_list[j].x_f; predict_mark.y = map_landmarks.landmark_list[j].y_f; predicted.push_back(predict_mark); } } // std::cout << "/* association */" << '\n'; //set association between observation and predicted dataAssociation(predicted, obs_tran); // std::cout << "/* update */" << '\n'; //update weights double sig_x = std_landmark[0]; double sig_y = std_landmark[1]; double w=1.0; for(int n=0;n<obs_tran.size();n++){ double x = obs_tran[n].x; double y = obs_tran[n].y; // std::cout << "w"<< n << '\n'; // std::cout << "obs_tran_id="<< obs_tran[n].id << '\n'; double u_x = map_landmarks.landmark_list[obs_tran[n].id-1].x_f; double u_y = map_landmarks.landmark_list[obs_tran[n].id-1].y_f; w = w*(1.0/(exp(((x-u_x)*(x-u_x)/(2*sig_x*sig_x))+((y-u_y)*(y-u_y)/(2*sig_y*sig_y)))*2*M_PI*sig_x*sig_y)); } // std::cout << "/* w = */"<< w << '\n'; particles[p].weight = w; weights[p] = w; } std::cout << weights[1] << '\n'; std::cout << "/* update_weights_end */" << '\n'; } void ParticleFilter::resample() { // TODO: Resample particles with replacement with probability proportional to their weight. // NOTE: You may find std::discrete_distribution helpful here. // http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution std::cout << "/* resample_start */" << '\n'; default_random_engine gen; std::discrete_distribution<int> distribution(weights.begin(),weights.end()); std::vector<Particle> resample_particles; for(int i=0;i<num_particles;i++){ resample_particles.push_back(particles[distribution(gen)]); } // std::cout << "x=" <<resample_particles[0].x<<"y="<<resample_particles[0].y<<"theta="<<resample_particles[0].theta<< '\n'; particles = resample_particles; // std::cout << "x=" <<particles[0].x<<"y="<<particles[0].y<<"theta="<<particles[0].theta<< '\n'; std::cout << "/* resample_end */" << '\n'; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
5e8c0da0836dcf12512aa053ef61a8e91c961955
[ "C++" ]
1
C++
Winaway/particle_filter_localization
f2ad2f47f04fbeebf4f6e081db3f59afce4e941c
3b5cac77f563061e2d5e84039062667a5634644f
refs/heads/master
<file_sep>package com.softhaxi.reflex.controller.common; import java.util.Date; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.softhaxi.reflex.domain.account.User; import com.softhaxi.reflex.service.account.UserService; /** * * @author ivohutasoit * @since 1.0.0 */ @Controller public class HomeController { @Autowired private UserService userService; @GetMapping("/") public String index() { return "common/index2"; } @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST}, produces = "text/html") public String login(Model model, @RequestParam(name="errorMessage", required = false) String errorMessage) { model.addAttribute("errorMessage", errorMessage); return "common/login"; } @RequestMapping(value = "/main", method = RequestMethod.GET) public String main(Model model) { return "common/main"; } @RequestMapping(value = "/home", method = RequestMethod.POST, produces = "text/html") public String home(Model model, @RequestParam("username") String userName, @RequestParam("password") String password) { User user = new User(); String message = ""; user.setUsername(userName); //user.setPassword(EncryptPasswordUtil.encrytePassword(password)); user.setPassword(password); Map<String, String> messageMap = userService.validateUser(user); if (null != messageMap.get("id")) { user = userService.getDetail(messageMap.get("id")); model.addAttribute("user", user); } else { message = messageMap.get("message"); model.addAttribute("errorMessage", message); return "redirect:login?errorMessage="+message; } return "common/main"; } @RequestMapping(value = "/menu", method = RequestMethod.GET, produces = "text/html") public String menu(Model model) { return "common/menu"; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logoutSuccessfulPage(Model model) { model.addAttribute("title", "Logout"); model.addAttribute("logoutMessage", "Logout successfully at: " + new Date()); return "common/login"; } } <file_sep>package com.softhaxi.reflex.application; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** * * @author ivohutasoit * @since 1.0.0 */ @SpringBootApplication @Configuration @EnableAutoConfiguration @ComponentScan(basePackages = "com.softhaxi.reflex") public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { SpringApplication.run(Application.class, args); logger.info("Reflex aplication started..."); } } <file_sep>app.name=Reflex advance.filter=Advance Filter download=Download first.name=First Name home=Home i18n.english.us=English (US) i18n.indonesian=Indonesian name=Name last.name=Last Name reference.no=Reference Number register.now=Register Now search=Search sign.in=Sign In<file_sep>app.name=Reflex advance.filter=Pencarian download=Unduh first.name=<NAME> home=Beranda i18n.english.us=Inggris (US) i18n.indonesian=Bahasa Indonesia name=Nama last.name=<NAME> reference.no=Nomor Referensi register.now=Daftar Sekarang search=Cari sign.in=Masuk<file_sep># reflex-web Web user interface
631451a318fa93343e33b9187418ede074869835
[ "Markdown", "Java", "INI" ]
5
Java
ivohutasoit/reflex-web
f9544f3661574a51637a614e6948e74ab511478b
306531f887406d08028ae7b23786de8f6ec9785a
refs/heads/master
<file_sep>import javax.swing.*; import java.awt.*; import java.util.ArrayList; public class Point { //поля координат точки private int x; private int y; //поле flg boolean flg; //сетеры void setX(int x) { this.x = x; } void setY(int y) { this.y = y; } void setFlg(boolean flg) { this.flg = flg; } //гетеры int getXP() { return this.x; } int getYP() { return this.y; } boolean getFlg() { return this.flg; } //конструкторы Point() { this.x = 0; this.y = 0; flg = true; } Point(int x, int y) { this.x = x; this.y = y; flg = true; } //формат вывода @Override public String toString() { return "(" + this.x + ";" + this.y + ")"; } //убирает точку из доступных для рассмотрения void del() { this.flg = false; } }
a4acb6b33d810347502b9b3e5c125ab8deef4c01
[ "Java" ]
1
Java
SweetWeakness/Project
5548753c6343acc0bd1bd7b213c7c2c64522ee7d
a32241e06323ad2657eac6533c1b7f3cb30948ee
refs/heads/master
<repo_name>awead/shoutr<file_sep>/app/models/shout.rb class Shout < ApplicationRecord belongs_to :user belongs_to :content, polymorphic: true validates :user, presence: true delegate :username, to: :user # Models know a lot about SQL... or use query object # scope :search ->(term) { joins("LEFT JOIN text_shouts ON content_type = 'TextShout' AND content_id = text_shouts.id").where("text_shouts.body LIKE ?", term) } # Don't put SQL here # def self.search(term) # joins("LEFT JOIN text_shouts ON content_type = 'TextShout' AND content_id = text_shouts.id") # .where("text_shouts.body LIKE ?", term) # end searchable do text :content do case content when TextShout then content.body when PhotoShout then content.image_file_name end end end end <file_sep>/db/migrate/20181129174510_create_following_relationships.rb # This seems to be the missing migration that needs to be created during the video # at 7:25. # I started with: # # rails g model FollowingRelationship follower_id:integer followed_user_id:integer # # But then edited to reflect the changes below. I'm not sure if there's a syntax for the # model migration that creates the belongs_to methods right off the bat. class CreateFollowingRelationships < ActiveRecord::Migration[5.2] def change create_table :following_relationships do |t| t.belongs_to :follower t.belongs_to :followed_user t.timestamps end end end
2e86b9f2b691a9d51c4258dd6f293a99d9118194
[ "Ruby" ]
2
Ruby
awead/shoutr
a835962d0340543f5dc1e911c94a26caac7c7018
0033e7b5147c6af8433b921b83e7e414a7a8cd41
refs/heads/master
<repo_name>fisthu/vue-edit-json<file_sep>/README.md # Vue-edit-json > View and edit JSON as an vue component ## **[DEMO](http://fingerpich.github.io/vue-edit-json)** </br> ## Getting Started ``` npm install Vue-edit-json --save ``` </br> ## Usage ``` javascript //import it in your project At your entry point import vue from 'vue' import JsonEditor from 'Vue-edit-json' Vue.use(JsonEditor) ``` </br> Pass json data using `v-model` or `:value` and make it editable using `is-edit` attribute as the following code ``` html <JsonEditor is-edit="true" v-model="jsonData" ></JsonEditor> ``` <file_sep>/webpack.example.js const webpack = require('webpack'); const config = require('./webpack.base.config'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); config.entry = './example/main.js'; config.mode = 'development'; config.output = { path: path.resolve(__dirname, './example/dist/'), publicPath: '', filename: '[name]_[hash].js', }; config.plugins = (config.plugins || []).concat([ new HtmlWebpackPlugin({ // filename: './example/index.html', template: './example/index.html', inject: true, }), ]); module.exports = config;
7df0d3d566c9a536756378ecb94717e2fe69ed1f
[ "Markdown", "JavaScript" ]
2
Markdown
fisthu/vue-edit-json
6e5734a39c8268bb06410397760b5fb5230d6f1a
7992800f3be06d55c1f738bb85bcdbf2a89d3937
refs/heads/master
<file_sep>var rainbow = require('./index'); console.log(rainbow.addSuffix('page', '.png')); <file_sep>## javascript utils tool<file_sep> var rainbow = {}; module['exports'] = rainbow; rainbow.addSuffix = function(str, suffix) { if (!str) return ''; return str + suffix; }
77507c9bb39af77dfe74f55a645e963a8d5127e5
[ "JavaScript", "Markdown" ]
3
JavaScript
LeonaYoung/rainbow-red
ba5f521fff825e0c59b731ae5a7f31d7c4f37a8e
0203a0d7d91377c9ecd1a7b57a897f7eae4d46c0
refs/heads/master
<file_sep># WEB Design & Development Coursework ## University of Westminster, Department of Computer Science ### Assignment Specification (2018/19) **Deadline: Tuesday, 19 March 2019** 1. (Student 1) A presentation page with title and the name of everyone in the group. After 4 seconds, a second page will be displayed (Main Web page). 2. (Student 2) Your Main page should be designed so that the user can access several parts of the site. The links on your main page should look like buttons and have a hover effect. This should be created using CSS. 3. (Student 1) Use JavaScript to create the functionality to increase / decrease the font size used on the website. The basic functionality should include two buttons - a button to make the font size smaller and a button to make the font size larger (half allocated marks). Advanced functionality will allow for the font size to increase in steps up and down (full allocated marks). 4. (Student 2) Your site should contain a form to send comments about your web site. This form should include: * Input fields for users to enter their details (name, email address) * A field to enter comments * A way to rate your web site (using radio buttons or select) * Use JavaScript validation to check that the user has filled-in the compulsory fields - 'name' and 'rating'. Do NOT use HTML5 validation for this part. * If the name and ratings are filled-in, the user should get an HTML popup window with the summary including the name, any comments and rating given on the form. For example, if the user entered "John" for their name, rated the site as "good" and entered "Very informative website", the popup window should say something like: "Dear John, Thank you very much for your feedback. You have rated our site as **Good** and your comment was **Very informative website** ." 5. (Student 1) Your site should contain a form to allow people to buy products related to the topic of your web site, i.e. if your topic is football, you could be selling football shirts, accessories, etc. This should include: * Personal details * At least 3 different products to choose from; * Number of items for each product; * Automatically provide the total price of the bill. * Use JavaScript validation to check that the user has filled-in the following compulsory fields - personal details, product and number of items. Do NOT use HTML5 validation for this part. * If the compulsory fields are filled-in, when the 'place order' button is clicked, the user should get a popup window with the summary of the order. For example, the text in the popup window could be something like: "Dear John, you have ordered 2 T-shirts size M at a cost of £20 each and a pair of trainers at a cost of £50. Your total bill is £90." 6. (Student 4) Your site should contain a sitemap. The sitemap should have navigation links to the appropriate part of the group website, and should be developed in SVG. 7. (Student 3) Your site should contain an interactive multiple choice quiz about the subject you are developing on your Web site. Once the quiz has been completed, it gives the user a mark on how he/she performed. This should be time limited. When the quiz is finished should also display the summary of the user performance (which answers were correct or incorrect, and how long it took to complete the quiz). The user will get 2 marks for each correct answer, and -1 for each wrong answer. The quiz should consist of 10 questions. The background colour of the page should change according to the awarded mark. 8. (Student 4) Create a page that allows the user to view images. This page contains a form, 5 thumbnail images, and 2 pull-down menus (to select the page background colour and the page text colour) and an area to display a larger image and associated description of that image. When the user selects a thumbnail image, the corresponding large image and the description of that image should display in the defined location on the form. You may use onMouseOver or radio buttons to select the thumbnail. 9. (Student 3) Your main page should contain four pictures of the members of the group. When the user moves the mouse over one picture, the details of that member should be displayed in an area on the page (for example, you could use a div below the pictures). The details should include the name and role that that student took for the coursework (e.g. <NAME>, Student 1). 10. Consistency of style should be ensured using * A unique external style sheet file main page and navigation(Student 2) * Used throughout the web site (all students) 11. (All students) Your site should contain a link to a CV for each member of your group. This should be a complete CV (written in html) similar to one you would present to a potential employer. Your CV should have your picture at the top right hand-side corner. This page is external to the group website and therefore on this occasion does not need to follow the design of the main website. 12. (All students) Any page longer than the screen size should have links to various parts of the text at the top of the page. 13. (All students) Each page should include your title logo at the top, and a link to the page editor (the person who wrote the page) at the bottom of the page. (E.g., here you could make a link to the CV of the person who created that page). 14. (All students) Feel free to use additional JavaScript to add interactivity and increase ease of navigation. <file_sep>//GLOBAL VARIABLES const games = [ { "name": "GOD_OF_WAR", "pc": 8000, "ps": 12000, "xbox": 13000, }, { "name": "COD", "pc": 6300, "ps": 7400, "xbox": 8333, }, { "name": "FIFA", "pc": 9000, "ps": 10000, "xbox": 10000, }, { "name": "TOMB_RIDER", "pc": 8799, "ps": 10000, "xbox": 8922, }, { "name": "CRICKET", "pc": 5600, "ps": 7800, "xbox": 80000, }, { "name": "OVERWATCH", "pc": 9000, "ps": 9500, "xbox": 9800, }, { "name": "GTA", "pc": 5000, "ps": 6700, "xbox": 7500, }, { "name": "GEAR_OF_WAR", "pc": 7500, "ps": 8000, "xbox": 12000, }, { "name": "PUBG", "pc": 2300, "ps": 4500, "xbox": 4600, }, { "name": "FORTNITE", "pc": 2300, "ps": 5500, "xbox": 5550, }, { "name": "CREED", "pc": 8700, "ps": 9288, "xbox": 7500, }, { "name": "WITCHER", "pc": 8900, "ps": 12000, "xbox": 13500, } ] let modal = document.getElementById('buyProductsModal'); let span = document.getElementsByClassName("close")[0]; let emailText = false let nameText = false let phoneNumberText = false let addressText = false let selectedValue = "" let invalidOperators = ["@","!","$","%","^","&","*","=","<",">","?","|","}","{","*","&"] //Function to get the Radio Values const getRadioValue = (radioArray) => { let i; let x = document.getElementById("AddressContent"); for (i = 0; i < radioArray.length; i++) { if (radioArray[i].checked) { //console.log(radioArray[i].value); if(radioArray[i].value == "Delivery"){ selectedValue = "Delivery"; x.style.display = "block"; }else{ selectedValue="Reserve"; x.style.display = "none"; } return radioArray[i].value; } } return ""; } //Function for Validation const validations = (id,promptMessage,promptId,promptColor,typeOfRegex) => { let values = document.getElementById(id).value; if(values.length == 0){ producePrompt(promptMessage,promptId,promptColor) }else{ if(typeOfRegex == "names"){ if(!values.match(/^[a-zA-Z\s]+$/)){ producePrompt("Please Enter a Valid name", "promptName", "red"); return false; } else { producePrompt("&#10003", "promptName", "green"); nameText = true } } if(typeOfRegex == "phoneNo"){ if(!values.match(/[+]947\d{8}$/)){ producePrompt("Please Enter a Valid phone Number", "promptnumber", "red"); return false; }else{ producePrompt("&#10003", "promptnumber", "green"); phoneNumberText = true } } if (typeOfRegex == "emails"){ if(!values.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)){ producePrompt("Please Enter a Valid Email", "promptemail", "red"); return false; } else { producePrompt("&#10003", "promptemail", "green"); emailText = true } } if (typeOfRegex == "address"){ if(invalidOperators.includes(values.slice(-1))){ producePrompt("Please Enter a Valid Address", "promptAddress", "red"); return false; }else{ producePrompt("&#10003", "promptAddress", "green"); addressText = true } } if(typeOfRegex == ""){ return } } } //Function to produce Prompts const producePrompt = (message,promptLocation,color) => { document.getElementById(promptLocation).innerHTML = message; document.getElementById(promptLocation).style.color = color; } //Function to add +94 When clicked on a text box const addInitials = (id) => { let val = document.getElementById(id).value; if (val == ""){ document.getElementById(id).value = '+94' } } //Submit Button Clicked const submitClicked = (chooseGames,gamingPlatform) => { //Selected Games let selectedGames = []; let i; for(i=0;i<chooseGames.length;i++) { if(chooseGames[i].checked) { selectedGames.push(chooseGames[i].value); } } //Selected Platform let selcetedPlatform = []; let j; for (j = 0; j < gamingPlatform.length; j++) { if (gamingPlatform[j].checked) { selcetedPlatform.push(gamingPlatform[j].value) } } //Call the function to Calculate Total Price const toatlPrice = getTotalPrice(selectedGames,selcetedPlatform); //varible to set error messages let errorMessage = ""; let radioVal = getRadioValue("orderType"); if(document.getElementById("name").value == ""){ errorMessage += "Please Enter Your Name \n"; }else{ if(nameText == false){ return false } } if(document.getElementById("email").value == ""){ errorMessage += "Please Enter Your Email \n"; }else{ if(emailText == false){ return false } } if(document.getElementById("number").value == ""){ errorMessage += "Please Enter Your PhoneNumber \n"; }else{ if(phoneNumberText == false){ return false } } if (selectedValue == ""){ errorMessage += "Should we deliver or are you reserving \n"; }else{ if(selectedValue == "Delivery"){ if(document.getElementById("address").value == ""){ errorMessage += "Please Enter Your Address For Us To Deliver \n"; }else{ if(addressText == false){ return false } } } } // if(radioVal == ""){ // errorMessage += "Should we deliver or are you reserving \n"; // }else{ // if(radioVal == "Delivery"){ // if(document.getElementById("address").value == ""){ // errorMessage += "Please Enter Your Address For Us To Deliver \n"; // } // } // } if (selcetedPlatform.length == 0){ errorMessage += "Please Select a Platform For Your Game\n"; } if(selectedGames.length == 0){ errorMessage += "Please Select a Game\n"; } if(errorMessage != ""){ alert(errorMessage); return false; }else{ modal.style.display = "block"; let name = document.getElementById("name").value document.getElementById("buyProductName").innerHTML = name document.getElementById("TotalPrice").innerHTML = "Your Total Price is Rs." + toatlPrice+".00"; document.getElementById("TotalPrice").style.fontWeight = 'bolder'; document.getElementById("TotalPrice").style.fontSize = '20px'; createGamesList(selectedGames,selcetedPlatform) } document.getElementById("purchaseForm").reset(); selcetedPlatform = [] selectedGames = [] } //Function to display the pop up span.onclick = () => { modal.style.display = "none"; } window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } } //Function for dismissing popup[] dismiss = () => { document.getElementById("purchaseStatement").innerHTML = "Thank You For Purchasing, Please wait until Purchase is made" document.getElementById("loader11").style.display = "inline-block" setTimeout(() => { window.location.href = '../HomePage/Home.html'; modal.style.display = "none"; },4000) } //Function to calculate the Total Price const getTotalPrice = (selectedGames,selectedPlatform) => { let totalPrice = 0; let noOfPlatform = selectedPlatform.length let gamesArray = [...games]; if (noOfPlatform == 1){ for(let platform of selectedPlatform){ if(platform == "PC"){ for(let value of selectedGames){ for(let val of gamesArray){ if(value == val.name){ totalPrice = totalPrice + val.pc; } } } }else if(platform == "PS"){ for(let value of selectedGames){ for(let val of gamesArray){ if(value == val.name){ totalPrice = totalPrice + val.ps; } } } }else{ for(let value of selectedGames){ for(let val of gamesArray){ if(value == val.name){ totalPrice = totalPrice + val.xbox; } } } } } } if(noOfPlatform == 2){ if((selectedPlatform.includes("PC")) && (selectedPlatform.includes("PS"))){ for(let value of selectedGames){ for(let val of gamesArray){ if(value == val.name){ totalPrice = totalPrice + val.ps + val.pc } } } }else if((selectedPlatform.includes("PC"))&&(selectedPlatform.includes("XBOX"))){ for(let value of selectedGames){ for(let val of gamesArray){ if(value == val.name){ totalPrice = totalPrice + val.pc + val.xbox } } } }else if((selectedPlatform.includes("PS"))&&(selectedPlatform.includes("XBOX"))){ for(let value of selectedGames){ for(let val of gamesArray){ if(value == val.name){ totalPrice = totalPrice + val.ps + val.xbox } } } } } if(noOfPlatform == 3){ for(let value of selectedGames){ for(let val of gamesArray){ if(value == val.name){ totalPrice = totalPrice + val.ps + val.pc + val.xbox } } } } return totalPrice; } //Function to render a dynamic game list in the popup const createGamesList = (selectedGames,selectedPlatform) => { let span = document.createElement('span') selectedPlatform.map((x => { console.log(x) let node = document.createTextNode(x); let node2 = document.createTextNode("/"); span.appendChild(node); span.appendChild(node2); let el = document.getElementById("SelectedPlatform").appendChild(span) })) for(let val of selectedGames){ let listItem = document.createElement("li"); let node = document.createTextNode(val); listItem.appendChild(node); let element = document.getElementById("purchasedList"); element.appendChild(listItem); } } //Function to increase the font size const increaseFont = () => { bodyId = document.getElementById('buyProductsBody'); style = window.getComputedStyle(bodyId, null).getPropertyValue('font-size'); currentSize = parseFloat(style); if(currentSize == 20){ return }else{ bodyId.style.fontSize = (currentSize + 1) + 'px'; } } //function to decrease the font size const decreaseFont = () => { bodyId = document.getElementById('buyProductsBody'); style = window.getComputedStyle(bodyId, null).getPropertyValue('font-size'); currentSize = parseFloat(style); if(currentSize == 8){ return }else{ bodyId.style.fontSize = (currentSize - 1) + 'px'; } } //Reset to default font size const resetDefaultFont = () => { bodyId = document.getElementById('buyProductsBody'); style = window.getComputedStyle(bodyId, null).getPropertyValue('font-size'); currentSize = parseFloat(style); currentSize = 16 bodyId.style.fontSize = (currentSize) + 'px'; } //SLIDE SHOW var slideIndex = 1; showSlides(slideIndex); // Next/previous controls function plusSlides(n) { showSlides(slideIndex += n); } // Thumbnail image controls function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); if (n > slides.length) {slideIndex = 1} if (n < 1) {slideIndex = slides.length} for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } slides[slideIndex-1].style.display = "block"; }<file_sep>const quizContainer = document.getElementById("quiz"); const resultsContainer = document.getElementById("results"); const wrongAnswerContainer = document.getElementById("wrongAnswer"); const submitButton = document.getElementById("submit"); const startButton = document.getElementById("start"); const retryButton = document.getElementById("retry"); let remainingSeconds = 600; let consumedSeconds = 0; let interval; //To store the wrong answer const wrongAnswer = []; function hideVisibilityInstructions() { document.getElementById("quiz-body-questions").style.display = 'block'; document.getElementById("quiz-body-instructions").style.display = 'none'; interval = setInterval(function(){ if (remainingSeconds === 600) { document.getElementById("time").innerHTML=`${Math.floor(remainingSeconds/60)} : 0${remainingSeconds%60}`; } else if (remainingSeconds%60<10) { document.getElementById("time").innerHTML=`0${Math.floor(remainingSeconds/60)} : 0${remainingSeconds%60}`; } else { document.getElementById("time").innerHTML=`0${Math.floor(remainingSeconds/60)} : ${remainingSeconds%60}`; } remainingSeconds--; consumedSeconds++; if (remainingSeconds === 0){ clearInterval(interval); showResults(remainingSeconds); } }, 1000); } function tryAgain() { window.location.href = "QuizUI.html"; } function buildQuiz(){ //Stores the HTML output const output = []; //For each question... myQuestions.forEach( (currentQuestion, questionNumber) => { //Stores the list of answer choices const answers = []; //For each available answer... for(let letter in currentQuestion.answers){ //...Adds an HTML radio button answers.push( `<label> <input type="radio" name="question${questionNumber}" value="${letter}"> ${letter} : ${currentQuestion.answers[letter]} </label>` ); } //Adds this question and its answers to the output output.push( `<div class="quiz-slide"> <div id="number" class="quiz-paragraph">Question ${questionNumber+1} of ${myQuestions.length}</div> <div class="quiz-heading2"> ${currentQuestion.question} </div> <div class="quiz-paragraph-answers"> ${answers.join("")} </div> </div>` ); } ); //Combines the output list into one string of HTML and put it on the page quizContainer.innerHTML = output.join(''); } function showResults(){ clearInterval(interval); document.getElementById("quiz-body-questions").style.display = 'none'; document.getElementById("quiz-body-summary").style.display = 'block'; //Gather answer containers from the quiz const answerContainers = quizContainer.querySelectorAll('.quiz-paragraph-answers'); //Keeps track of user's answers let numCorrect = 0; let numWrong = 0; //For each question... myQuestions.forEach( (currentQuestion, questionNumber) => { //Find selected answer const answerContainer = answerContainers[questionNumber]; const selector = `input[name=question${questionNumber}]:checked`; const userAnswer = (answerContainer.querySelector(selector) || {}).value; //"{}" Initializing an empty object to deal with empty answers //Checks if answer is correct or wrong if(userAnswer === currentQuestion.correctAnswer){ //Add to the number of correct answers numCorrect++; } else{ //Add to the number of wrong answers numWrong++; wrongAnswer.push( `<div class="quiz-paragraph">• ${currentQuestion.question}</div>` ) } }); if (numCorrect>=5) { document.body.style.backgroundColor = "MediumSeaGreen"; } else { document.body.style.backgroundColor = "Tomato"; } //Shows the number of correct answers out of the total resultsContainer.innerHTML = `You've got ${numCorrect} answers correct out of ${myQuestions.length}<br/>and have achieved ${(numCorrect*2)-(numWrong)} points`; //Combines the wrongAnswer list into one string of HTML and put it on the page wrongAnswerContainer.innerHTML = wrongAnswer.join(''); if (consumedSeconds === 600) { document.getElementById("timeSummary").innerHTML=`${Math.floor(consumedSeconds/60)} : 0${consumedSeconds%60}`; } else if (consumedSeconds%60<10) { document.getElementById("timeSummary").innerHTML=`0${Math.floor(consumedSeconds/60)} : 0${consumedSeconds%60}`; } else { document.getElementById("timeSummary").innerHTML=`0${Math.floor(consumedSeconds/60)} : ${consumedSeconds%60}`; } } function showSlide(n) { slides[currentSlide].classList.remove("quiz-slide-active"); slides[n].classList.add("quiz-slide-active"); currentSlide = n; if (currentSlide === 0) { previousButton.style.display = "none"; } else { previousButton.style.display = "inline-block"; } if (currentSlide === slides.length - 1) { nextButton.style.display = "none"; submitButton.style.display = "inline-block"; } else { nextButton.style.display = "inline-block"; submitButton.style.display = "none"; } } function showNextSlide() { showSlide(currentSlide + 1); } function showPreviousSlide() { showSlide(currentSlide - 1); } //Displays the Quiz instantly buildQuiz(); //Pagination const previousButton = document.getElementById("previous"); const nextButton = document.getElementById("next"); const slides = document.querySelectorAll(".quiz-slide"); let currentSlide = 0; showSlide(0); submitButton.addEventListener('click', showResults); previousButton.addEventListener("click", showPreviousSlide); nextButton.addEventListener("click", showNextSlide); startButton.addEventListener("click", hideVisibilityInstructions); retryButton.addEventListener("click", tryAgain); <file_sep>window.onscroll = function () { showHideNavBar() }; var navbar = document.getElementById("navbar"); var sticky = navbar.offsetTop; function showHideNavBar() { if (window.pageYOffset >= sticky) { navbar.classList.add("sticky") document.getElementById("navbartitle-li").innerHTML = "<a href=\"../HomePage/Home.html\"><img src=\"../Assets/Images/Gameradar.png\" class=\"main-logo\"/></a>"; } else { navbar.classList.remove("sticky"); document.getElementById("navbartitle-li").innerHTML = " "; } if ((window.innerHeight + window.scrollY + 400) >= document.body.offsetHeight) { document.getElementById('navbar').style.display = 'none'; } else { document.getElementById('navbar').style.display = ''; } }
2cdcfa0670d8efe49cc28dd413f159c540ddec2a
[ "Markdown", "JavaScript" ]
4
Markdown
mfmsajidh/IIT-WEB-CW2
0915ab569ab0df8c3abc60b334617d9e840830d7
ceee98a258597af9bdeafcf4363939f266995eee
refs/heads/master
<repo_name>ko8/bonus-drink<file_sep>/bonus_drink.rb class BonusDrink def self.total_count_for(amount) bonus = amount while bonus >= 3 amount += (bonus / 3) bonus = (bonus % 3) + (bonus / 3) end amount end #begin # print "0,", BonusDrink.total_count_for(0),"\n" # print "1,", BonusDrink.total_count_for(1),"\n" # print "3,", BonusDrink.total_count_for(3),"\n" # print "4,", BonusDrink.total_count_for(4),"\n" # print "5,", BonusDrink.total_count_for(5),"\n" # print "6,", BonusDrink.total_count_for(6),"\n" # print "7,", BonusDrink.total_count_for(7),"\n" # print "8,", BonusDrink.total_count_for(8),"\n" # print "11,", BonusDrink.total_count_for(11),"\n" # print "100,", BonusDrink.total_count_for(100),"\n" #end end
ea92cb556bdbac0617d79e92ac637ba92310af8b
[ "Ruby" ]
1
Ruby
ko8/bonus-drink
89e5fd81f3262145a1cea880f1719a930eacdbd2
5a9d9cb6464edd41965d7a1166db90f4bb17742c
refs/heads/master
<repo_name>dspim/Hfoundation-Troubled-Family-Risk-Profiling<file_sep>/Analysis/10_descriptive_statistic_of_risk_factors_assessment.R library(ggplot2) library(dplyr) ## ## Attaching package: 'dplyr' ## The following objects are masked from 'package:stats': ## ## filter, lag ## The following objects are masked from 'package:base': ## ## intersect, setdiff, setequal, union rf <- read.csv("SummaryRisk.csv",header = TRUE,fileEncoding = "BIG5") rf <- mutate(rf,風險編號2 = substring(rf$風險編號,0,1)) factor <- filter(rf,風險編號2 != "N") factor <- filter(factor,風險編號2 !="") table(factor$風險編號2) ## ## A B C D E F G ## 401 727 565 158 26 327 154 ggplot(factor,aes(x = 風險編號2,fill = 風險編號2)) +geom_bar() + theme(text = element_text(family = "楷體-繁 黑體",size = 10))+ scale_fill_discrete(name="Riskfactor",breaks=c("A", "B", "C","D","E","F","G"), labels=c("經濟功能", "教育功能","保護與照護功能","居住安全","生育功能","情感功能","其它")) # Factor A A <- filter(rf,風險編號2 == "A") ggplot(rfc_A,aes(x = 風險編號,fill = 風險編號)) + geom_bar() + theme(text = element_text(family = "楷體-繁 黑體",size = 7)) # Factor B rfc_B <- filter(rf,風險編號2 == "B") ggplot(rfc_B,aes(x = 風險編號,fill = 風險編號)) + geom_bar() + theme(text = element_text(family = "楷體-繁 黑體",size = 7)) # Factor C rfc_B <- filter(rf,風險編號2 == "B") ggplot(rfc_B,aes(x = 風險編號,fill = 風險編號)) + geom_bar() + theme(text = element_text(family = "楷體-繁 黑體",size = 7)) # Factor D rfc_B <- filter(rf,風險編號2 == "B") ggplot(rfc_B,aes(x = 風險編號,fill = 風險編號)) + geom_bar() + theme(text = element_text(family = "楷體-繁 黑體",size = 7)) # Factor E rfc_B <- filter(rf,風險編號2 == "B") ggplot(rfc_B,aes(x = 風險編號,fill = 風險編號)) + geom_bar() + theme(text = element_text(family = "楷體-繁 黑體",size = 7)) # Factor F rfc_B <- filter(rf,風險編號2 == "B") ggplot(rfc_B,aes(x = 風險編號,fill = 風險編號)) + geom_bar() + theme(text = element_text(family = "楷體-繁 黑體",size = 7)) # Factor G rfc_B <- filter(rf,風險編號2 == "B") ggplot(rfc_B,aes(x = 風險編號,fill = 風險編號)) + geom_bar() + theme(text = element_text(family = "楷體-繁 黑體",size = 7)) <file_sep>/Analysis/21_markchainfun.R ################## sumMoth combine month data ## you can try 'new_sparse_data.csv' # data <- read.csv('new_sparse_data.csv') # ex: sumMonth(data) sumMonth <- function(data){ A <- matrix(0, nrow = 1, ncol = ncol(data)) colnames(A) <- colnames(data) Id <- levels(data[, 1]) for (i in 1:length(Id)){ iddata <- data[ data[, 1] == Id[i], 1:ncol(data)] date <- as.Date(iddata[, 2]) ym <- format(date, '%y%m') count1 <- table(ym) levelsym <- levels(factor(ym)) newcadata <- sapply(1:length(levelsym), FUN = function(x){ nu <- count1[levelsym[x]] if(nu > 1){ submndata <- iddata[ ym == levelsym[x], 3:ncol(data) ] L <- apply(submndata, 2, sum) class(L) L[L!=0] = 1 L <- as.integer(L) ve <- L }else{ submndata <- iddata[ ym == levelsym[x], 3:ncol(data) ] ve <- as.integer(submndata) } return(ve) }) PP <- data.frame('ID'=rep(Id[i], length(levelsym) ),'Date'=paste(1, levelsym,sep=''), t(newcadata) ) colnames(PP) <- colnames(data) A <- rbind(A, PP) } A <- data.frame( A[-1, ] ) return(A) } ##### transprob function can calulate parmeters of markov chain # ex : monthdata <- sumMonth(data) # transprob(monthdata) transprob <- function(data){ Id <- levels(factor( data[, 1] ) ) data1 <- data[, 3:ncol(data)] chlidnames <- data[, 1] sum1 <- apply(data1, 2, sum) nonzeros <- which(sum1 != 0) trcount <- t( sapply(1:length(nonzeros) , FUN = function(i){ cadata <- data1[, nonzeros[i]] apply( sapply(1:length(Id), FUN = function(j){ idcadata <- cadata[ chlidnames == Id[j]] if(length(idcadata) > 1){ count <- apply( sapply(1:(length(idcadata)-1), FUN = function(x){ xbt <- idcadata[x] xnt <- idcadata[(x+1)] if (xbt == 0 & xnt == 0){ y <- c(1, 0, 0, 0) }else if(xbt == 0 & xnt == 1){ y <- c(0, 1, 0, 0) }else if(xbt == 1 & xnt == 0){ y <- c(0, 0, 1, 0) }else{ y <- c(0, 0, 0, 1) } return(y) }),1, sum)} else{count <- rep(0, 4)} return(count) }), 1, sum) }) ) trprob <- sapply(1:length(nonzeros), FUN = function(x){ if ( sum(trcount[x, 1:2] ) != 0 & sum(trcount[x, 3:4] ) != 0 ){ c( trcount[x, 1:2] / sum(trcount[x, 1:2] ), trcount[x, 3:4] / sum(trcount[x, 3:4]) ) }else if(sum(trcount[x, 1:2] ) != 0 & sum(trcount[x, 3:4] ) == 0 ){ c( trcount[x, 1:2] / sum(trcount[x, 1:2] ), rep(0, 2) ) }else if( sum(trcount[x, 1:2] ) == 0 & sum(trcount[x, 3:4] ) != 0 ) { c( rep(0, 2), trcount[x, 3:4] / sum(trcount[x, 3:4]) ) } }) rownames(trprob) <- c('0-0', '0-1', '1-0', '1-1') colnames(trprob) <- colnames( data1)[nonzeros] return(t( trprob) ) } <file_sep>/App/ui.R library(shinydashboard) library(plotly) load("loading.RData") dashboardPage(skin = "green", dashboardHeader( title = "D4SG X 漢慈" ), dashboardSidebar( selectInput("dataset", label ="個案代號:", choices = names), sidebarMenu( menuItem("歷史資料", tabName = "past", icon = icon("address-book-o"), menuItem("風險因子警示燈號", tabName = "light", icon = icon("lightbulb-o")), menuItem("風險因子組成比例", tabName = "pie", icon = icon("pie-chart")), menuItem("各類風險因子出現頻率", tabName = "bar", icon = icon("bar-chart")), menuItem("風險因子變化趨勢", tabName = "time", icon = icon("line-chart")) ), menuItem("此次資料", tabName = "present", icon = icon("user-o")), menuItem("未來風險預測", tabName = "future", icon = icon("user-circle")) ) ), dashboardBody( tabItems( tabItem(tabName = "past", h2("Pesent!") ), tabItem(tabName = "light", fluidRow( box( title = "歷史風險因子警示燈號", status = "primary", solidHeader = TRUE, width = 12, collapsible = TRUE, height=5, plotlyOutput("TimeRiskLevels") ) ) ), tabItem(tabName = "pie", fluidRow( box( title = "風險因子組成比例", status = "primary", solidHeader = TRUE, width = 12, collapsible = TRUE, plotlyOutput("Pie_Chart_new") ) ) ), tabItem(tabName = "bar", fluidRow( tabBox( title = "各類風險因子出現頻率", side = "right", width = 12, id = "tabset1", tabPanel('其他', plotlyOutput("Hist_G")), tabPanel('情感', plotlyOutput("Hist_F")), tabPanel('生育', plotlyOutput("Hist_E")), tabPanel('居住', plotlyOutput("Hist_D")), tabPanel('保護&照顧', plotlyOutput("Hist_C")), tabPanel('教育', plotlyOutput("Hist_B")), tabPanel('經濟', plotlyOutput("Hist_A")) ) ) ), tabItem(tabName = "time", fluidRow( box(title = "主要風險因子", status = "info", solidHeader = TRUE, width=4, uiOutput("datavars") ), box( title = "風險因子變化", status = "warning", solidHeader = TRUE, width =8, plotlyOutput("TimeplotNew") ) ) ), tabItem(tabName = "present", fluidRow( valueBoxOutput(outputId = "RecentIntViewTime", width = 3), valueBoxOutput(outputId = "FollowPeriod", width = 3), box(title = "時間區間選擇", status = "info", solidHeader = TRUE, uiOutput("TimePeriodChoose"))), fluidRow( box(title = "現在發生危險因子", status = "info", solidHeader = TRUE, width = 4, DT::dataTableOutput("RecentRiskFactor")), box(title = "潛在發生危險因子", status = "info", solidHeader = TRUE, width = 4, DT::dataTableOutput("PossibleRiskFactor")), box(title = "未來發生危險因子", status = "info", solidHeader = TRUE, width = 4) ) ), tabItem(tabName = "future", h2("Future!") ) ) ) )<file_sep>/Preprocess/01_parse_risk_factor_csv_into_spread_sheet.py #!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sun Jan 22 00:37:53 2017 @author: kevin """ import pandas as pd import re #read the file data = pd.read_csv('/Users/kevin/D4SG/SummaryRisk.csv', header=0, encoding='Big5').iloc[:,[0,1,3]] data.columns = ['Id', 'Date', 'Category'] #deal with the colunm : Id data['Id'] = map(lambda x: str(x[:3]), data['Id']) #deal with the colunm : Category for i in range(len(data)): try: if re.match('\w\d{2}', data['Category'][i]) is not None: data['Category'][i] = data['Category'][i][0] + '-' + data['Category'][i][1:3] elif data['Category'][i] == 'None': data['Category'][i] = float('nan') except: data['Category'][i] = float('nan') data = data[data['Category'].notnull()] data.index = range(len(data)) #deal with the colunm : Date df_b = pd.DataFrame() pat = ['\d{3}.\d{1,2}.\d{1,2}', '\d{3}/\d{1,2}/\d{1,2}'] for i in range(len(data)): if pd.isnull(data['Date'][i]) or data['Date'][i] == u'同上': data['Date'][i] = float('nan') else: if re.match(pat[0], data['Date'][i]) is not None: if len(re.findall(pat[0], data['Date'][i])) == 1: data['Date'][i] = '/'.join(map(lambda x: x.zfill(2), str(re.findall(pat[0], data['Date'][i])[0]).split('.'))) else: tmp = [] for j in range(2): tmp.append('/'.join(map(lambda x: x.zfill(2), str(re.findall(pat[0], data['Date'][i])[j]).split('.')))) data['Date'][i] = tmp[0] tmp_data = pd.DataFrame(data.ix[i, :]).transpose() tmp_data['Date'] = tmp[1] df_b = df_b.append(tmp_data) elif re.findall(pat[1], data['Date'][i]) is not None: if len(re.findall(pat[1], data['Date'][i])) == 1: data['Date'][i] = str(data['Date'][i]) else: tmp = [] for j in range(2): tmp.append(map(lambda x: str(x), re.findall(pat[1], data['Date'][i]))[j]) data['Date'][i] = tmp[0] tmp_data = pd.DataFrame(data.ix[i,:]).transpose() tmp_data['Date'] = tmp[1] df_b = df_b.append(tmp_data) data = data.fillna(method='ffill') #data processing df_a = pd.DataFrame() for i in df_b.index: risk_cat = data[data['Date']==data.ix[i]['Date']][data['Id']==data.ix[i]['Id']]['Category'] df_b_tmp = df_b.ix[i, :].to_frame().transpose() df_a_tmp = pd.concat([df_b_tmp.drop('Category', axis=1), risk_cat], axis=1, join='outer').fillna(method='ffill') df_a = df_a.append(df_a_tmp) df_a = df_a.fillna(method='bfill') data_tmp = data.append(df_a).sort(['Id', 'Date']).drop_duplicates(['Id', 'Date', 'Category'], keep='first') final_data = pd.DataFrame(data_tmp.values.tolist(), columns=['Id', 'Date', 'Category']) col_list = [] for i, j in [('A', 46), ('B', 40), ('C', 43), ('D', 11), ('E', 5), ('F', 15), ('G', 25)]: col_list = col_list + [i+"-"+"%.2d" % j for j in range(1, j+1)] drop_list = [] for i in range(len(final_data)): if final_data['Category'][i] not in col_list: drop_list.append(i) final_data = final_data.drop(final_data.index[drop_list]) final_data = final_data.set_index(['Id', 'Date']) #create Sparse-form data spar_mat = pd.DataFrame(0, index=final_data.index, columns=col_list).groupby(level=[0, 1]).first() for i in range(len(final_data)): spar_mat.loc[final_data.index[i]][final_data.ix[i, 'Category']] = 1 <file_sep>/Preprocess/00_parse_risk_factor_into_csv.R library(dplyr) library(plyr) library(data.table) # a "real" Word doc path <- "C:/Users/USER/Desktop/資料英雄" setwd(path) RiskUrl = list.files("會談風險因子") RiskUrl = RiskUrl[-grep("~",RiskUrl)] TimeTran = function(time){ NA_index = which(time!="") s = cut(1:length(time), breaks = c(NA_index,NA_index[length(NA_index)]+1),include.lowest =T,right =F,labels = time[NA_index]) s = as.POSIXlt(as.Date(as.character(s))) s$year =s$year + 1911 s = as.Date(s) return(s) } RiskList=lapply(RiskUrl,function(file_name){ real_world_risk <-read_docx(paste0("會談風險因子/",file_name)) print(file_name) if(docx_tbl_count(real_world_risk)!=1){ print (paste0(docx_tbl_count(real_world_risk)," : ",file_name)) } Table_Risk <- lapply(1:docx_tbl_count(real_world_risk),function(i){ docx_extract_tbl(real_world_risk,i,header=F) }) Table_Risk = do.call(rbind,Table_Risk) Table_Risk = Table_Risk %>% filter(V1!="會談日期") Table_Risk = Table_Risk[!apply(Table_Risk =="",1,all),] Table_Risk =cbind(name = file_name,Table_Risk) #Table_Risk$V1TimeTran return(Table_Risk) } ) SummaryRisk = do.call(rbind,RiskList) colnames(SummaryRisk) = c("name","會談日期","風險等級","風險編號","風險編號說明","處遇編號", "處遇說明說明","會談社工" ,"會談志工","會談老師","會談其他","處遇社工","處遇日期","會談地點","備註") write.csv(SummaryRisk,"SummaryRisk.csv",row.names = F) <file_sep>/README.md # Applying Data Science For Social Good In Nonprofit Organization With Troubled Family Risk Profiling R Dashboard Application ## author <NAME><sup>1</sup>,<NAME><sup>2</sup>,<NAME><sup>3</sup>,<NAME><sup>4</sup>,Ning-<NAME>yu<sup>5</sup>,Ting-<NAME><sup>6</sup>,Shing-<NAME><sup>7</sup>,<NAME><sup>8</sup>,<NAME><sup>9</sup>,Chun-Yu Yin<sup>8</sup>,<NAME><sup>10,11</sup> 1. Genome and Systems Biology Degree Program, National Taiwan University and Academia Sinica 2. TAO Info Co.Ltd 3. inQ Technology Co.Ltd 4. Pegatron Co.Ltd 5. Department of Electrical Engineering, National Tsing-Hua University 6. Department of applied mathematics, Feng Chia University 7. Department of Computer Science, National Tsing-Hua University 8. Hfoundataion 9. NETivism Co.Ltd 10. Department of Computer Science, National Chengchi University 11. DSP Co.Ltd **Keywords**: troubled family risk profiling, data science for social good, association rule analysis, steady-state analysis, topic model, shiny application **Webpages**: https://weitinglin.shinyapps.io/d4sg_dashboard_v1/ # Abstract Assessing the troubled families risk status and distributing the resources appropriately is a big issue for nonprofit organizations, not to mention the national program like UK Trouble Families Program^1^. Unfortunately, those organizations and national programs still use the conventional way to deal with these problems^2^. As the increasing demands for social assistance and longterm shortage of social workers in these field, a more precise and continuous way to handle the social resources wisely and efficiently is needed. Besides, the junior social workers are hard to quickly get a hang of several families through lots of interview records and past documents, then decide whether providing their intervention. And most importantly of all, they lack of ability to utilize those information with proper data engineering and summarize those experience through data analysis. So here We first apply a evidence-based approach on assessing the troubled families's risk status with a *R* dashboard application integrated the prediction model generated from those families archives, follow-up records under the Data Science For Social Good Program in Taiwan with the cooperation between a volunteer data science team and local nonprofit organization HFoundation. In the beginning, the organization and volunteer data science team use customer journey analysis to map the social worker's experience and organization workflow in order to understand how organization generate their different types of data and define the proper scale of framework in dealing with their problems. Overall, There are now 57 families accepted active aid by organization and with maximum following time up to 6 years. The documents from these families have basic socioeconomic information, following interview records from home visits with various follow-up time by the social workers, mainly text files. After de-identification of those documents, we preprocess their family archives and cases follow-up interview into suitable format for further management. Then, We use risk factors system to tag each home visit interview events in order to create family risk prediction model. There are seven major risk factors categories range from financial problems to housing problems. And we also use topic model to extract more information related to those risk factors from families archives. Then, we use association rule analysis in those home visit records during these 6 years and discuss the result rules to the senior social workers and in the same time the steady state analysis with Markov chain were performed to calculate recurrence rate of high risk factors for each home visit event. Those result can help to detect possible underline risk factors and predict the possible recurrence rate for each risk factors from recent family status. The dashboard shiny application was build with the above analysis result to assist the social worker on their daily work in recognizing the possible risk factors from those troubled families and prioritizing their resources to manage families high recurrence risk factors. The application provide a overview visualization of each case's family data in timeline with risk factors and basic summary statistic. Social workers can easily get the insights from cases families past records and know the possible underline risk factors with the association rules and decide which families's problems should tackle first with the highest recurrence rate predicted from the model. In addition, the social workers can input their home visit or interview data into the application which can update the model and become their day-to-day working tools and make their workflow more efficiently and precisely. In the end, the high-risk family profiling R dashboard application can be a great tool to provide those nonprofit organizations, not only HFoundation, in these field to precisely and efficiently manage their family cases and prioritizing their resources on managing families problems. # References 1. <NAME>, <NAME>, <NAME>, <NAME>.(2012). The British government’s Troubled Families Programme. BMJ2012;344:e3403. doi: https://10.1136/bmj.e3403 2. <NAME>, <NAME>.(2016). <NAME>. Troubled families, troubled policy making. BMJ 2016; 355 doi: https://doi.org/10.1136/bmj.i5879 <file_sep>/App/server.R load("loading1.RData") load("relationship_association.Rdata") library(shiny) library(ggplot2) library(gridExtra) library(grid) library(plotly) library(magrittr) library(purrr) library(lubridate) library(stringr) library(dplyr) risk_mapping_table$dscpt = iconv(as.character(risk_mapping_table$dscpt), from = 'UTF-8') high_level = 5 initial_risk_levels_table$level[initial_risk_levels_table$level==3] = high_level risk_mapping_table$level[risk_mapping_table$level==3] = high_level risk_mapping_table$dscpt = gsub("功","公",risk_mapping_table$dscpt) # transform the date transformTime <- function(date){ date <- date %>% map(as.character) %>% str_split("/") %>% map(.,function(x){x[1] <- as.numeric(x[1])+1911;return(x)}) %>% map_chr(~reduce(.,paste,sep="-")) %>% ymd return(date) } large_zero <- function(number){ return(number >0)} factor.summarise <- function(x, col){ for (i in col){ x[,i] <- sapply(x[,i],large_zero) } return(x) } # Define server logic required to summarize and view the selected # dataset shinyServer(function(input, output) { # Return the requested dataset datasetInput <- reactive({ data[data[, 1] == input$dataset, 2:ncol(data)] }) get_initial_risk<- reactive({ initial_risk_levels_table[initial_risk_levels_table$Id==input$dataset,"level"] }) datasetTime <- reactive({ datasetInput() %>% mutate(Date = transformTime(Date)) }) dataRecentFactor <- reactive({ choose.time <-as.Date("1970-01-01") + as.numeric(input$RecentTimeChoose) tmp <- datasetTime() index <- tmp %>% filter(Date > choose.time) %>% dplyr::select(-Date) %>% summarise_each(funs(sum)) colnames(tmp)[index > 0] }) output$datavars <- renderUI({ data <- datasetInput() data1 <- data[, -1] happenedname <- colnames(data1)[apply(data1, 2, sum) != 0] names(happenedname) = risk_mapping_table$dscpt[match(happenedname,risk_mapping_table$index)] selectInput("vars", label = "請選擇想要檢視的風險因子", happenedname, multiple=TRUE, selectize=F, selected = happenedname[1:3]) }) ### New Pie chart output$Pie_Chart_new = renderPlotly({ data <- datasetInput() data1 <- data[, -1] tofactor <- LETTERS[1:7] name <- c('經濟', '教育', '保護&照顧', '居住', '生育', '情感', '其他') count <- apply(data1, 2, sum) #print(count) count.type <- sapply(1:7, FUN = function(x){ location <- grep(tofactor[x], colnames(data1)) bprob <- sum(count[location]) return(bprob) }) plot_ly(labels = name, values = count.type, type = 'pie') %>% layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE), yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE)) }) ### Bar_chart_Single for(FactorType in LETTERS[1:7]){ local({ myFactor <- FactorType output[[paste0("Hist_",myFactor)]]= renderPlotly({ data <- datasetInput() data1 <- data[, -1] count <- as.data.frame(as.table(apply(data1, 2, sum))) names(count)[1] <- "Factor" count %<>% filter(Freq!=0) %>% arrange(desc(Freq)) loc2 <- grep(myFactor, count[, 1]) subcount <- count[loc2, ] plot_data = subcount[subcount[, 2] != 0, ] plot_data$Factor = risk_mapping_table$dscpt[match(plot_data$Factor, risk_mapping_table$index)] plot_data$Factor = factor(as.character(plot_data$Factor), levels = as.character(plot_data$Factor)) p <- plot_ly(plot_data, x = ~Factor, y = ~Freq, type = 'bar', color = ~Factor) %>% layout(yaxis = list(title = '頻率'), xaxis = list(title = '風險因子'), barmode = 'group') p }) }) } #### TimeplotNew output$TimeplotNew <- renderPlotly({ data <- datasetInput() data1 <- data[, -1] loc1 <- which(colnames(data1) %in% input$vars) subdata <- data1[, loc1, drop = F] subdata$x <- 1:nrow(subdata) subdata_colnames = risk_mapping_table$dscpt[match(colnames(subdata), risk_mapping_table$index)] p <- plot_ly(subdata, x = ~x, y = as.formula(paste0("~",colnames(subdata)[1])), name = subdata_colnames[1], type = 'scatter', mode = 'lines') if(ncol(subdata)>2){ for(i in 2:(ncol(subdata)-1)){ p %<>% add_trace(y = as.formula(paste0("~", colnames(subdata)[i])), name = subdata_colnames[i], mode = 'lines') } } xaxis = list(title = "時間點") yaxis_list = list(title = "是否發生", tickvals = c(0,1), ticktext = c("否","是"), range = c(-0.5, 1.5)) p %>% layout(showlegend = T, xaxis = xaxis, yaxis = yaxis_list) }) #### TimeRiskLevels output$TimeRiskLevels <- renderPlotly({ data <- datasetInput() risk_score = risk_mapping_table[match(colnames(data)[-1], risk_mapping_table$index),"level"] df = data.frame( Date = data$Date, Risk=as.matrix(data[, -1]) %*% matrix(risk_score,ncol=1) /apply(as.matrix(data[, -1]),1,sum) ) df$Level=1+(df$Risk >=1.5) +( df$Risk >=3) p <- plot_ly(type = "scatter",mode="markers") initial_risk_score = get_initial_risk() initial_risk_levels = 1+(initial_risk_score >=1.5) +( initial_risk_score >=3) p <- add_trace(p, x = c(0,1)-.5, y = 0, mode = "lines", line = list(color = c("green","yellow","red")[initial_risk_levels], width = 50), showlegend = F, hoverinfo = "text", text = paste("[開案初期]<br>", "風險高低: ", c("低","中","高")[initial_risk_levels], "<br>") #evaluate = T ) for(i in 1:(nrow(df) - 1)){ p <- add_trace(p, x = c(i,i+1)-.5, y = 0, mode = "lines", line = list(color = c("green","yellow","red")[df$Level[i]], width = 50), showlegend = F, hoverinfo = "text", text = paste("[第",i,"次訪談]<br>", "風險高低: ", c("低","中","高")[df$Level[i]], "<br>", "訪談時間: ", df$Date[i], "<br>")#, #evaluate = T ) } yaxis_list = list(tickvals = 0, ticktext = "警示燈號") xaxis_list = list(title = "訪談次數", tickvals = 0:(nrow(df) - 1), ticktext = c("初期",1:(nrow(df) - 1))) p %>% layout(showlegend = T,yaxis = yaxis_list,xaxis=xaxis_list) }) output$RecentIntViewTime <- renderValueBox({ valueBox(subtitle = "最近訪談時間", value = max(datasetTime()$Date), color="orange") }) output$FollowPeriod <- renderValueBox({ valueBox(subtitle = "開案時間", value =ymd(min(datasetTime()$Date)), color="orange") }) output$TimePeriodChoose <- renderUI({ sliderInput(inputId = "RecentTimeChoose", label = "", ticks = TRUE, timeFormat = "%F", min = min(datasetTime()$Date), max = max(datasetTime()$Date), value = max(datasetTime()$Date) ) }) output$RecentRiskFactor <- DT::renderDataTable({ recentRiskFactor.select <- risk_mapping_table %>% filter(index %in% dataRecentFactor()) colnames(recentRiskFactor.select) <- c("編碼", "解釋") DT::datatable(recentRiskFactor.select, options = list(orderClasses = TRUE)) }) output$PossibleRiskFactor <- DT::renderDataTable({ possiblerisk <- relationship.association %>% filter(left %in% dataRecentFactor()) %>% with(right) recentRiskFactor.select <- risk_mapping_table %>% filter(index %in% possiblerisk & !(index %in% dataRecentFactor())) colnames(recentRiskFactor.select) <- c("編碼", "解釋") DT::datatable(recentRiskFactor.select, options = list(orderClasses = TRUE)) }) }) <file_sep>/Preprocess/02_family_document_parse.R # case family document setwd("/Users/Weitinglin/Documents/2015-2016 日常專案/2017 D4SG/家戶資料/") library(docxtractr) library(dplyr) library(stringr) library(purrr) library(tibble) # Input ------------------------------------------------------------------- #use the mac command textutil to convert all doc into docx #system("for item in $(ls *.doc)\n do\n textutil -convert docx ${item}\n done\n") case.names <-list.files(pattern = ".docx") total.case.document <- data.frame(Id = character(), Geneder = factor(), Family_Category = character(), Monitor = logical(), Receive_Professional_Help = logical(), Social_Found = logical(), Special_Disease = logical(), Disable = logical(), Family_Problem_Summary = character(), School_Visit_Summary = character(), Family_Background_Summary = character(), Case_Receice_Resources = character() ) # parse the docx for ( name in case.names){ test <- read_docx(name) table_test <- docx_extract_tbl(test, 1, header=TRUE) print(paste("Loading files:",name)) print(test) # 代號 ---------------------------------------------------------------------- case.id <- colnames(table_test)[2] %>% as.character # 性別 (case.gender) -------------------------------------------------------- gender_str <- table_test[1,4] %>% str_split_fixed("[:space:]+",2) %>% str_detect("■") if (gender_str[1]){ case.gender <- "M" } if (gender_str[2]){ case.gender <- "F" } # 家庭類別 -------------------------------------------------------------------- case.family.category <- table_test[3,2] %>% str_extract_all("■\\S+|█[:space:]+\\S+|█\\S+|▓[:space:]+\\S+|▓\\S+") %>% unlist case.family.category <- case.family.category %>% reduce(paste) %>% as.character # 是否列管 -------------------------------------------------------------------- case.monitor <- table_test[4,2] %>% str_split_fixed("[:space:]+",2) case.monitor <- case.monitor[1,1] %>% str_extract("■[:space:]+\\S|■\\S") if (is.na(case.monitor)){ case.monitor <- table_test[4,2] case.monitor <- case.monitor %>% str_extract("■ \\S+|■[:space:]+\\S|■\\S|█[:space:]+\\S|█\\S|▓[:space:]+\\S|▓\\S") } if (str_detect(case.monitor,"否")){ case.monitor <- F } if (str_detect(case.monitor,"是")){ case.monitor <- T } # 專業協助 ------------------------------------------------------------------ case.prof <- table_test[5,2] case.prof <- case.prof %>% str_split_fixed(":",3) if (str_detect(case.prof[1,3],"無")){ case.prof.assist <- F } else if (str_detect(case.prof[1,1],"有")){ case.prof.assist <- T } # 社會補助 -------------------------------------------------------------------- case.social.fund <- table_test[6,2] %>% str_extract_all("■\\S+|█[:space:]+\\S|█\\S") %>% unlist case.social.fund <- case.social.fund %>% reduce(paste) %>% as.character if ( identical(case.social.fund, character(0)) ){ case.social.fund <- "無" } # 特殊疾病 -------------------------------------------------------------------- case.special.disease <- table_test[7,2] %>% str_extract_all("■\\S|█[:space:]+\\S|█\\S|▓\\S|▓[:space:]+\\S") %>% unlist if (str_detect(case.special.disease,"有")){ case.special.disease <- T } if (str_detect(case.special.disease,"無")){ case.special.disease <- F } # 使否領有殘障手冊 ---------------------------------------------------------------- case.disable <- table_test[7,4] %>% str_extract_all("■\\S|█[:space:]+\\S|█\\S|▓\\S|▓[:space:]+\\S") %>% unlist if ( identical(case.disable, character(0)) ){ case.disable <- NA } if (!is.na(case.disable)){ if (str_detect(case.disable,"是")){ case.disable <- T } if (str_detect(case.disable,"否")){ case.disable <- F } } # 家系圖 --------------------------------------------------------------------- for (i in 1:nrow(table_test)){ if (str_detect(table_test[i,1],"家 系 圖|家系圖")){ post_family_line <- i } } # 家庭問題摘要 ------------------------------------------------------------------ case.str.family.problem.summary <- table_test[post_family_line+2,1] %>% as.character() # 學校訪視 ------------------------------------------------------------------ case.str.school.visit <- table_test[post_family_line+3,1] %>% as.character() # 個案背景 ------------------------------------------------------------------ case.str.background <- table_test[post_family_line+4,1] %>% as.character() # 評估與處理 ----------------------------------------------------------------- case.str.assessment <- table_test[post_family_line+5,1] %>% as.character() # 本會提供之資源 --------------------------------------------------------------- case.receive.resource <- table_test[post_family_line+6,1] case.receive.resource <- case.receive.resource %>% str_extract_all("■ \\S+。|█\\S+。|█ \\S+。|█\\S+。|▓ \\S+。|▓\\S+。") %>% unlist case.receive.resource <- case.receive.resource %>% reduce(paste) %>% as.character() # merge the data -------------------------------------------------------- case.document <- data.frame( case.id , case.gender, case.family.category, case.monitor, case.prof.assist, case.social.fund, case.special.disease, case.disable, case.str.family.problem.summary, case.str.school.visit, case.str.background, case.receive.resource) colnames(case.document) <- c("Id", "Gender", "Family_Category", "Monitor", "Receive_Professional_Help", "Social_Found", "Special_Disease", "Disable", "Family_Problem_Summary", "School_Visit_Summary", "Family_Background_Summary", "Case_Received_Resources") total.case.document <- rbind(total.case.document, case.document) } # add label --------------------------------------------------------------- label <- c("", "", "家暴家庭(開案時即有)/兒少行為偏差(偷竊105.12/霸凌104.11)", "吸毒(開案時即有102.05入監服刑)/兒少行為偏差(偷竊105.12/霸凌105.04)", "", "家暴家庭(開案時即有)/兒少遭受霸凌(可能風險)", "家暴(可能風險)", "兒少遭受霸凌(可能風險)/家暴(言語暴力可能風險)/兒少偏差行為(偷竊可能風險)/疏於照顧(可能風險)", "", "自殺風險", "失業(106.02)", "自殺(102.12/105.01)/兒少偏差行為(偷竊105.12)", "吸毒(開案前即有/105.02再次被發現)/家暴(開案前即有)/酗酒(未來可能風險)", "家暴(105.03)/失業(105.11)/霸凌(霸凌或被霸凌:可能風險)", "家暴(105.01)/吸毒(104.08)/ 自殺(可能風險)", "失業(可能風險)/酗酒(可能風險)", "", "家暴(可能風險)/兒少行為偏差(偷竊105.04/用酒&檳榔105.04)/失業(可能風險)", "失業(104.06)/性侵及亂倫(可能風險)", "家暴(可能風險)/遭受霸凌(可能風險)", "家暴(可能風險)/吸毒(可能風險)/霸凌(可能風險)/兒少中輟(可能風險)", "兒少遭受霸凌(可能風險)", "家暴(開案時即有-前夫)", "兒少遭受霸凌(可能風險)", "酗酒(可能風險)", "", "吸毒(開案時即有)/兒少偏差行為(開案時即有,本會發現偷竊105.05/105.12)", "", "兒少偏差行為(偷竊105.09)", "家暴(開案時即有)/吸毒(開案時即有)/自殺(開案時即有/105.11)/失業(105.11)/疏於照顧(可能風險)", "性侵(可能風險)/酗酒(可能風險)", "兒少遭受霸凌(可能風險)/家暴(原生家庭)", "", "吸毒(開案前即有)/疏於照顧(開案前即有)/兒少偏差行為(偷竊103.10)", "", "疏於照顧(開案前即有)", "家暴(102.10)/兒少偏差行為(逃家103.09/暴力104.05、105.02)", "", "家暴(開案前即有)/疏於照顧(開案前即有)/兒少偏差行為(104.12、105.04、105.05)/棄養(未來可能風險)", "吸毒(開案前即有)", "兒少偏差行為(偷竊104.05)", "兒少偏差行為(偷竊103年)/疏於照顧(可能風險)", "", "", "疏於照顧(105年)", "", "家暴(開案前即有)/性侵(102年)/兒少偏差行為(可能風險)", "家暴(開案前即有)", "兒少行為偏差(性偏差102年)/兒少行為偏差(因性偏差未來可能觸法風險)", "兒少偏差行為(偷竊104.06)/疏於照顧(可能風險)", "家暴(開案前即有)/疏於照顧(開案前即有,103.10再發生)/兒少偏差行為(可能風險)", "", "", "", "家庭偷竊行為(105.06)", "", "", "") total.case.document <- total.case.document %>% mutate(Risk_Labels = label) write.csv(total.case.document, file = "Case_Family_Documents.csv", fileEncoding = "utf-8") # test section ------------------------------------------------------------ case.id case.gender case.family.category case.monitor case.prof.assist case.social.fund case.special.disease case.disable case.str.family.problem.summary case.str.school.visit case.str.background case.receive.resource <file_sep>/App/runapp.R ## installing shiny R ### Ū?? loading R workspace ## name = APP ex:C:/Users/robert/Desktop/App ## Please setwd this folder install.packages('shiny') install.packages('shinydashboard') install.packages('ggplot2') install.packages("gridExtra") install.packages('plotly') library('shiny') library('shinydashboard') library('ggplot2') library('gridExtra') library('plotly') runApp('/Users/kevin/D4SG_project/App') <file_sep>/Analysis/30_transfer.R ### risk-transfer function ### # input the index of old risk-factor, like 'A-01' (string formed) # and it will output the new category of risk-factor risk_transfer <- function(x){ result <- table[substr(table[, 1], start = 2, stop = 5) == x, 2] return(as.character(result)) } <file_sep>/Analysis/20_use_aprior_in_analysis.R rm(list=ls()) library(arules) df <- read.table("C:\\Users\\NingYuan\\Data_SparseForm.csv", header = TRUE, sep = ",") df$Id <- NULL df$Date <- NULL rule = c() for (itm in list("A","B","C","D","E","F","G")) { df.iter <- df df.iter <- df.iter [substring(colnames(df.iter),0,1)==itm ] trans <- as(data.matrix(df.iter),"transactions") rule.iter <- apriori(trans, parameter = list(support=0.006,confidence=0.6)) rule <- c(rule, rule.iter ) } inspect(head(rule[[1]],5)) idx2=1 for (itm in list("A","B","C","D","E","F","G")) { set <- subset(rule[[idx2]] , subset = lift>1.2) inspect(set) idx2<-idx2+1 }
43198ff948508cc18bf860ea0aa62d37cdb7cfee
[ "Markdown", "Python", "R" ]
11
R
dspim/Hfoundation-Troubled-Family-Risk-Profiling
c8d9d8151f082bdf09b9b1d26b4f975c13a37335
b66344cf43f28b9316678e02d99fbf06c232b0fc
refs/heads/master
<file_sep>package org.zkoss.mvvm.shadow; public class Modal { private ModalType type = ModalType.INFO; private String message; public ModalType getType() { return type; } public void setType(ModalType type) { this.type = type; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } <file_sep>package org.zkoss.mvvm.shadow; public enum ModalType { INFO, WARN, ERROR } <file_sep># ZK MVVM A project to introduce ZK MVVM pattern # Articles * [ZK MVVM Pattern: Server-Side Data Binding](https://dzone.com/articles/zk-mvvm-approach-server-side-data-binding) # How to Run ## No Maven installed You can run the project with maven wrapper by the command below (it will automatically download required maven): ### Linux/Mac `./mvnw jetty:run` ### Windows `mvnw jetty:run` ## Maven installed With the command below: `mvn jetty:run` ## After the server started visit [http://localhost:8080/zk-mvvm/todolist.zul](http://localhost:8080/zk-mvvm/todolist.zul)
28a68aa4bde63bfeab8392ba10237e2f21cd964d
[ "Markdown", "Java" ]
3
Java
hawkchen/zk-mvvm
179f7e43f03d67ef61534742d4ac292319e923db
1aa6eb36faf006a3e40b3c6a3ae036c723c62d0d
refs/heads/master
<repo_name>areebbeigh/coding-portfolio<file_sep>/templates/projects_page.html {% extends "layout.html" %} {% block title %}Viewing {{language}} projects{% endblock %} {% block content %} <img class="project_list_lang_thumbnail" src="{{language.get_thumbnail}}" alt="Thumbnail"> <h1 class="project_list_title">Viewing {{language.name}} projects</h1> <hr/> {% include "project_list.html" %} {% endblock %}<file_sep>/README.rst ================ Coding Portfolio ================ A Django webapp for setting up your programming portoflio. .. image:: preview.png What's new? ----------- - New project fields - Platform and Website - A new project summary display - Support for vector images (SVGs) - Expanded the scope of search keywords - A more efficient way to manage images/thumbnails What does this app do? ---------------------- Coding Portfolio is a simple webapp for the Django framework that provides you a ready-made website where you can post your projects right from the default Django administration interface. Features: --------- - Easy to setup - It should take you only a few minutes to setup your website with this app. - Clean UI - Coding Portfolio uses Bootstrap & Font-Awesome for it's CSS and Icons. - Mobile friendly - Automatic classification of your projects based on the programming language / framework - Automatic sitemap generator - The sitemap is generated automatically is available at /sitemap.xml - Easy to use - If you know how to use the Django administration interface this should be a piece of cake. and more.. Why did you make this app? -------------------------- Well to put it short - I needed to host a website where I could display my programming projects but I was too broke to afford a good webhost or a VPS so I went for free webhosts. I setup a WordPress blog ran it for a month but it was not good enough, the website would go down frequently, slow loading etc. (after all it was a free webhost) So finally I decided to make a web app of my own for this purpose. The idea was to make something **simple** and **light** (I am a lazy person) good enough to use and Coding Portfolio was born. My website: `<NAME> <http://areeb12.pythonanywhere.com>`_ Setup ----- Setting up coding portfolio is easy, just download it, put it's contents in your Django website folder (in a folder named ``coding_portfolio``) and add it to the ``INSTALLED_APPS`` in your website's settings file just like you add any other web app to your website. Add a url to the ``urlpatterns`` of your Django website and include the ``coding_portfolio.urls`` file. Edit the templates ``layout.html`` and ``index.html`` to change the default text. Next add some objects to the ``Contacts`` model, you'll see the About dropdown gets populated automatically. Finally in the Django administration interface add some content in the ``Abouts`` model. You're done! For reference you can check my `website <https://github.com/areebbeigh/mywebsite>`_ source. Contributing ------------ Found a bug? typo? error? or do you have a feature that you can implement? Coding Portfolio is my first Django project feel free to use or expand the project! I'll be waiting for your pull requests! | Developer: <NAME> <<EMAIL>> | Version: 1.0.1 | GitHub Repo: https://github.com/areebbeigh/coding-portfolio <file_sep>/admin.py """ Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.contrib import admin from django import forms from .customfields.imagefields import SVGAndImageFormField from .models import * # Model Forms class ImageModelForm(forms.ModelForm): class Meta: exclude = [] field_classes = { 'image': SVGAndImageFormField, } # Model Admin Classes class BaseAdmin(admin.ModelAdmin): """ Base class for other model admin classes """ def get_thumbnail(self, obj): return mark_safe('<img src="' + obj.get_thumbnail() + '" alt="Thumbnail" width="100px" height="100px"') get_thumbnail.short_description = "Thumbnail" class ProjectAdmin(BaseAdmin): list_display = ('name', 'short_description', 'publish_date') list_filter = ['publish_date'] class PlatformAdmin(BaseAdmin): list_display = ('name', 'get_thumbnail') class LanguageAdmin(BaseAdmin): list_display = ('name', 'get_thumbnail') class WebsiteAdmin(BaseAdmin): list_display = ('name', 'url', 'get_thumbnail') class ContactAdmin(BaseAdmin): list_display = ('name', 'url') class ImageAdmin(admin.ModelAdmin): form = ImageModelForm fields = ('image_preview', 'name', 'image') list_display = ('name', 'image_preview',) readonly_fields = ('image_preview',) admin.site.register(Project, ProjectAdmin) admin.site.register(Platform, PlatformAdmin) admin.site.register(Language, LanguageAdmin) admin.site.register(Website, WebsiteAdmin) admin.site.register(About) admin.site.register(Contact, ContactAdmin) admin.site.register(Image, ImageAdmin) <file_sep>/models.py """ Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.conf import settings from django.core.exceptions import ValidationError from django.db import models from django.urls import reverse from django.utils.safestring import mark_safe def validate_only_one_instance(obj): """ Ensures that the model can have only one instance """ # Thanks to http://stackoverflow.com/a/6436008/4591121 model = obj.__class__ if model.objects.count() > 0 and obj.id != model.objects.get().id: raise ValidationError( "You can create only one %s instance, edit the previous one to make any changes." % model.__name__) class BaseModel: """ Base class for other model classes """ def get_thumbnail(self, is_project=False, is_website=False): """ Returns the URL to the thumbnail associated with this object. """ if is_project: DEFAULT_THUMBNAIL = "default_project_thumbnail.png" elif is_website: DEFAULT_THUMBNAIL = "default_website_thumbnail.svg" else: DEFAULT_THUMBNAIL = "default_thumbnail.png" if self.thumbnail: return self.thumbnail.get_thumbnail() else: return settings.STATIC_URL + "thumbnails/" + DEFAULT_THUMBNAIL # Default thumbnail class Image(models.Model): """ Image model """ def __str__(self): return self.name def image_preview(self): return mark_safe('<img src="%s" alt="Image" width="100px" height="100px" />' % self.image.url) def get_thumbnail(self): return self.image.url name = models.CharField(max_length=50, help_text='Name of the image.') image = models.ImageField(help_text='The image.') class Platform(BaseModel, models.Model): """ Platform model """ def __str__(self): return self.name name = models.CharField(max_length=100, unique=True, help_text='Name of the platform.') thumbnail = models.ForeignKey(Image, blank=True, null=True, help_text='A thumbnail for the platform.') class Language(BaseModel, models.Model): """ Stores programming languages. """ def __str__(self): return self.name name = models.CharField(max_length=50, unique=True, help_text='A programming language or coding framework name.') thumbnail = models.ForeignKey(Image, blank=True, null=True, help_text='A thumbnail for the language.') class Website(BaseModel, models.Model): """ Website model. """ def __str__(self): return self.url def get_thumbnail(self): return super().get_thumbnail(is_website=True) name = models.CharField(max_length=50, help_text='Website name.') url = models.URLField(help_text='Website url.') thumbnail = models.ForeignKey(Image, null=True, blank=True, help_text='Website thumbnail.') class Project(BaseModel, models.Model): """ Stores projects, with their name, description, thumbnail, publish date and languages. """ def __str__(self): return self.name def get_thumbnail(self): return super().get_thumbnail(is_project=True) def get_absolute_url(self): """ Returns the absolute URL to the project page """ return reverse('project_detail', args=[self.id]) is_project = True name = models.CharField(max_length=50, help_text='Project name.') website = models.ManyToManyField(Website, help_text='Project website.') short_description = models.CharField(help_text='A short description of the project.', max_length=100) description = models.TextField(help_text='A more detailed description of the project.') platform = models.ManyToManyField(Platform, help_text='The platform this project is intended for.') languages = models.ManyToManyField(Language, help_text='The language(s) your project is based on.') thumbnail = models.ForeignKey(Image, null=True, blank=True) publish_date = models.DateTimeField("Publish Date", auto_now_add=True) class Contact(models.Model): """ Represents a contact to display in the contact information """ name = models.CharField(max_length=50, help_text='Name of the contact type e.g GitHub.', unique=True) font_awesome_class = models.CharField(max_length=50, help_text='Font Awesome class for the contact icon e.g fa-github') url = models.URLField(help_text='A redirecting URL for the contact.') class About(models.Model): """ Stores information to display on the about page """ def clean(self): validate_only_one_instance(self) description = models.TextField(help_text='Stuff about yourself.') <file_sep>/templates/layout.html <!DOCTYPE html> <html lang="en"> <head> {% load static %} {% load custom_filters %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initialscale=1.0"> {% block extend %}{% endblock %} <!-- Static files mainly for development --> <!-- <link href="{% static 'bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <link href="{% static 'css/font-awesome.min.css' %}" rel="stylesheet"> <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'bootstrap/js/bootstrap.min.js' %}"></script> --> <link href="{% static 'css/style.css' %}" rel="stylesheet"> <!-- CDN STARTS HERE --> <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script>$(function () { $("[data-toggle='popover']").popover(); });</script> <!-- Popover script --> <script> $(document).ready(function () { $('[data-toggle="tooltip"]').tooltip(); }); </script> <title>Coding Portfolio | {% block title %}{% endblock %}</title> </head> <body> <div class="navbar navbar-default navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Coding Portfolio</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'index' %}"><span class="fa fa-home"></span> Home</a></li> <li> <a href="" class="dropdown-toggle" data-toggle="dropdown"><span class="fa fa-star"></span> Projects <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> {% with languages=""|getlanguages %} {% for lang in languages %} <li class="presentation"><a href="{% url 'projects_page' lang %}"><span class="fa fa-angle-right"></span> {{lang}}</a></li> {% endfor %} {% endwith %} </ul> </li> <li><a href="{% url 'project_feed' %}" target="_blank"><span class="fa fa-rss"></span> RSS</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li> <a class="dropdown-toggle" href="" data-toggle="dropdown">About <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li class="dropdown-header">About</li> <li class="presentation"><a href="{% url 'about_page' %}"><span class="fa fa-fw fa-info"></span> What is this?</a></li> <li class="dropdown-header">Contact</li> {% with contacts=""|getcontacts %} {% for contact in contacts %} <li class="presentation"><a href="{{contact.url}}" target="_blank"> <span class="fa {{contact.font_awesome_class}}"></span> {{contact.name}}</a> </li> {% endfor %} {% endwith %} </ul> </li> <li> <form class="navbar-form" method="get" action="{% url 'search_page' %}"> <div class="input-group"> <input type="text" name="q" class="form-control" placeholder="Search"> <span class="input-group-btn"><button type="submit" class="btn btn-default"><span class="fa fa-search"></span></button></span> </div> </form> </li> </ul> </div> </div> </div> <br/><br/><br/> <div class="container body-content"> {% block content %} {% endblock %} <hr/> <footer> <p class="pull-left">{% now "Y" as current_yr %}&copy; {{current_yr}} <NAME> (edit me in layout.html)</p> {# DO NOT REMOVE #} <p class="pull-right">Powered by <a href="https://www.djangoproject.com" target="_blank">Django</a> and <a href="https://github.com/areebbeigh/coding-portfolio" target="_blank">Coding Portfolio</a></p> </footer> </div> </body> </html><file_sep>/feeds.py """ Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.contrib.syndication.views import Feed from coding_portfolio.models import Project class ProjectFeeds(Feed): """ A basic feed page for all the projects on the website """ title = "Projects Feed" link = "/rss/" description = "An RSS feed of all the projects on this website" def items(self): return Project.objects.order_by("-publish_date") def item_title(self, item): return item.name def item_description(self, item): return item.short_description def item_link(self, item): return item.get_absolute_url() <file_sep>/views.py """ Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage from django.conf import settings from django.db.models import Q from django.shortcuts import render, get_object_or_404, HttpResponseRedirect from .models import Project, Language, About, Platform # TODO: Be able to show <code> or <pre> blocks as code in posts. - Need help with this! def index(request): """ Index view, returns a list of recent projects in the context """ recent_projects = [] for i in range(0, 6): try: recent_projects.append(Project.objects.order_by('-publish_date')[i]) except IndexError: break context = { 'projects': recent_projects, } return render(request, 'index.html', context) def project_list(request, language): """ Returns the projects list for a given language """ language = get_object_or_404(Language, name=language) paginator = Paginator(language.project_set.order_by('-publish_date'), 6) if 'page' not in request.GET: page = 1 else: page = request.GET['page'] try: projects = paginator.page(page) except PageNotAnInteger: projects = paginator.page(1) except EmptyPage: projects = paginator.page(paginator.num_pages) context = { 'projects': projects, 'language': language, } return render(request, 'projects_page.html', context) def project_detail(request, project_id): """ Returns view for individual project pages """ project_object = get_object_or_404(Project, id=project_id) # Temporary, till custom website icons are supported website_thumbnail = settings.MEDIA_URL + "default_website_thumbnail.svg" context = { 'project': project_object, 'website_thumbnail': website_thumbnail, } return render(request, 'project_detail.html', context) def search(request): """ Search view """ if "q" in request.GET: queries = request.GET['q'].split() projects = [] for q in queries: projects.extend(list(Project.objects.filter( Q(name__icontains=q) | Q(description__icontains=q) | Q(short_description__icontains=q)))) for lang in Language.objects.filter(name__icontains=q): for project in lang.project_set.all(): projects.append(project) for platform in Platform.objects.filter(name__icontains=q): for project in platform.project_set.all(): projects.append(project) try: # If a number is given, include the project with that ID if any q = int(q) projects.append(Project.objects.get(id=q)) except: pass projects = set(projects) context = { 'projects': list(projects), } return render(request, 'search_page.html', context) else: return HttpResponseRedirect("/") def about(request): """ About view """ try: about = About.objects.get().description except: about = "No information here yet." return render(request, 'about_page.html', {'about': about}) <file_sep>/templatetags/custom_filters.py """ Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Python imports import collections from html.parser import HTMLParser # Django imports from django import template # Local imports from ..models import Language, Contact # http://stackoverflow.com/questions/753052/strip-html-from-strings-in-python class MLStripper(HTMLParser): def __init__(self): self.reset() self.strict = False self.convert_charrefs = True self.fed = [] def handle_data(self, d): self.fed.append(d) def get_data(self): return ''.join(self.fed) def strip_tags(html): s = MLStripper() s.feed(html) return s.get_data() register = template.Library() @register.filter def stripmarkup(value): """ Removes the HTML tags from the text """ return strip_tags(value) @register.filter def getsubdivisions(value, subdivisions): """ Given a list, returns a new two-dimensional list with each internal list containing 'subdivisions' number of elements. If len(value) % 3 != 0 then the last list will contain len(value) % 3 number of elements. Example: getsubdivisions([1,2,3,4,5,6,7], 3) -> [[1,2,3],[4,5,6],[7]] """ if not value: # NoneType return [] if not isinstance(value, collections.Iterable): raise ValueError("Expected value type: " + str(collections.Iterable) + ", got: " + str(type(value))) try: subdivisions = int(subdivisions) except ValueError: subdivisions = 3 subdivided_list = [] subdivision = [] index = 0 while index < len(value): subdivision.append(value[index]) if len(subdivision) == subdivisions: subdivided_list.append(subdivision) subdivision = [] index += 1 if subdivision: subdivided_list.append(subdivision) return subdivided_list @register.filter def getrange(value): """ Returns a range(1, value + 1) """ try: value = int(value) except ValueError: raise ValueError("Expected type: " + str(int) + ", got: " + str(type(value))) return range(1, value + 1) @register.filter def getlanguages(value): """ Returns a list of the languages in the Language model which have at least one project associated with them (not a filter). This is here to automatically generate the Projects dropdown menu items. """ return [lang.name for lang in Language.objects.all() if lang.project_set.all()] @register.filter def getcontacts(value): """ Returns a list of dictionary of the type: { 'name': '<contact_name>', 'font_awesome_class': '<font_awesome_class>', 'url': '<contact url>' } """ result = [] for contact in Contact.objects.all(): dictionary = {} dictionary["name"] = contact.name dictionary["font_awesome_class"] = contact.font_awesome_class dictionary["url"] = contact.url result.append(dictionary) return result """ -> A close yet fucked up attempt at displaying <code></code> blocks as-is in posts. -> Problem: It shows <br> tags in the code as well, instead of marking them as safe. -> Looking for an alternative. If you can fix it please feel free to make a pull request. @register.filter def checkcode(value): # Checks for <code> or <pre> tags in the text and preserves them code_block_regex = r"<code>(.*?)</code>|<pre>(.*?)</pre>" search_objects = re.finditer(code_block_regex, value) temp = value # print(list(search_objects)) for search in search_objects: print(search) span = search.span() print("Span:", span) code_block = value[span[0]:span[1]] print("Code block:", code_block) if code_block.endswith("</code>"): print("Ends with </code>") inside = value[span[0] + 6:span[1] - 7] else: inside = value[span[0] + 5:span[1] - 6] print("Inside:", inside) escaped_code = conditional_escape(inside) print("Escaped code:", escaped_code) escaped_code_block = code_block.replace(inside, escaped_code) print("Escaped code block:", escaped_code_block) temp = temp.replace(code_block, escaped_code_block) value = temp return mark_safe(value) """ <file_sep>/apps.py from django.apps import AppConfig class CodingPortfolioConfig(AppConfig): name = 'coding_portfolio' <file_sep>/tests.py """ Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # Django imports from django.conf import settings from django.test import TestCase # Local imports from .models import Project, Language from .templatetags.custom_filters import getsubdivisions, getrange, stripmarkup, getlanguages class CustomTemplateFilterTests(TestCase): def test_stripmarkup(self): HTML = '<html><body><p>This is my <a href="github.com/areebbeigh">github</a>, go on and <b>follow me</b>.</body></html>' STRIPPED_TEXT = 'This is my github, go on and follow me.' self.assertEqual(stripmarkup(HTML), STRIPPED_TEXT) def test_getsubdivisions(self): self.assertEqual(getsubdivisions(range(1, 8), 3), [[1, 2, 3], [4, 5, 6], [7]]) self.assertEqual(getsubdivisions(range(1, 8), "random garbage value"), [[1, 2, 3], [4, 5, 6], [7]]) with self.assertRaises(ValueError): getsubdivisions(2134, "bullshit value") def test_getrange(self): self.assertEqual(getrange(5), range(1, 6)) with self.assertRaises(ValueError): getrange("crap") def test_getlanguages(self): lang1 = Language.objects.create(name='Java') lang2 = Language.objects.create(name='Python') lang3 = Language.objects.create(name='PHP') p = Project.objects.create( name='Coding Portfolio', description='Programming portfolio for lazy people like me', ) p.languages.add(lang1, lang2) self.assertEqual(getlanguages(""), [lang.name for lang in p.languages.all()]) <file_sep>/urls.py """ Copyright 2016 <NAME> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from django.conf.urls import url from django.contrib.sitemaps.views import sitemap from . import feeds # Feeds from . import views # Views from .sitemap import ProjectSitemap sitemaps = { 'projects': ProjectSitemap() } urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^projects/view/(\d+)/$', views.project_detail, name='project_detail'), url(r'^projects/(.+)/$', views.project_list, name='projects_page'), url(r'^query/', views.search, name='search_page'), url(r'^about/$', views.about, name='about_page'), url(r'^rss/$', feeds.ProjectFeeds(), name='project_feed'), url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'), ]
8df95b704197aaaf0df37ea751d07fb0834391e7
[ "Python", "HTML", "reStructuredText" ]
11
HTML
areebbeigh/coding-portfolio
c1aaeca687a5bd9c8c41e3363dbce28c6b52f7cb
2b40f4a359b14b7299f403827e78241fee211ccf