repo_name
stringlengths
5
114
repo_url
stringlengths
24
133
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
directory_id
stringlengths
40
40
branch_name
stringclasses
209 values
visit_date
timestamp[ns]
revision_date
timestamp[ns]
committer_date
timestamp[ns]
github_id
int64
9.83k
683M
star_events_count
int64
0
22.6k
fork_events_count
int64
0
4.15k
gha_license_id
stringclasses
17 values
gha_created_at
timestamp[ns]
gha_updated_at
timestamp[ns]
gha_pushed_at
timestamp[ns]
gha_language
stringclasses
115 values
files
listlengths
1
13.2k
num_files
int64
1
13.2k
rushabhbid/LAN-Monitoring
https://github.com/rushabhbid/LAN-Monitoring
bf4367baa6715472a7ad6571332d825bc51fc0f8
68f63ef1765c1e393065f1ccef983018a11091f3
0bc279c266235677a369726bd62e84b904163be7
refs/heads/master
2022-12-09T19:59:13.583923
2020-08-25T03:31:25
2020-08-25T03:31:25
290,032,457
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.9047619104385376, "alphanum_fraction": 0.9047619104385376, "avg_line_length": 9.75, "blob_id": "f4c84f72f315275752f85103af9199adcb4f249d", "content_id": "0e63704b576f12bd3f932a667ecd020c7bb204ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 42, "license_type": "no_license", "max_line_length": 13, "num_lines": 4, "path": "/SOURCE CODE/CLIENT/requirements.txt", "repo_name": "rushabhbid/LAN-Monitoring", "src_encoding": "UTF-8", "text": "pillow\npytesseract\nopencv-python\npyautogui" }, { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 59, "blob_id": "5850f04a740776b364a55e736b392ad1041a38a0", "content_id": "de5f118047d2dafa0a60aad126f6d023a3894a85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 120, "license_type": "no_license", "max_line_length": 102, "num_lines": 2, "path": "/README.md", "repo_name": "rushabhbid/LAN-Monitoring", "src_encoding": "UTF-8", "text": "# LAN-Monitoring\nAn application for computer lab instructors to monitor and administer lab computers from their device.\n" }, { "alpha_fraction": 0.46516329050064087, "alphanum_fraction": 0.4800933003425598, "avg_line_length": 25.903766632080078, "blob_id": "1582783ca48f7d90e87309ff693d1ba9487cffc3", "content_id": "ad49afa1a18c0b83c9299a5701e7aaff019acc18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6430, "license_type": "no_license", "max_line_length": 150, "num_lines": 239, "path": "/SOURCE CODE/SERVER/mains.py", "repo_name": "rushabhbid/LAN-Monitoring", "src_encoding": "UTF-8", "text": "from threading import Thread, Lock\nimport socket\nimport os\nimport time\nimport shutil\n\nclients = []\naddrs = []\nisStudent = []\nkeyset = \"`~\"\ncolors = [\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\",\"Aqua\"]\nlock = Lock()\nflag = 0\n\ndef createFolders():\n for i in range(20):\n clientfolder = \"static/img/comp\"+str(i+1)\n if not os.path.exists(clientfolder):\n os.makedirs(clientfolder)\n static_img = \"static/img/comp\"+str(i+1)+\"/0.png\"\n if os.path.exists(static_img):\n onlyfiles = len(next(os.walk(clientfolder))[2])\n new_img = \"static/img/comp\"+str(i+1)+\"/\"+str(onlyfiles)+\".png\"\n os.rename(static_img,new_img)\n shutil.copyfile(\"static/blank.png\",static_img)\n\ndef emptyFolders():\n global flag\n \n while flag==1:\n time.sleep(0.2)\n \n flag = 1\n \n for i in range(20):\n clientfolder = \"static/img/comp\"+str(i+1)\n for file in os.listdir(clientfolder):\n file_path = os.path.join(clientfolder, file)\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except Exception as e:\n print(e)\n static_img = clientfolder+\"/0.png\"\n shutil.copyfile(\"static/blank.png\",static_img)\n flag = 0\n\ndef acceptClients(s):\n global clients,isStudent,keyset\n global addrs\n while True:\n ind = -1\n c, addr = s.accept()\n addr = str(addr)\n only_ip = addr.split(',')\n for add in addrs:\n compare_ip = add.split(',')\n if compare_ip[0] == only_ip[0]:\n ind = addrs.index(add)\n break\n \n if ind != -1:\n clients[ind] = c\n addrs[ind] = addr\n isStudent[ind] = True\n \n else:\n clients.append(c)\n addrs.append(addr)\n isStudent.append(True)\n \n print(\"Client IP: <\"+ addr+\"> connected successfully !!\");\n sendkeywords(c, keyset)\n\ndef sessionkey(string):\n global keyset\n keyset = string\t\n\ndef reqSS(c):\n global clients,addrs,colors,flag\n \n while flag==1:\n time.sleep(0.2)\n \n flag = 1\n \n try:\n c.send(str.encode(\"BHEJO\"))\n print(1)\n data = c.recv(1024)\n datastr = data.decode(\"UTF-8\")\n if datastr[:6] == \"EXISTS\":\n filesize = int(datastr[6:])\n print(filesize)\n message = 'Y' #input(\"File exists, \" + str(filesize) + \"Bytes, download? (Y/N)? -> \")\n if message == 'Y':\n c.send(str.encode(\"OK\"))\n \n clientfolder = \"static/img/comp\"+str(clients.index(c)+1)\n static_img = \"static/img/comp\"+str(clients.index(c)+1)+\"/0.png\"\n onlyfiles = len(next(os.walk(clientfolder))[2])\n new_img = \"static/img/comp\"+str(clients.index(c)+1)+\"/\"+str(onlyfiles)+\".png\"\n newfile = \"static/img/comp\"+str(clients.index(c)+1)+\"/temp.png\"\n \n f = open(newfile, 'wb')\n data = c.recv(1024)\n totalRecv = len(data)\n f.write(data)\n while totalRecv < filesize:\n data = c.recv(1024)\n totalRecv += len(data)\n f.write(data)\n print(\"{0:.2f}\".format((totalRecv / float(filesize)) * 100) + \"% Done\")\n f.close()\n print(\"Download Complete!\")\n \n print(onlyfiles)\n \n os.rename(static_img,new_img)\n os.rename(newfile,static_img)\n \n \n else:\n print(\"File Does Not Exist!\")\n \n except:\n print('sock error') \n \n flag = 0\n\n\ndef sendmessage(c,msg):\n try:\n global clients,addrs,colors,flag\n \n while flag==1:\n time.sleep(0.2)\n \n flag = 1\n c.send(str.encode(\"MESSAGE\"))\n ack = c.recv(1024)\n if ack == b\"OK\":\n c.send(str.encode(str(msg)))\n print('on the way')\n flag = 0\n \n except:\n print(\"sock error\")\n \ndef disconn(addr):\n global clients,addrs,colors,flag,isStudent\n \n while flag==1:\n time.sleep(0.2)\n \n flag = 1\n \n if addr in addrs:\n ind = addrs.index(addr)\n if isStudent[ind]:\n isStudent[ind] = False\n clientfolder = \"static/img/comp\"+str(ind+1)\n static_img = \"static/img/comp\"+str(ind+1)+\"/0.png\"\n if os.path.exists(static_img):\n onlyfiles = len(next(os.walk(clientfolder))[2])\n new_img = \"static/img/comp\"+str(ind+1)+\"/\"+str(onlyfiles)+\".png\"\n os.rename(static_img,new_img)\n shutil.copyfile(\"static/blank.png\",static_img)\n else:\n isStudent[ind] = True\n\n flag = 0\n\ndef shutdown(c):\n try:\n global clients,addrs,colors,flag\n \n while flag==1:\n time.sleep(0.2)\n \n flag = 1\n c.send(str.encode(\"SHUTDOWN\"))\n flag = 0\n \n except:\n print(\"sock error\")\n\ndef sendkeywords(c,string2):\n try:\n global clients,addrs,colors,flag\n\t\t\n while flag==1:\n time.sleep(0.2)\n \n flag = 1\n c.send(str.encode(\"KEYWORDS\"))\n ack = c.recv(1024)\n if ack == b\"OK\":\n c.send(str.encode(str(string2)))\n print('on the way')\n flag = 0\n \n except:\n print(\"sock error\")\n \ndef Main():\n \n global clients,isStudent\n global addrs\n \n str = open('server_ip.txt', 'r').read()\n print(str)\n \n host = str\n port = 2224\n \n try: \n s = socket.socket()\n s.bind((host,port))\n \n s.listen(5)\n \n print(\"Server Started!!\")\n \n Thread(target = acceptClients, args = (s,)).start()\n while True: \n print(clients)\n print(addrs)\n for c in clients:\n ind = clients.index(c)\n if isStudent[ind]:\n reqSS(c)\n time.sleep(1)\n time.sleep(10)\n \n except:\n print(\"Some jhol\")\n finally:\n s.close()\n" }, { "alpha_fraction": 0.6167126893997192, "alphanum_fraction": 0.6205110549926758, "avg_line_length": 24.069564819335938, "blob_id": "f86bf6465e276a038ea3ded756cd752edf404a7b", "content_id": "2ab7b58c5f39a803ea7b82c640dbc57b498e3944", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2896, "license_type": "no_license", "max_line_length": 101, "num_lines": 115, "path": "/SOURCE CODE/SERVER/flasklan.py", "repo_name": "rushabhbid/LAN-Monitoring", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, request, jsonify, redirect\nfrom flask_bootstrap import Bootstrap\nfrom mains import *\n#import Queue\n\n\n\napp = Flask(__name__)\n\nBootstrap(app)\n\nips=[]\n\[email protected]('/')\ndef index():\n Thread(target = Main, args = ()).start()\n createFolders()\n return redirect(\"/monitor\")\n\[email protected]('/monitor') \ndef monitor(): \n return render_template('index.html',var = ips, adds = addrs, col = colors, isStudent = isStudent)\n \[email protected]('/try1')\ndef try1():\n emptyFolders()\n return redirect(\"/monitor\")\n\[email protected]('/', methods=['POST'])\ndef getvalue():\n msg=request.form['submit']\n return redirect(\"/monitor\")\n\n \n#gets ip for live ss of 1 pc\[email protected]('/live', methods=['POST'])\ndef live():\n global clients,addrs,isStudent\n ipA=request.form['submit']\n if ipA in addrs:\n ind = addrs.index(ipA)\n if isStudent[ind]:\n reqSS(clients[ind])\n return redirect(\"/monitor\")\n\n#send keywords to all connected PCs\[email protected]('/disconnect', methods=['POST'])\ndef disconnect():\n global clients,addrs,isStudent\n ipA=request.form['submit']\n if ipA in addrs:\n disconn(ipA)\n return redirect(\"/monitor\")\n\n#disconnects specific pc\[email protected]('/keyword', methods=['POST'])\ndef keyword():\n global clients,addrs,isStudent,keyset\n string2 = request.form['key_words']\n sessionkey(string2)\n for c in clients:\n ind = clients.index(c)\n if isStudent[ind]:\n sendkeywords(c,string2)\n return redirect(\"/monitor\")\n\n#gets ip for switching off 1 pc\[email protected]('/off1', methods=['POST'])\ndef off1():\n global clients,addrs,isStudent\n ipA=request.form['submit']\n if ipA in addrs:\n ind = addrs.index(ipA)\n if isStudent[ind]:\n shutdown(clients[ind])\n return redirect(\"/monitor\")\n \n#switchoff all pcs \[email protected]('/offall')\ndef offall():\n global clients,addrs,isStudent\n for c in clients:\n ind = clients.index(c)\n if isStudent[ind]:\n shutdown(c)\n return redirect(\"/monitor\")\n \n#gets the broadcast message from user and saves it in the variable msg\[email protected]('/broadcast', methods=['POST'])\ndef broadcast():\n global clients,addrs,isStudent\n msg=request.form['b_msg']\n for c in clients:\n ind = clients.index(c)\n if isStudent[ind]:\n sendmessage(c,msg) \n return redirect(\"/monitor\") \n \n#gets ip and message for one pc \[email protected]('/message1', methods=['POST'])\ndef message1():\n global clients,addrs,isStudent\n IPa=request.form['get_ip']\n print(IPa)\n msg=request.form['message']\n if IPa in addrs:\n ind = addrs.index(IPa)\n if isStudent[ind]:\n sendmessage(clients[ind],msg)\n print('msg sent'+str(ind))\n return redirect(\"/monitor\")\n\nif __name__ == '__main__':\n \n app.run(debug=True)\n \n\n\n \n" }, { "alpha_fraction": 0.4841040372848511, "alphanum_fraction": 0.5074662566184998, "avg_line_length": 25.11320686340332, "blob_id": "2cc744b7423b21ddd04a788a7c3aa92f08007cea", "content_id": "85accb43b2bd3fe3bfc4f8b031f1b794c87661e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4152, "license_type": "no_license", "max_line_length": 92, "num_lines": 159, "path": "/SOURCE CODE/CLIENT/Clientfinal.py", "repo_name": "rushabhbid/LAN-Monitoring", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 5 23:39:40 2018\n\n@author: Rushabh\n\"\"\"\n\nfrom PIL import Image,ImageOps\nimport pytesseract\nimport cv2\nimport socket\nfrom threading import Thread\nimport time\nimport os\nimport pyautogui\nimport subprocess\nimport ctypes # An included library with Python install.\n \nmessage = \"null\"\nstr2 = \"\"\n\ndef shutdown():\n subprocess.call([\"shutdown\", \"-f\", \"-s\", \"-t\", \"1\"])\n\ndef RetrFile(name,sock):\n\n global str2\n pyautogui.screenshot('demo.png')\n \n image = cv2.imread('demo.png')\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n gray = cv2.threshold(gray, 0, 255,\n cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]\n filename = \"{}.png\".format(os.getpid())\n cv2.imwrite(filename, gray)\n text = pytesseract.image_to_string(Image.open(filename))\n os.remove(filename)\n import re\n words = re.split(r'\\W+', text)\n \n str1=[x.lower() for x in words]\n print(str1)\n \n a = str2.split(\",\")\n str12 = [x.lower() for x in a]\n print(str12)\n \n count = 0\n for num in str1:\n if num in str12:\n count=count+1\n \n if count < 1:\n color = 'red'\n ImageOps.expand(Image.open('demo.png'),border=50,fill='red').save('demo.png')\n elif count >= 1 and count < 2:\n color = 'yellow'\n ImageOps.expand(Image.open('demo.png'),border=50,fill='yellow').save('demo.png')\n else:\n color = 'green'\n ImageOps.expand(Image.open('demo.png'),border=50,fill='green').save('demo.png')\n \n print(\"color\")\n print(color)\n \n filename = 'demo.png'\n \n if os.path.isfile(filename):\n print(filename)\n binostr = \"EXISTS\"+str(os.path.getsize(filename))\n bino = str.encode(binostr)\n sock.send(bino)\n filesize = int(binostr[6:])\n #filesize = int.from_bytes(binostr[6:], byteorder = 'big', signed = True)\n print(filesize)\n userResponse = sock.recv(1024)\n print(userResponse)\n if userResponse[:2] == b'OK':\n with open(filename, 'rb') as f:\n bytesToSend = f.read(1024)\n sock.send(bytesToSend)\n while bytesToSend :\n bytesToSend = f.read(1024)\n sock.send(bytesToSend)\n print(1)\n \n else:\n sock.send(\"ERR \")\n print('no file')\n \n \n f = open(\"myfile.txt\", \"w\")\n with open(\"myfile.txt\" , \"w\", encoding=\"utf-8\") as f:\n f.write(str(words))\n\n \n return\n \ndef Mbox(title, text, style):\n return ctypes.windll.user32.MessageBoxW(0, text, \"Message From ADMIN\", style)\n \ndef viewmessage(s):\n s.send(str.encode(\"OK\"))\n msg = s.recv(1024)\n message = msg.decode(\"UTF-8\")\n t = Thread(target = Mbox, args = ('Message From ADMIN', message, 0,))\n t.daemon = True\n t.start()\n \n\ndef setkeywords(s):\n global str2\n s.send(str.encode(\"OK\"))\n string2 = s.recv(1024)\n str2 = string2.decode(\"UTF-8\")\n print(str2)\n\ndef sendInvoke(s):\n while True:\n command = s.recv(1024)\n if command == b\"BHEJO\":\n RetrFile(\"RetrThread\",s)\n print(1)\n command = b\"Mat BHEJO THODI DER\"\n print(command)\n \n elif command == b\"SHUTDOWN\":\n shutdown()\n \n elif command == b\"MESSAGE\":\n print(\"Message\")\n viewmessage(s)\n\n elif command == b\"KEYWORDS\":\n print(\"Keywords\")\n setkeywords(s)\n\ndef Main():\n \n str = open('server_ip.txt', 'r').read()\n host = str\n port = 2224\n \n s = socket.socket()\n \n while True:\n try:\n s.connect((host,port))\n break\n except socket.error as e:\n print(str(e))\n time.sleep(10)\n \n sendInvoke(s)\n \n s.close()\n \nif __name__ == '__main__':\n Main()\n" } ]
5
PAN-YI-HSUAN/Graph-Based-Geometry-Solver
https://github.com/PAN-YI-HSUAN/Graph-Based-Geometry-Solver
98fe9e501c37948cd2f00d20b8cab4bbee8d7583
d5be20940112db031b9ee56798baac8e93213331
63f8ff0ff24a909547700be41f39202e569c0770
refs/heads/master
2022-12-06T13:50:37.018158
2020-08-31T02:20:02
2020-08-31T02:20:02
290,974,274
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5568519830703735, "alphanum_fraction": 0.5662319660186768, "avg_line_length": 30.91240882873535, "blob_id": "94742b227070ddfe40008de97006bae5423a779e", "content_id": "492dccb63cae5df80b9c0a44a97d537bf5778593", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4385, "license_type": "no_license", "max_line_length": 115, "num_lines": 137, "path": "/Data_processing/parse_for_sentence.py", "repo_name": "PAN-YI-HSUAN/Graph-Based-Geometry-Solver", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nimport requests\nimport json\nimport re\n\n\ndef parse(sentence):\n \"\"\"Parse a sentence with a remote corenlp server\"\"\"\n text = sentence.encode(\"utf-8\")\n\n properties = {\n 'pipelineLanguage': 'zh',\n 'annotators':'tokenize,ssplit,pos,parse,depparse, openie'\n }\n request_params = {\"properties\": json.dumps(properties)}\n res= requests.post('http://140.109.19.191:9000/', data=text, params=request_params)\n res = res.json()\n return res\n\ndef load_raw_data(filename): # load the json data to list(dict()) for MATH 23K\n print(\"Reading lines...\")\n f = open(filename, encoding=\"utf-8\")\n js = \"\"\n data = []\n all_original_text = []\n for i, s in enumerate(f):\n js += s\n i += 1\n if i % 7 == 0: # every 7 line is a json\n data_d = json.loads(js)\n if \"千米/小时\" in data_d[\"equation\"]:\n data_d[\"equation\"] = data_d[\"equation\"][:-5]\n data.append(data_d)\n js = \"\"\n\n for sent in data:\n all_original_text.append(sent[\"original_text\"])\n \n return all_original_text\n\n\n\ndef load_data(path):\n print('Reading lines...')\n all_original_text = []\n with open(path,'r') as f:\n problem_list = json.load(f)\n for problem in problem_list:\n all_original_text.append(problem['original_text'])\n return all_original_text\n\nall_original_text = load_data(\"data/geometry_mwps.json\")\n# all_original_text = load_data(\"data/Math23K_geometry.json\")\n\n\ndef get_tokens_and_dependencies(all_original_text):\n processed_data = []\n for sent in all_original_text:\n tmp = dict()\n res = parse(sent)\n tmp[\"tokens\"] = res[\"sentences\"][0][\"tokens\"]\n tmp[\"dependencies\"] = res[\"sentences\"][0][\"basicDependencies\"]\n processed_data.append(tmp)\n return processed_data\n\ndef get_num_position(tokens):\n group_num = []\n for token in tokens:\n idx, word, pos = token[\"index\"], token[\"word\"], token[\"pos\"]\n if pos == \"CD\":\n pattern = re.compile(\"\\d*\\(\\d+/\\d+\\)\\d*|\\d+\\.\\d+%?|\\d+%?\")\n is_digit = re.search(pattern, word)\n if is_digit:\n group_num.append(idx)\n elif word == \"多少\" or word == '几':\n group_num.append(idx)\n return group_num\n\nprocessed_data = get_tokens_and_dependencies(all_original_text)\n\nfor sent in processed_data:\n sent[\"group_num\"] = get_num_position(sent[\"tokens\"])\n\ndef find_dependency(data, id = 0):\n dependency_list = ['dobj', 'aux:asp', 'advmod', 'nsub', 'dep', 'mark:clf']\n pos_list = ['VV', 'VC', 'DT']\n tmp = []\n if id != 0:\n if data['tokens'][id-1]['pos'] in pos_list:\n for dep in data['dependencies']:\n start_id, end_id, dep, group_num = dep[\"governor\"], dep[\"dependent\"], dep[\"dep\"], data['group_num']\n if (start_id == id) and (dep in dependency_list):\n tmp.extend(find_dependency(data, end_id))\n tmp.append(id)\n return tmp\n\n for dep in data['dependencies']:\n start_id, end_id, dep, group_num = dep[\"governor\"], dep[\"dependent\"], dep[\"dep\"], data['group_num']\n if start_id == 0:\n continue\n if start_id in group_num:\n if dep == 'mark:clf':\n tmp.append(end_id)\n continue\n if end_id in group_num:\n if dep == 'dep':\n tmp.extend(find_dependency(data, start_id))\n elif data['tokens'][start_id-1]['pos'] == 'VV':\n tmp.extend(find_dependency(data, start_id))\n elif dep == 'nummod':\n tmp.extend(find_dependency(data, start_id))\n return tmp\n\nproblem_list = []\ncount = 0\nfor idx, sent in enumerate(processed_data):\n count += 1\n tmp = dict()\n sent['group_num'].extend(find_dependency(sent))\n sent['group_num'] = list(set(sent['group_num']))\n sent['group_num'].sort()\n tmp[\"id\"] = str(count)\n tmp[\"group_num\"] = sent[\"group_num\"]\n problem_list.append(tmp)\n #print(idx, sent['group_num'])\n#print(problem_list[0])\n\nfor problem in problem_list:\n tmp = []\n for num in problem['group_num']:\n tmp.append(num-1)\n problem['group_num'] = tmp\n\n#print(problem_list[0])\n\nwith open(\"geometry_mwps_processed.json\", 'w', encoding='utf-8') as f:\n json.dump(problem_list, f, ensure_ascii = False, indent = 4)" }, { "alpha_fraction": 0.6538236737251282, "alphanum_fraction": 0.6678342223167419, "avg_line_length": 46.58333206176758, "blob_id": "c451b4ff5f687f0b651de87708b2d04f657124b1", "content_id": "9e071e5ce48b1617596300ffacbd844fbab4c8d6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1941, "license_type": "no_license", "max_line_length": 533, "num_lines": 36, "path": "/README.md", "repo_name": "PAN-YI-HSUAN/Graph-Based-Geometry-Solver", "src_encoding": "UTF-8", "text": "# Graph-Based-Geometry-Solver\n```\n├── Graph-Based-Geometry-Solver\n│ ├── Graph2Tree\n│ │ ├── math23k\n│ │ ├── README.md\n│ │ └── requirement.txt\n│ ├── Graph2Tree_on_our_data\n│ │ ├── __pycache__\n│ │ ├── data\n│ │ ├── GCN.py\n│ │ ├── graph.py\n│ │ ├── GraphConvolution.py\n│ │ ├── model_traintest\n│ │ ├── out\n│ │ ├── prev_out.txt\n│ │ ├── readme\n│ │ ├── run_seq2tree_graph.py\n│ │ ├── run_seq2tree_train.py\n│ │ ├── run_seq2tree.py\n│ │ └── src\n│ └── Data_processing\n│ ├── data\n│ ├── geometry_mwps_filter.py\n│ ├── parse_for_sentence.py\n│ └── problem_type_analysis.ipynb\n└──\n```\n## Graph2Tree\nThis model is from [https://github.com/2003pro/Graph2Tree](https://) by the authors Zhang, Jipeng and Wang, Lei and Lee, Roy Ka-Wei and Bin, Yi and Shao, Jie and Lim, Ee-Peng. We mainly run the run_seq2tree_graph.py to test their module.\n\n## Graph2Tree_on_our_data\nIn this folder, there are our processed data including geometry_mwps.json and Math23K_geometry.json. In run_seq2tree_graph.py, we load geometry math word problems to train and test this graph2tree model. And there are consequences of experiments in 'out' directory.\n\n## Data_processing\nThis folder includs all we need code to make our data feasible on graph2tee model. Aiming to focus on geometric math word problems, geometry_mwps_filter.py can load Math_23K dataset and filter out the problems about geometry. The code parse_for_sentence.py can be used to get the relevant word about cardinal numbers from any chinese contexts, and the method is using stanford corenlp toolkit to parsing the POS of each sentence. According to the technique report, we analize the problems in Math_23K by problem_type_analysis.ipynb.\n" }, { "alpha_fraction": 0.4996102750301361, "alphanum_fraction": 0.5183164477348328, "avg_line_length": 26.913043975830078, "blob_id": "bb6de75fddecb50d0a3dd8d3b1712e86bdc6ca12", "content_id": "03f75211500ddd927ed17035e193670b93786c78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 79, "num_lines": 46, "path": "/Data_processing/geometry_mwps_filter.py", "repo_name": "PAN-YI-HSUAN/Graph-Based-Geometry-Solver", "src_encoding": "UTF-8", "text": "import json\n\ndef read_json(path):\n with open(path,'r') as f:\n file = json.load(f)\n return file\n\ndef load_raw_data(filename): # load the json data to list(dict()) for MATH 23K\n print(\"Reading lines...\")\n f = open(filename, encoding=\"utf-8\")\n js = \"\"\n data = []\n for i, s in enumerate(f):\n js += s\n i += 1\n if i % 7 == 0: # every 7 line is a json\n data_d = json.loads(js)\n if \"千米/小时\" in data_d[\"equation\"]:\n data_d[\"equation\"] = data_d[\"equation\"][:-5]\n data.append(data_d)\n js = \"\"\n\n return data\n\ndata_23k = load_raw_data(\"data/Math_23K.json\")\n\nkeyword = ['正方', '长方', '圆', '平行四边', '面积', '体积', '边长', '周长', '宽', '立方', '形']\ncount = 0\nproblem_list = []\nfor problem in data_23k:\n if '3.14' in problem['equation']:\n count += 1\n tmp = problem\n tmp['id'] = count\n problem_list.append(problem)\n continue\n for word in keyword:\n if word in problem['original_text']:\n count += 1\n tmp = problem\n tmp['id'] = count\n problem_list.append(problem)\n break\n\nwith open(\"Math23K_geometry.json\", \"w\", encoding='utf-8') as f:\n json.dump(problem_list, f, ensure_ascii = False, indent = 4 )" }, { "alpha_fraction": 0.5934579372406006, "alphanum_fraction": 0.6004672646522522, "avg_line_length": 24.235294342041016, "blob_id": "899241aed985041488e1fde304827b668a3091ca", "content_id": "8c4b99cdaa389d548e1efeef689d40bdba46bd9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 428, "license_type": "no_license", "max_line_length": 72, "num_lines": 17, "path": "/Graph2Tree_on_our_data/data/test.py", "repo_name": "PAN-YI-HSUAN/Graph-Based-Geometry-Solver", "src_encoding": "UTF-8", "text": "import json\n\ndef read_json(path):\n with open(path,'r') as f:\n file = json.load(f)\n return file\n\ngroup_num = read_json('geometry_mwps_processed.json')\nfor i in group_num:\n tmp = []\n for num in i['group_num']:\n num += 1\n tmp.append(num)\n i['group_num'] = tmp\n\nwith open(\"geometry_mwps_processed_r.json\", 'w', encoding='utf-8') as f:\n json.dump(group_num, f, ensure_ascii = False, indent = 4)" } ]
4
MCMXCIII/Django-Blog
https://github.com/MCMXCIII/Django-Blog
55c67ce07567f5a828374964afde20d9a10cd9d8
be9401c0ca6dbeb9c678f03bd9000325d9065c1d
aa46b3ab5c87abf8f0795b247c10ff287eac8110
refs/heads/master
2021-05-12T16:39:59.992074
2018-03-15T00:32:12
2018-03-15T00:32:12
117,017,893
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6942148804664612, "alphanum_fraction": 0.6942148804664612, "avg_line_length": 29.25, "blob_id": "676c19858a6aacda431693fea89ca0f53880ff5d", "content_id": "0c772601cd5fee4b7feb481e874639b693066596", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "no_license", "max_line_length": 74, "num_lines": 8, "path": "/blog/forms.py", "repo_name": "MCMXCIII/Django-Blog", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Files\n\n#For Class Meta it links back to the mode check the model to make changes.\nclass FileForm(forms.ModelForm):\n class Meta:\n model = Files\n fields = ('description', 'video', )\n" }, { "alpha_fraction": 0.7814207673072815, "alphanum_fraction": 0.7814207673072815, "avg_line_length": 19.22222137451172, "blob_id": "0dfb6eaa4c39847d0100cc8abe87a21f1807d6e1", "content_id": "67454172e2f78b635946ddb4023bdbfdf30e455a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 183, "license_type": "no_license", "max_line_length": 32, "num_lines": 9, "path": "/blog/admin.py", "repo_name": "MCMXCIII/Django-Blog", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Post\nfrom .models import Video\n# Register your models here.\n# new Models\n\nadmin.site.register(Post)\nadmin.site.register(Video)\n\n" }, { "alpha_fraction": 0.47294119000434875, "alphanum_fraction": 0.5435293912887573, "avg_line_length": 19.238094329833984, "blob_id": "34bf38084567f946140c711e6eb4ec65a892eda8", "content_id": "c405075bbc35690062a94fe4a850bec15f0ed260", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 425, "license_type": "no_license", "max_line_length": 45, "num_lines": 21, "path": "/blog/migrations/0004_auto_20180225_2048.py", "repo_name": "MCMXCIII/Django-Blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0 on 2018-02-26 01:48\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0003_auto_20180225_1152'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='video',\n name='title',\n ),\n migrations.RemoveField(\n model_name='video',\n name='urlembed',\n ),\n ]\n" }, { "alpha_fraction": 0.6721469759941101, "alphanum_fraction": 0.6721469759941101, "avg_line_length": 26.157894134521484, "blob_id": "10c555a13ac2056adb6007ba0bebcab61b4d63f4", "content_id": "1ac590cb0a5a9ddc16ea3426ab1b3636ebd0e39d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1034, "license_type": "no_license", "max_line_length": 62, "num_lines": 38, "path": "/blog/views.py", "repo_name": "MCMXCIII/Django-Blog", "src_encoding": "UTF-8", "text": "#Remeber that these functions have to be impoted, check docs!\nfrom django.shortcuts import render\nfrom django.shortcuts import redirect\n\n#Reference the Post model from earlier\nfrom .models import Post\nfrom .models import Video\nfrom .forms import FileForm\n\n# Create your views here.\ndef index(request):\n posts = Post.objects.order_by('-date_pub')\n\n show_posts = {'posts' : posts}\n\n return render(request, 'blog/index.html', show_posts)\n\n#Views for tube extension\ndef tube(request):\n videos = Video.objects.order_by('-date_pub')\n\n show_videos = {'videos' : videos}\n\n return render(request, 'blog/tube.html', show_videos)\n\n\n#This will be moved to another view to merga this with a page.\ndef model_form_upload(request):\n if request.method == 'POST':\n form = FileForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('tube')\n else:\n form = FileForm()\n return render(request, 'blog/model_form_upload.html', {\n 'form': form\n })\n\n\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 26.3125, "blob_id": "4767f5527ad05c4f52c25569db34804c3cc16bf6", "content_id": "aefb119b6022f4c345ffc02807f4c7ed656dbf44", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 437, "license_type": "no_license", "max_line_length": 63, "num_lines": 16, "path": "/questions.py", "repo_name": "MCMXCIII/Django-Blog", "src_encoding": "UTF-8", "text": "from discord.ext import commands\nfrom random import choice, shuffle\nimport aiohttp\nimport functools\nimport asyncio\n\nclass query:\n def __init__(self,bot):\n self.bot = bot\n\[email protected](name=\"question\", no_pm=True,pass_context=True)\nasync def getquestion(self,ctx):\n \"\"\"Built in Helpdesk style ticketing syste for questions\"\"\"\n await self.bot.send_cmd_help(ctx)\n\[email protected](pass_context=True, name=\"question\")\n" }, { "alpha_fraction": 0.4967212975025177, "alphanum_fraction": 0.5508196949958801, "avg_line_length": 23.399999618530273, "blob_id": "1161c556e53d6f95138830029a56bffb4ec7da48", "content_id": "9134de277aec148e506e6ed3d077743a6e8ec181", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 610, "license_type": "no_license", "max_line_length": 63, "num_lines": 25, "path": "/blog/migrations/0005_auto_20180225_2056.py", "repo_name": "MCMXCIII/Django-Blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0 on 2018-02-26 01:56\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0004_auto_20180225_2048'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='video',\n name='title',\n field=models.CharField(default='', max_length=250),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='video',\n name='urlembed',\n field=models.URLField(default=''),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.6902654767036438, "alphanum_fraction": 0.6991150379180908, "avg_line_length": 28.91176414489746, "blob_id": "905c254b215537b51c87652ec4c400671fab9a10", "content_id": "8e3476f00880122573f0c794f67d05321fec827a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1017, "license_type": "no_license", "max_line_length": 64, "num_lines": 34, "path": "/blog/models.py", "repo_name": "MCMXCIII/Django-Blog", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\n\n#new models forms.\n\n\n# Create your models here.\n# New models here\n# Post Model for Blog not Tube\nclass Post(models.Model):\n title = models.CharField(max_length=250)\n body = models.TextField()\n date_pub = models.DateTimeField(default=timezone.now)\n\n def __str__(self):\n return '<Title: {}, ID: {}>'.format(self.title, self.id)\n#For tube posting videos from admin console.\nclass Video(models.Model):\n title = models.CharField(max_length=255)\n slug = models.SlugField(unique = True,help_text=\"Url slugs\")\n video_posts = models.TextField()\n date_pub = models.DateTimeField(default=timezone.now)\n allow_comments = models.BooleanField(default=False)\n\n\n\n def __str__(self):\n return '<ID: {}'.format(self.id)\n\n#For Uploading stuff\nclass Files(models.Model):\n description = models.CharField(max_length=255)\n video = models.FileField(upload_to='videos/')\n uploaded_at = models.DateTimeField(auto_now_add=True)\n" }, { "alpha_fraction": 0.5099502205848694, "alphanum_fraction": 0.5509950518608093, "avg_line_length": 25.799999237060547, "blob_id": "6a795da58b441adcbd39a25be601a9ef56ffdfb1", "content_id": "cf1e6ac656068a5ceaf2bc453783f51b4a861200", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "no_license", "max_line_length": 83, "num_lines": 30, "path": "/blog/migrations/0007_auto_20180226_1222.py", "repo_name": "MCMXCIII/Django-Blog", "src_encoding": "UTF-8", "text": "# Generated by Django 2.0 on 2018-02-26 17:22\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('blog', '0006_auto_20180225_2057'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='video',\n name='allow_comments',\n field=models.BooleanField(default=False),\n ),\n migrations.AddField(\n model_name='video',\n name='slug',\n field=models.SlugField(default='', help_text='Url slugs', unique=True),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='video',\n name='title',\n field=models.CharField(default='', max_length=255),\n preserve_default=False,\n ),\n ]\n" } ]
8
eyobofficial/Payment-Tracker
https://github.com/eyobofficial/Payment-Tracker
3313d79000ee5a849bc1711770d62b908c41a942
da6acaced8a05022c88ab8fa2321765d7c792bd0
7f7d8e9607c3d16a4e6f746b3ea37536f506f7c6
refs/heads/master
2021-03-19T04:50:42.699074
2020-09-20T12:07:37
2020-09-20T12:07:37
247,133,150
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.3554757535457611, "alphanum_fraction": 0.5852782726287842, "avg_line_length": 29.94444465637207, "blob_id": "70f334fb806ce2959fed14b35eb9e321d24ac032", "content_id": "3e49dbdb2d817c8fd0ef1b4e32c42aca62a02fc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 557, "license_type": "no_license", "max_line_length": 224, "num_lines": 18, "path": "/orders/migrations/0016_auto_20200920_1452.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-09-20 11:52\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0015_auto_20200614_1426'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='batch',\n name='year',\n field=models.PositiveIntegerField(choices=[(2010, '2010/2011'), (2011, '2011/2012'), (2012, '2012/2013'), (2013, '2013/2014'), (2014, '2014/2015'), (2015, '2015/2016'), (2016, '2016/2017'), (2017, '2017/2018')]),\n ),\n ]\n" }, { "alpha_fraction": 0.6682316064834595, "alphanum_fraction": 0.6682316064834595, "avg_line_length": 21.785715103149414, "blob_id": "2d5c73fee3031d46a8e8de4c1347a6d942ff56bc", "content_id": "090b958bd60cbd5646bac036e3fd293c574decff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 639, "license_type": "no_license", "max_line_length": 70, "num_lines": 28, "path": "/users/mixins.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib.auth import get_user_model\n\nfrom shared.constants import ROLE_ADMIN\nfrom shared.mixins import BaseAccessMixin\n\n\nUser = get_user_model()\n\n\nclass BaseUserView(BaseAccessMixin):\n \"\"\"\n Base view for all `uers` app views.\n \"\"\"\n page_name = 'users'\n access_roles = [ROLE_ADMIN]\n\n\nclass BaseUserEditView(BaseUserView):\n \"\"\"\n Base view for user related generic and edit views.\n \"\"\"\n model = User\n queryset = User.objects.filter(is_active=True, is_superuser=False)\n\n def get_queryset(self):\n qs = super().get_queryset()\n qs = qs.exclude(pk=self.request.user.pk)\n return qs\n\n" }, { "alpha_fraction": 0.5275833010673523, "alphanum_fraction": 0.5564267635345459, "avg_line_length": 45.376625061035156, "blob_id": "d2a2d8a2822ca02b85a4d20cc1e23b40c2dd3262", "content_id": "d6f14cb2a67fe93a94217cdb0f819c64de7451ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3571, "license_type": "no_license", "max_line_length": 169, "num_lines": 77, "path": "/purchases/migrations/0001_initial.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-10 08:43\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django_countries.fields\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('shared', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ProductCategory',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=120)),\n ],\n options={\n 'verbose_name': 'Product Category',\n 'verbose_name_plural': 'Product Categories',\n 'ordering': ('name',),\n },\n ),\n migrations.CreateModel(\n name='Supplier',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=60, verbose_name='company name')),\n ('city', models.CharField(max_length=60)),\n ('country', django_countries.fields.CountryField(max_length=2)),\n ],\n options={\n 'ordering': ('name',),\n },\n ),\n migrations.CreateModel(\n name='Product',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=120)),\n ('description', models.TextField(blank=True)),\n ('category', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='products', to='purchases.ProductCategory')),\n ('unit', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='products', to='shared.Unit')),\n ],\n options={\n 'ordering': ('name',),\n 'default_related_name': 'products',\n },\n ),\n migrations.CreateModel(\n name='Batch',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=120)),\n ('quantity', models.DecimalField(decimal_places=2, help_text='Quantity in the selected product unit.', max_digits=10)),\n ('rate', models.DecimalField(decimal_places=2, help_text='Price is in USD.', max_digits=10)),\n ('year', models.PositiveIntegerField(choices=[(2008, '2008/2009'), (2009, '2009/2010'), (2010, '2010/2011'), (2011, '2011/2012'), (2012, '2012/2013')])),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('update_at', models.DateTimeField(auto_now=True)),\n ('is_deleted', models.BooleanField(default=False, verbose_name='deleted')),\n ('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='batches', to='purchases.Product')),\n ('supplier', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='batches', to='purchases.Supplier')),\n ],\n options={\n 'verbose_name': 'Purchasing Batch',\n 'verbose_name_plural': 'Purchasing Batches',\n 'ordering': ('-created_at',),\n 'default_related_name': 'batches',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6700167655944824, "alphanum_fraction": 0.6700167655944824, "avg_line_length": 23.875, "blob_id": "b5b133035086f17e803611efb93c5889f91d7118", "content_id": "2216b4ed9570b35c1333da397f020a1f7d63bf6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 597, "license_type": "no_license", "max_line_length": 54, "num_lines": 24, "path": "/purchases/admin.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import ProductCategory, Product, Supplier\n\n\[email protected](Supplier)\nclass SupplierAdmin(admin.ModelAdmin):\n list_display = (\n 'name', 'short_name', 'city', 'email',\n 'phone_number', 'fax_number', 'country'\n )\n\n\[email protected](ProductCategory)\nclass ProductCategoryAdmin(admin.ModelAdmin):\n list_display = ('name', )\n search_fields = ('name', )\n\n\[email protected](Product)\nclass ProductAdmin(admin.ModelAdmin):\n list_display = ('name', 'category', 'unit')\n list_filter = ('category', )\n search_fields = ('name', )\n" }, { "alpha_fraction": 0.6521739363670349, "alphanum_fraction": 0.6687370538711548, "avg_line_length": 26.865385055541992, "blob_id": "e7441d0feb6a362cef049b78cf88a14321c26074", "content_id": "848157ce35a81e5a4432c2bcf344bb55518016fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1449, "license_type": "no_license", "max_line_length": 81, "num_lines": 52, "path": "/accounts/forms.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib.auth.forms import UserCreationForm, UserChangeForm\nfrom django import forms\n\nfrom phonenumber_field.formfields import PhoneNumberField\n\nfrom .models import CustomUser\n\n\nclass CustomUserCreationForm(UserCreationForm):\n phone_number = PhoneNumberField(\n required=False,\n empty_value=None,\n region='ET',\n error_messages={\n 'invalid': 'Enter a valid mobile phone number (e.g. 0911427805)'\n }\n )\n\n class Meta(UserCreationForm.Meta):\n model = CustomUser\n fields = ('email', 'phone_number')\n\n\nclass CustomUserChangeForm(UserChangeForm):\n phone_number = PhoneNumberField(required=False, empty_value=None)\n\n class Meta(UserChangeForm.Meta):\n model = CustomUser\n fields = ('email', 'phone_number')\n\n\nclass UserRegistrationForm(CustomUserCreationForm):\n first_name = forms.CharField(max_length=60)\n last_name = forms.CharField(max_length=60)\n\n class Meta(CustomUserCreationForm.Meta):\n fields = CustomUserCreationForm.Meta.fields + ('first_name', 'last_name')\n\n\nclass ProfileUpdateForm(forms.ModelForm):\n phone_number = PhoneNumberField(\n required=False,\n empty_value=None,\n region='ET',\n error_messages={\n 'invalid': 'Enter a valid mobile phone number (e.g. 0911427805)'\n }\n )\n\n class Meta:\n model = CustomUser\n fields = ('first_name', 'last_name', 'phone_number')\n" }, { "alpha_fraction": 0.5799614787101746, "alphanum_fraction": 0.6416184902191162, "avg_line_length": 26.3157901763916, "blob_id": "88cd7333aa0aa805e442a2815073cde911563d89", "content_id": "cd5be9b45a9322531ff7f4a9ee0af5448c8baebc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 519, "license_type": "no_license", "max_line_length": 144, "num_lines": 19, "path": "/orders/migrations/0010_auto_20200607_2332.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-07 20:32\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0009_auto_20200607_2303'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='deliveryorder',\n name='batch',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='delivery_orders', to='orders.Batch'),\n ),\n ]\n" }, { "alpha_fraction": 0.6669049263000488, "alphanum_fraction": 0.6726232767105103, "avg_line_length": 28.14583396911621, "blob_id": "252a0c9ddcd259d4daa096e691f840e2dbd28042", "content_id": "8b973055572d29284f2c2267533a4c1c3997473c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2798, "license_type": "no_license", "max_line_length": 79, "num_lines": 96, "path": "/purchases/models.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import pendulum\nimport uuid\n\nfrom decimal import Decimal\nfrom functools import reduce\n\nfrom django.conf import settings\nfrom django.db import models\nfrom django_countries.fields import CountryField\n\nfrom phonenumber_field.modelfields import PhoneNumberField\n\nfrom shared.constants import ADVANCE, RETENTION\nfrom shared.models import Unit\nfrom orders.models import Batch\n\nfrom .managers import BatchManager\n\n\nclass Supplier(models.Model):\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n name = models.CharField('company name', max_length=60)\n short_name = models.CharField('abbreviation', max_length=60, blank=True)\n email = models.EmailField(max_length=60, blank=True)\n phone_number = PhoneNumberField(null=True, unique=True)\n fax_number = PhoneNumberField(null=True, unique=True)\n city = models.CharField(max_length=60)\n country = CountryField()\n\n class Meta:\n ordering = ('name', )\n\n def __str__(self):\n return self.short_name or self.name\n\n def get_open_batches(self):\n \"\"\"Returns associated batches with `OPEN` status.\n\n Returns:\n batches (queryset): A queryset of open batches.\n \"\"\"\n return self.batches.filter(status=Batch.OPEN)\n\n def get_closed_batches(self):\n \"\"\"Returns associated batches with `CLOSED` status.\n\n Returns:\n batches (queryset): A queryset of closed batches.\n \"\"\"\n return self.batches.filter(status=Batch.CLOSED)\n\n\nclass ProductCategory(models.Model):\n \"\"\"\n Category of products available for purchase.\n \"\"\"\n name = models.CharField(max_length=120)\n\n class Meta:\n ordering = ('name', )\n verbose_name = 'Product Category'\n verbose_name_plural = 'Product Categories'\n\n def __str__(self):\n return self.name\n\n\nclass Product(models.Model):\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n category = models.ForeignKey(ProductCategory, on_delete=models.PROTECT)\n name = models.CharField(max_length=120)\n unit = models.ForeignKey(Unit, null=True, on_delete=models.SET_NULL)\n description = models.TextField(blank=True)\n\n class Meta:\n ordering = ('name', )\n default_related_name = 'products'\n\n def __str__(self):\n return self.name\n\n def get_open_batches(self):\n \"\"\"Returns associated batches with `OPEN` status.\n\n Returns:\n batches (queryset): A queryset of open batches.\n \"\"\"\n return self.batches.filter(status=Batch.OPEN)\n\n def get_closed_batches(self):\n \"\"\"Returns associated batches with `CLOSED` status.\n\n Returns:\n batches (queryset): A queryset of closed batches.\n \"\"\"\n return self.batches.filter(status=Batch.CLOSED)\n" }, { "alpha_fraction": 0.744339644908905, "alphanum_fraction": 0.7476415038108826, "avg_line_length": 29.724637985229492, "blob_id": "6bd4f453362f29a5c06deb5a1d1aa8e3077a5c71", "content_id": "db9843c67040c37bc12f33278f7bb4f29f14e80e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2120, "license_type": "no_license", "max_line_length": 80, "num_lines": 69, "path": "/orders/tests/factories.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import factory\nimport random\n\nfrom customers.tests.factories import CustomerFactory, LocationFactory, \\\n UnionFactory\nfrom purchases.tests.factories import ProductFactory, SupplierFactory\nfrom orders.models import Batch, UnionDistribution, DeliveryOrder, Allocation, \\\n UnionAllocation, Distribution, UnionDistribution\n\n\nclass BatchFactory(factory.django.DjangoModelFactory):\n name = factory.Sequence(lambda n: f'Batch {n}')\n lc_number = factory.Sequence(lambda n: f'lc_number{n}')\n product = factory.SubFactory(ProductFactory)\n supplier = factory.SubFactory(SupplierFactory)\n year = factory.LazyFunction(lambda: random.choice(Batch.YEAR_CHOICES)[0])\n quantity = 0\n rate = 0\n\n class Meta:\n model = Batch\n\n\nclass DeliveryOrderFactory(factory.django.DjangoModelFactory):\n batch = factory.SubFactory(BatchFactory)\n vessel = factory.Sequence(lambda n: f'Vessel {n}')\n bill_of_loading = factory.Sequence(lambda n: f'bill_of_loading{n}')\n arrival_date = factory.Faker('date_this_decade')\n\n class Meta:\n model = DeliveryOrder\n\n\nclass AllocationFactory(factory.django.DjangoModelFactory):\n delivery_order = factory.SubFactory(DeliveryOrderFactory)\n buyer = factory.SubFactory(CustomerFactory)\n\n class Meta:\n model = Allocation\n\n\nclass UnionAllocationFactory(factory.django.DjangoModelFactory):\n allocation = factory.SubFactory(AllocationFactory)\n union = factory.SubFactory(UnionFactory)\n location = factory.SubFactory(LocationFactory)\n quantity = 0\n\n class Meta:\n model = UnionAllocation\n\n\nclass DistributionFactory(factory.django.DjangoModelFactory):\n delivery_order = factory.SubFactory(DeliveryOrderFactory)\n buyer = factory.SubFactory(CustomerFactory)\n\n class Meta:\n model = Distribution\n\n\nclass UnionDistributionFactory(factory.django.DjangoModelFactory):\n distribution = factory.SubFactory(DistributionFactory)\n union = factory.SubFactory(UnionFactory)\n location = factory.SubFactory(LocationFactory)\n quantity = 0\n shortage = 0\n over = 0\n\n class Meta:\n model = UnionDistribution\n" }, { "alpha_fraction": 0.6714285612106323, "alphanum_fraction": 0.6714285612106323, "avg_line_length": 23.34782600402832, "blob_id": "65cc58e3a7233f97b4cbaf8abb54078724357406", "content_id": "c3c107ac9e4a34d6c46350300f511b5d66825dc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 560, "license_type": "no_license", "max_line_length": 45, "num_lines": 23, "path": "/customers/admin.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Customer, Location, Union\n\n\[email protected](Customer)\nclass CustomerAdmin(admin.ModelAdmin):\n list_display = ('name', 'region', 'code')\n search_fields = ('name', )\n\n\[email protected](Location)\nclass LocationAdmin(admin.ModelAdmin):\n list_display = ('name', 'customer')\n list_filter = ('customer', )\n search_fields = ('name', )\n\n\[email protected](Union)\nclass UnionAdmin(admin.ModelAdmin):\n list_display = ('name', 'customer')\n list_filter = ('customer', )\n search_fields = ('name', )\n" }, { "alpha_fraction": 0.6792849898338318, "alphanum_fraction": 0.6792849898338318, "avg_line_length": 24.70270347595215, "blob_id": "ad36c5b34ae73b81cacb4f43941a4a566e8870ef", "content_id": "20492598a6a071c856c0e1802b05e35efbc72da3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 951, "license_type": "no_license", "max_line_length": 60, "num_lines": 37, "path": "/customers/tests/factories.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import random\nimport factory\n\nfrom customers.models import Union, Customer, Location\n\n\nclass CustomerFactory(factory.django.DjangoModelFactory):\n name = factory.Sequence(lambda n: f'Customer {n}')\n region = factory.Sequence(lambda n: f'Region {n}')\n code = factory.Sequence(lambda n: f'c{n}')\n\n class Meta:\n model = Customer\n\n\nclass UnionFactory(factory.django.DjangoModelFactory):\n name = factory.LazyAttributeSequence(\n lambda obj, n: f'{obj.customer.region} union {n}'\n )\n customer = factory.LazyFunction(\n lambda: random.choice(Customer.objects.all())\n )\n\n class Meta:\n model = Union\n\n\nclass LocationFactory(factory.django.DjangoModelFactory):\n name = factory.LazyAttributeSequence(\n lambda obj, n: f'{obj.customer.region} location {n}'\n )\n customer = factory.LazyFunction(\n lambda: random.choice(Customer.objects.all())\n )\n\n class Meta:\n model = Location\n" }, { "alpha_fraction": 0.6405797004699707, "alphanum_fraction": 0.6405797004699707, "avg_line_length": 19.294116973876953, "blob_id": "b757f43c4e3cde00a33e3072bf496fbb2e816e71", "content_id": "38a4ff9f8ff348d6d0ed2927b3839586bf47fd4d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 345, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/orders/mixins.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from shared.mixins import BaseAccessMixin\n\n\nclass BaseOrderView(BaseAccessMixin):\n \"\"\"\n Base view for all `orders` app views.\n \"\"\"\n page_name = 'delivery-orders'\n access_roles = []\n\n\nclass BaseBatchesView(BaseAccessMixin):\n \"\"\"\n Base view for all `Batch` model views.\n \"\"\"\n page_name = 'batches'\n access_roles = []\n" }, { "alpha_fraction": 0.6370192170143127, "alphanum_fraction": 0.6370192170143127, "avg_line_length": 27.689655303955078, "blob_id": "0575f333b97f3eac91aa3ca383fc121536cfdcd7", "content_id": "8304a3f1303edf37db4c06334a7c44e3430b681c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 832, "license_type": "no_license", "max_line_length": 68, "num_lines": 29, "path": "/accounts/backends.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import phonenumbers\n\nfrom phonenumbers.phonenumberutil import NumberParseException\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.backends import ModelBackend\n\n\nUser = get_user_model()\n\n\nclass PhoneNumberBackend(ModelBackend):\n \"\"\"\n Custom authentication backend to login users using phone number.\n \"\"\"\n\n def authenticate(self, request, username=None, password=None):\n try:\n number = phonenumbers.parse(username, 'ET')\n if not phonenumbers.is_valid_number(number):\n return\n try:\n user = User.objects.get(phone_number=number)\n if user.check_password(password):\n return user\n except User.DoesNotExist:\n return\n except NumberParseException:\n return\n" }, { "alpha_fraction": 0.7272727489471436, "alphanum_fraction": 0.7272727489471436, "avg_line_length": 19.16666603088379, "blob_id": "8a38bf75bd11d87d48762e44a7562ae6d44d69f6", "content_id": "f21820117379981d35b6a6907bd3778ae41c8ff0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 121, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/config/settings/staging.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from .base import *\nfrom decouple import config, Csv\n\n\nDEBUG = False\nALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())\n" }, { "alpha_fraction": 0.6618497371673584, "alphanum_fraction": 0.6734104156494141, "avg_line_length": 15.476190567016602, "blob_id": "a5fc9bd13196dbd1ae20fe2a5a4a65f66289cc96", "content_id": "84da49676771da64319e0b823b113801fe1ec70f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 346, "license_type": "no_license", "max_line_length": 30, "num_lines": 21, "path": "/shared/constants.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from decimal import Decimal\n\n\n\"\"\"Groups\"\"\"\nROLE_ADMIN = 'Admin'\nROLE_MANAGEMENT = 'Management'\nROLE_STAFF = 'Staff'\nROLE_SUPPLIER = 'Supplier'\nROLE_GUEST = 'Guest'\n\n\n\"\"\"Rates\"\"\"\nADVANCE = Decimal('0.9')\nRETENTION = Decimal('0.1')\n\n\"\"\"Environments\"\"\"\nLOCAL = 'LOCAL'\nPRODUCTION = 'PRODUCTION'\nSTAGING = 'STAGING'\nDEMO = 'DEMO'\nTESTING = 'TESTING'\n" }, { "alpha_fraction": 0.5415878891944885, "alphanum_fraction": 0.5935727953910828, "avg_line_length": 53.25640869140625, "blob_id": "b02242c87faa8c4885142241aa41c0c30b2485c7", "content_id": "41b88bd04d052436043146df02d5017f3ca54579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2116, "license_type": "no_license", "max_line_length": 169, "num_lines": 39, "path": "/orders/migrations/0008_batch.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-07 20:02\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0010_auto_20200606_1609'),\n ('orders', '0007_remove_deliveryorder_status'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Batch',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=120)),\n ('lc_number', models.CharField(help_text='Document number for the letter of credit.', max_length=30, verbose_name='L/C number')),\n ('quantity', models.DecimalField(decimal_places=4, help_text='Quantity in the selected product unit.', max_digits=20)),\n ('rate', models.DecimalField(decimal_places=4, help_text='Price is in USD.', max_digits=12)),\n ('year', models.PositiveIntegerField(choices=[(2008, '2008/2009'), (2009, '2009/2010'), (2010, '2010/2011'), (2011, '2011/2012'), (2012, '2012/2013')])),\n ('status', models.CharField(choices=[('OPEN', 'open'), ('CLOSED', 'closed')], default='OPEN', max_length=10)),\n ('is_deleted', models.BooleanField(default=False, verbose_name='deleted')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('product', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='purchases.Product')),\n ('supplier', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='purchases.Supplier')),\n ],\n options={\n 'verbose_name': 'Purchasing Batch',\n 'verbose_name_plural': 'Purchasing Batches',\n 'ordering': ('-created_at',),\n 'permissions': [('close_batch', 'Close purchasing batch'), ('reopen_batch', 'Re-open purchasing batch')],\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5921052694320679, "avg_line_length": 21.799999237060547, "blob_id": "b591cdeb22a0fb6bbcaa4e2a51c84021392acbb4", "content_id": "b76e9574a43f06f960859898fe4d542513d557b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 684, "license_type": "no_license", "max_line_length": 64, "num_lines": 30, "path": "/shared/models.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import uuid\n\nfrom django.db import models\n\n\nclass Unit(models.Model):\n \"\"\"Measurement units.\"\"\"\n WEIGHT = 'WEIGHT'\n VOLUME = 'VOLUME'\n LENGTH = 'LENGTH'\n COUNTER = 'COUNTER'\n\n TYPE_CHOICES = (\n (WEIGHT, 'Weight/Mass'),\n (VOLUME, 'Volume'),\n (LENGTH, 'Length/Distance'),\n (COUNTER, 'Counter')\n )\n\n name = models.CharField(max_length=60)\n code = models.CharField(max_length=10)\n type = models.CharField(max_length=10, choices=TYPE_CHOICES)\n\n class Meta:\n ordering = ('name', )\n verbose_name = 'Measurement Unit'\n verbose_name_plural = 'Measurement Units'\n\n def __str__(self):\n return self.name\n" }, { "alpha_fraction": 0.6610738039016724, "alphanum_fraction": 0.6879194378852844, "avg_line_length": 18.866666793823242, "blob_id": "2657a07dc9219df7405aed378ef6029741bcfe77", "content_id": "9d926f3fd6c028a4ea56761085e75e01ab0f0fa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 298, "license_type": "no_license", "max_line_length": 55, "num_lines": 15, "path": "/Dockerfile", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "FROM python:3.6\nLABEL maintainer='Eyob Tariku'\n\nENV PYTHONDONTWRITEBYTECODE 1\nENV PYTHONUNBUFFERED 1\n\nWORKDIR /code\nCOPY Pipfile* ./\nRUN apt-get update -y && apt-get install netcat -y && \\\n pip install --upgrade pip && \\\n pip install pipenv && \\\n pipenv install --system\nCOPY . .\n\nEXPOSE 8000\n" }, { "alpha_fraction": 0.7643835544586182, "alphanum_fraction": 0.7643835544586182, "avg_line_length": 21.8125, "blob_id": "c044dc4ad160818cc0caf66d98669cb2922f8101", "content_id": "0fc5feed8299e45fb3f2b172f0664f427a8b6401", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "no_license", "max_line_length": 66, "num_lines": 16, "path": "/config/celery.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import, unicode_literals\n\nimport os\nfrom celery import Celery\nfrom decouple import config\n\nfrom django.conf import settings\n\nos.environ.setdefault(\n 'DJANGO_SETTINGS_MODULE',\n config('DJANGO_SETTINGS_MODULE')\n)\n\napp = Celery('config')\napp.config_from_object('django.conf:settings', namespace='CELERY')\napp.autodiscover_tasks()\n" }, { "alpha_fraction": 0.5406626462936401, "alphanum_fraction": 0.5978915691375732, "avg_line_length": 27.869565963745117, "blob_id": "077a658c8cfcff8afc59b90553d0275b2b029489", "content_id": "121552419a21e2cf3fd6f26237002b18f6762a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 123, "num_lines": 23, "path": "/purchases/migrations/0006_auto_20200526_1708.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-26 14:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0005_auto_20200513_2046'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='batch',\n name='quantity',\n field=models.DecimalField(decimal_places=4, help_text='Quantity in the selected product unit.', max_digits=20),\n ),\n migrations.AlterField(\n model_name='batch',\n name='rate',\n field=models.DecimalField(decimal_places=4, help_text='Price is in USD.', max_digits=12),\n ),\n ]\n" }, { "alpha_fraction": 0.508849561214447, "alphanum_fraction": 0.5840708017349243, "avg_line_length": 24.11111068725586, "blob_id": "202edbe6e21db1e05ada4d270726fd8007d40816", "content_id": "2d21f0a1ffb50ebea43b2211938ef08736466a43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 116, "num_lines": 18, "path": "/purchases/migrations/0009_batch_status.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-04 22:29\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0008_auto_20200531_1414'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='batch',\n name='status',\n field=models.CharField(choices=[('OPEN', 'open'), ('CLOSED', 'closed')], default='OPEN', max_length=10),\n ),\n ]\n" }, { "alpha_fraction": 0.5307409167289734, "alphanum_fraction": 0.5480819940567017, "avg_line_length": 36.313724517822266, "blob_id": "c6b5c61618953ee3c96feb57622b44b43b706d5b", "content_id": "e57fd954c1329ec0d5e7db0bf142a2ae074ee427", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1903, "license_type": "no_license", "max_line_length": 144, "num_lines": 51, "path": "/customers/migrations/0001_initial.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-10 08:43\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Customer',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(help_text='Customer company or office name.', max_length=120)),\n ('region', models.CharField(max_length=120, unique=True)),\n ('code', models.CharField(max_length=4, unique=True)),\n ],\n options={\n 'ordering': ('name',),\n },\n ),\n migrations.CreateModel(\n name='Union',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=120)),\n ('location', models.CharField(blank=True, max_length=60)),\n ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='unions', to='customers.Customer')),\n ],\n options={\n 'order_with_respect_to': 'customer',\n },\n ),\n migrations.CreateModel(\n name='Location',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=120)),\n ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='locations', to='customers.Customer')),\n ],\n options={\n 'order_with_respect_to': 'customer',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6041163802146912, "alphanum_fraction": 0.6110153198242188, "avg_line_length": 62.0217399597168, "blob_id": "cdea8b5befe8bea1277dbc614d9d80bc1d9fc057", "content_id": "7a9b62880ce6c4aefde554dcb56f92b272083d95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8697, "license_type": "no_license", "max_line_length": 186, "num_lines": 138, "path": "/orders/migrations/0001_initial.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-10 08:46\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django_countries.fields\nimport orders.models\nimport uuid\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('purchases', '0001_initial'),\n ('customers', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='DeliveryOrder',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('lc_number', models.CharField(max_length=30, verbose_name='letter of credit number')),\n ('vessel', models.CharField(help_text='Shipment vessel name.', max_length=120)),\n ('quantity', models.DecimalField(decimal_places=2, max_digits=10, verbose_name='agreement quantity')),\n ('bill_of_loading', models.CharField(help_text='Bill of loading (B/L) number.', max_length=30)),\n ('arrival_date', models.DateField(verbose_name='vessel arrival date')),\n ('status', models.CharField(choices=[('OPEN', 'open'), ('CLOSED', 'closed')], default='OPEN', max_length=10)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('batch', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='delivery_orders', to='purchases.Batch')),\n ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_orders', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Delivery Order',\n 'verbose_name_plural': 'Delivery Orders',\n 'ordering': ('-created_at',),\n 'permissions': [('close_deliveryorder', 'Close delivery order'), ('reopen_deliveryorder', 'Re-open delivery order')],\n 'default_related_name': 'delivery_orders',\n },\n ),\n migrations.CreateModel(\n name='Distribution',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('buyer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='distributions', to='customers.Customer')),\n ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_distributions', to=settings.AUTH_USER_MODEL)),\n ('delivery_order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='distributions', to='orders.DeliveryOrder')),\n ('updated_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='updated_distributions', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Delivery Order Distribution',\n 'verbose_name_plural': 'Delivery Order Distributions',\n 'ordering': ('delivery_order', 'created_at'),\n 'default_related_name': 'distributions',\n 'unique_together': {('delivery_order', 'buyer')},\n },\n ),\n migrations.CreateModel(\n name='Port',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=120, unique=True)),\n ('country', django_countries.fields.CountryField(countries=orders.models.NeighbourCountry, max_length=2)),\n ('office', models.CharField(blank=True, max_length=120)),\n ('is_default', models.BooleanField(default=False, verbose_name='default')),\n ],\n options={\n 'verbose_name': 'Dispatch Port',\n 'verbose_name_plural': 'Dispatch Ports',\n 'ordering': ('-is_default', 'name'),\n },\n ),\n migrations.AddField(\n model_name='deliveryorder',\n name='port',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='delivery_orders', to='orders.Port'),\n ),\n migrations.AddField(\n model_name='deliveryorder',\n name='updated_by',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='updated_orders', to=settings.AUTH_USER_MODEL),\n ),\n migrations.CreateModel(\n name='Allocation',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('buyer', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='allocations', to='customers.Customer')),\n ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='created_allocations', to=settings.AUTH_USER_MODEL)),\n ('delivery_order', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='allocations', to='orders.DeliveryOrder')),\n ('updated_by', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='updated_allocations', to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Delivery Order Allocation',\n 'verbose_name_plural': 'Delivery Order Allocations',\n 'ordering': ('delivery_order', 'created_at'),\n 'default_related_name': 'allocations',\n 'unique_together': {('delivery_order', 'buyer')},\n },\n ),\n migrations.CreateModel(\n name='UnionDistribution',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('quantity', models.DecimalField(decimal_places=2, help_text='Quantity received by the union in product unit.', max_digits=10, verbose_name='received quantity')),\n ('shortage', models.DecimalField(decimal_places=2, help_text='Quantity deficit after transportation in product unit.', max_digits=10, verbose_name='dispatch shortage')),\n ('over', models.DecimalField(decimal_places=2, help_text='Over quantity supplied in product unit.', max_digits=10, verbose_name='over supplied quantity')),\n ('distribution', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='union_distributions', to='orders.Distribution')),\n ('location', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='union_distributions', to='customers.Location')),\n ('union', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='union_distributions', to='customers.Union')),\n ],\n options={\n 'default_related_name': 'union_distributions',\n 'order_with_respect_to': 'distribution',\n },\n ),\n migrations.CreateModel(\n name='UnionAllocation',\n fields=[\n ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),\n ('quantity', models.DecimalField(decimal_places=2, help_text='Quantity allocated to the union in product unit.', max_digits=10, verbose_name='allocated quantity')),\n ('allocation', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='union_allocations', to='orders.Allocation')),\n ('location', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='union_allocations', to='customers.Location')),\n ('union', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='union_allocations', to='customers.Union')),\n ],\n options={\n 'default_related_name': 'union_allocations',\n 'order_with_respect_to': 'allocation',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5972850918769836, "alphanum_fraction": 0.6262443661689758, "avg_line_length": 38.46428680419922, "blob_id": "272263bfca21233a23de28e12f7951d08045ca6c", "content_id": "517a838de722f981a467bcd4476fa0b60273082a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1105, "license_type": "no_license", "max_line_length": 273, "num_lines": 28, "path": "/orders/migrations/0011_auto_20200607_2341.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-07 20:41\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0010_auto_20200607_2332'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='batch',\n options={'default_related_name': 'batches', 'ordering': ('-created_at',), 'permissions': [('close_batch', 'Close purchasing batch'), ('reopen_batch', 'Re-open purchasing batch')], 'verbose_name': 'Purchasing Batch', 'verbose_name_plural': 'Purchasing Batches'},\n ),\n migrations.AlterField(\n model_name='batch',\n name='product',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='batches', to='purchases.Product'),\n ),\n migrations.AlterField(\n model_name='batch',\n name='supplier',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='batches', to='purchases.Supplier'),\n ),\n ]\n" }, { "alpha_fraction": 0.5873873829841614, "alphanum_fraction": 0.630630612373352, "avg_line_length": 26.75, "blob_id": "164ed2be3e7d41091088bf7073e06da1cd5f1e51", "content_id": "791d4e77b25e521e256cdc1f6ce07b28fffaff24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 555, "license_type": "no_license", "max_line_length": 152, "num_lines": 20, "path": "/accounts/migrations/0002_customuser_supplier.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-10 08:43\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0001_initial'),\n ('accounts', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='customuser',\n name='supplier',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='users', to='purchases.Supplier'),\n ),\n ]\n" }, { "alpha_fraction": 0.5350877046585083, "alphanum_fraction": 0.5935672521591187, "avg_line_length": 19.117647171020508, "blob_id": "cd340c500c3b8e5c74cf038123416fb5eb1eb295", "content_id": "3e6ba1bc042215124a7153f70fb479b2eec2ebb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 342, "license_type": "no_license", "max_line_length": 57, "num_lines": 17, "path": "/orders/migrations/0014_remove_batch_is_deleted.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-13 21:16\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0013_remove_deliveryorder_quantity'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='batch',\n name='is_deleted',\n ),\n ]\n" }, { "alpha_fraction": 0.5066371560096741, "alphanum_fraction": 0.5309734344482422, "avg_line_length": 31.285715103149414, "blob_id": "0e2ce661ac53f10140991842e8e75bbe547744c4", "content_id": "5f2e9b833186fcd726cb175ac9df78d99e0deee8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 904, "license_type": "no_license", "max_line_length": 172, "num_lines": 28, "path": "/shared/migrations/0001_initial.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-10 08:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Unit',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=60)),\n ('code', models.CharField(max_length=10)),\n ('type', models.CharField(choices=[('WEIGHT', 'Weight/Mass'), ('VOLUME', 'Volume'), ('LENGTH', 'Length/Distance'), ('COUNTER', 'Counter')], max_length=10)),\n ],\n options={\n 'verbose_name': 'Measurement Unit',\n 'verbose_name_plural': 'Measurement Units',\n 'ordering': ('name',),\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6078431606292725, "alphanum_fraction": 0.6078431606292725, "avg_line_length": 25.0930233001709, "blob_id": "3234c323d72f55287335f85f3ccbccfd5fa46e3e", "content_id": "ec75ad80e71f3216f11aa946ca397cfd4c2eb346", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1122, "license_type": "no_license", "max_line_length": 75, "num_lines": 43, "path": "/purchases/urls.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom .views import ProductListView, ProductCreateView, ProductUpdateView, \\\n ProductDeleteView, SupplierListView, SupplierCreateView, \\\n SupplierUpdateView, SupplierDeleteView\n\n\napp_name = 'purchases'\n\nurlpatterns = [\n path('products/', ProductListView.as_view(), name='product-list'),\n path(\n 'products/create/',\n ProductCreateView.as_view(),\n name='product-create'\n ),\n path(\n 'products/<uuid:pk>/update/',\n ProductUpdateView.as_view(),\n name='product-update'\n ),\n path(\n 'products/<uuid:pk>/delete/',\n ProductDeleteView.as_view(),\n name='product-delete'\n ),\n path('suppliers/', SupplierListView.as_view(), name='supplier-list'),\n path(\n 'suppliers/create/',\n SupplierCreateView.as_view(),\n name='supplier-create'\n ),\n path(\n 'suppliers/<uuid:pk>/update/',\n SupplierUpdateView.as_view(),\n name='supplier-update'\n ),\n path(\n 'suppliers/<uuid:pk>/delete/',\n SupplierDeleteView.as_view(),\n name='supplier-delete'\n ),\n]\n" }, { "alpha_fraction": 0.6467616558074951, "alphanum_fraction": 0.6481865048408508, "avg_line_length": 34.412845611572266, "blob_id": "440076b2efa8f607cc62d85349025e9ebcba7e65", "content_id": "aad42a5d1a07e124c1d17d570aa8ed03e80e0213", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7720, "license_type": "no_license", "max_line_length": 80, "num_lines": 218, "path": "/orders/views/batches.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from collections import namedtuple, Counter\n\nfrom django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.db.models import Q\nfrom django.http import JsonResponse\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView, CreateView, UpdateView, DeleteView, \\\n DetailView\n\nfrom shared.constants import ROLE_ADMIN, ROLE_MANAGEMENT, ROLE_STAFF, \\\n ROLE_SUPPLIER, ROLE_GUEST\nfrom purchases.models import Supplier, Product\n\nfrom orders.forms import BatchForm\nfrom orders.mixins import BaseBatchesView\nfrom orders.models import Batch, Port\n\n\nclass BaseBatchListView(BaseBatchesView, ListView):\n \"\"\"Abstract base class for open & closed batch list views.\"\"\"\n model = Batch\n paginate_by = 10\n page_name = 'batches'\n status = None\n\n def get_queryset(self):\n qs = super().get_queryset()\n product_pk = self.request.GET.get('product')\n supplier_pk = self.request.GET.get('supplier')\n search_query = self.request.GET.get('search')\n user = self.request.user\n if user.role and user.role.name == ROLE_SUPPLIER:\n qs = qs.filter(supplier=user.supplier)\n if product_pk is not None:\n qs = qs.filter(product__pk=product_pk)\n if supplier_pk is not None:\n qs = qs.filter(supplier__pk=supplier_pk)\n if search_query is not None:\n qs = self.get_search_result(search_query)\n return qs\n\n def get_context_data(self, **kwargs):\n user = self.request.user\n supplier_list = Supplier.objects.filter(\n batches__status=self.status\n ).distinct()\n product_list = Product.objects.filter(\n batches__status=self.status\n ).distinct()\n if user.role is not None and user.role.name == ROLE_SUPPLIER:\n supplier_list = supplier_list.filter(pk=user.supplier.pk)\n product_list = product_list.filter(\n batches__supplier__pk=user.supplier.pk\n )\n kwargs.update({\n 'product_list': product_list,\n 'selected_product': self.request.GET.get('product'),\n 'supplier_list': supplier_list,\n 'selected_supplier': self.request.GET.get('supplier'),\n 'batch_count': self.queryset.count(),\n 'search_query': self.request.GET.get('search', '').strip()\n })\n return super().get_context_data(**kwargs)\n\n def get_search_result(self, query):\n \"\"\"Returns matching batches using search query.\"\"\"\n search_qs = self.queryset.filter(\n Q(name__istartswith=query) | Q(lc_number__istartswith=query) )\n return search_qs\n\n\nclass OpenBatchListView(BaseBatchListView):\n \"\"\"List view of OPEN purchasing batches (lots).\"\"\"\n template_name = 'orders/open_batch_list.html'\n queryset = Batch.objects.filter(status=Batch.OPEN)\n status = Batch.OPEN\n access_roles = '__all__'\n\n\nclass ClosedBatchListView(BaseBatchListView):\n \"\"\"List view of CLOSED purchasing batches (lots).\"\"\"\n template_name = 'orders/closed_batch_list.html'\n queryset = Batch.objects.filter(status=Batch.CLOSED)\n status = Batch.CLOSED\n access_roles = '__all__'\n\n\nclass BatchDetailView(BaseBatchesView, DetailView):\n \"\"\"Detail view for a purchasing batch instance.\"\"\"\n template_name = 'orders/batch_detail.html'\n model = Batch\n queryset = Batch.objects.all()\n page_name = 'batches'\n access_roles = [ROLE_ADMIN, ROLE_MANAGEMENT, ROLE_STAFF, ROLE_GUEST]\n\n def get_context_data(self, **kwargs):\n kwargs['active_pk'] = self.get_active_tab()\n kwargs['port_list'] = Port.objects.all()\n return super().get_context_data(**kwargs)\n\n def get_active_tab(self):\n \"\"\"\n Returns the id of the delivery order that should be\n displayed in the active tab.\n \"\"\"\n active_pk = self.request.GET.get('active_delivery_order')\n if active_pk is None:\n batch = self.get_object()\n default_delivery_order = batch.delivery_orders.first()\n if default_delivery_order is not None:\n active_pk = default_delivery_order.pk\n return active_pk\n\n\nclass BatchCreateView(BaseBatchesView, SuccessMessageMixin, CreateView):\n \"\"\"Create view for creating purchasing batch.\"\"\"\n template_name = 'orders/modals/batches/batch_form.html'\n form_class = BatchForm\n model = Batch\n success_message = 'A new LOT record is successfully created.'\n page_name = 'batches'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_context_data(self, **kwargs):\n kwargs.update({\n 'supplier_list': Supplier.objects.all(),\n 'product_list': Product.objects.all(),\n 'year_choice_list': Batch.YEAR_CHOICES\n })\n return super().get_context_data(**kwargs)\n\n def form_valid(self, form):\n super().form_valid(form)\n return JsonResponse({\n 'status_code': 201,\n 'redirect_url': self.get_success_url()\n })\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass BatchUpdateView(BaseBatchesView, SuccessMessageMixin, UpdateView):\n \"\"\"Update view for editing purchasing batch.\"\"\"\n template_name = 'orders/modals/batches/batch_form.html'\n form_class = BatchForm\n model = Batch\n success_message = 'The LOT data is successfully updated.'\n page_name = 'batches'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_context_data(self, **kwargs):\n kwargs.update({\n 'supplier_list': Supplier.objects.all(),\n 'product_list': Product.objects.all(),\n 'year_choice_list': Batch.YEAR_CHOICES\n })\n return super().get_context_data(**kwargs)\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass BatchCloseView(BaseBatchesView, UpdateView):\n \"\"\"Closes a batch instance.\"\"\"\n template_name = 'orders/modals/batches/batch_close.html'\n model = Batch\n fields = ('status', )\n access_roles = [ROLE_ADMIN]\n\n def form_valid(self, form):\n redirect_url = super().form_valid(form)\n self.object.updated_by=self.request.user\n self.object.save()\n return redirect_url\n\n\nclass BatchReopenView(BaseBatchesView, UpdateView):\n \"\"\"Re-open a closed batch instance.\"\"\"\n template_name = 'orders/modals/batches/batch_reopen.html'\n model = Batch\n fields = ('status', )\n access_roles = [ROLE_ADMIN]\n\n def form_valid(self, form):\n redirect_url = super().form_valid(form)\n self.object.updated_by=self.request.user\n self.object.save()\n return redirect_url\n\n\nclass BatchDeleteView(BaseBatchesView, SuccessMessageMixin, DeleteView):\n \"\"\"Delete view to delete purchasing batch.\"\"\"\n template_name = 'orders/modals/batches/batch_delete_form.html'\n model = Batch\n success_url = reverse_lazy('orders:open-batch-list')\n success_message = 'The selected LOT is successfully deleted.'\n page_name = 'batches'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def delete(self, request, *args, **kwargs):\n \"\"\"Overwrites delete method to change is_delete status `True`.\"\"\"\n redirect_url = super().delete(request, *args, **kwargs)\n messages.success(request, self.success_message)\n return redirect_url\n\n\nclass SupplierPopupView(BaseBatchesView, DetailView):\n \"\"\"A popup modal for supplier summary page.\"\"\"\n template_name = 'orders/modals/supplier_popup.html'\n model = Supplier\n access_roles = '__all__'\n" }, { "alpha_fraction": 0.4957983195781708, "alphanum_fraction": 0.5495798587799072, "avg_line_length": 22.799999237060547, "blob_id": "7938126ac279cb75797649ce3bd36998847c89ca", "content_id": "c22105ccce6f127dacdc7e7b66c36b40467347dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 595, "license_type": "no_license", "max_line_length": 49, "num_lines": 25, "path": "/customers/migrations/0004_auto_20200526_1727.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-26 14:27\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customers', '0003_auto_20200512_1247'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='location',\n options={'ordering': ('name',)},\n ),\n migrations.AlterModelOptions(\n name='union',\n options={'ordering': ('name',)},\n ),\n migrations.AlterOrderWithRespectTo(\n name='location',\n order_with_respect_to=None,\n ),\n ]\n" }, { "alpha_fraction": 0.5859213471412659, "alphanum_fraction": 0.6273291707038879, "avg_line_length": 27.41176414489746, "blob_id": "e0323f2829ebe29579f879e876a45f994a7592d4", "content_id": "6ccfb9e37ee90aa45f855914fa34fc26319e6387", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 169, "num_lines": 17, "path": "/orders/migrations/0015_auto_20200614_1426.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-14 11:26\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0014_remove_batch_is_deleted'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='deliveryorder',\n options={'default_related_name': 'delivery_orders', 'ordering': ('created_at',), 'verbose_name': 'Delivery Order', 'verbose_name_plural': 'Delivery Orders'},\n ),\n ]\n" }, { "alpha_fraction": 0.678174614906311, "alphanum_fraction": 0.6936507821083069, "avg_line_length": 29.361446380615234, "blob_id": "0e1bfd8dcb42e1c5390e1874dde9fb0b9600ebab", "content_id": "8eabef1586d4ce163aabda896142d0b879e1aafd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2520, "license_type": "no_license", "max_line_length": 116, "num_lines": 83, "path": "/README.md", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Woreket Tracker\n## A web application for tracking fertilizer payments\n\n![Thumbnail](thumbnail.png)\n\n### Prerequisites\n* [Python 3.8+](https://www.python.org/downloads/)\n* [Pipenv](https://pipenv.readthedocs.io/en/latest/)\n* [MYSQL 5.7+](https://dev.mysql.com/downloads/mysql/)\n\n\n### Setting up development environment\n\n1. Clone this repo and change to the directory of the project.\n2. Install the project dependencies by running the following command:\n\n ```bash\n $ pipenv install --dev\n ```\n3. Make sure the MySQL Server is up and running.\n\n4. Create a new database. (Example: `woreket_tracker_db`)\n\n5. At the project root directory, there is a file named `.env_example`. Copy the file and rename the copy as `.env`.\n\n6. Open the `.env` file in a text editor and add the following line.\n\n ```bash\n SECRET_KEY='<django secret key>'\n DB_NAME='woreket_tracker_db'\n DB_USER='<database user name>'\n DB_PASSWORD='<database user password>'\n DB_HOST='<host>'\n DJANGO_SETTINGS_MODULE='<setting module path. Eg. config.settings.local>'\n\n ```\n\n **TIP**: To generate a unique secret key value, you can use this [website](https://djecrety.ir/).\n\n7. Save the file.\n\n8. Run fixtures to load initial data.\n\n ```bash\n $ python manage.py runfixtures\n ```\n\n9. Run the following commands to setup database schema and to create dummy data:\n\n ```bash\n $ python manage.py migrate\n ```\n\n10. Run the following command to create an `admin` user:\n\n ```bash\n $ python manage.py defaultsuperuser\n ```\n\n### Usage\n1. Run the following command to run the development web server:\n\n ```bash\n $ python ./manage.py runserver 0.0.0.0:8000\n ```\n\n2. Open a web browser and go to: [http://localhost:8000/admin](http://localhost:8000/admin)\n\n\n### List of Main Tools and Packages Used\n* [Python 3.8+](https://www.python.org/downloads/)\n* [Pipenv](https://pipenv.readthedocs.io/en/latest/)\n* [Django 2.2](https://www.djangoproject.com/download/)\n* [DRF 3.9](https://www.django-rest-framework.org/)\n* [django-cors-headers](https://pypi.org/project/django-cors-headers/)\n* [celery](https://docs.celeryproject.org/)\n* [redis](https://redis.io)\n* [Python Decouple](https://github.com/henriquebastos/python-decouple)\n* [Travis-CI](https://travis-ci.org/)\n* [Gunicorn](https://gunicorn.org/)\n* [django-phonenumber-field](https://github.com/stefanfoulis/django-phonenumber-field)\n* [python-docx](https://python-docx.readthedocs.io/en/latest/)\n* [django-countries](https://github.com/SmileyChris/django-countries/)\n" }, { "alpha_fraction": 0.7222222089767456, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 19.25, "blob_id": "1b17e3f53679ce6a0d7a6e33fe23dcbf02a80225", "content_id": "098386fcae22e7fd0cd910e92230c1d6f80f40e7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 162, "license_type": "no_license", "max_line_length": 43, "num_lines": 8, "path": "/shared/admin.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Unit\n\n\[email protected](Unit)\nclass UnitAdmin(admin.ModelAdmin):\n list_display = ('name', 'code', 'type')\n" }, { "alpha_fraction": 0.6371119618415833, "alphanum_fraction": 0.6375823020935059, "avg_line_length": 33.01599884033203, "blob_id": "a83f5ebb846e5cad352a07572f15b8f8f45ec411", "content_id": "435f7ed05c2bf9fb65c87c13fdfafad63e7e671c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4252, "license_type": "no_license", "max_line_length": 78, "num_lines": 125, "path": "/users/views.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from collections import namedtuple\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group\nfrom django.db.models import Q\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView, DetailView, UpdateView, DeleteView\n\nfrom shared.constants import ROLE_ADMIN, ROLE_MANAGEMENT, ROLE_STAFF, \\\n ROLE_SUPPLIER, ROLE_GUEST\nfrom purchases.models import Supplier\n\nfrom .forms import UserForm\nfrom .mixins import BaseUserEditView\n\n\nUser = get_user_model()\n\n\nclass UserListView(BaseUserEditView, ListView):\n template_name = 'users/user_list.html'\n paginate_by = 10\n access_roles = [ROLE_ADMIN, ROLE_GUEST]\n\n def get_queryset(self):\n qs = super().get_queryset()\n status = self.request.GET.get('status')\n role = self.request.GET.get('role')\n search_query = self.request.GET.get('search')\n\n if status is not None:\n qs = qs.filter(status=status)\n\n if role is not None:\n qs = qs.filter(groups__name=role)\n\n if search_query is not None:\n search_query = search_query.strip()\n qs = self.get_search_result(search_query)\n\n return qs.order_by('status')\n\n def get_context_data(self, **kwargs):\n # status\n status = self.request.GET.get('status')\n all_count = self.queryset.count()\n pending_list = self.queryset.filter(status=User.PENDING)\n active_list = self.queryset.filter(status=User.ACTIVE)\n disabled_list = self.queryset.filter(status=User.DISABLED)\n\n # Role\n role = self.request.GET.get('role')\n admin_list = self.queryset.filter(groups__name=ROLE_ADMIN)\n management_list = self.queryset.filter(groups__name=ROLE_MANAGEMENT)\n staff_list = self.queryset.filter(groups__name=ROLE_STAFF)\n supplier_list = self.queryset.filter(groups__name=ROLE_SUPPLIER)\n guest_list = self.queryset.filter(groups__name=ROLE_GUEST)\n\n kwargs.update({\n # Status\n 'selected_status': status,\n 'all_count': all_count,\n 'pending_count': pending_list.count(),\n 'active_count': active_list.count(),\n 'disabled_count': disabled_list.count(),\n\n # Status Constants\n 'PENDING': User.PENDING,\n 'ACTIVE': User.ACTIVE,\n 'DISABLED': User.DISABLED,\n\n # Role\n 'selected_role': role,\n 'admin_count': admin_list.count(),\n 'management_count': management_list.count(),\n 'staff_count': staff_list.count(),\n 'supplier_count': supplier_list.count(),\n 'guest_count': guest_list.count(),\n\n # Role Constants\n 'ROLE_ADMIN': ROLE_ADMIN,\n 'ROLE_MANAGEMENT': ROLE_MANAGEMENT,\n 'ROLE_STAFF': ROLE_STAFF,\n 'ROLE_SUPPLIER': ROLE_SUPPLIER,\n 'ROLE_GUEST': ROLE_GUEST\n })\n return super().get_context_data(**kwargs)\n\n def get_search_result(self, query):\n \"\"\"Returns a user queryset using search query.\"\"\"\n search_qs = self.queryset.filter(\n Q(first_name__istartswith=query) | Q(last_name__istartswith=query)\n )\n return search_qs\n\n\nclass UserDetailView(BaseUserEditView, DetailView):\n template_name = 'users/modals/user_detail.html'\n access_roles = [ROLE_ADMIN, ROLE_GUEST]\n\n def get_context_data(self, **kwargs):\n kwargs.update(ROLE_SUPPLIER=ROLE_SUPPLIER)\n return super().get_context_data(**kwargs)\n\n\nclass UserUpdateView(BaseUserEditView, UpdateView):\n template_name = 'users/modals/user_form.html'\n form_class = UserForm\n success_url = reverse_lazy('users:user-list')\n\n def get_context_data(self, **kwargs):\n kwargs.update(role_supplier=Group.objects.get(name=ROLE_SUPPLIER))\n return super().get_context_data(**kwargs)\n\n\nclass UserActivateView(BaseUserEditView, UpdateView):\n template_name = 'users/modals/user_activate.html'\n fields = ('status', )\n success_url = reverse_lazy('users:user-list')\n\n\nclass UserDeactivateView(BaseUserEditView, UpdateView):\n template_name = 'users/modals/user_deactivate.html'\n fields = ('status', )\n success_url = reverse_lazy('users:user-list')\n" }, { "alpha_fraction": 0.6231647729873657, "alphanum_fraction": 0.6231647729873657, "avg_line_length": 25.65217399597168, "blob_id": "678468b74e17ff7fa37bfbf3299fe670db2cdd39", "content_id": "b8d80eb1626bf0f3bb53cabcdf8e4c6d900d7844", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 76, "num_lines": 23, "path": "/users/urls.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom .views import UserListView, UserDetailView, UserUpdateView, \\\n UserActivateView, UserDeactivateView\n\n\napp_name = 'users'\n\nurlpatterns = [\n path('', UserListView.as_view(), name='user-list'),\n path('<uuid:pk>/', UserDetailView.as_view(), name='user-detail'),\n path('<uuid:pk>/update/', UserUpdateView.as_view(), name='user-update'),\n path(\n '<uuid:pk>/activate/',\n UserActivateView.as_view(),\n name='user-activate'\n ),\n path(\n '<uuid:pk>/deactivate/',\n UserDeactivateView.as_view(),\n name='user-deactivate'\n ),\n]\n" }, { "alpha_fraction": 0.6316935420036316, "alphanum_fraction": 0.6338702440261841, "avg_line_length": 27.012195587158203, "blob_id": "80f8a9f327e57f87404b5cd5a6524e6b0221338c", "content_id": "0888fb7eb422baa995b9b43068da139c0c8965e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2297, "license_type": "no_license", "max_line_length": 74, "num_lines": 82, "path": "/accounts/models.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from uuid import uuid4\n\nfrom django.conf import settings\nfrom django.contrib.auth.models import AbstractUser, Permission, Group\nfrom django.db import models\n\nfrom phonenumber_field.modelfields import PhoneNumberField\n\nfrom shared.constants import ROLE_ADMIN, ROLE_MANAGEMENT, ROLE_STAFF, \\\n ROLE_SUPPLIER, ROLE_GUEST\nfrom purchases.models import Supplier\n\nfrom .managers import CustomUserManager\n\n\nROLE_GROUPS = [\n ROLE_ADMIN, ROLE_MANAGEMENT,\n ROLE_STAFF, ROLE_SUPPLIER, ROLE_GUEST\n]\n\n\nclass CustomUser(AbstractUser):\n PENDING = 1\n ACTIVE = 2\n DISABLED = 3\n\n STATUS_CHOICES = (\n (PENDING, 'Pending'),\n (ACTIVE, 'Active'),\n (DISABLED, 'Disabled')\n )\n\n id = models.UUIDField(primary_key=True, editable=False, default=uuid4)\n email = models.EmailField('email address', unique=True)\n phone_number = PhoneNumberField(null=True, unique=True)\n status = models.IntegerField(\n choices=STATUS_CHOICES,\n default=PENDING\n )\n supplier = models.ForeignKey(\n Supplier,\n null=True, blank=True,\n on_delete=models.SET_NULL,\n )\n username = None\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['phone_number']\n\n objects = CustomUserManager()\n\n class Meta(AbstractUser.Meta):\n default_related_name = 'users'\n\n def __str__(self):\n return self.email\n\n @property\n def role(self):\n \"\"\"Gets user role.\"\"\"\n return self.groups.filter(name__in=ROLE_GROUPS).first()\n\n @role.setter\n def role(self, role_name):\n \"\"\"Set user role.\"\"\"\n try:\n # Predefined roles\n admin_group = Group.objects.get(name=ROLE_ADMIN)\n staff_group = Group.objects.get(name=ROLE_STAFF)\n management_group = Group.objects.get(name=ROLE_MANAGEMENT)\n supplier_group = Group.objects.get(name=ROLE_SUPPLIER)\n guest_group = Group.objects.get(name=ROLE_GUEST)\n\n # New role\n group = Group.objects.get(name=role_name)\n self.groups.remove(\n admin_group, staff_group, management_group,\n supplier_group, guest_group\n )\n self.groups.add(group)\n except Group.DoesNotExist:\n raise ValueError(f'{role_name} role does not exists.')\n" }, { "alpha_fraction": 0.5593984723091125, "alphanum_fraction": 0.5984962582588196, "avg_line_length": 27.913043975830078, "blob_id": "e9cd4ed32b52ae97efcfbb6b06fed0b065aea4d5", "content_id": "4174cab2598a4c239093e22cb9930b7b3d5180f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 665, "license_type": "no_license", "max_line_length": 123, "num_lines": 23, "path": "/purchases/migrations/0004_auto_20200513_2020.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-13 17:20\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0003_supplier_short_name'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='batch',\n name='quantity',\n field=models.DecimalField(decimal_places=3, help_text='Quantity in the selected product unit.', max_digits=10),\n ),\n migrations.AlterField(\n model_name='batch',\n name='rate',\n field=models.DecimalField(decimal_places=3, help_text='Price is in USD.', max_digits=10),\n ),\n ]\n" }, { "alpha_fraction": 0.7047872543334961, "alphanum_fraction": 0.707446813583374, "avg_line_length": 24.931034088134766, "blob_id": "a9bf9c2079e95b862020c4e490953f960f7ebb2a", "content_id": "08b45e7a6667bea2e86b706ee94cc3edcaed0d28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1504, "license_type": "no_license", "max_line_length": 78, "num_lines": 58, "path": "/orders/admin.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\nfrom .models import Port, DeliveryOrder, Batch, Allocation, UnionAllocation, \\\n Distribution, UnionDistribution\n\n\[email protected](Port)\nclass PortAdmin(admin.ModelAdmin):\n list_display = ('name', 'country', 'is_default')\n list_filter = ('country', 'is_default')\n search_fields = ('name', 'country')\n\n\[email protected](Batch)\nclass BatchAdmin(admin.ModelAdmin):\n list_display = ('name', 'lc_number', 'supplier', 'year')\n list_filter = ('product', 'year')\n search_fields = ('name', )\n\n\nclass AllocationInline(admin.TabularInline):\n model = Allocation\n extra = 0\n\n\nclass DistributionInline(admin.TabularInline):\n model = Distribution\n extra = 0\n\n\[email protected](DeliveryOrder)\nclass DeliveryOrderAdmin(admin.ModelAdmin):\n list_display = ('vessel', 'batch', 'lc_number', 'created_at')\n list_filter = ('batch', 'created_at')\n search_fields = ('lc_number', 'vessel')\n inlines = (AllocationInline, DistributionInline)\n\n\nclass UnionAllocationInline(admin.TabularInline):\n model = UnionAllocation\n extra = 0\n\n\[email protected](Allocation)\nclass AllocationAdmin(admin.ModelAdmin):\n list_display = ('delivery_order', 'buyer')\n inlines = (UnionAllocationInline, )\n\n\nclass UnionDistributionInline(admin.TabularInline):\n model = UnionDistribution\n extra = 0\n\n\[email protected](Distribution)\nclass DistributionAdmin(admin.ModelAdmin):\n list_display = ('delivery_order', 'buyer')\n inlines = (UnionDistributionInline, )\n" }, { "alpha_fraction": 0.5216323733329773, "alphanum_fraction": 0.5314566493034363, "avg_line_length": 34.52349090576172, "blob_id": "8e9a01a6e2d2964d2950ff0cdb50750816e76b44", "content_id": "9a40030b50b3b634df002f2a1d67c6210c567c8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5293, "license_type": "no_license", "max_line_length": 80, "num_lines": 149, "path": "/orders/letters/allocationletter.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from docx.shared import Pt\n\nfrom shared.letters import LetterTemplate, Receiver, Paragraph, Text\nfrom customers.models import Customer\n\n\nclass AllocationLetter(LetterTemplate):\n \"\"\"Class for generating allocation letters.\n\n Attributes:\n receiver: An instance of the Receiver class\n object: An instance of the DeliveryOrder model\n \"\"\"\n BANK_ACCOUNT = '1000176361038'\n\n def __init__(self, delivery_order, *args, **kwargs):\n self.receiver = Receiver(\n name='Commercial Bank of Ethiopia',\n department='Trade Service Special Outlet',\n city='Addis Ababa'\n )\n self.object = delivery_order\n super().__init__(self.receiver, *args, **kwargs)\n\n @property\n def subject(self):\n return f'Documentary Credit Number {self.object.batch.lc_number}'\n\n def _build_content(self, *args, **kwargs):\n \"\"\"Builds the letter content.\"\"\"\n vessel = self.object.vessel\n quantity = self.object.get_allocated_quantity()\n quantity = round(quantity, 2)\n product = self.object.batch.product.name\n category = self.object.batch.product.category.name.lower()\n bol = self.object.bill_of_loading # bill of loading\n batch = self.object.batch.name\n port = self.object.port.name\n office = self.object.port.office\n arrival_date = self.object.arrival_date\n supplier = self.object.batch.supplier.name\n unit = self.object.unit.code\n eabc = Customer.objects.get(code='EABC')\n\n greeting = Paragraph(self.document)\n greeting.add_text(Text('Dear Sirs,'))\n\n p1 = Paragraph(self.document)\n p1.add_texts(\n Text('Reading the subject in caption '),\n Text(vessel, bold=True),\n Text(' a vessel carrying '),\n Text(f'{quantity:,} {unit} {product} {category} ', bold=True),\n Text(f'under B/L {bol} for {batch} ', bold=True),\n Text('will arrive at port of '),\n Text(f'{port} ', bold=True),\n Text('around '),\n Text(f'{arrival_date:%d/%m/%Y}.', bold=True)\n )\n\n p2 = Paragraph(self.document)\n p2.add_texts(\n Text(\n 'On the other hand, we have not yet received original shipping '\n 'documents from our supplier '\n ),\n Text(f'{supplier}. ', bold=True),\n Text(\n 'Therefore, we hereby request your good office to issue us '\n 'delivery order addressing '\n ),\n Text(\n f'{office} and Customs Commissions Addis Ababa Kality Customs '\n 'Branch Office and Debit:',\n bold=True\n )\n )\n\n for allocation in self.object.allocations.all():\n p3 = Paragraph(\n self.document, style='List Bullet',\n line_spacing=1.4, left_indent=Pt(12)\n )\n allocation_quantity = round(allocation.get_total_quantity(), 2)\n if allocation.buyer.code == 'TIG':\n p3.add_texts(\n Text(\n f'{eabc} bank account no. '\n F'{self.BANK_ACCOUNT} for the value of '\n f'{allocation_quantity:,} {unit} '\n f'({allocation.buyer.region} Allocation)',\n bold=True\n )\n )\n else:\n p3.add_texts(\n Text(\n f'{allocation.buyer.name} account for the value of '\n f'{allocation_quantity:,} {unit} ',\n bold=True\n )\n )\n\n p4 = Paragraph(self.document)\n p4.add_texts(\n Text(\n 'For any discrepancies that may occur during the presentation '\n 'of these documents, the Ethiopian Agricultural Business '\n 'Corporation will undertake the responsibility.'\n )\n )\n\n p5 = Paragraph(self.document, space_after=Pt(18))\n p5.add_texts(\n Text('Please note that, we authorize you to debit our bank '),\n Text(f'A/C {self.BANK_ACCOUNT} ', bold=True),\n Text(\n 'with CBE Addis Ababa branch for any related charge to the '\n 'issuance of delivery order.'\n )\n )\n\n salute = Paragraph(self.document)\n salute.add_text(Text('Sincerely yours,', bold=True))\n\n # CC\n p6 = Paragraph(self.document, space_before=Pt(60), space_after=Pt(0))\n p6.add_text(Text('C.C:', bold=True))\n\n p7 = Paragraph(\n self.document, style='List Bullet',\n left_indent=Pt(24), space_before=Pt(0)\n )\n p7.add_text(\n Text('Agricultural Inputs Procurement Department', bold=True)\n )\n\n p8 = Paragraph(\n self.document, style='List Bullet',\n left_indent=Pt(24), space_after=Pt(0)\n )\n p8.add_text(\n Text('Finance Department', bold=True)\n )\n\n p9 = Paragraph(self.document, left_indent=Pt(36), space_before=Pt(0))\n p9.add_text(\n Text('AISS', bold=True, underline=True)\n )\n" }, { "alpha_fraction": 0.6206163763999939, "alphanum_fraction": 0.6206163763999939, "avg_line_length": 19.45652198791504, "blob_id": "78d616adb16b326933adf9602585915153a4c894", "content_id": "8f2708d59ad6bd1603d912ed2536dad0b1fc6ab5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 941, "license_type": "no_license", "max_line_length": 62, "num_lines": 46, "path": "/shared/templatetags/shared_tags.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django import template\n\nregister = template.Library()\n\n\[email protected](name='whole_part')\ndef whole_part(value):\n \"\"\"Returns the whole number part of a decimal.\n\n Args:\n value (Decimal): A decimal number\n\n Returns:\n whole_num (str): A whole number part of the decimal\n \"\"\"\n num = str(value)\n whole, _ = num.split('.')\n return whole\n\n\[email protected](name='decimal_part')\ndef decimal_part(value):\n \"\"\"Returns the decimal part of a number.\n\n Args:\n value (Decimal): A decimal number\n\n Returns:\n decimal_num (str): A decimal number part of the number\n \"\"\"\n num = str(value)\n _, decimal = num.split('.')\n return decimal\n\n\[email protected](name='type')\ndef object_type(value):\n \"\"\"Returns the python object type of the value.\n\n Args:\n value (object): A python object\n\n Returns:\n type (str): The type of the object\n \"\"\"\n return type(value)\n" }, { "alpha_fraction": 0.6162697076797485, "alphanum_fraction": 0.6384190320968628, "avg_line_length": 34.47346878051758, "blob_id": "da0d85ba9f1f0f042b8501afa802ee0f945910f2", "content_id": "4309edcf5136455605ceb301d1725a83e94cf97c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17382, "license_type": "no_license", "max_line_length": 82, "num_lines": 490, "path": "/orders/tests/test_models.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from decimal import Decimal\n\nfrom django.test import TestCase\n\nfrom customers.tests.factories import CustomerFactory\nfrom purchases.tests.factories import ProductFactory\nfrom .factories import BatchFactory, DeliveryOrderFactory, AllocationFactory, \\\n UnionAllocationFactory, DistributionFactory, UnionDistributionFactory\n\n\nclass BatchModelTests(TestCase):\n \"\"\"\n Tests for the `Batch` model.\n \"\"\"\n fixtures = ['units']\n\n def setUp(self):\n self.batch = BatchFactory(name='Test batch', quantity=100, rate=50)\n\n # Delivery Order 1\n delivery_order_1 = DeliveryOrderFactory(batch=self.batch)\n allocation_1_1 = AllocationFactory(delivery_order=delivery_order_1)\n UnionAllocationFactory(allocation=allocation_1_1, quantity=10)\n UnionAllocationFactory(allocation=allocation_1_1, quantity=20)\n\n distribution_1_1 = DistributionFactory(delivery_order=delivery_order_1)\n UnionDistributionFactory(\n distribution=distribution_1_1,\n quantity=10, shortage=1, over=2\n )\n UnionDistributionFactory(\n distribution=distribution_1_1,\n quantity=20, shortage=1, over=2\n )\n\n allocation_1_2 = AllocationFactory(delivery_order=delivery_order_1)\n UnionAllocationFactory(allocation=allocation_1_2, quantity=30)\n UnionAllocationFactory(allocation=allocation_1_2, quantity=40)\n\n distribution_1_2 = DistributionFactory(delivery_order=delivery_order_1)\n UnionDistributionFactory(\n distribution=distribution_1_2,\n quantity=10, shortage=1, over=2\n )\n UnionDistributionFactory(\n distribution=distribution_1_2,\n quantity=20, shortage=1, over=2\n )\n\n # Delivery Order 2\n delivery_order_2 = DeliveryOrderFactory(batch=self.batch)\n allocation_2_1 = AllocationFactory(delivery_order=delivery_order_2)\n UnionAllocationFactory(allocation=allocation_2_1, quantity=50)\n UnionAllocationFactory(allocation=allocation_2_1, quantity=60)\n\n distribution_2_1 = DistributionFactory(delivery_order=delivery_order_2)\n UnionDistributionFactory(\n distribution=distribution_2_1,\n quantity=10, shortage=1, over=2\n )\n UnionDistributionFactory(\n distribution=distribution_2_1,\n quantity=20, shortage=1, over=2\n )\n\n allocation_2_2 = AllocationFactory(delivery_order=delivery_order_2)\n UnionAllocationFactory(allocation=allocation_2_2, quantity=70)\n UnionAllocationFactory(allocation=allocation_2_2, quantity=80)\n\n distribution_2_2 = DistributionFactory(delivery_order=delivery_order_2)\n UnionDistributionFactory(\n distribution=distribution_2_2,\n quantity=10, shortage=1, over=2\n )\n UnionDistributionFactory(\n distribution=distribution_2_2,\n quantity=20, shortage=1, over=2\n )\n\n def test_get_agreement_amount_method(self):\n \"\"\"\n Ensure `get_agreement_amount` method returns the multiplication\n of `quantity` and `rate`.\n \"\"\"\n self.assertEqual(self.batch.get_agreement_amount(), 5000.0000)\n\n def test_get_allocated_quantity_method(self):\n \"\"\"\n Ensure `get_allocated_quantity` method returns the total allocated\n quantities in the product unit.\n \"\"\"\n self.assertEqual(self.batch.get_allocated_quantity(), Decimal('360.0000'))\n\n def test_get_allocated_amount_method(self):\n \"\"\"\n Ensure `get_allocated_amount` method returns the total allocated\n amount in monetary currency.\n \"\"\"\n expected_amount = Decimal('18000.0000')\n self.assertEqual(self.batch.get_allocated_amount(), expected_amount)\n\n def test_get_advance_amount_method(self):\n \"\"\"\n Ensure `get_advance_amount` method returns 90% of the total\n allocated amount for the batch.\n \"\"\"\n expected_amount = Decimal('16200.0000')\n self.assertEqual(self.batch.get_advance_amount(), expected_amount)\n\n def test_get_retention_amount_method(self):\n \"\"\"\n Ensure `get_retention_amount` method returns 10% of the total\n allocated amount for the batch.\n \"\"\"\n expected_amount = Decimal('1800.0000')\n self.assertEqual(self.batch.get_retention_amount(), expected_amount)\n\n def test_get_distributed_quantity_method(self):\n \"\"\"\n Ensure `get_distributed_quantity` method returns the total distributed\n quantities in the product unit.\n \"\"\"\n expected_quantity = Decimal('144.0000')\n self.assertEqual(\n self.batch.get_distributed_quantity(),\n expected_quantity\n )\n\n def test_get_distributed_shortage_method(self):\n \"\"\"\n Ensure `get_distributed_shortage` method returns the total distributed\n shortage (shortage + over quantity) in the product unit.\n \"\"\"\n expected_quantity = Decimal('24.0000')\n self.assertEqual(\n self.batch.get_distributed_shortage(),\n expected_quantity\n )\n\n def test_get_distributed_amount_method(self):\n \"\"\"\n Ensure `get_distributed_amount` method returns the total distributed\n amount in monetary currency.\n \"\"\"\n expected_amount = Decimal('7200.0000')\n self.assertEqual(self.batch.get_distributed_amount(), expected_amount)\n\n\nclass DeliveryOrderTests(TestCase):\n \"\"\"\n Tests for the `DeliveryOrder` model methods.\n \"\"\"\n fixtures = ['units']\n\n def setUp(self):\n batch = BatchFactory(rate=5)\n self.delivery_order = DeliveryOrderFactory(batch=batch)\n\n # Create customers\n self.customer_1 = CustomerFactory()\n self.customer_2 = CustomerFactory()\n self.customer_3 = CustomerFactory()\n\n def test_is_fully_allocated_method_no_allocation(self):\n \"\"\"\n Ensure `is_fully_allocated` method returns `False` when a\n delivery_order instance has no allocation.\n \"\"\"\n self.assertFalse(self.delivery_order.is_fully_allocated())\n\n\n def test_is_fully_allocated_method_with_partial_allocations(self):\n \"\"\"\n Ensure `is_fully_allocated` method returns `False` when a\n delivery order instance is only partially allocated.\n \"\"\"\n AllocationFactory(\n delivery_order=self.delivery_order,\n buyer=self.customer_1\n )\n self.assertFalse(self.delivery_order.is_fully_allocated())\n\n def test_is_fully_allocated_method_with_fully_allocated_order(self):\n \"\"\"\n Ensure `is_fully_allocated` method returns `True` when a\n delivery order instance is fully allocated.\n \"\"\"\n AllocationFactory(\n delivery_order=self.delivery_order,\n buyer=self.customer_1\n )\n AllocationFactory(\n delivery_order=self.delivery_order,\n buyer=self.customer_2\n )\n AllocationFactory(\n delivery_order=self.delivery_order,\n buyer=self.customer_3\n )\n self.assertTrue(self.delivery_order.is_fully_allocated())\n\n def test_is_fully_distributed_method_no_distribution(self):\n \"\"\"\n Ensure `is_fully_distributed` method returns `False` when a\n delivery_order instance has no distribution.\n \"\"\"\n self.assertFalse(self.delivery_order.is_fully_distributed())\n\n def test_is_fully_distributed_method_with_partial_distribution(self):\n \"\"\"\n Ensure `is_fully_distributed` method returns `False` when a\n delivery order instance is only partially distributed.\n \"\"\"\n DistributionFactory(\n delivery_order=self.delivery_order,\n buyer=self.customer_1\n )\n self.assertFalse(self.delivery_order.is_fully_distributed())\n\n def test_is_fully_distributed_method_with_fully_distributed_order(self):\n \"\"\"\n Ensure `is_fully_distributed` method returns `True` when a\n delivery order instance is fully distributed.\n \"\"\"\n DistributionFactory(\n delivery_order=self.delivery_order,\n buyer=self.customer_1\n )\n DistributionFactory(\n delivery_order=self.delivery_order,\n buyer=self.customer_2\n )\n DistributionFactory(\n delivery_order=self.delivery_order,\n buyer=self.customer_3\n )\n self.assertTrue(self.delivery_order.is_fully_distributed())\n\n def test_get_allocated_quantity_method(self):\n \"\"\"\n Ensure `get_allocated_quantity` method returns the total allocated\n quantity of related unions.\n \"\"\"\n allocation_1 = AllocationFactory(delivery_order=self.delivery_order)\n UnionAllocationFactory(allocation=allocation_1, quantity=10)\n UnionAllocationFactory(allocation=allocation_1, quantity=20)\n\n expected_quantity = Decimal('30.0000')\n self.assertEqual(\n self.delivery_order.get_allocated_quantity(),\n expected_quantity\n )\n\n def test_get_distributed_quantity_method(self):\n \"\"\"\n Ensure `get_distributed_quantity` method returns the total distributed\n quantity of related unions.\n \"\"\"\n distribution_1 = DistributionFactory(delivery_order=self.delivery_order)\n UnionDistributionFactory(\n distribution=distribution_1,\n quantity=10, shortage=1, over=2\n )\n UnionDistributionFactory(\n distribution=distribution_1,\n quantity=20, shortage=3, over=4\n )\n\n expected_quantity = Decimal('40.0000')\n self.assertEqual(\n self.delivery_order.get_distributed_quantity(),\n expected_quantity\n )\n\n def test_get_distributed_shortage_method(self):\n \"\"\"\n Ensure `get_distributed_shortage` method returns the total distributed\n shortage quantity of related unions.\n \"\"\"\n distribution_1 = DistributionFactory(delivery_order=self.delivery_order)\n UnionDistributionFactory(\n distribution=distribution_1,\n quantity=10, shortage=1, over=2\n )\n UnionDistributionFactory(\n distribution=distribution_1,\n quantity=20, shortage=3, over=4\n )\n\n expected_quantity = Decimal('10.0000')\n self.assertEqual(\n self.delivery_order.get_distributed_shortage(),\n expected_quantity\n )\n\n def test_get_allocated_amount_method(self):\n \"\"\"\n Ensure `get_allocated_amount` method returns the total allocated\n amount of related unions.\n \"\"\"\n allocation_1 = AllocationFactory(delivery_order=self.delivery_order)\n UnionAllocationFactory(allocation=allocation_1, quantity=10)\n UnionAllocationFactory(allocation=allocation_1, quantity=20)\n\n expected_amount = Decimal('150.0000')\n self.assertEqual(\n self.delivery_order.get_allocated_amount(),\n expected_amount\n )\n\n def test_get_allocated_advance_method(self):\n \"\"\"\n Ensure `get_allocated_advance` method returns 90% of the total\n allocated amount of related unions.\n \"\"\"\n allocation_1 = AllocationFactory(delivery_order=self.delivery_order)\n UnionAllocationFactory(allocation=allocation_1, quantity=10)\n UnionAllocationFactory(allocation=allocation_1, quantity=20)\n\n expected_advance = Decimal('135.0000')\n self.assertEqual(\n self.delivery_order.get_allocated_advance(),\n expected_advance\n )\n\n def test_get_allocated_retention_method(self):\n \"\"\"\n Ensure `get_allocated_retention` method returns 10% of the total\n allocated amount of related unions.\n \"\"\"\n allocation_1 = AllocationFactory(delivery_order=self.delivery_order)\n UnionAllocationFactory(allocation=allocation_1, quantity=10)\n UnionAllocationFactory(allocation=allocation_1, quantity=20)\n\n expected_retention = Decimal('15.0000')\n self.assertEqual(\n self.delivery_order.get_allocated_retention(),\n expected_retention\n )\n\n def test_get_distributed_amount_method(self):\n \"\"\"\n Ensure `get_distributed_amount` method returns the total distributed\n amount of related unions.\n \"\"\"\n distribution_1 = DistributionFactory(delivery_order=self.delivery_order)\n UnionDistributionFactory(\n distribution=distribution_1,\n quantity=10, shortage=1, over=2\n )\n UnionDistributionFactory(\n distribution=distribution_1,\n quantity=20, shortage=3, over=4\n )\n\n expected_amount = Decimal('200.0000')\n self.assertEqual(\n self.delivery_order.get_distributed_amount(),\n expected_amount\n )\n\n\nclass AllocationTests(TestCase):\n \"\"\"\n Tests for `Allocation` model methods.\n \"\"\"\n fixtures = ['units']\n\n def setUp(self):\n batch = BatchFactory(rate=5)\n self.delivery_order = DeliveryOrderFactory(batch=batch)\n\n def test_get_total_quantity_method(self):\n \"\"\"\n Ensure `get_total_quantity` method returns the total union allocations\n quantity for an `Allocation` model instance.\n \"\"\"\n allocation = AllocationFactory(delivery_order=self.delivery_order)\n UnionAllocationFactory(allocation=allocation, quantity=10)\n UnionAllocationFactory(allocation=allocation, quantity=20)\n self.assertEqual(allocation.get_total_quantity(), Decimal('30'))\n\n def test_get_percentage_method(self):\n \"\"\"\n Ensure `get_percentage` method returns the percentage of the allocation\n quantity with respect to the related delivery order.\n \"\"\"\n allocation_1 = AllocationFactory(delivery_order=self.delivery_order)\n UnionAllocationFactory(allocation=allocation_1, quantity=10)\n UnionAllocationFactory(allocation=allocation_1, quantity=20)\n\n allocation_2 = AllocationFactory(delivery_order=self.delivery_order)\n UnionAllocationFactory(allocation=allocation_2, quantity=30)\n UnionAllocationFactory(allocation=allocation_2, quantity=40)\n\n self.assertEqual(allocation_1.get_percentage(), Decimal('30'))\n self.assertEqual(allocation_2.get_percentage(), Decimal('70'))\n\n\nclass DistributionTests(TestCase):\n \"\"\"\n Tests for `Distribution` model methods.\n \"\"\"\n fixtures = ['units']\n\n def setUp(self):\n batch = BatchFactory(rate=5)\n self.delivery_order = DeliveryOrderFactory(batch=batch)\n\n def test_get_total_quantity_method(self):\n \"\"\"\n Ensure `get_total_quantity` method returns the total union distribution\n quantity for an `Allocation` model instance.\n \"\"\"\n distribution = DistributionFactory(delivery_order=self.delivery_order)\n kwargs_1 = {\n 'distribution': distribution,\n 'quantity': 10,\n 'shortage': 1,\n 'over': 2\n }\n kwargs_2 = {\n 'distribution': distribution,\n 'quantity': 20,\n 'shortage': 3,\n 'over': 4\n }\n UnionDistributionFactory(**kwargs_1)\n UnionDistributionFactory(**kwargs_2)\n self.assertEqual(distribution.get_total_quantity(), Decimal('40'))\n\n def test_get_percentage_method(self):\n \"\"\"\n Ensure `get_percentage` method returns the percentage of the\n distribution quantity with respect to the related delivery order.\n \"\"\"\n distribution_1 = DistributionFactory(delivery_order=self.delivery_order)\n UnionDistributionFactory(\n distribution=distribution_1,\n quantity=50, shortage=0, over=0\n )\n UnionDistributionFactory(\n distribution=distribution_1,\n quantity=100, shortage=0, over=0\n )\n\n distribution_2 = DistributionFactory(delivery_order=self.delivery_order)\n UnionDistributionFactory(\n distribution=distribution_2,\n quantity=150, shortage=0, over=0\n )\n UnionDistributionFactory(\n distribution=distribution_2,\n quantity=200, shortage=0, over=0\n )\n\n self.assertEqual(distribution_1.get_percentage(), Decimal('30'))\n self.assertEqual(distribution_2.get_percentage(), Decimal('70'))\n\n\nclass UnionDistributionTests(TestCase):\n \"\"\"\n Tests for `UnionDistribution` model methods.\n \"\"\"\n fixtures = ['units']\n\n def setUp(self):\n self.union_distribution = UnionDistributionFactory(\n quantity=100, shortage=10, over=5\n )\n\n def test_get_total_quantity_method(self):\n \"\"\"\n Ensure `get_total_quantity` method returns the total quantity of\n the union distribution quantity.\n \"\"\"\n self.assertEqual(\n self.union_distribution.get_total_quantity(),\n Decimal('115')\n )\n\n def test_get_total_shortage_method(self):\n \"\"\"\n Ensure `get_total_shortage` method returns the total shortage of\n the union distribution shortage quantity.\n \"\"\"\n self.assertEqual(\n self.union_distribution.get_total_shortage(),\n Decimal('15')\n )\n" }, { "alpha_fraction": 0.6673623919487, "alphanum_fraction": 0.669449508190155, "avg_line_length": 34.82242965698242, "blob_id": "92be6be3fbcff3d53f2e7727a2041b84a31ec47a", "content_id": "81e504e105cd4d15f091efbb2165768649515fe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3833, "license_type": "no_license", "max_line_length": 80, "num_lines": 107, "path": "/customers/views.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.db.models import Q\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView, CreateView, UpdateView, DeleteView\n\nfrom shared.constants import ROLE_ADMIN, ROLE_MANAGEMENT, ROLE_STAFF, ROLE_GUEST\n\nfrom .mixins import BaseCustomersView\nfrom .models import Customer, Union\n\n\nclass UnionListView(BaseCustomersView, ListView):\n \"\"\"List view of registered unions.\"\"\"\n template_name = 'customers/union_list.html'\n model = Union\n paginate_by = 10\n page_name = 'unions'\n queryset = Union.objects.all()\n access_roles = [ROLE_STAFF, ROLE_MANAGEMENT, ROLE_ADMIN, ROLE_GUEST]\n\n def get_queryset(self):\n qs = super().get_queryset()\n region_pk = self.request.GET.get('region', '')\n search_query = self.request.GET.get('search')\n\n if region_pk:\n qs = qs.filter(customer__pk=region_pk)\n\n if search_query is not None:\n qs = self.get_search_result(search_query)\n\n return qs\n\n def get_context_data(self, **kwargs):\n kwargs['customer_list'] = Customer.objects.all()\n kwargs['selected_region'] = self.request.GET.get('region')\n kwargs['union_count'] = self.queryset.count()\n kwargs['search_query'] = self.request.GET.get('search', '').strip()\n return super().get_context_data(**kwargs)\n\n def get_search_result(self, query):\n \"\"\"Returns matching unions using search query.\"\"\"\n return self.queryset.filter(name__istartswith=query)\n\n\nclass UnionCreateView(BaseCustomersView, SuccessMessageMixin, CreateView):\n \"\"\"Create view for creating new unions.\"\"\"\n template_name = 'customers/modals/unions/union_form.html'\n model = Union\n fields = ('name', 'customer')\n success_url = reverse_lazy('customers:union-list')\n success_message = 'A new union is successfully created.'\n page_name = 'unions'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_context_data(self, **kwargs):\n kwargs.update({\n 'customer_list': Customer.objects.all(),\n })\n return super().get_context_data(**kwargs)\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass UnionUpdateView(BaseCustomersView, SuccessMessageMixin, UpdateView):\n \"\"\"Update view for editing existing union.\"\"\"\n template_name = 'customers/modals/unions/union_form.html'\n model = Union\n fields = ('name', 'customer')\n success_url = reverse_lazy('customers:union-list')\n success_message = 'The selected union is successfully updated.'\n page_name = 'unions'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_context_data(self, **kwargs):\n kwargs.update({\n 'customer_list': Customer.objects.all()\n })\n return super().get_context_data(**kwargs)\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass UnionDeleteView(BaseCustomersView, SuccessMessageMixin, DeleteView):\n \"\"\"Delete view to delete a union.\"\"\"\n template_name = 'customers/modals/unions/union_delete_form.html'\n model = Union\n success_url = reverse_lazy('customers:union-list')\n success_message = 'The selected union is successfully deleted.'\n page_name = 'unions'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def delete(self, request, *args, **kwargs):\n \"\"\"Overwrites delete method to send success message.\"\"\"\n self.object = self.get_object()\n self.object.delete()\n success_url = self.get_success_url()\n messages.success(request, self.success_message)\n return redirect(success_url)\n" }, { "alpha_fraction": 0.6635622978210449, "alphanum_fraction": 0.6655579805374146, "avg_line_length": 39.628379821777344, "blob_id": "ca2ba6810ab390fb85570014f58c4b0352ea4e09", "content_id": "2fcf9c926c9e7b53b1d0c02584acbb90dd8b3968", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6013, "license_type": "no_license", "max_line_length": 80, "num_lines": 148, "path": "/orders/views/distributions.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.forms import modelform_factory\nfrom django.shortcuts import get_object_or_404\nfrom django.urls import reverse\nfrom django.views.generic import CreateView, UpdateView, DeleteView, DetailView\n\nfrom shared.constants import ROLE_SUPPLIER, ROLE_ADMIN, ROLE_STAFF\nfrom customers.models import Customer, Union, Location\n\nfrom orders.forms import UnionDistributionFormSet, DistributionForm\nfrom orders.mixins import BaseOrderView\nfrom orders.models import DeliveryOrder, Distribution\n\n\nclass DistributionDetailView(BaseOrderView, DetailView):\n \"\"\"Modal detail view for the distribution quantity calculation.\"\"\"\n template_name = 'orders/modals/distributions/distribution_detail.html'\n model = Distribution\n access_roles = '__all__'\n\n\nclass BaseDistributionEditView(BaseOrderView):\n \"\"\"Base abstract class for Distribution Create & Update views.\"\"\"\n model = Distribution\n form_class = UnionDistributionFormSet\n prefix = 'formset'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def form_invalid(self, formset):\n response = super().form_invalid(formset)\n response.status_code = 400\n return response\n\n\nclass DistributionCreateView(BaseDistributionEditView, CreateView):\n \"\"\"Creates a distribution report for delivery order.\"\"\"\n template_name = 'orders/modals/distributions/distribution_create_form.html'\n\n def get_delivery_order(self):\n order_pk = self.kwargs.get('pk')\n order = get_object_or_404(DeliveryOrder, pk=order_pk)\n return order\n\n def get_context_data(self, **kwargs):\n customers = Customer.objects.all()\n order = self.get_delivery_order()\n distributed_buyers = order.distributions.values_list('buyer', flat=True)\n buyer_choices = [c for c in customers if c.pk not in distributed_buyers]\n\n try:\n buyer_pk = int(self.request.GET.get('buyer'))\n union_choices = Union.objects.filter(customer__pk=buyer_pk)\n location_choices = Location.objects.filter(customer__pk=buyer_pk)\n except TypeError:\n union_choices = Union.objects.all()\n location_choices = Location.objects.all()\n\n DistributionForm = modelform_factory(Distribution, fields=('buyer', ))\n kwargs.update({\n 'buyer_choices': buyer_choices,\n 'union_choices': union_choices,\n 'location_choices': location_choices,\n 'order': order,\n 'formset': self.get_form(),\n 'distribution_form': DistributionForm(self.request.POST or None)\n })\n return super().get_context_data(**kwargs)\n\n def get_success_url(self):\n order_pk = self.kwargs.get('pk')\n delivery_order = get_object_or_404(DeliveryOrder, pk=order_pk)\n batch_id = delivery_order.batch.pk\n url = reverse('orders:batch-detail', args=[batch_id])\n url = f'{url}?active_delivery_order={delivery_order.pk}'\n return url\n\n def form_valid(self, formset):\n context = self.get_context_data()\n distribution_form = context['distribution_form']\n if distribution_form.is_valid():\n self.object = distribution_form.save(commit=False)\n self.object.delivery_order = self.get_delivery_order()\n self.object.created_by = self.request.user\n self.object.save()\n\n formset.instance = self.object\n self.object.delivery_order.touch(updated_by=self.request.user)\n return super().form_valid(formset)\n return super().form_invalid(formset)\n\n\nclass DistributionUpdateView(BaseDistributionEditView, UpdateView):\n \"\"\"Updates a distribution for delivery order.\"\"\"\n template_name = 'orders/modals/distributions/distribution_update_form.html'\n\n def get_context_data(self, **kwargs):\n union_choices = Union.objects.filter(customer=self.object.buyer)\n location_choices = Location.objects.filter(customer=self.object.buyer)\n DistributionForm = modelform_factory(Distribution, fields=('buyer', ))\n kwargs.update({\n 'union_choices': union_choices,\n 'location_choices': location_choices,\n 'order': self.object.delivery_order,\n 'formset': self.get_form(),\n 'distribution_form': DistributionForm(\n self.request.POST or None,\n instance=self.object.buyer\n )\n })\n return super().get_context_data(**kwargs)\n\n def get_success_url(self):\n distribution = self.get_object()\n batch_pk = distribution.delivery_order.batch.pk\n delivery_order_pk = distribution.delivery_order.pk\n url = reverse('orders:batch-detail', args=[batch_pk])\n url = f'{url}?active_delivery_order={delivery_order_pk}'\n return url\n\n def form_valid(self, formset):\n redirect_url = super().form_valid(formset)\n self.object = formset.instance\n self.object.delivery_order.touch(updated_by=self.request.user)\n return redirect_url\n\n\nclass DistributionDeleteView(BaseOrderView, DeleteView):\n \"\"\"Deletes a distribution instance for delivery order.\"\"\"\n template_name = 'orders/modals/distributions/distribution_delete_form.html'\n model = Distribution\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_context_data(self, **kwargs):\n page_section = self.request.GET.get('section')\n kwargs.update(section=page_section)\n return super().get_context_data(**kwargs)\n\n def get_success_url(self):\n batch_pk = self.get_object().delivery_order.batch.pk\n delivery_order_pk = self.get_object().delivery_order.pk\n url = reverse('orders:batch-detail', args=[batch_pk])\n url = f'{url}?active_delivery_order={delivery_order_pk}'\n return url\n\n def delete(self, request, *args, **kwargs):\n delivery_order = self.get_object().delivery_order\n redirect_url = super().delete(request, *args, **kwargs)\n delivery_order.touch(updated_by=request.user)\n return redirect_url\n" }, { "alpha_fraction": 0.5558139681816101, "alphanum_fraction": 0.6069767475128174, "avg_line_length": 22.88888931274414, "blob_id": "a8ce29eb2c558d493dade94d41bdefc6b6ffbefd", "content_id": "69f8a55dcfca18acb06ccc647ff9629b2c7d1824", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 91, "num_lines": 18, "path": "/purchases/migrations/0003_supplier_short_name.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-12 16:17\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0002_supplier_email'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='supplier',\n name='short_name',\n field=models.CharField(blank=True, max_length=60, verbose_name='abbreviation'),\n ),\n ]\n" }, { "alpha_fraction": 0.6048131585121155, "alphanum_fraction": 0.6345788240432739, "avg_line_length": 40.55263137817383, "blob_id": "2199a3ba4021eaf570c09f576fb4d6aa84a28a67", "content_id": "21ac3505343e1c48e424f22478eff196f50309c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1579, "license_type": "no_license", "max_line_length": 173, "num_lines": 38, "path": "/orders/migrations/0003_auto_20200513_2046.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-13 17:46\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0002_auto_20200513_2020'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='deliveryorder',\n name='quantity',\n field=models.DecimalField(decimal_places=4, max_digits=10, verbose_name='agreement quantity'),\n ),\n migrations.AlterField(\n model_name='unionallocation',\n name='quantity',\n field=models.DecimalField(decimal_places=4, help_text='Quantity allocated to the union in product unit.', max_digits=10, verbose_name='allocated quantity'),\n ),\n migrations.AlterField(\n model_name='uniondistribution',\n name='over',\n field=models.DecimalField(decimal_places=4, help_text='Over quantity supplied in product unit.', max_digits=10, verbose_name='over supplied quantity'),\n ),\n migrations.AlterField(\n model_name='uniondistribution',\n name='quantity',\n field=models.DecimalField(decimal_places=4, help_text='Quantity received by the union in product unit.', max_digits=10, verbose_name='received quantity'),\n ),\n migrations.AlterField(\n model_name='uniondistribution',\n name='shortage',\n field=models.DecimalField(decimal_places=4, help_text='Quantity deficit after transportation in product unit.', max_digits=10, verbose_name='dispatch shortage'),\n ),\n ]\n" }, { "alpha_fraction": 0.514018714427948, "alphanum_fraction": 0.5763239860534668, "avg_line_length": 17.882352828979492, "blob_id": "c79db12bb0df9a2d24b5ec28ff435fdd23a1c2ea", "content_id": "8b67ba6a571b2e241e25c0b4bbedb6c0ad3cf88e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 321, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/customers/migrations/0002_remove_union_location.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-11 23:43\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('customers', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='union',\n name='location',\n ),\n ]\n" }, { "alpha_fraction": 0.6258277893066406, "alphanum_fraction": 0.6258277893066406, "avg_line_length": 26.454545974731445, "blob_id": "1e5f77f85c3183403511e174e0fa708bda79ca9b", "content_id": "293b29eeda61c84debf19936bb42ba0ce5f6bdaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 68, "num_lines": 33, "path": "/purchases/forms.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django_countries.fields import CountryField\n\nfrom phonenumber_field.formfields import PhoneNumberField\n\nfrom shared.fields import FormattedNumberField\nfrom .models import Supplier\n\n\nclass SupplierForm(forms.ModelForm):\n \"\"\"Model for creating new supplier.\"\"\"\n phone_number = PhoneNumberField(\n required=False,\n empty_value=None,\n error_messages={\n 'invalid': 'Enter a valid mobile phone number.'\n }\n )\n fax_number = PhoneNumberField(\n required=False,\n empty_value=None,\n error_messages={\n 'invalid': 'Enter a valid fax phone number.'\n }\n )\n country = CountryField(blank_label='Choose country').formfield()\n\n class Meta:\n model = Supplier\n fields = (\n 'name', 'short_name', 'email',\n 'phone_number', 'fax_number', 'city', 'country'\n )\n" }, { "alpha_fraction": 0.6719576716423035, "alphanum_fraction": 0.6719576716423035, "avg_line_length": 20, "blob_id": "210602f663f0868e480c84ca291c4e2a80a0248b", "content_id": "bc2daabf415af8e819aecbd38595fa89eead2a8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 189, "license_type": "no_license", "max_line_length": 43, "num_lines": 9, "path": "/purchases/mixins.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from shared.mixins import BaseAccessMixin\n\n\nclass BasePurchasesView(BaseAccessMixin):\n \"\"\"\n Base view for all `purchses` app views.\n \"\"\"\n page_name = None\n access_roles = []\n" }, { "alpha_fraction": 0.649115264415741, "alphanum_fraction": 0.649115264415741, "avg_line_length": 22.393939971923828, "blob_id": "ab98894dd1ae449962f0d620f22f2f067a70e6bb", "content_id": "0d93a0ddfba0faf25a02b089c6a4248b8969186f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2317, "license_type": "no_license", "max_line_length": 74, "num_lines": 99, "path": "/accounts/tests/factories.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import factory\n\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group\n\nfrom shared.constants import ROLE_ADMIN, ROLE_MANAGEMENT, ROLE_SUPPLIER, \\\n ROLE_STAFF, ROLE_GUEST\nfrom purchases.tests.factories import SupplierFactory\n\n\nUser = get_user_model()\n\n\nclass BaseUserFactory(factory.django.DjangoModelFactory):\n first_name = factory.Faker('first_name')\n last_name = factory.Faker('last_name')\n email = factory.LazyAttribute(lambda o: '{}.{}@test.mail'.format(\n o.first_name, o.last_name))\n\n class Meta:\n model = User\n\n\nclass GroupFactory(factory.django.DjangoModelFactory):\n\n class Meta:\n model = Group\n\n\nclass UserFactory(BaseUserFactory):\n \"\"\"\n Create a random `User` instance with no role assigned.\n \"\"\"\n is_staff = False\n\n\nclass SuperuserFactory(BaseUserFactory):\n \"\"\"\n Create a random `Superuser` instance.\n \"\"\"\n is_staff = True\n is_superuser = True\n\n\nclass AdminUserFactory(UserFactory):\n \"\"\"\n Create a random user with `Admin` role.\n \"\"\"\n @factory.post_generation\n def _attach_role(obj, created, extracted, **kwargs):\n if not created:\n return\n obj.role = ROLE_ADMIN\n\n\nclass ManagementUserFactory(UserFactory):\n \"\"\"\n Create a random user with `Management` role.\n \"\"\"\n @factory.post_generation\n def _attach_role(obj, created, extracted, **kwargs):\n if not created:\n return\n obj.role = ROLE_MANAGEMENT\n\n\nclass StaffUserFactory(UserFactory):\n \"\"\"\n Create a random user with `Staff` role.\n \"\"\"\n @factory.post_generation\n def _attach_role(obj, created, extracted, **kwargs):\n if not created:\n return\n obj.role = ROLE_STAFF\n\n\nclass GuestUserFactory(UserFactory):\n \"\"\"\n Create a random user with `Guest` role.\n \"\"\"\n @factory.post_generation\n def _attach_role(obj, created, extracted, **kwargs):\n if not created:\n return\n obj.role = ROLE_GUEST\n\n\nclass SupplierUserFactory(UserFactory):\n \"\"\"\n Create a random user with `Supplier` role.\n \"\"\"\n supplier = factory.SubFactory(SupplierFactory)\n\n @factory.post_generation\n def _attach_role(obj, created, extracted, **kwargs):\n if not created:\n return\n obj.role = ROLE_SUPPLIER\n\n" }, { "alpha_fraction": 0.5954465866088867, "alphanum_fraction": 0.6304728388786316, "avg_line_length": 32.588233947753906, "blob_id": "c7944077c0869396df09b4a5dfca13446264b2a1", "content_id": "ec4b54df91b67649712feecd407c704046217d15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 571, "license_type": "no_license", "max_line_length": 273, "num_lines": 17, "path": "/purchases/migrations/0010_auto_20200606_1609.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-06 13:09\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0009_batch_status'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='batch',\n options={'default_related_name': 'batches', 'ordering': ('-created_at',), 'permissions': [('close_batch', 'Close purchasing batch'), ('reopen_batch', 'Re-open purchasing batch')], 'verbose_name': 'Purchasing Batch', 'verbose_name_plural': 'Purchasing Batches'},\n ),\n ]\n" }, { "alpha_fraction": 0.6736842393875122, "alphanum_fraction": 0.6736842393875122, "avg_line_length": 20.11111068725586, "blob_id": "2ec6eb1df4d471a365c5318e27860bef8875ca03", "content_id": "928b1cb3a5ec26adc4990bfa2e085e85af59372b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 44, "num_lines": 9, "path": "/customers/mixins.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from shared.mixins import BaseAccessMixin\n\n\nclass BaseCustomersView(BaseAccessMixin):\n \"\"\"\n Base view for all `customers` app views.\n \"\"\"\n page_name = None\n access_roles = []\n" }, { "alpha_fraction": 0.6431670188903809, "alphanum_fraction": 0.6431670188903809, "avg_line_length": 27.8125, "blob_id": "de2aa13217360f6dbf2b41e929d86160c78b0236", "content_id": "ce986ecacd82f98e706c541215cd6ccbf9f21038", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1844, "license_type": "no_license", "max_line_length": 78, "num_lines": 64, "path": "/shared/mixins.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.auth.models import Group\nfrom django.urls import reverse\nfrom django.views.generic.base import ContextMixin\n\n\nUser = get_user_model()\n\n\nclass BaseViewMixin(ContextMixin):\n \"\"\"\n Base view for all views.\n \"\"\"\n page_name = None\n\n def get_context_data(self, **kwargs):\n kwargs.update(page_name=self.page_name)\n kwargs.update({\n 'page_name': self.page_name,\n 'environment': settings.ENVIRONMENT\n })\n return super().get_context_data(**kwargs)\n\n\nclass BaseAccessMixin(LoginRequiredMixin, UserPassesTestMixin, BaseViewMixin):\n \"\"\"\n Base view to filter active users.\n \"\"\"\n access_roles = []\n\n def test_func(self):\n user = self.request.user\n if user.is_superuser:\n return True\n\n if user.status != User.ACTIVE or user.role is None:\n return False\n\n elif (self.access_roles == '__all__' or\n user.role.name in self.access_roles or user.is_superuser):\n return True\n\n def get_permission_denied_message(self):\n user = self.request.user\n if user.status == User.PENDING:\n return 'Your account is not activated yet.'\n elif user.status == User.DISABLED:\n return 'Your account has been disabled.'\n else:\n return \"You don't have the right permission to access this page.\"\n\n\nclass BaseSettingsMixin(BaseAccessMixin):\n \"\"\"\n Base view for all settings pages.\n \"\"\"\n page_name = 'settings'\n setting_name = None\n\n def get_context_data(self, **kwargs):\n kwargs.update(setting_name=self.setting_name)\n return super().get_context_data(**kwargs)\n" }, { "alpha_fraction": 0.6578947305679321, "alphanum_fraction": 0.6578947305679321, "avg_line_length": 24.33333396911621, "blob_id": "fc1948c5e7bc217d1278e272ad381ddf188b4fe4", "content_id": "2122fa0bdc2988f405ba3a5e1aae90b83d20c73f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 228, "license_type": "no_license", "max_line_length": 47, "num_lines": 9, "path": "/shared/fields.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django import forms\n\n\nclass FormattedNumberField(forms.DecimalField):\n \"\"\"Comma separated decimal field.\"\"\"\n\n def to_python(self, value):\n value = value.replace(',', '')\n return super().to_python(value)\n" }, { "alpha_fraction": 0.6214224696159363, "alphanum_fraction": 0.6249642968177795, "avg_line_length": 31.001827239990234, "blob_id": "5037ead8c3f27139173b89d018c6e44d573d9a05", "content_id": "41e3196df1831fbd77f2ee7f565561978d55fda9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17505, "license_type": "no_license", "max_line_length": 78, "num_lines": 547, "path": "/customers/tests/test_views.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom accounts.tests.factories import UserFactory, AdminUserFactory, \\\n GuestUserFactory, ManagementUserFactory, StaffUserFactory\n\nfrom customers.models import Customer, Union\nfrom .factories import CustomerFactory, UnionFactory\n\n\nUser = get_user_model()\n\n\nclass UnionListViewTests(TestCase):\n \"\"\"\n Tests for the `UnionListView` test.\n \"\"\"\n fixtures = ['roles']\n\n def setUp(self):\n self.template = 'customers/union_list.html'\n self.url = reverse('customers:union-list')\n self.user = UserFactory()\n self.admin = AdminUserFactory()\n self.management = ManagementUserFactory()\n self.staff = StaffUserFactory()\n self.guest = GuestUserFactory()\n\n def test_request_with_anonymous_user(self):\n \"\"\"\n Ensure unauthenticated users cannot access the `UnionListView` view.\n \"\"\"\n response = self.client.get(self.url, follow=True)\n expected_url = f'{reverse(\"accounts:login\")}?next=/customers/unions/'\n\n # Assertions\n self.assertRedirects(response, expected_url)\n\n def test_request_with_activated_user_with_admin_role(self):\n \"\"\"\n Ensure activated users with assigned `ADMIN` role can access\n the `UnionListView` view.\n \"\"\"\n # Disable user\n self.admin.status = User.ACTIVE\n self.admin.save()\n\n self.client.force_login(self.admin)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_request_with_activated_user_with_management_role(self):\n \"\"\"\n Ensure activated users with assigned `MANAGEMENT` role can access\n the `UnionListView` view.\n \"\"\"\n # Activate user\n self.management.status = User.ACTIVE\n self.management.save()\n\n self.client.force_login(self.management)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_request_with_activated_user_with_staff_role(self):\n \"\"\"\n Ensure activated users with assigned `STAFF` role can access\n the `UnionListView` view.\n \"\"\"\n # Activate user\n self.staff.status = User.ACTIVE\n self.staff.save()\n\n self.client.force_login(self.staff)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_request_with_activated_user_with_guest_role(self):\n \"\"\"\n Ensure activated users with assigned `GUEST` role can access\n the `UnionListView` view.\n \"\"\"\n # Activate user\n self.guest.status = User.ACTIVE\n self.guest.save()\n\n self.client.force_login(self.guest)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_request_with_disabled_user(self):\n \"\"\"\n Ensure disabled users cannot access the `UnionListView` view.\n \"\"\"\n # Disable user\n self.admin.status = User.DISABLED\n self.admin.save()\n\n self.client.force_login(self.admin)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 403)\n\n def test_request_with_pending_user(self):\n \"\"\"\n Ensure users with pending status cannot access the\n `UnionListView` view.\n \"\"\"\n # Convert user status to pending\n self.admin.status = User.PENDING\n self.admin.save()\n\n self.client.force_login(self.admin)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 403)\n\n\nclass UnionCreateViewTests(TestCase):\n \"\"\"\n Tests for the `UnionCreateView` test.\n \"\"\"\n fixtures = ['roles']\n\n def setUp(self):\n self.template = 'customers/modals/unions/union_form.html'\n self.url = reverse('customers:union-create')\n self.user = UserFactory()\n self.admin = AdminUserFactory()\n self.management = ManagementUserFactory()\n self.staff = StaffUserFactory()\n self.guest = GuestUserFactory()\n\n def test_request_with_anonymous_user(self):\n \"\"\"\n Ensure unauthenticated users cannot access the `UnionCreateView` view.\n \"\"\"\n response = self.client.get(self.url, follow=True)\n queryparam = '/customers/unions/create/'\n expected_url = f'{reverse(\"accounts:login\")}?next={queryparam}'\n\n # Assertions\n self.assertRedirects(response, expected_url)\n\n def test_GET_request_with_activated_user_with_admin_role(self):\n \"\"\"\n Ensure activated users with assigned `ADMIN` role can access\n the `UnionCreateView` view.\n \"\"\"\n # Activate user\n self.admin.status = User.ACTIVE\n self.admin.save()\n\n self.client.force_login(self.admin)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_POST_request_with_activated_user_with_admin_role(self):\n \"\"\"\n Ensure activated users with assigned `ADMIN` role can send POST\n requests to the `UnionCreateView` view.\n \"\"\"\n # Activate user\n self.admin.status = User.ACTIVE\n self.admin.save()\n\n customer = CustomerFactory()\n payload = {\n 'name': 'Test union 01',\n 'customer': customer.pk\n }\n\n self.client.force_login(self.admin)\n response = self.client.post(self.url, payload, follow=True)\n expected_url = reverse('customers:union-list')\n\n # Assertions\n self.assertRedirects(response, expected_url)\n self.assertEqual(Customer.objects.count(), 1)\n\n def test_GET_request_with_activated_user_with_staff_role(self):\n \"\"\"\n Ensure activated users with assigned `STAFF` role can access\n the `UnionCreateView` view.\n \"\"\"\n # Activate user\n self.staff.status = User.ACTIVE\n self.staff.save()\n\n self.client.force_login(self.staff)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_POST_request_with_activated_user_with_staff_role(self):\n \"\"\"\n Ensure activated users with assigned `STAFF` role can send POST\n requests to the `UnionCreateView` view.\n \"\"\"\n # Activate user\n self.staff.status = User.ACTIVE\n self.staff.save()\n\n customer = CustomerFactory()\n payload = {\n 'name': 'Test union 01',\n 'customer': customer.pk\n }\n\n self.client.force_login(self.staff)\n response = self.client.post(self.url, payload, follow=True)\n expected_url = reverse('customers:union-list')\n\n # Assertions\n self.assertRedirects(response, expected_url)\n self.assertEqual(Union.objects.count(), 1)\n\n def test_GET_request_with_activated_user_with_management_role(self):\n \"\"\"\n Ensure activated users with assigned `MANAGEMENT` role cannot access\n the `UnionCreateView` view.\n \"\"\"\n # Activate user\n self.management.status = User.ACTIVE\n self.management.save()\n\n self.client.force_login(self.management)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 403)\n\n def test_GET_request_with_activated_user_with_guest_role(self):\n \"\"\"\n Ensure activated users with assigned `GUEST` role cannot access\n the `UnionCreateView` view.\n \"\"\"\n # Activate user\n self.guest.status = User.ACTIVE\n self.guest.save()\n\n self.client.force_login(self.guest)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 403)\n\nclass UnionUpdateViewTests(TestCase):\n \"\"\"\n Tests for the `UnionUpdateView` test.\n \"\"\"\n fixtures = ['roles', 'customers']\n\n def setUp(self):\n self.template = 'customers/modals/unions/union_form.html'\n self.union = UnionFactory()\n self.url = reverse('customers:union-update', args=[self.union.pk])\n self.user = UserFactory()\n self.admin = AdminUserFactory()\n self.management = ManagementUserFactory()\n self.staff = StaffUserFactory()\n self.guest = GuestUserFactory()\n\n def test_request_with_anonymous_user(self):\n \"\"\"\n Ensure unauthenticated users cannot access the `UnionUpdateView` view.\n \"\"\"\n response = self.client.get(self.url, follow=True)\n queryparam = f'/customers/unions/{self.union.pk}/update/'\n expected_url = f'{reverse(\"accounts:login\")}?next={queryparam}'\n\n # Assertions\n self.assertRedirects(response, expected_url)\n\n def test_GET_request_with_activated_user_with_admin_role(self):\n \"\"\"\n Ensure activated users with assigned `ADMIN` role can access\n the `UnionUpdateView` view.\n \"\"\"\n # Activate user\n self.admin.status = User.ACTIVE\n self.admin.save()\n\n self.client.force_login(self.admin)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_POST_request_with_activated_user_with_admin_role(self):\n \"\"\"\n Ensure activated users with assigned `ADMIN` role can send POST\n requests to the `UnionUpdateView` view.\n \"\"\"\n # Activate user\n self.admin.status = User.ACTIVE\n self.admin.save()\n\n customer = CustomerFactory(name='Test customer updated')\n payload = {\n 'name': 'Test union updated',\n 'customer': customer.pk\n }\n\n self.client.force_login(self.admin)\n response = self.client.post(self.url, payload, follow=True)\n expected_url = reverse('customers:union-list')\n\n self.union.refresh_from_db()\n\n # Assertions\n self.assertRedirects(response, expected_url)\n self.assertEqual(self.union.name, payload['name'])\n self.assertEqual(self.union.customer.pk, payload['customer'])\n\n def test_GET_request_with_activated_user_with_staff_role(self):\n \"\"\"\n Ensure activated users with assigned `STAFF` role can access\n the `UnionUpdateView` view.\n \"\"\"\n # Activate user\n self.staff.status = User.ACTIVE\n self.staff.save()\n\n self.client.force_login(self.staff)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_POST_request_with_activated_user_with_staff_role(self):\n \"\"\"\n Ensure activated users with assigned `STAFF` role can send POST\n requests to the `UnionDeleteView` view.\n \"\"\"\n # Activate user\n self.staff.status = User.ACTIVE\n self.staff.save()\n\n customer = CustomerFactory(name='Test customer updated')\n payload = {\n 'name': 'Test union updated',\n 'customer': customer.pk\n }\n\n self.client.force_login(self.staff)\n response = self.client.post(self.url, payload, follow=True)\n expected_url = reverse('customers:union-list')\n\n self.union.refresh_from_db()\n\n # Assertions\n self.assertRedirects(response, expected_url)\n self.assertEqual(self.union.name, payload['name'])\n self.assertEqual(self.union.customer.pk, payload['customer'])\n\n def test_GET_request_with_activated_user_with_management_role(self):\n \"\"\"\n Ensure activated users with assigned `MANAGEMENT` role cannot access\n the `UnionUpdateView` view.\n \"\"\"\n # Activate user\n self.management.status = User.ACTIVE\n self.management.save()\n\n self.client.force_login(self.management)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 403)\n\n def test_GET_request_with_activated_user_with_guest_role(self):\n \"\"\"\n Ensure activated users with assigned `GUEST` role cannot access\n the `UnionUpdateView` view.\n \"\"\"\n # Activate user\n self.guest.status = User.ACTIVE\n self.guest.save()\n\n self.client.force_login(self.guest)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 403)\n\n\n\n\n\nclass UnionDeleteViewTests(TestCase):\n \"\"\"\n Tests for the `UnionDeleteView` test.\n \"\"\"\n fixtures = ['roles', 'customers']\n\n def setUp(self):\n self.template = 'customers/modals/unions/union_delete_form.html'\n self.union = UnionFactory()\n self.url = reverse('customers:union-delete', args=[self.union.pk])\n self.user = UserFactory()\n self.admin = AdminUserFactory()\n self.management = ManagementUserFactory()\n self.staff = StaffUserFactory()\n self.guest = GuestUserFactory()\n\n def test_request_with_anonymous_user(self):\n \"\"\"\n Ensure unauthenticated users cannot access the `UnionDeleteView` view.\n \"\"\"\n response = self.client.get(self.url, follow=True)\n queryparam = f'/customers/unions/{self.union.pk}/delete/'\n expected_url = f'{reverse(\"accounts:login\")}?next={queryparam}'\n\n # Assertions\n self.assertRedirects(response, expected_url)\n\n def test_GET_request_with_activated_user_with_admin_role(self):\n \"\"\"\n Ensure activated users with assigned `ADMIN` role can access\n the `UnionDeleteView` view.\n \"\"\"\n # Activate user\n self.admin.status = User.ACTIVE\n self.admin.save()\n\n self.client.force_login(self.admin)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_POST_request_with_activated_user_with_admin_role(self):\n \"\"\"\n Ensure activated users with assigned `ADMIN` role can send POST\n requests to the `UnionDeleteView` view.\n \"\"\"\n # Activate user\n self.admin.status = User.ACTIVE\n self.admin.save()\n\n customer = CustomerFactory(name='Test customer updated')\n payload = {\n 'name': 'Test union updated',\n 'customer': customer.pk\n }\n\n self.client.force_login(self.admin)\n response = self.client.post(self.url, payload, follow=True)\n expected_url = reverse('customers:union-list')\n\n # Assertions\n self.assertRedirects(response, expected_url)\n self.assertEqual(Union.objects.count(), 0)\n\n\n def test_GET_request_with_activated_user_with_staff_role(self):\n \"\"\"\n Ensure activated users with assigned `STAFF` role can access\n the `UnionDeleteView` view.\n \"\"\"\n # Activate user\n self.staff.status = User.ACTIVE\n self.staff.save()\n\n self.client.force_login(self.staff)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 200)\n self.assertTemplateUsed(response, self.template)\n\n def test_POST_request_with_activated_user_with_staff_role(self):\n \"\"\"\n Ensure activated users with assigned `STAFF` role can send POST\n requests to the `UnionDeleteView` view.\n \"\"\"\n # Activate user\n self.staff.status = User.ACTIVE\n self.staff.save()\n\n customer = CustomerFactory(name='Test customer updated')\n payload = {\n 'name': 'Test union updated',\n 'customer': customer.pk\n }\n\n self.client.force_login(self.staff)\n response = self.client.post(self.url, payload, follow=True)\n expected_url = reverse('customers:union-list')\n\n # Assertions\n self.assertRedirects(response, expected_url)\n self.assertEqual(Union.objects.count(), 0)\n\n def test_GET_request_with_activated_user_with_management_role(self):\n \"\"\"\n Ensure activated users with assigned `MANAGEMENT` role cannot access\n the `UnionDeleteView` view.\n \"\"\"\n # Activate user\n self.management.status = User.ACTIVE\n self.management.save()\n\n self.client.force_login(self.management)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 403)\n\n def test_GET_request_with_activated_user_with_guest_role(self):\n \"\"\"\n Ensure activated users with assigned `GUEST` role cannot access\n the `UnionDeleteView` view.\n \"\"\"\n # Activate user\n self.guest.status = User.ACTIVE\n self.guest.save()\n\n self.client.force_login(self.guest)\n response = self.client.get(self.url)\n\n # Assertions\n self.assertEqual(response.status_code, 403)\n" }, { "alpha_fraction": 0.7105262875556946, "alphanum_fraction": 0.7763158082962036, "avg_line_length": 24.33333396911621, "blob_id": "1e9acb476bffc7e5bd81934ea64e21deddb6aad2", "content_id": "42f0257d33ff960a47296de81c0b0901c3a135cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 76, "license_type": "no_license", "max_line_length": 48, "num_lines": 3, "path": "/nginx/Dockerfile", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "FROM nginx:1.15.12-alpine\n\nCOPY default.conf /etc/nginx/conf.d/default.conf\n" }, { "alpha_fraction": 0.7242424488067627, "alphanum_fraction": 0.739393949508667, "avg_line_length": 21.758621215820312, "blob_id": "328d6ab516a8e726f39af90acb9ff5ba659eef07", "content_id": "11b906846383fa0fec8f94a1568d7f95e32c659c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 660, "license_type": "no_license", "max_line_length": 67, "num_lines": 29, "path": "/script/run_web.sh", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Check if database is ready\necho 'Waiting for database....'\nwhile ! nc -z $DB_HOST $DB_PORT; do\n sleep 1s\ndone\n\necho 'Database is ready.'\n\n# Prepare app\necho 'Run migrations...'\npython manage.py makemigrations # TODO: Remove in production code\npython manage.py migrate --no-input\n\n# Run initial fixtures\npython manage.py runfixtures\n\n# Create a default superuser account\necho 'Create a default superuser account...'\npython manage.py defaultsuperuser\n\n\necho 'Collect static files...'\npython manage.py collectstatic --no-input --clear\n\n# Run gunicorn server\necho 'Start Gunicorn server...'\ngunicorn --bind 0.0.0.0:8000 --workers 3 config.wsgi\n" }, { "alpha_fraction": 0.47925013303756714, "alphanum_fraction": 0.4978368878364563, "avg_line_length": 45.92481231689453, "blob_id": "f32ca5dcc6257ffea7bfc31419ec660074aedbe5", "content_id": "4ba400d38b39d6078333861249828a00b7ed384b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 6241, "license_type": "no_license", "max_line_length": 157, "num_lines": 133, "path": "/orders/templates/orders/partials/delivery_order_tabs.html", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "{% load humanize %}\n\n<div id=\"tab-container\" class=\"mg-t-30\">\n <!-- Tab Menus -->\n <ul class=\"nav nav-tabs\" id=\"delivery-orders-tab\" role=\"tablist\">\n {% for delivery_order in object.delivery_orders.all %}\n <li class=\"nav-item\">\n <a\n class=\"nav-link {% if active_pk|safe == delivery_order.pk|safe %}active{% endif %}\"\n id=\"tab-{{ delivery_order.pk }}\" data-toggle=\"tab\" role=\"tab\"\n href=\"#tab-pane-{{ delivery_order.pk }}\">{{ delivery_order.vessel }}</a>\n </li>\n {% endfor %}\n\n {% if object.status == object.OPEN and perms.orders.add_deliveryorder %}\n <li class=\"nav-item\">\n <a\n class=\"nav-link {% if not active_pk %}active{% endif %}\"\n id=\"tab-new\" data-toggle=\"tab\" role=\"tab\" href=\"#tab-pane-new\"><i class=\"fas fa-plus tx-12\"></i></a>\n </li>\n {% endif %}\n </ul><!-- ./ End Tab Menu -->\n\n <!-- Tab Content -->\n <div class=\"tab-content bd bd-gray-300 bd-t-0 pd-20\" id=\"delivery-orders-tab-content\">\n {% for delivery_order in object.delivery_orders.all %}\n <div class=\"tab-pane fade {% if active_pk|safe == delivery_order.pk|safe %}active show{% endif %}\" role=\"tabpanel\" id=\"tab-pane-{{ delivery_order.pk }}\">\n <div class=\"d-flex justify-content-between\">\n <div>\n {% if object.status == object.OPEN and perms.orders.change_deliveryorder %}\n <button data-url=\"{% url 'orders:order-update' delivery_order.pk %}\" class=\"btn btn-sm pd-x-20 btn-primary btn-uppercase mg-l-5 btn-modal\">\n <i data-feather=\"edit\" class=\"wd-10 mg-r-5\"></i> Edit\n </button>\n {% endif %}\n </div>\n\n <div>\n <a href=\"{% url 'orders:order-allocation-letter' delivery_order.pk %}\" class=\"btn btn-sm pd-x-20 btn-white btn-uppercase mg-l-5\">\n <i data-feather=\"file-text\" class=\"wd-10 mg-r-5\"></i> Letter\n </a>\n {% if object.status == object.OPEN and perms.orders.delete_deliveryorder %}\n <button data-url=\"{% url 'orders:order-delete' delivery_order.pk %}\" class=\"btn btn-sm pd-x-20 btn-danger btn-uppercase mg-l-5 btn-modal\">\n <i data-feather=\"trash\" class=\"wd-10 mg-r-5\"></i> Delete\n </button>\n {% endif %}\n </div>\n </div>\n <div class=\"card mg-t-20 mg-b-30\">\n <div class=\"card-header\">\n <h5 class=\"mg-b-0\">{{ delivery_order.vessel }} Vessel Summary</h5>\n </div>\n <div class=\"card-body pd-0\">\n <div class=\"row no-gutters\">\n <div class=\"col col-sm-6 col-lg\">\n <div class=\"crypto\">\n <div class=\"media mg-b-10 pd-y-25\">\n <div class=\"crypto-icon bg-secondary\">\n <i class=\"fas fa-truck-loading\"></i>\n </div><!-- crypto-icon -->\n <div class=\"media-body pd-l-8\">\n <h6 class=\"tx-11 tx-spacing-1 tx-uppercase tx-color-03 mg-b-5\">Bill of Loading</h6>\n <div class=\"d-flex align-items-baseline tx-rubik\">\n <h5 class=\"tx-18 mg-b-0\">{{ delivery_order.bill_of_loading }}</h5>\n </div>\n </div><!-- media-body -->\n </div><!-- media -->\n </div><!-- crypto -->\n </div>\n\n <div class=\"col col-sm-6 col-lg bd-t bd-sm-t-0 bd-sm-l\">\n <div class=\"crypto\">\n <div class=\"media mg-b-10 pd-y-25\">\n <div class=\"crypto-icon bg-success\">\n <i class=\"fas fa-anchor\"></i>\n </div>\n <div class=\"media-body pd-l-8\">\n <h6 class=\"tx-11 tx-spacing-1 tx-uppercase tx-color-03 mg-b-5\">Port</h6>\n <div class=\"d-flex align-items-baseline tx-rubik\">\n <h5 class=\"tx-18 mg-b-0\">{{ delivery_order.port }}</h5>\n </div>\n </div><!-- media-body -->\n </div><!-- media -->\n </div><!-- crypto -->\n </div>\n <div class=\"col col-sm-6 col-lg bd-t bd-lg-t-0 bd-lg-l\">\n <div class=\"crypto\">\n <div class=\"media mg-b-10 pd-y-25\">\n <div class=\"crypto-icon bg-litecoin\">\n <i class=\"far fa-calendar\"></i>\n </div><!-- crypto-icon -->\n <div class=\"media-body pd-l-8\">\n <h6 class=\"tx-11 tx-spacing-1 tx-uppercase tx-color-03 mg-b-5\">Arrival Date</h6>\n <div class=\"d-flex align-items-baseline tx-rubik\">\n <h5 class=\"tx-18 mg-b-0\">{{ delivery_order.arrival_date|date:'M d, Y' }}</h5>\n </div>\n </div><!-- media-body -->\n </div><!-- media -->\n </div><!-- crypto -->\n </div>\n <div class=\"col col-sm-6 col-lg bd-t bd-lg-t-0 bd-sm-l\">\n <div class=\"crypto\">\n <div class=\"media mg-b-10 pd-y-25\">\n <div class=\"crypto-icon bg-primary\">\n <i class=\"fas fa-balance-scale\"></i>\n </div><!-- crypto-icon -->\n <div class=\"media-body pd-l-8\">\n <h6 class=\"tx-11 tx-spacing-1 tx-uppercase tx-color-03 mg-b-5\">Quantity ({{ delivery_order.unit.code }})</h6>\n <div class=\"d-flex align-items-baseline tx-rubik\">\n <h5 class=\"tx-18 mg-b-0\">{{ delivery_order.get_allocated_quantity|floatformat:2|intcomma }}</h5>\n </div>\n </div><!-- media-body -->\n </div><!-- media -->\n </div><!-- crypto -->\n </div>\n </div>\n </div>\n </div>\n\n <!-- Allocation Summary -->\n {% include 'orders/partials/allocation_summary.html' with object=delivery_order %}\n\n <!-- Distribution Summary -->\n {% include 'orders/partials/distribution_summary.html' with object=delivery_order %}\n </div>\n {% endfor %}\n\n {% if object.status == object.OPEN and perms.orders.add_deliveryorder %}\n <div class=\"tab-pane fade {% if not active_pk %}active show{% endif %}\" id=\"tab-pane-new\">\n {% include 'orders/order_create_form.html' %}\n </div>\n {% endif %}\n </div><!-- ./ Tab Content -->\n</div>\n" }, { "alpha_fraction": 0.6093640923500061, "alphanum_fraction": 0.6198462843894958, "avg_line_length": 22.459016799926758, "blob_id": "3b007d5c4c7859586a247ba68ecf58e04a0561c6", "content_id": "854d3b01cec878c8ef8be01cd242ca368019cef5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1431, "license_type": "no_license", "max_line_length": 79, "num_lines": 61, "path": "/customers/models.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import uuid\n\nfrom django.db import models\n\n\nclass Customer(models.Model):\n \"\"\"\n Customer that is paying for the product.\n \"\"\"\n name = models.CharField(\n max_length=120,\n help_text='Customer company or office name.'\n )\n region = models.CharField(max_length=120, unique=True)\n code = models.CharField(max_length=4, unique=True)\n\n class Meta:\n ordering = ('name', )\n\n def __str__(self):\n return self.name\n\n\nclass Location(models.Model):\n \"\"\"\n City, town or special location within the cutomer's region\n \"\"\"\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n customer = models.ForeignKey(\n Customer,\n on_delete=models.CASCADE,\n related_name='locations'\n )\n name = models.CharField(max_length=120)\n\n class Meta:\n ordering = ('name', )\n\n def __str__(self):\n return self.name\n\n\nclass Union(models.Model):\n \"\"\"\n Regional unions.\n \"\"\"\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n customer = models.ForeignKey(\n Customer,\n on_delete=models.CASCADE,\n related_name='unions'\n )\n name = models.CharField(max_length=120)\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n ordering = ('name', )\n\n def __str__(self):\n return self.name\n" }, { "alpha_fraction": 0.6678200960159302, "alphanum_fraction": 0.6747404932975769, "avg_line_length": 31.11111068725586, "blob_id": "6ea3fd153a5b31ba0462218697ff59a3e2b421c7", "content_id": "4f320bd05194280377113dbe3b34eca4232e4be6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 867, "license_type": "no_license", "max_line_length": 80, "num_lines": 27, "path": "/shared/management/commands/fakedata.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import random\n\nfrom django.core.management import BaseCommand\n\nfrom purchases.tests.factories import SupplierFactory, ProductCategoryFactory, \\\n ProductFactory, BatchFactory\n\n\nclass Command(BaseCommand):\n help = 'Create fake data for development.'\n\n def handle(self, *args, **kwargs):\n suppliers = SupplierFactory.create_batch(5)\n product_categories = ProductCategoryFactory.create_batch(5)\n\n products = []\n for _ in range(10):\n category = random.choice(product_categories)\n product = ProductFactory(category=category)\n products.append(product)\n\n for _ in range(20):\n product = random.choice(products)\n supplier = random.choice(suppliers)\n BatchFactory(product=product, supplier=supplier)\n\n self.stdout.write('Database is populated with fake data.')\n" }, { "alpha_fraction": 0.5950000286102295, "alphanum_fraction": 0.6299999952316284, "avg_line_length": 46.619049072265625, "blob_id": "024c48b85eba9f93c851e729d3080ece57138e92", "content_id": "f6353c6bdc7142eb5b5f77b2116e362eb4c5b6b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1000, "license_type": "no_license", "max_line_length": 127, "num_lines": 21, "path": "/accounts/templates/registration/success.html", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "{% extends 'accounts/base.html' %}\n{% load static %}\n\n{% block content %}\n<div class=\"content content-fixed\">\n <div class=\"container ht-100p\">\n <div class=\"ht-100p d-flex flex-column align-items-center justify-content-center\">\n <div class=\"wd-150 wd-sm-250 mg-b-30\"><img src=\"{% static 'shared/img/img17.png' %}\" class=\"img-fluid\" alt=\"\"></div>\n <h4 class=\"tx-20 tx-sm-24\">Thank You For Registering</h4>\n <p class=\"tx-color-03 mg-b-40 text-center\">\n Before you can start using your account, it has to be verified &amp; activated by our admins first. <br>\n You will receive an e-mail when your account is ready.\n </p>\n <div class=\"tx-13 tx-lg-14 mg-b-40\">\n <a href=\"{% url 'accounts:login' %}\" class=\"btn btn-brand-02 d-inline-flex align-items-center\">Back to Sign In Page</a>\n <a href=\"\" class=\"btn btn-white d-inline-flex align-items-center mg-l-5\">Contact Support</a>\n </div>\n </div>\n </div><!-- container -->\n</div>\n{% endblock %}\n" }, { "alpha_fraction": 0.6091853976249695, "alphanum_fraction": 0.6142542362213135, "avg_line_length": 30.450885772705078, "blob_id": "566904456056268e1cc90ca2bd76b3a9572ca376", "content_id": "aaaecf49c5d1f831965dcf67dfc78c8b58c18d63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 19531, "license_type": "no_license", "max_line_length": 80, "num_lines": 621, "path": "/orders/models.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "import uuid\nimport pendulum\nfrom decimal import Decimal\nfrom functools import reduce\n\nfrom django.contrib.auth import get_user_model\nfrom django.conf import settings\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.utils import timezone\n\nfrom django_countries import Countries\nfrom django_countries.fields import CountryField\n\nfrom shared.constants import ADVANCE, RETENTION\nfrom shared.models import Unit\nfrom customers.models import Customer, Union, Location\n\n\nUser = settings.AUTH_USER_MODEL\n\n\nclass NeighbourCountry(Countries):\n only = ['DJ', 'ER', 'SO', 'SD', 'KE']\n\n\nclass Port(models.Model):\n \"\"\"Dispatch ports.\"\"\"\n name = models.CharField(max_length=120, unique=True)\n country = CountryField(countries=NeighbourCountry)\n office = models.CharField(max_length=120, blank=True)\n is_default = models.BooleanField('default', default=False)\n\n class Meta:\n ordering = ('-is_default', 'name')\n verbose_name = 'Dispatch Port'\n verbose_name_plural = 'Dispatch Ports'\n\n def __str__(self):\n return self.name\n\n\nclass Batch(models.Model):\n \"\"\"Product purchasing batches.\"\"\"\n today = pendulum.today(tz=settings.TIME_ZONE)\n\n # Calculate duration range\n start_offset = 3\n end_offset = 5\n ethiopian_year = today.year - 7\n\n choice_tuple = (\n ethiopian_year - start_offset,\n ethiopian_year + end_offset\n )\n\n YEAR_CHOICES = [\n (y, f'{y}/{y + 1}')\n for y in range(*choice_tuple)\n ]\n\n # Status\n OPEN = 'OPEN'\n CLOSED = 'CLOSED'\n\n STATUS_CHOICES = (\n (OPEN, 'open'),\n (CLOSED, 'closed')\n )\n\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n name = models.CharField(max_length=120)\n lc_number = models.CharField(\n 'L/C number', max_length=30,\n help_text='Document number for the letter of credit.'\n )\n product = models.ForeignKey(\n 'purchases.Product',\n null=True, on_delete=models.SET_NULL\n )\n supplier = models.ForeignKey(\n 'purchases.Supplier',\n null=True, on_delete=models.SET_NULL\n )\n quantity = models.DecimalField(\n max_digits=20,\n decimal_places=4,\n help_text='Quantity in the selected product unit.'\n )\n rate = models.DecimalField(\n max_digits=12,\n decimal_places=4,\n help_text='Price is in USD.'\n )\n year = models.PositiveIntegerField(\n choices=YEAR_CHOICES,\n )\n status = models.CharField(\n max_length=10,\n choices=STATUS_CHOICES,\n default=OPEN\n )\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n default_related_name='batches'\n verbose_name = 'Purchasing Batch'\n verbose_name_plural = 'Purchasing Batches'\n ordering = ('-created_at', )\n permissions = [\n ('close_batch', 'Close purchasing batch'),\n ('reopen_batch', 'Re-open purchasing batch')\n ]\n\n def __str__(self):\n return f'{self.name} ({self.product}) - {self.get_year_display()}'\n\n def get_absolute_url(self):\n return reverse('orders:batch-detail', args=[self.pk])\n\n def get_agreement_amount(self):\n \"\"\"Returns the amount as per the agreement in USD.\n\n Returns:\n amount (Decimal): total agreement amount in USD\n \"\"\"\n return round(self.quantity * self.rate, 4)\n\n def get_allocated_quantity(self):\n \"\"\"Returns the total allocated (actual) quantity.\n\n Return:\n quantity (Decimal): total allocated quantity in product unit\n \"\"\"\n delivery_orders = self.delivery_orders.all()\n quantity = reduce(\n lambda total, order: total + order.get_allocated_quantity(),\n delivery_orders,\n Decimal(0)\n )\n return quantity\n\n def get_allocated_amount(self):\n \"\"\"Returns the total allocated (actual) amount.\n\n Return:\n amount (Decimal): total allocated amount in USD.\n \"\"\"\n delivery_orders = self.delivery_orders.all()\n amount = reduce(\n lambda total, order: total + order.get_allocated_amount(),\n delivery_orders,\n Decimal(0)\n )\n return amount\n\n def get_advance_amount(self):\n \"\"\"Returns the 90% allocated advance amount.\n\n Return:\n amount (Decimal): total 90% allocated advance amount in USD.\n \"\"\"\n delivery_orders = self.delivery_orders.all()\n amount = reduce(\n lambda total, order: total + order.get_allocated_advance(),\n delivery_orders,\n Decimal(0)\n )\n return amount\n\n def get_retention_amount(self):\n \"\"\"Returns the 10% allocated retention amount.\n\n Return:\n amount (Decimal): total 10% allocated retention amount in USD.\n \"\"\"\n delivery_orders = self.delivery_orders.all()\n amount = reduce(\n lambda total, order: total + order.get_allocated_retention(),\n delivery_orders,\n Decimal(0)\n )\n return amount\n\n def get_distributed_quantity(self):\n \"\"\"Returns the total distributed (actual) quantity.\n\n Return:\n quantity (Decimal): total distributed quantity in product unit\n \"\"\"\n delivery_orders = self.delivery_orders.all()\n quantity = reduce(\n lambda total, order: total + order.get_distributed_quantity(),\n delivery_orders,\n Decimal(0)\n )\n return quantity\n\n def get_distributed_shortage(self):\n \"\"\"Returns the total distributed shortage (actual) quantity.\n\n Return:\n quantity (Decimal): total distributed shortage in product unit\n \"\"\"\n delivery_orders = self.delivery_orders.all()\n quantity = reduce(\n lambda total, order: total + order.get_distributed_shortage(),\n delivery_orders,\n Decimal(0)\n )\n return quantity\n\n def get_distributed_amount(self):\n \"\"\"Returns the total distributed (actual) amount.\n\n Return:\n amount (Decimal): total distributed amount in USD.\n \"\"\"\n delivery_orders = self.delivery_orders.all()\n amount = reduce(\n lambda total, order: total + order.get_distributed_amount(),\n delivery_orders,\n Decimal(0)\n )\n return amount\n\n\nclass DeliveryOrder(models.Model):\n \"\"\"Product delivery orders.\"\"\"\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n vessel = models.CharField(max_length=120, help_text='Shipment vessel name.')\n batch = models.ForeignKey(Batch, null=True, on_delete=models.SET_NULL)\n bill_of_loading = models.CharField(\n max_length=30,\n help_text='Bill of loading (B/L) number.'\n )\n port = models.ForeignKey(\n Port,\n null=True,\n on_delete=models.SET_NULL,\n )\n arrival_date = models.DateField('vessel arrival date')\n created_by = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n related_name='created_orders',\n null=True\n )\n updated_by = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n related_name='updated_orders',\n null=True, blank=True\n )\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n default_related_name = 'delivery_orders'\n ordering = ('created_at', )\n verbose_name = 'Delivery Order'\n verbose_name_plural = 'Delivery Orders'\n\n def __str__(self):\n return self.vessel\n\n @property\n def unit(self):\n return self.batch.product.unit\n\n @property\n def lc_number(self):\n return self.batch.lc_number\n\n @property\n def status(self):\n return self.batch.status\n\n def touch(self, **kwargs):\n \"\"\"\n Modifies `updated_at` field to to the current timestamp.\n \"\"\"\n user = kwargs.get('updated_by')\n if user is not None:\n self.updated_by = user\n self.updated_at = timezone.now()\n self.save()\n\n def is_fully_allocated(self):\n \"\"\"Checks if all regions are allocated.\n\n Returns:\n True (bool): If all regions are allocated\n False (bool): If all regions are not fully allocated yet\n \"\"\"\n customers = Customer.objects.all()\n allocated_buyers = self.allocations.values_list('buyer', flat=True)\n\n for customer in customers:\n if customer.pk not in allocated_buyers:\n return False\n return True\n\n def is_fully_distributed(self):\n \"\"\"Checks if distribution data is added to all allocated regions.\n\n Returns:\n True (bool): If all allocated regions have distribtion data\n False (bool): If some allocated regions are missing distribution\n data\n \"\"\"\n customers = Customer.objects.all()\n distributed_buyers = self.distributions.values_list('buyer', flat=True)\n\n for customer in customers:\n if customer.pk not in distributed_buyers:\n return False\n return True\n\n def get_allocated_quantity(self):\n \"\"\"Returns the total allocated quantity in product unit.\n\n Returns:\n quantity (Decimal): the total allocated quantity\n \"\"\"\n quantity = Decimal('0')\n for allocation in self.allocations.all():\n quantity += allocation.get_total_quantity()\n return round(quantity, 4)\n\n def get_distributed_quantity(self):\n \"\"\"Returns the total distributed quantity in product unit.\n\n Returns:\n quantity (Decimal): the total distributed quantity\n \"\"\"\n quantity = Decimal('0')\n for distribution in self.distributions.all():\n quantity += distribution.get_total_quantity()\n return round(quantity, 4)\n\n def get_distributed_shortage(self):\n \"\"\"Returns the difference between the total allocated quantity\n and the actual delivered quantity.\n\n Returns:\n quantity (Decimal): quantity shortage between allocated & delivered\n \"\"\"\n quantity = Decimal('0')\n for distribution in self.distributions.all():\n quantity += distribution.get_total_shortage()\n return round(quantity, 4)\n\n def get_allocated_amount(self):\n \"\"\"Returns the total allocated amount in USD.\n\n Returns:\n amount (Decimal): the total allocated amount in USD\n \"\"\"\n amount = Decimal('0')\n for allocation in self.allocations.all():\n amount += allocation.get_amount()\n return round(amount, 4)\n\n def get_allocated_advance(self):\n \"\"\"Returns the total allocated advance amount in USD.\n\n Returns:\n amount (Decimal): the total allocated advance amount in USD\n \"\"\"\n return round(self.get_allocated_amount() * ADVANCE)\n\n def get_allocated_retention(self):\n \"\"\"Returns the total allocated retention amount in USD.\n\n Returns:\n amount (Decimal): the total allocated retention amount in USD\n \"\"\"\n return round(self.get_allocated_amount() * RETENTION)\n\n def get_distributed_amount(self):\n \"\"\"Returns the total delivered amount in USD.\n\n Returns:\n amount (Decimal): the total delivered amount in USD\n \"\"\"\n amount = Decimal('0')\n for distribution in self.distributions.all():\n amount += distribution.get_amount()\n return round(amount, 4)\n\n\nclass Allocation(models.Model):\n \"\"\"Region allocation for delivery orders.\"\"\"\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n delivery_order = models.ForeignKey(DeliveryOrder,on_delete=models.CASCADE)\n buyer = models.ForeignKey(\n Customer,\n null=True,\n on_delete=models.SET_NULL\n )\n created_by = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n related_name='created_allocations',\n null=True\n )\n updated_by = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n related_name='updated_allocations',\n null=True, blank=True\n )\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n default_related_name = 'allocations'\n ordering = ('delivery_order', 'created_at', )\n unique_together = ('delivery_order', 'buyer')\n verbose_name = 'Delivery Order Allocation'\n verbose_name_plural = 'Delivery Order Allocations'\n\n def __str__(self):\n return f'{self.buyer.name} - {self.get_total_quantity()}'\n\n def get_total_quantity(self):\n \"\"\"Returns the total allocation quantity.\n\n Returns:\n quantity (Decimal): total allocated quantities of the unions\n \"\"\"\n union_allocations = self.union_allocations.all()\n quantity = reduce(\n lambda total, union: total + union.quantity,\n union_allocations,\n Decimal(0)\n )\n return round(quantity, 4)\n\n def get_amount(self):\n \"\"\"Returns the total amount for this allocation.\n\n Returns:\n amount (Decimal): Allocation amount in USD\n \"\"\"\n amount = self.get_total_quantity() * self.delivery_order.batch.rate\n return round(amount, 4)\n\n def get_percentage(self):\n \"\"\"Returns the region allocation percentage.\n\n Returns:\n percentage (Decimal): allocation quantity in percent.\n \"\"\"\n quantity = self.get_total_quantity()\n total_allocation = self.delivery_order.get_allocated_quantity()\n if total_allocation > 0:\n return round((quantity / total_allocation) * 100, 2)\n return 0\n\nclass UnionAllocation(models.Model):\n \"\"\"Allocation data to the unions for the delivery order.\"\"\"\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n allocation = models.ForeignKey(Allocation, on_delete=models.CASCADE)\n union = models.ForeignKey(Union, on_delete=models.PROTECT)\n location = models.ForeignKey(Location, on_delete=models.PROTECT)\n quantity = models.DecimalField(\n 'allocated quantity',\n max_digits=20, decimal_places=4,\n help_text='Quantity allocated to the union in product unit.'\n )\n\n class Meta:\n order_with_respect_to = 'allocation'\n default_related_name = 'union_allocations'\n\n def __str__(self):\n return f'{self.union.name} allocation'\n\n\nclass Distribution(models.Model):\n \"\"\"Actual distribution data for the delivery order.\"\"\"\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n delivery_order = models.ForeignKey(DeliveryOrder, on_delete=models.CASCADE)\n buyer = models.ForeignKey(\n Customer,\n null=True,\n on_delete=models.SET_NULL\n )\n created_by = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n related_name='created_distributions',\n null=True\n )\n updated_by = models.ForeignKey(\n User,\n on_delete=models.SET_NULL,\n related_name='updated_distributions',\n null=True, blank=True\n )\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n default_related_name = 'distributions'\n ordering = ('delivery_order', 'created_at')\n unique_together = ('delivery_order', 'buyer')\n verbose_name = 'Delivery Order Distribution'\n verbose_name_plural = 'Delivery Order Distributions'\n\n def __str__(self):\n return f'{self.delivery_order} distribution'\n\n def get_total_quantity(self):\n \"\"\"Returns the distribution quantity with shortage and over supply.\n\n Returns:\n quantity (Decimal): received quantity + shortage + over\n \"\"\"\n union_distributions = self.union_distributions.all()\n quantity = reduce(\n lambda total, union: total + union.get_total_quantity(),\n union_distributions,\n Decimal(0)\n )\n return round(quantity, 4)\n\n def get_total_shortage(self):\n \"\"\"Returns the distribution shortage quantity.\n\n Returns:\n shortage quantity (Decimal): received shortage + over\n \"\"\"\n union_distributions = self.union_distributions.all()\n quantity = reduce(\n lambda total, union: total + union.get_total_shortage(),\n union_distributions,\n Decimal(0)\n )\n return round(quantity, 4)\n\n def get_amount(self):\n \"\"\"Returns the total amount for this distribution.\n\n Returns:\n amount (Decimal): Distribution amount in USD\n \"\"\"\n amount = self.get_total_quantity() * self.delivery_order.batch.rate\n return round(amount, 4)\n\n def get_retention(self):\n \"\"\"Returns the 10% retention amount for this dis.\n\n Returns:\n retention (Decimal): 10% retention amount in USD\n \"\"\"\n rate = self.delivery_order.batch.rate\n amount = self.get_total_quantity() * rate * RETENTION\n return round(amount, 4)\n\n def get_percentage(self):\n \"\"\"Returns the region distribution percentage.\n\n Returns:\n percentage (Decimal): distribution quantity in percent.\n \"\"\"\n quantity = self.get_total_quantity()\n total_distribution = self.delivery_order.get_distributed_quantity()\n if total_distribution > 0:\n percent = (quantity / total_distribution) * 100\n return round(percent, 2)\n return 0\n\n\nclass UnionDistribution(models.Model):\n \"\"\"Actual distribution data to the unions for the delivery order.\"\"\"\n id = models.UUIDField(primary_key=True, editable=False, default=uuid.uuid4)\n distribution = models.ForeignKey(Distribution, on_delete=models.CASCADE)\n union = models.ForeignKey(Union, on_delete=models.PROTECT)\n location = models.ForeignKey(Location, on_delete=models.PROTECT)\n quantity = models.DecimalField(\n 'received quantity',\n max_digits=16, decimal_places=4,\n help_text='Quantity received by the union in product unit.'\n )\n shortage = models.DecimalField(\n 'dispatch shortage',\n max_digits=20, decimal_places=4,\n help_text='Quantity deficit after transportation in product unit.'\n )\n over = models.DecimalField(\n 'over supplied quantity',\n max_digits=20, decimal_places=4,\n help_text='Over quantity supplied in product unit.'\n )\n\n class Meta:\n order_with_respect_to = 'distribution'\n default_related_name = 'union_distributions'\n\n def __str__(self):\n return f'{self.union.name} distribution'\n\n def get_total_quantity(self):\n \"\"\"Returns the distribution quantity with shortage and over supply.\n\n Returns:\n quantity (Decimal): received quantity + shortage + over\n \"\"\"\n return round(self.quantity + self.shortage + self.over, 4)\n\n def get_total_shortage(self):\n \"\"\"Returns the distribution total shortage.\n\n Returns:\n shortage quantity (Decimal): received shortage + over\n \"\"\"\n return round(self.shortage + self.over, 4)\n" }, { "alpha_fraction": 0.7111111283302307, "alphanum_fraction": 0.7111111283302307, "avg_line_length": 30.5, "blob_id": "0ab3294ea46c53a2bc1b490b8c0eab9712f2fa84", "content_id": "e2b8614fdb994eff531a3316c5ff4d184f622b26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "no_license", "max_line_length": 62, "num_lines": 10, "path": "/shared/management/commands/runfixtures.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.core.management import BaseCommand, call_command\n\n\nclass Command(BaseCommand):\n help = 'Run all start-up fixtures from the settings file.'\n\n def handle(self, *args, **kwargs):\n for fixture in settings.FIXTURES:\n call_command('loaddata', fixture)\n" }, { "alpha_fraction": 0.5239773392677307, "alphanum_fraction": 0.5394587516784668, "avg_line_length": 46.01183319091797, "blob_id": "894c10e556b80244566d699d53413f3a25926c15", "content_id": "01f063280b33e75d3aeff642fdf133983e54e198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 7945, "license_type": "no_license", "max_line_length": 127, "num_lines": 169, "path": "/orders/templates/orders/batch_detail.html", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "{% extends 'orders/base.html' %}\n{% load humanize %}\n{% load shared_tags %}\n\n{% block title %} {{ object.lc_number }} | Payment Tracker{% endblock %}\n\n{% block content %}\n<div class=\"content content-fixed mg-b-20\">\n <div class=\"container pd-x-0 pd-lg-x-10 pd-xl-x-0 batch-detail-container\">\n\n <!-- BREADCRUMB -->\n <div class=\"d-sm-flex align-items-center justify-content-between mg-b-20 mg-lg-b-25 mg-xl-b-30\">\n <div>\n <nav aria-label=\"breadcrumb\">\n <ol class=\"breadcrumb breadcrumb-style1 mg-b-10\">\n <li class=\"breadcrumb-item\"><a href=\"#\">Dashbooard</a></li>\n {% if object.status == object.CLOSED %}\n <li class=\"breadcrumb-item\"><a href=\"#\">Closed Purchased Batch</a></li>\n {% else %}\n <li class=\"breadcrumb-item\"><a href=\"#\">Open Purchased Batch</a></li>\n {% endif %}\n <li class=\"breadcrumb-item active\" aria-current=\"page\">{{ object.lc_number }} </li>\n </ol>\n </nav>\n <h4 class=\"mg-b-0 tx-spacing--1\">{{ object.lc_number }}</h4>\n </div>\n\n {% if object.status == object.OPEN %}\n <div class=\"d-none d-md-block\">\n {% if perms.orders.close_batch %}\n <button class=\"btn btn-sm pd-x-15 btn-white btn-uppercase btn-modal\"\n data-url=\"{% url 'orders:batch-close' object.pk %}\">\n <i data-feather=\"flag\" class=\"wd-10 mg-r-5\"></i> Close\n </button>\n {% endif %}\n\n <button class=\"btn btn-sm pd-x-15 btn-white btn-uppercase mg-l-5 btn-modal\" disabled\n data-url=\"\">\n <i data-feather=\"file-text\" class=\"wd-10 mg-r-5\"></i> Letter\n </button>\n\n {% if perms.orders.change_batch %}\n <button class=\"btn btn-sm pd-x-15 btn-white btn-uppercase mg-l-5 btn-modal\"\n data-url=\"{% url 'orders:batch-update' object.pk %}\">\n <i data-feather=\"edit\" class=\"wd-10 mg-r-5\"></i> Edit\n </button>\n {% endif %}\n\n {% if perms.orders.delete_batch %}\n <button class=\"btn btn-sm pd-x-15 btn-danger btn-uppercase mg-l-5 btn-modal \"\n data-url=\"{% url 'orders:batch-delete' object.pk %}\">\n <i data-feather=\"trash\" class=\"wd-10 mg-r-5\"></i> Delete\n </button>\n {% endif %}\n </div>\n {% else %}\n <div class=\"d-none d-md-block\">\n {% if perms.orders.reopen_batch %}\n <button class=\"btn btn-sm pd-x-15 btn-white btn-uppercase mg-l-5 btn-modal\"\n data-url=\"{% url 'orders:batch-reopen' object.pk %}\">\n <i data-feather=\"share\" class=\"wd-10 mg-r-5\"></i> Re-Open\n </button>\n {% endif %}\n\n {% if perms.orders.delete_batch %}\n <button class=\"btn btn-sm pd-x-15 btn-danger btn-uppercase mg-l-5 btn-modal\"\n data-url=\"{% url 'orders:batch-delete' object.pk %}\">\n <i data-feather=\"trash\" class=\"wd-10 mg-r-5\"></i> Delete\n </button>\n {% endif %}\n </div>\n {% endif %}\n </div>\n <!-- END BREADCRUMB -->\n\n <!-- MESSAGES -->\n {% for message in messages %}\n <div class=\"alert alert-outline alert-success d-flex align-items-center mg-b-20\" role=\"alert\">\n <i data-feather=\"check-circle\" class=\"mg-r-10\"></i> {{ message }}\n </div>\n {% endfor %}\n\n {% if object.status == object.CLOSED %}\n <!-- Delivery Order Closed Alert -->\n <div class=\"alert alert-info d-flex align-items-center\" role=\"alert\">\n <i data-feather=\"info\" class=\"mg-r-10\"></i> This purchased batch was closed on {{ object.updated_at|date:'d/m/Y'}}.\n </div>\n {% endif %}\n\n <!-- BATCH SUMMARY AND GRAPH -->\n {% include 'orders/partials/batch_summary.html' with object=object %}\n\n <div class=\"row row-xs\">\n <div class=\"col mg-t-20\">\n <div class=\"card card-dashboard-table\" id=\"delivery-order-summary-card\">\n <div class=\"pd-b-30 table-responsive\">\n <table class=\"table table-bordered table-hover\" id=\"delivery-order-summary-table\">\n <thead>\n <tr>\n <th class=\"bg-white\">&nbsp;</th>\n <th colspan=\"4\" class=\"text-center bg-white text-uppercase tx-medium\">Allocations</th>\n <th colspan=\"3\" class=\"text-center bg-white text-uppercase tx-medium\">Distributions</th>\n </tr>\n <tr>\n <th>Delivery Orders</th>\n <th>Quantity ({{ object.product.unit.code }})</th>\n <th>Total Amount</th>\n <th>90% Advance</th>\n <th>10% Settlement</th>\n <th>Quantity ({{ object.product.unit.code }})</th>\n <th>Shortage ({{ object.product.unit.code }})</th>\n <th>Amount</th>\n </tr>\n </thead>\n <tbody>\n {% if object.delivery_orders.count > 0 %}\n {% for delivery_order in object.delivery_orders.all %}\n <tr>\n <td><a class=\"tx-medium text-primary\">{{ delivery_order.vessel }}</a></td>\n <td class=\"tz-color-03 tx-normal\">{{ delivery_order.get_allocated_quantity|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">${{ delivery_order.get_allocated_amount|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">${{ delivery_order.get_allocated_advance|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">${{ delivery_order.get_allocated_retention|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">{{ delivery_order.get_distributed_quantity|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">{{ delivery_order.get_distributed_shortage|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">${{ delivery_order.get_distributed_amount|floatformat:2|intcomma }}</td>\n </tr>\n {% endfor %}\n <tr>\n <td><a class=\"tx-semibold tx-spacing-1 tx-rubik\">TOTAL</a></td>\n <td class=\"tz-color-03 tx-normal\">{{ object.get_allocated_quantity|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">${{ object.get_allocated_amount|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">${{ object.get_advance_amount|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal tx-pink\">${{ object.get_retention_amount|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">{{ object.get_distributed_quantity|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">{{ object.get_distributed_shortage|floatformat:2|intcomma }}</td>\n <td class=\"tz-color-03 tx-normal\">${{ object.get_distributed_amount|floatformat:2|intcomma }}</td>\n </tr>\n {% else %}\n <tr>\n <td colspan=\"8\" style=\"border-bottom: none;\">\n <h4 class=\"text-center pd-t-40 pd-b-20 text-secondary text-uppercase op-6\">No Delivery Order</h4>\n </td>\n </tr>\n {% endif %}\n </tbody>\n </table>\n </div><!-- table-responsive -->\n </div><!-- card -->\n </div>\n </div>\n\n {% if object.status == object.OPEN or object.delivery_orders.count > 0 %}\n <!-- DELIVERY ORDER TABS -->\n {% include 'orders/partials/delivery_order_tabs.html' with object=object %}\n {% endif %}\n </div><!-- container -->\n</div><!-- content -->\n\n<script>\n $(function () {\n // Dynamically highlight columns\n $('.list-group-item[data-target]').hover(\n function () { $('.' + $(this).data('target')).addClass('bg-highlight'); },\n function () { $('.' + $(this).data('target')).removeClass('bg-highlight'); }\n );\n });\n</script>\n{% endblock %}\n" }, { "alpha_fraction": 0.6563166379928589, "alphanum_fraction": 0.6591609120368958, "avg_line_length": 33.300811767578125, "blob_id": "30b9945c8e8ef04e0db06bcb063609b983840b1f", "content_id": "d52d3e6b54f4ae07cba7e9a5475bd57de8070aa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4219, "license_type": "no_license", "max_line_length": 80, "num_lines": 123, "path": "/orders/views/deliveryorders.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from collections import Counter, namedtuple\n\nfrom django.db.models import Q\nfrom django.shortcuts import redirect, get_object_or_404\nfrom django.views.generic import ListView, CreateView, UpdateView, DeleteView, \\\n DetailView\nfrom django.urls import reverse_lazy, reverse\n\nfrom shared.constants import ROLE_SUPPLIER, ROLE_ADMIN, ROLE_STAFF, ROLE_GUEST\nfrom customers.models import Customer\nfrom purchases.models import Product\n\nfrom orders.forms import DeliveryOrderForm\nfrom orders.mixins import BaseOrderView\nfrom orders.models import Batch, DeliveryOrder, Allocation, Port, Distribution\n\n\nclass BaseOrderDetailView(BaseOrderView):\n \"\"\"Base class for all delivery order detail views.\"\"\"\n model = DeliveryOrder\n\n\nclass OrderDetailView(BaseOrderDetailView, DetailView):\n \"\"\"Displays a detail of a single delivery order.\"\"\"\n template_name = 'orders/order_detail.html'\n access_roles = '__all__'\n\n def get_queryset(self):\n qs = super().get_queryset()\n user = self.request.user\n if user.role is None and not user.is_superuser:\n qs = DeliveryOrder.objects.none()\n elif user.role is not None and user.role.name == ROLE_SUPPLIER:\n qs = qs.filter(batch__supplier=user.supplier)\n return qs\n\n def get_context_data(self, **kwargs):\n customers = Customer.objects.all()\n distributed_buyers = self.object.distributions.values_list(\n 'buyer', flat=True\n )\n buyer_choices = [c for c in customers if c.pk not in distributed_buyers]\n kwargs.update({'buyer_choices': buyer_choices,})\n return super().get_context_data(**kwargs)\n\n\nclass OrderCreateView(BaseOrderView, CreateView):\n \"\"\"Creates new delivery order instances.\"\"\"\n template_name = 'orders/order_create_form.html'\n form_class = DeliveryOrderForm\n model = DeliveryOrder\n object = None\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_batch(self):\n batch_pk = self.kwargs.get('batch_pk')\n return get_object_or_404(Batch, pk=batch_pk)\n\n def get_context_data(self, **kwargs):\n kwargs.update({\n 'batch': self.get_batch(),\n 'port_list': Port.objects.all()\n })\n return super().get_context_data(**kwargs)\n\n def get_success_url(self):\n batch = self.get_batch()\n url = reverse('orders:batch-detail', args=[batch.pk])\n if self.object is not None:\n url = f'{url}?active_delivery_order={self.object.pk}'\n return url\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n self.object.batch = self.get_batch()\n self.object.created_by = self.request.user\n self.object.save()\n return redirect(self.get_success_url())\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass OrderUpdateView(BaseOrderDetailView, UpdateView):\n \"\"\"Updates the a dilvery order instance.\"\"\"\n template_name = 'orders/modals/order_form.html'\n form_class = DeliveryOrderForm\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_context_data(self, **kwargs):\n kwargs.update({\n 'batch_list': Batch.objects.all(),\n 'port_list': Port.objects.all()\n })\n return super().get_context_data(**kwargs)\n\n def get_success_url(self):\n url = reverse('orders:batch-detail', args=[self.object.batch.pk])\n url = f'{url}?active_delivery_order={self.object.pk}'\n return url\n\n def form_valid(self, form):\n redirect_url = super().form_valid(form)\n self.object.touch(updated_by=self.request.user)\n return redirect_url\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass OrderDeleteView(BaseOrderDetailView, DeleteView):\n \"\"\"Deletes a deliver order instance.\"\"\"\n template_name = 'orders/modals/order_delete_form.html'\n access_roles = [ROLE_ADMIN]\n\n def get_success_url(self):\n delivery_order = self.get_object()\n batch_pk = delivery_order.batch.pk\n return reverse_lazy('orders:batch-detail', args=[batch_pk])\n" }, { "alpha_fraction": 0.6829268336296082, "alphanum_fraction": 0.6829268336296082, "avg_line_length": 12.666666984558105, "blob_id": "809a7df642e1dd5317b4acca66a9af8300c6bc18", "content_id": "966067d36f3c6ca5ce8ab328f9b81e5fe1eeae7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 82, "license_type": "no_license", "max_line_length": 24, "num_lines": 6, "path": "/config/settings/testing.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from .base import *\nfrom decouple import Csv\n\n\nDEBUG = True\nALLOWED_HOSTS = ['*']\n" }, { "alpha_fraction": 0.636904776096344, "alphanum_fraction": 0.636904776096344, "avg_line_length": 29.454545974731445, "blob_id": "82f4fe066bc4c4783f0d2c3e7ac49ea2d32013d2", "content_id": "7d3374bc73c29e07a3803cbbd392bf37fcff510f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 336, "license_type": "no_license", "max_line_length": 61, "num_lines": 11, "path": "/purchases/managers.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass BatchManager(models.Manager):\n \"\"\"Custom ORM manager for the Batch model.\"\"\"\n\n def get_queryset(self, *args, **kwargs):\n \"\"\"Returns a queryset by removing deleted batches.\"\"\"\n qs = super().get_queryset(*args, **kwargs)\n qs = qs.filter(is_deleted=False)\n return qs\n\n" }, { "alpha_fraction": 0.7358490824699402, "alphanum_fraction": 0.7819706201553345, "avg_line_length": 16.629629135131836, "blob_id": "1d7d03147ba2443f3249c5d5299d9ab0c6ca728b", "content_id": "1f2d2abae90d1d93e951fb21c29febcbc004a21a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 477, "license_type": "no_license", "max_line_length": 47, "num_lines": 27, "path": "/.env.example", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Django Project settings\nSECRET_KEY=\nALLOWED_HOSTS=.localhost, .127.0.0.1\nDJANGO_SETTINGS_MODULE=config.settings.local\nENVIRONMENT=LOCAL\n\n# Admin Settings\nADMIN_EMAIL=\nADMIN_PHONE_NUMBER=\nADMIN_PASSWORD=\nADMIN_FIRST_NAME=\nADMIN_LAST_NAME=\n\n# Database variables\nDB_ROOT_PASSWORD=\nDB_NAME=\nDB_USER=root\nDB_PASSWORD=\nDB_HOST=db\nDB_PORT=3306\n\n# NGINX variables\nNGINX_PORT=8080\n\n# CELERY\nCELERY_BROKER_URL=redis://redis-server:6379\nCELERY_RESULT_BACKEND=redis://redis-server:6379\n\n" }, { "alpha_fraction": 0.7485029697418213, "alphanum_fraction": 0.7485029697418213, "avg_line_length": 26.83333396911621, "blob_id": "917d744bcc08df310341ef51ce16f7b07f84c478", "content_id": "d2d6d227bd233bb5ac182c49204d2fa1d26509f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 167, "license_type": "no_license", "max_line_length": 58, "num_lines": 6, "path": "/accounts/mixins.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from shared.mixins import BaseAccessMixin\n\n\nclass AccountMixin(BaseAccessMixin):\n \"\"\"Base view mixin to restricted account app views.\"\"\"\n page_name = 'accounts'\n" }, { "alpha_fraction": 0.6231343150138855, "alphanum_fraction": 0.6231343150138855, "avg_line_length": 23.363636016845703, "blob_id": "afca3e5be87f27add8d940ccdeac51955a56d053", "content_id": "41dca0c02657015d23091a26a63e83e77a8a2c3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 536, "license_type": "no_license", "max_line_length": 75, "num_lines": 22, "path": "/customers/urls.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom .views import UnionListView, UnionCreateView, UnionUpdateView, \\\n UnionDeleteView\n\n\napp_name = 'customers'\n\nurlpatterns = [\n path('unions/', UnionListView.as_view(), name='union-list'),\n path('unions/create/', UnionCreateView.as_view(), name='union-create'),\n path(\n 'unions/<uuid:pk>/update/',\n UnionUpdateView.as_view(),\n name='union-update'\n ),\n path(\n 'unions/<uuid:pk>/delete/',\n UnionDeleteView.as_view(),\n name='union-delete'\n )\n]\n" }, { "alpha_fraction": 0.610304594039917, "alphanum_fraction": 0.610304594039917, "avg_line_length": 28.033058166503906, "blob_id": "f1af39a40b87729826cab98599a4038a18fdb36f", "content_id": "74f0f0b2966d6f74e9730cf6509838287950ccd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3513, "license_type": "no_license", "max_line_length": 79, "num_lines": 121, "path": "/orders/urls.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom .views.batches import OpenBatchListView, ClosedBatchListView, \\\n BatchCreateView, BatchUpdateView, BatchCloseView, BatchReopenView, \\\n BatchDeleteView, BatchDetailView, SupplierPopupView\nfrom .views.deliveryorders import OrderCreateView, \\\n OrderUpdateView, OrderDetailView, OrderDeleteView\nfrom .views.allocations import AllocationCreateView, AllocationUpdateView, \\\n AllocationDeleteView, LetterFormView, AllocationLetterView, \\\n AllocationDetailView\nfrom .views.distributions import DistributionCreateView, \\\n DistributionUpdateView, DistributionDeleteView, DistributionDetailView\n\n\napp_name = 'orders'\n\nurlpatterns = [\n path('', OpenBatchListView.as_view(), name='open-batch-list'),\n path(\n 'batches/closed/',\n ClosedBatchListView.as_view(),\n name='closed-batch-list'\n ),\n path('batches/create/', BatchCreateView.as_view(), name='batch-create'),\n path('batches/<uuid:pk>/', BatchDetailView.as_view(), name='batch-detail'),\n path(\n 'batches/<uuid:pk>/update/',\n BatchUpdateView.as_view(),\n name='batch-update'\n ),\n path(\n 'batches/<uuid:pk>/close/',\n BatchCloseView.as_view(),\n name='batch-close'\n ),\n path(\n 'batches/<uuid:pk>/reopen/',\n BatchReopenView.as_view(),\n name='batch-reopen'\n ),\n path(\n 'batches/<uuid:pk>/delete/',\n BatchDeleteView.as_view(),\n name='batch-delete'\n ),\n path(\n 'supplier/<uuid:pk>/popup/',\n SupplierPopupView.as_view(),\n name='supplier-popup'\n ),\n path(\n 'delivery-orders/<uuid:pk>/',\n OrderDetailView.as_view(),\n name='order-detail'\n ),\n path(\n '<uuid:batch_pk>/delivery-orders/create/',\n OrderCreateView.as_view(),\n name='order-create'\n ),\n path(\n 'delivery-orders/<uuid:pk>/update/',\n OrderUpdateView.as_view(),\n name='order-update'\n ),\n path(\n 'delivery-orders/<uuid:pk>/delete/',\n OrderDeleteView.as_view(),\n name='order-delete'\n ),\n path(\n 'delivery-orders/<uuid:pk>/letter-form/',\n LetterFormView.as_view(),\n name='order-letter-form'\n ),\n path(\n 'delivery-orders/<uuid:pk>/allocation-letter/',\n AllocationLetterView.as_view(),\n name='order-allocation-letter'\n ),\n path(\n 'allocations/<uuid:pk>/',\n AllocationDetailView.as_view(),\n name='order-allocation-detail'\n ),\n path(\n 'delivery-orders/<uuid:pk>/allocations/create/',\n AllocationCreateView.as_view(),\n name='order-allocation-create'\n ),\n path(\n 'allocations/<uuid:pk>/update/',\n AllocationUpdateView.as_view(),\n name='order-allocation-update'\n ),\n path(\n 'allocations/<uuid:pk>/delete/',\n AllocationDeleteView.as_view(),\n name='allocation-delete'\n ),\n path(\n 'distributions/<uuid:pk>/',\n DistributionDetailView.as_view(),\n name='order-distribution-detail'\n ),\n path(\n 'delivery-orders/<uuid:pk>/distributions/create/',\n DistributionCreateView.as_view(),\n name='order-distribution-create'\n ),\n path(\n 'distributions/<uuid:pk>/update/',\n DistributionUpdateView.as_view(),\n name='order-distribution-update'\n ),\n path(\n 'distribution/<uuid:pk>/delete/',\n DistributionDeleteView.as_view(),\n name='distribution-delete'\n ),\n]\n" }, { "alpha_fraction": 0.5659574270248413, "alphanum_fraction": 0.6127659678459167, "avg_line_length": 25.11111068725586, "blob_id": "c5ac51e0c6833982d7cf336fc4950388fa164d0b", "content_id": "c790a7092afcc9227f25499bf297f41360b628a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 132, "num_lines": 18, "path": "/purchases/migrations/0008_auto_20200531_1414.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-31 11:14\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0007_batch_lc_number'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='batch',\n name='lc_number',\n field=models.CharField(help_text='Document number for the letter of credit.', max_length=30, verbose_name='L/C number'),\n ),\n ]\n" }, { "alpha_fraction": 0.5948275923728943, "alphanum_fraction": 0.596930205821991, "avg_line_length": 30.289474487304688, "blob_id": "fc0e55bfa18bc1086ef8884ad13b4f407a54469b", "content_id": "5b135f60ae5dd4b55acb9a9f3a19bd84912bcc20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4756, "license_type": "no_license", "max_line_length": 77, "num_lines": 152, "path": "/shared/letters.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "\"\"\"Module for generating letters in MS-Word docx file format.\"\"\"\nfrom docx import Document\nfrom docx.shared import Pt\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\n\n\nclass Text:\n \"\"\"Class to abstract run level text.\"\"\"\n\n def __init__(self, text, **kwargs):\n self.text = text\n self.bold = kwargs.get('bold', False)\n self.italic = kwargs.get('italic', False)\n self.underline = kwargs.get('underline', False)\n\n\nclass Paragraph:\n \"\"\"Class to easily modify docx pararaphs.\"\"\"\n\n def __init__(self, document, *args, **kwargs):\n \"\"\"Initializes the object.\n\n Args:\n document (Document object): python-docx Document object instance\n \"\"\"\n self.paragraph = document.add_paragraph()\n self.paragraph.style = kwargs.get('style', 'Normal')\n\n # Paragraph format\n paragraph_format = self.paragraph.paragraph_format\n paragraph_format.alignment = kwargs.get(\n 'alignment',\n WD_ALIGN_PARAGRAPH.JUSTIFY\n )\n paragraph_format.line_spacing = kwargs.get('line_spacing', 1.2)\n paragraph_format.space_before = kwargs.get('space_before', Pt(8))\n paragraph_format.space_after = kwargs.get('space_after', Pt(8))\n paragraph_format.left_indent = kwargs.get('left_indent', Pt(0))\n paragraph_format.right_indent = kwargs.get('right_indent', Pt(0))\n\n # Default font (Note: Can be overwritten at text level)\n self.font_name = kwargs.get('font_name', 'Times New Roman')\n self.font_size = kwargs.get('font_size', Pt(12))\n\n def add_text(self, text, **kwargs):\n \"\"\"Adds run level text to the `paragraph` object.\n\n Args:\n text (Text): an instance of the Text class\n \"\"\"\n run = self.paragraph.add_run(text.text)\n\n # Run level settings\n run.bold = text.bold\n run.italic = text.italic\n run.underline = text.underline\n\n # Font settings\n font = run.font\n font.name = self.font_name\n font.size = self.font_size\n\n def add_texts(self, *text_list):\n \"\"\"Add multiple run level text to the `paragraph` object.\n\n Args:\n text_list (list<Text>): A list of the Text class instances\n \"\"\"\n for text in text_list:\n self.add_text(text)\n\n\nclass Receiver:\n \"\"\"Class to abstract letter receiver.\"\"\"\n\n def __init__(self, name, **kwargs):\n self.name = name\n self.department = kwargs.get('department')\n self.city = kwargs.get('city')\n\n\nclass LetterTemplate:\n \"\"\"Base class for letter templates.\"\"\"\n subject = ''\n\n def __init__(self, receiver, *args, **kwargs):\n \"\"\"Initialize the instance object.\n\n Args:\n response (HttpResponse): HTTP response object\n \"\"\"\n self.document = Document()\n self.receiver = receiver\n\n def _blank_line(self, count=1):\n \"\"\"Writes a blank line to the document.\n\n Args:\n count (int): The number of blank lines to write. Default is 1.\n \"\"\"\n for c in range(count):\n self.document.add_paragraph()\n\n def _build_receiver(self):\n \"\"\"Builds the letter receiver address section.\"\"\"\n\n # Company paragraph\n company = Paragraph(self.document)\n company.add_text(Text(f'To: {self.receiver.name}', bold=True))\n\n # Department paragraph\n if self.receiver.department:\n department = Paragraph(self.document)\n department.add_text(Text(self.receiver.department, bold=True))\n\n # City paragraph\n if self.receiver.city:\n city = Paragraph(self.document)\n city.add_text(Text(self.receiver.city, bold=True))\n\n def _build_subject(self):\n \"\"\"Builds the letter subject section.\"\"\"\n subject = Paragraph(self.document)\n subject.add_text(Text('Subject: \\t', bold=True))\n subject.add_text(Text(self.subject, bold=True, underline=True))\n\n def _build_content(self):\n \"\"\"Builds the content of the letter.\"\"\"\n content = Paragraph(self.document)\n content.add_text(Text('content body'))\n # Overwrite this method in child classes\n\n def _build_cc(self):\n \"\"\"Builds the C.C. content of the letter.\"\"\"\n pass\n\n def _build(self, *args, **kwargs):\n \"\"\"Build the docx file.\"\"\"\n self._build_receiver()\n self._blank_line()\n self._build_subject()\n self._build_content()\n\n def generate(self, response, *args, **kwargs):\n \"\"\"Generate docx letter file.\n\n Returns:\n response (HttpResponse): HTTP response object with generated file\n \"\"\"\n self._build()\n self.document.save(response)\n return response\n" }, { "alpha_fraction": 0.594936728477478, "alphanum_fraction": 0.6315048933029175, "avg_line_length": 28.625, "blob_id": "321ccae19e6674a7879e3b5e1a7c5e7c33ba351d", "content_id": "d7bb613948054ac1fbeedc8a7d1fb24d1a656680", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 711, "license_type": "no_license", "max_line_length": 118, "num_lines": 24, "path": "/purchases/migrations/0012_auto_20200614_0016.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-13 21:16\n\nfrom django.db import migrations\nimport phonenumber_field.modelfields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0011_delete_batch'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='supplier',\n name='fax_number',\n field=phonenumber_field.modelfields.PhoneNumberField(max_length=128, null=True, region=None, unique=True),\n ),\n migrations.AddField(\n model_name='supplier',\n name='phone_number',\n field=phonenumber_field.modelfields.PhoneNumberField(max_length=128, null=True, region=None, unique=True),\n ),\n ]\n" }, { "alpha_fraction": 0.48961156606674194, "alphanum_fraction": 0.5029358863830566, "avg_line_length": 37.842105865478516, "blob_id": "5cbf8033259ef484d04ba62ad573443498488138", "content_id": "b1e34866101c95bda5fa3e06d2a434935d2e0206", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 4428, "license_type": "no_license", "max_line_length": 114, "num_lines": 114, "path": "/customers/templates/customers/modals/unions/union_form.html", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "<div class=\"modal-dialog\" role=\"document\">\n <div class=\"modal-content\">\n <div class=\"modal-header pd-y-20 pd-x-20 pd-sm-x-30\">\n <a href=\"\" role=\"button\" class=\"close pos-absolute t-15 r-15\" data-dismiss=\"modal\" aria-label=\"Close\">\n <span aria-hidden=\"true\">&times;</span>\n </a>\n <div class=\"media align-items-center\">\n <div class=\"media-body\">\n {% if object %}\n <h4 class=\"tx-18 tx-sm-20 mg-b-2\">Edit Union</h4>\n <p class=\"tx-13 tx-color-03 mg-b-0\">Update an existing union.</p>\n {% else %}\n <h4 class=\"tx-18 tx-sm-20 mg-b-2\">New Union</h4>\n <p class=\"tx-13 tx-color-03 mg-b-0\">Create and add a new union to the system.</p>\n {% endif %}\n </div>\n </div><!-- media -->\n </div><!-- modal-header -->\n\n <!-- Product Form -->\n <form action=\"{{ request.path }}\" method=\"POST\" id=\"union-form\">\n {% csrf_token %}\n\n <div class=\"modal-body pd-sm-t-10 pd-sm-b-30 pd-sm-x-30\">\n <div class=\"row\">\n <div class=\"col-sm-9\">\n <!-- Name -->\n <div class=\"form-group\">\n <label for=\"name\" class=\"tx-10 tx-uppercase tx-medium tx-spacing-1 mg-b-5 tx-color-03\">Name</label>\n <input\n id=\"name\" class=\"form-control {% if form.name.errors %}parsley-error{% endif %}\"\n name=\"name\" value=\"{{ form.name.value|default:'' }}\"\n placeholder=\"Enter union name\" required autocomplete=\"off\"\n />\n {% if form.name.errors %}\n <ul class=\"parsley-errors-list filled\">\n {% for error in form.name.errors %}\n <li class=\"parsley-required\">{{ error }}</li>\n {% endfor %}\n </ul>\n {% endif %}\n </div>\n\n <!-- Customers -->\n <div class=\"form-group\">\n <label for=\"customer\"\n class=\"tx-10 tx-uppercase tx-medium tx-spacing-1 mg-b-5 tx-color-03\">Region</label>\n <select name=\"customer\" id=\"customer\"\n class=\"form-control custom-select {% if form.customer.errors %}parsley-error{% endif %}\" required>\n {% if not form.instance.customer %}\n <option selected disabled value=\"\">Choose region</option>\n {% endif %}\n\n {% for customer in customer_list %}\n <option value=\"{{ customer.pk }}\"\n {% if form.customer.value|safe == customer.pk|safe %}selected{% endif %}>\n {{ customer.region }}\n </option>\n {% endfor %}\n </select>\n {% if form.customer.errors %}\n <ul class=\"parsley-errors-list filled\">\n {% for error in form.customer.errors %}\n <li class=\"parsley-required\">{{ error }}</li>\n {% endfor %}\n </ul>\n {% endif %}\n </div>\n </div><!-- modal-body -->\n </div><!-- /.row -->\n </div><!-- /.modal-body -->\n <div class=\"modal-footer pd-x-20 pd-y-15\">\n <button type=\"button\" class=\"btn btn-white\" data-dismiss=\"modal\">Cancel</button>\n <button type=\"submit\" class=\"btn btn-primary wd-80\">Save</button>\n </div>\n </form>\n </div><!-- modal-content -->\n</div><!-- modal-dialog -->\n\n<script>\n $(function () {\n $('#modal-widget').on('submit', '#union-form', function (e) {\n e.preventDefault();\n\n const $submitBtn = $('#union-form button[type=submit]');\n const $spinner = $('<i>', { 'class': 'fas fa-spin fa-circle-notch' });\n\n $submitBtn.attr('disabled', true).html($spinner);\n\n const url = $(this).attr('action');\n const formData = $(this).serialize();\n const request = $.ajax({\n method: 'POST',\n url: url,\n data: formData,\n dataType: 'html'\n });\n\n request.done(data => {\n const $updatedPage = $(data).find('#union-list-container');\n $('#union-list-container').replaceWith($updatedPage);\n $('#modal-widget').modal('hide');\n feather.replace();\n });\n\n request.fail(jqXHR => {\n const $form = $('#union-form');\n const $responseForm = $(jqXHR.responseText).find('#union-form');\n $form.replaceWith($responseForm);\n $form.find('button[type=submit]').text('Save').removeAttr('disabled');\n });\n });\n });\n</script>\n" }, { "alpha_fraction": 0.49408283829689026, "alphanum_fraction": 0.5887573957443237, "avg_line_length": 18.882352828979492, "blob_id": "dad8d8d099100eeba810bcd6ff69cd9c65a63c68", "content_id": "bf4067b546bee9f67bc575207f7420ac69d2452e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/orders/migrations/0006_remove_deliveryorder_lc_number.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-31 10:30\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0005_auto_20200531_1309'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='deliveryorder',\n name='lc_number',\n ),\n ]\n" }, { "alpha_fraction": 0.49554896354675293, "alphanum_fraction": 0.5905044674873352, "avg_line_length": 18.823530197143555, "blob_id": "de55b701a5f81c35b8bffe30bb221e0d5a642b29", "content_id": "b298cacbfd4d9e2cf7bf09fccf0464c6c6b06394", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 337, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/orders/migrations/0013_remove_deliveryorder_quantity.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-13 13:36\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0012_auto_20200609_1511'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='deliveryorder',\n name='quantity',\n ),\n ]\n" }, { "alpha_fraction": 0.6735751032829285, "alphanum_fraction": 0.6735751032829285, "avg_line_length": 28.69230842590332, "blob_id": "191129d205fabc245ef84dfd40184b89c5540551", "content_id": "ba20b6b64ed2e9665a078bb804b39ec7485fcd81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 772, "license_type": "no_license", "max_line_length": 72, "num_lines": 26, "path": "/accounts/urls.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.contrib.auth import views as auth_views\nfrom django.urls import path, include\n\nfrom .views import UserRegistrationView, RegistrationSuccessView, \\\n PasswordUpdateView, ProfileUpdateView, CustomLoginView\n\n\napp_name = 'accounts'\n\n\nurlpatterns = [\n path('login/', CustomLoginView.as_view(), name='login'),\n path('logout/', auth_views.LogoutView.as_view(), name='logout'),\n path(\n 'password-change/',\n PasswordUpdateView.as_view(),\n name='password-change'\n ),\n path('register/', UserRegistrationView.as_view(), name='register'),\n path(\n 'register/success/',\n RegistrationSuccessView.as_view(),\n name='register-success'\n ),\n path('profile/', ProfileUpdateView.as_view(), name='profile-update')\n]\n" }, { "alpha_fraction": 0.611361563205719, "alphanum_fraction": 0.611361563205719, "avg_line_length": 24.79069709777832, "blob_id": "3fa156b3e6fa9ec26a7f7e9d01839bb0b933cfc8", "content_id": "137288fe7f9d1ad998641f15d48a620a4dfbe20d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1109, "license_type": "no_license", "max_line_length": 71, "num_lines": 43, "path": "/users/forms.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.models import Group\n\nfrom shared.constants import ROLE_ADMIN, ROLE_MANAGEMENT, ROLE_STAFF, \\\n ROLE_SUPPLIER, ROLE_GUEST\nfrom purchases.models import Supplier\n\n\nUser = get_user_model()\n\n\nclass UserForm(forms.ModelForm):\n role = forms.ModelChoiceField(\n queryset=Group.objects.filter(\n name__in=[\n ROLE_ADMIN, ROLE_MANAGEMENT,\n ROLE_STAFF, ROLE_SUPPLIER, ROLE_GUEST\n ]\n ),\n required=True, empty_label=None\n )\n supplier = forms.ModelChoiceField(\n queryset=Supplier.objects.all(),\n required=False, empty_label=None\n )\n\n class Meta:\n model = User\n fields = ('first_name', 'last_name', 'role', 'supplier')\n\n def save(self, commit=True):\n role = self.cleaned_data['role']\n\n user = super().save(commit)\n user.groups.clear()\n user.groups.add(role)\n\n if user.role.name != ROLE_SUPPLIER:\n user.supplier = None\n user.save()\n\n return user\n" }, { "alpha_fraction": 0.5676795840263367, "alphanum_fraction": 0.6049723625183105, "avg_line_length": 18.052631378173828, "blob_id": "2d4a8d48e6db34d813c5de5da8b08be6bee9e571", "content_id": "e8fe4c351df549c58d623ccf2e2315a546a34055", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 724, "license_type": "no_license", "max_line_length": 68, "num_lines": 38, "path": "/Pipfile", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "[[source]]\nname = \"pypi\"\nurl = \"https://pypi.org/simple\"\nverify_ssl = true\n\n[dev-packages]\nautopep8 = \"*\"\n\n[packages]\npython-decouple = \"==3.1\"\npytz = \"==2018.5\"\ndjango-extensions = \"==2.0.7\"\nsix = \"==1.11.0\"\ntyping = \"==3.6.4\"\ndjango = \"==2.2.13\"\nmysqlclient = \"*\"\nfactory-boy = \"*\"\ndjangorestframework = \"*\"\nmarkdown = \"*\"\ndjango-filter = \"*\"\ndjango-cors-headers = \"*\"\ndjango-environ = \"*\"\ngunicorn = \"*\"\nredis = \"*\"\ndjango-celery-beat = \"*\"\ncoverage = \"*\"\ndjango-celery-results = \"*\"\npython-docx = \"*\"\npendulum = \"*\"\ncelery = \"==4.4.2\"\npyyaml = \"*\"\ndjango-countries = \"*\"\nipython = \"*\"\ndjango-phonenumber-field = {extras = [\"phonenumbers\"],version = \"*\"}\ndjango-livereload-server = \"*\"\n\n[requires]\npython_version = \"3.8\"\n" }, { "alpha_fraction": 0.54747474193573, "alphanum_fraction": 0.6161616444587708, "avg_line_length": 26.5, "blob_id": "7f56196f50122095cc944b84d217942806698caf", "content_id": "110d29593409b8163dc82ce3c5c6c0f668b9becf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 156, "num_lines": 18, "path": "/purchases/migrations/0007_batch_lc_number.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-31 10:08\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0006_auto_20200526_1708'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='batch',\n name='lc_number',\n field=models.CharField(blank=True, default='', help_text='Document number for the letter of credit.', max_length=30, verbose_name='L/C number'),\n ),\n ]\n" }, { "alpha_fraction": 0.6614619493484497, "alphanum_fraction": 0.6635346412658691, "avg_line_length": 38.331520080566406, "blob_id": "eb1d024126759c0778a9441c80240be9123b9cac", "content_id": "dad57b50ab2a377d3c5acc0bb20e6f427311be7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7237, "license_type": "no_license", "max_line_length": 98, "num_lines": 184, "path": "/orders/views/allocations.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.forms import modelform_factory\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect, get_object_or_404\nfrom django.views.generic import CreateView, UpdateView, DeleteView, \\\n DetailView, FormView\nfrom django.views.generic.detail import BaseDetailView\nfrom django.urls import reverse\n\nfrom shared.constants import ROLE_SUPPLIER, ROLE_ADMIN, ROLE_STAFF\nfrom customers.models import Customer, Union, Location\n\nfrom orders.forms import AllocationForm, LetterDownloadForm, \\\n UnionAllocationFormSet\nfrom orders.mixins import BaseOrderView\nfrom orders.models import DeliveryOrder, Allocation\nfrom orders.letters.allocationletter import AllocationLetter\n\n\nclass AllocationDetailView(BaseOrderView, DetailView):\n \"\"\"Modal detail view for the allocation quantity calculation.\"\"\"\n template_name = 'orders/modals/allocations/allocation_detail.html'\n model = Allocation\n access_roles = '__all__'\n\n\nclass BaseAllocationEditView(BaseOrderView):\n \"\"\"Abstract base class for allocation create & update people.\"\"\"\n model = Allocation\n form_class = UnionAllocationFormSet\n prefix = 'formset'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def form_invalid(self, formset):\n response = super().form_invalid(formset)\n response.status_code = 400\n return response\n\n\nclass AllocationCreateView(BaseAllocationEditView, CreateView):\n \"\"\"Creates an allocation for delivery order.\"\"\"\n template_name = 'orders/modals/allocations/allocation_create_form.html'\n\n def get_delivery_order(self):\n order_pk = self.kwargs.get('pk')\n order = get_object_or_404(DeliveryOrder, pk=order_pk)\n return order\n\n def get_context_data(self, **kwargs):\n customers = Customer.objects.all()\n order = self.get_delivery_order()\n allocated_buyers = order.allocations.values_list('buyer', flat=True)\n buyer_choices = [c for c in customers if c.pk not in allocated_buyers]\n\n try:\n buyer_pk = int(self.request.GET.get('buyer'))\n union_choices = Union.objects.filter(customer__pk=buyer_pk)\n location_choices = Location.objects.filter(customer__pk=buyer_pk)\n except TypeError:\n union_choices = Union.objects.all()\n location_choices = Location.objects.all()\n\n AllocationForm = modelform_factory(Allocation, fields=('buyer', ))\n kwargs.update({\n 'buyer_choices': buyer_choices,\n 'union_choices': union_choices,\n 'location_choices': location_choices,\n 'order': order,\n 'formset': self.get_form(),\n 'allocation_form': AllocationForm(self.request.POST or None)\n })\n return super().get_context_data(**kwargs)\n\n def get_success_url(self):\n order_pk = self.kwargs.get('pk')\n delivery_order = get_object_or_404(DeliveryOrder, pk=order_pk)\n batch_id = delivery_order.batch.pk\n url = reverse('orders:batch-detail', args=[batch_id])\n url = f'{url}?active_delivery_order={delivery_order.pk}'\n return url\n\n def form_valid(self, formset):\n context = self.get_context_data()\n allocation_form = context['allocation_form']\n if allocation_form.is_valid():\n self.object = allocation_form.save(commit=False)\n self.object.delivery_order = self.get_delivery_order()\n self.object.created_by = self.request.user\n self.object.save()\n\n formset.instance = self.object\n self.object.delivery_order.touch(updated_by=self.request.user)\n return super().form_valid(formset)\n return super().form_invalid(formset)\n\n\nclass AllocationUpdateView(BaseAllocationEditView, UpdateView):\n \"\"\"Updates an allocation for delivery order.\"\"\"\n template_name = 'orders/modals/allocations/allocation_update_form.html'\n\n def get_context_data(self, **kwargs):\n union_choices = Union.objects.filter(customer=self.object.buyer)\n location_choices = Location.objects.filter(customer=self.object.buyer)\n AllocationForm = modelform_factory(Allocation, fields=('buyer', ))\n kwargs.update({\n 'union_choices': union_choices,\n 'location_choices': location_choices,\n 'order': self.object.delivery_order,\n 'formset': self.get_form(),\n 'allocation_form': AllocationForm(\n self.request.POST or None,\n instance=self.object.buyer\n )\n })\n return super().get_context_data(**kwargs)\n\n def get_success_url(self):\n allocation = self.get_object()\n batch_pk = allocation.delivery_order.batch.pk\n delivery_order_pk = allocation.delivery_order.pk\n url = reverse('orders:batch-detail', args=[batch_pk])\n url = f'{url}?active_delivery_order={delivery_order_pk}'\n return url\n\n def form_valid(self, formset):\n redirect_url = super().form_valid(formset)\n self.object = formset.instance\n self.object.delivery_order.touch(updated_by=self.request.user)\n return redirect_url\n\n\nclass AllocationDeleteView(BaseOrderView, DeleteView):\n \"\"\"Deletes an allocation instance for delivery order.\"\"\"\n template_name = 'orders/modals/allocations/allocation_delete_form.html'\n model = Allocation\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_success_url(self):\n batch_pk = self.get_object().delivery_order.batch.pk\n delivery_order_pk = self.get_object().delivery_order.pk\n url = reverse('orders:batch-detail', args=[batch_pk])\n url = f'{url}?active_delivery_order={delivery_order_pk}'\n return url\n\n def delete(self, request, *args, **kwargs):\n delivery_order = self.get_object().delivery_order\n redirect_url = super().delete(request, *args, **kwargs)\n delivery_order.touch(updated_by=request.user)\n return redirect_url\n\n\nclass LetterFormView(BaseOrderView, FormView):\n \"\"\"Form view to select a letter to download.\"\"\"\n template_name = 'orders/modals/letter_form.html'\n form_class = LetterDownloadForm\n access_roles = '__all__'\n\n def get_context_data(self, **kwargs):\n pk = self.kwargs.get('pk')\n kwargs['object'] = get_object_or_404(DeliveryOrder, pk=pk)\n return super().get_context_data(**kwargs)\n\n def form_valid(self, form):\n letter_type = form.cleaned_data['type']\n pk = self.kwargs.get('pk')\n if letter_type == self.form_class.ALLOCATION_LETTER:\n view_url = reverse('orders:order-allocation-letter', args=[pk])\n return redirect(view_url)\n return\n\n\nclass AllocationLetterView(BaseOrderView, BaseDetailView):\n \"\"\"Generates delivery order allocation letter.\"\"\"\n model = DeliveryOrder\n access_roles = '__all__'\n\n def get(self, request, *args, **kwargs):\n self.object = self.get_object()\n letter = AllocationLetter(self.object)\n response = HttpResponse(\n content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'\n )\n response['Content-Disposition'] = 'attachment; filename=allocation.docx'\n letter.generate(response)\n return response\n" }, { "alpha_fraction": 0.6681898832321167, "alphanum_fraction": 0.6750444173812866, "avg_line_length": 28.395523071289062, "blob_id": "8db039227b46c77abde01649c0a79c5045684318", "content_id": "13304d083e7afd157acf9f9d017660b573d77e24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3939, "license_type": "no_license", "max_line_length": 76, "num_lines": 134, "path": "/orders/forms.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.forms import inlineformset_factory, BaseInlineFormSet\n\nfrom shared.fields import FormattedNumberField\nfrom customers.models import Union, Location\n\nfrom .models import Batch, DeliveryOrder, Allocation, Distribution, \\\n UnionDistribution, UnionAllocation\n\n\nclass BatchForm(forms.ModelForm):\n \"\"\"Model for creating new batch instance.\"\"\"\n quantity = FormattedNumberField(max_digits=20, decimal_places=4)\n rate = FormattedNumberField(max_digits=12, decimal_places=4)\n\n class Meta:\n model = Batch\n fields = ('name', 'lc_number', 'product',\n 'supplier', 'quantity', 'rate', 'year')\n\n\nclass DeliveryOrderForm(forms.ModelForm):\n \"\"\"Model form for creating new deliveries.\"\"\"\n class Meta:\n model = DeliveryOrder\n fields = (\n 'bill_of_loading', 'port', 'vessel', 'arrival_date'\n )\n\n\nclass AllocationForm(forms.ModelForm):\n \"\"\"Model form for creating new delivery order allocation.\"\"\"\n quantity = FormattedNumberField(max_digits=20, decimal_places=4)\n\n class Meta:\n model = Allocation\n fields = ('buyer', )\n\n\nclass UnionAllocationForm(forms.ModelForm):\n \"\"\"Model form for creating new union allocation instance.\"\"\"\n union = forms.ModelChoiceField(\n queryset=Union.objects.all(),\n empty_label=None,\n required=True\n )\n location = forms.ModelChoiceField(\n queryset=Location.objects.all(),\n empty_label=None,\n required=True\n )\n quantity = FormattedNumberField(max_digits=20, decimal_places=4)\n\n class Meta:\n model = UnionAllocation\n fields = ('union', 'location', 'quantity')\n\n\nclass BaseUnionAllocationFormSet(BaseInlineFormSet):\n def clean(self):\n \"\"\"Remove validation for forms to be deleted.\"\"\"\n for form in self.forms:\n if self.can_delete and self._should_delete_form(form):\n continue\n\n\nUnionAllocationFormSet = inlineformset_factory(\n Allocation,\n UnionAllocation,\n form=UnionAllocationForm,\n formset=BaseUnionAllocationFormSet,\n extra=0, min_num=1,\n validate_min=True, can_delete=True\n)\n\n\nclass DistributionForm(forms.ModelForm):\n \"\"\"Model form for creating new delivery order distribution.\"\"\"\n\n class Meta:\n model = Distribution\n fields = ('buyer', )\n\n\nclass UnionDistributionForm(forms.ModelForm):\n \"\"\"Model form for creating new union distribution instance.\"\"\"\n union = forms.ModelChoiceField(\n queryset=Union.objects.all(),\n empty_label=None,\n required=True\n )\n location = forms.ModelChoiceField(\n queryset=Location.objects.all(),\n empty_label=None,\n required=True\n )\n quantity = FormattedNumberField(max_digits=20, decimal_places=4)\n shortage = FormattedNumberField(max_digits=20, decimal_places=4)\n over = FormattedNumberField(max_digits=20, decimal_places=4)\n\n class Meta:\n model = UnionDistribution\n fields = ('union', 'location', 'quantity', 'shortage', 'over')\n\n\nclass BaseUnionDistributionFormSet(BaseInlineFormSet):\n def clean(self):\n \"\"\"Remove validation for forms to be deleted.\"\"\"\n for form in self.forms:\n if self.can_delete and self._should_delete_form(form):\n continue\n\n\nUnionDistributionFormSet = inlineformset_factory(\n Distribution,\n UnionDistribution,\n form=UnionDistributionForm,\n formset=BaseUnionDistributionFormSet,\n extra=0, min_num=1,\n validate_min=True, can_delete=True\n)\n\n\nclass LetterDownloadForm(forms.Form):\n \"\"\"Form for selecting a letter to download\"\"\"\n ALLOCATION_LETTER = 'ALLOCATION'\n RETENTION_LETTER = 'RETENTION'\n\n TYPE_CHOICES = (\n (ALLOCATION_LETTER, 'Delivery Order Allocation Letter'),\n (RETENTION_LETTER, '10% Payment Release Request Letter')\n )\n\n type = forms.ChoiceField(choices=TYPE_CHOICES, widget=forms.RadioSelect)\n" }, { "alpha_fraction": 0.5906040072441101, "alphanum_fraction": 0.6442952752113342, "avg_line_length": 34.05882263183594, "blob_id": "ab9fb1f4c2281d9c7b1e4c160eee245d3782695b", "content_id": "e03f4e54b4bdaf147a1c199c00b7f78caeff3507", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 596, "license_type": "no_license", "max_line_length": 287, "num_lines": 17, "path": "/orders/migrations/0012_auto_20200609_1511.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-09 12:11\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0011_auto_20200607_2341'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='deliveryorder',\n options={'default_related_name': 'delivery_orders', 'ordering': ('created_at',), 'permissions': [('close_deliveryorder', 'Close delivery order'), ('reopen_deliveryorder', 'Re-open delivery order')], 'verbose_name': 'Delivery Order', 'verbose_name_plural': 'Delivery Orders'},\n ),\n ]\n" }, { "alpha_fraction": 0.6686621308326721, "alphanum_fraction": 0.6707444190979004, "avg_line_length": 36.30097198486328, "blob_id": "11a3e8a8b74d53a7cff7620c0e46e72884eb7d8f", "content_id": "a7be3c83727cfd8717edc343c482c1e25b9d4bd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7684, "license_type": "no_license", "max_line_length": 80, "num_lines": 206, "path": "/purchases/views.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from collections import namedtuple, Counter\n\nfrom django.contrib import messages\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.db.models import Q\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy\nfrom django.views.generic import ListView, CreateView, UpdateView, DeleteView, \\\n DetailView\n\nfrom shared.constants import ROLE_ADMIN, ROLE_MANAGEMENT, ROLE_STAFF, ROLE_GUEST\nfrom shared.models import Unit\n\nfrom .forms import SupplierForm\nfrom .mixins import BasePurchasesView\nfrom .models import ProductCategory, Product, Supplier\n\n\nclass ProductListView(BasePurchasesView, ListView):\n \"\"\"List view of fertilier products.\"\"\"\n template_name = 'purchases/product_list.html'\n model = Product\n paginate_by = 10\n page_name = 'products'\n queryset = Product.objects.all()\n access_roles = [ROLE_STAFF, ROLE_MANAGEMENT, ROLE_ADMIN, ROLE_GUEST]\n\n def get_queryset(self):\n qs = super().get_queryset()\n category_pk = self.request.GET.get('category')\n search_query = self.request.GET.get('search')\n\n if category_pk is not None:\n qs = qs.filter(category__pk=category_pk)\n\n if search_query is not None:\n qs = self.get_search_result(search_query)\n\n return qs\n\n def get_context_data(self, **kwargs):\n kwargs['category_list'] = ProductCategory.objects.all()\n kwargs['selected_category'] = self.request.GET.get('category')\n kwargs['product_count'] = self.queryset.count()\n kwargs['search_query'] = self.request.GET.get('search', '').strip()\n return super().get_context_data(**kwargs)\n\n def get_search_result(self, query):\n \"\"\"Returns matching products using search query.\"\"\"\n return self.queryset.filter(name__istartswith=query)\n\n\nclass ProductCreateView(BasePurchasesView, SuccessMessageMixin, CreateView):\n \"\"\"Create view for creating product.\"\"\"\n template_name = 'purchases/modals/products/product_form.html'\n model = Product\n fields = ('name', 'category', 'unit')\n success_url = reverse_lazy('purchases:product-list')\n success_message = 'A new product is successfully created.'\n page_name = 'products'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_context_data(self, **kwargs):\n kwargs.update({\n 'category_list': ProductCategory.objects.all(),\n 'unit_list': Unit.objects.all()\n })\n return super().get_context_data(**kwargs)\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass ProductUpdateView(BasePurchasesView, SuccessMessageMixin, UpdateView):\n \"\"\"Update view for editing existing product.\"\"\"\n template_name = 'purchases/modals/products/product_form.html'\n model = Product\n fields = ('name', 'category', 'unit')\n success_url = reverse_lazy('purchases:product-list')\n success_message = 'The selected product is successfully updated.'\n page_name = 'products'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def get_context_data(self, **kwargs):\n kwargs.update({\n 'category_list': ProductCategory.objects.all(),\n 'unit_list': Unit.objects.all()\n })\n return super().get_context_data(**kwargs)\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass ProductDeleteView(BasePurchasesView, SuccessMessageMixin, DeleteView):\n \"\"\"Delete view to delete a product.\"\"\"\n template_name = 'purchases/modals/products/product_delete_form.html'\n model = Product\n success_url = reverse_lazy('purchases:product-list')\n success_message = 'The selected product is successfully deleted.'\n page_name = 'products'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def delete(self, request, *args, **kwargs):\n \"\"\"Overwrites delete method to send success message.\"\"\"\n self.object = self.get_object()\n self.object.delete()\n success_url = self.get_success_url()\n messages.success(request, self.success_message)\n return redirect(success_url)\n\n\nclass SupplierListView(BasePurchasesView, ListView):\n \"\"\"List view of fertilier suppliers.\"\"\"\n template_name = 'purchases/supplier_list.html'\n model = Supplier\n paginate_by = 10\n page_name = 'suppliers'\n queryset = Supplier.objects.all()\n access_roles = [ROLE_STAFF, ROLE_MANAGEMENT, ROLE_ADMIN, ROLE_GUEST]\n\n def get_queryset(self):\n qs = super().get_queryset()\n country = self.request.GET.get('country')\n\n if country is not None:\n qs = qs.filter(country=country)\n\n search_query = self.request.GET.get('search')\n if search_query is not None:\n qs = self.get_search_result(search_query)\n return qs\n\n def get_context_data(self, **kwargs):\n supplier_countries = [s.country for s in Supplier.objects.all()]\n countries_count = Counter(supplier_countries)\n Country = namedtuple('Country', ['name', 'code', 'count'])\n kwargs['country_list'] = [\n Country(name=c.name, code=c.code, count=count)\n for c, count in countries_count.items()\n ]\n kwargs['selected_country'] = self.request.GET.get('country')\n kwargs['suppliers_count'] = self.queryset.count()\n kwargs['search_query'] = self.request.GET.get('search', '').strip()\n return super().get_context_data(**kwargs)\n\n def get_search_result(self, query):\n \"\"\"Returns matching suppliers using search query.\"\"\"\n search_qs = self.queryset.filter(\n Q(name__istartswith=query) | Q(short_name__istartswith=query)\n )\n return search_qs\n\n\nclass SupplierCreateView(BasePurchasesView, SuccessMessageMixin, CreateView):\n \"\"\"Create view for creating new supplier.\"\"\"\n template_name = 'purchases/modals/suppliers/supplier_form.html'\n model = Supplier\n form_class = SupplierForm\n success_url = reverse_lazy('purchases:supplier-list')\n success_message = 'A new supplier is successfully created.'\n page_name = 'suppliers'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass SupplierUpdateView(BasePurchasesView, SuccessMessageMixin, UpdateView):\n \"\"\"Update view for editing existing supplier.\"\"\"\n template_name = 'purchases/modals/suppliers/supplier_form.html'\n model = Supplier\n form_class = SupplierForm\n success_url = reverse_lazy('purchases:supplier-list')\n success_message = 'The selected supplier is successfully updated.'\n page_name = 'suppliers'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def form_invalid(self, form):\n response = super().form_invalid(form)\n response.status_code = 400\n return response\n\n\nclass SupplierDeleteView(BasePurchasesView, SuccessMessageMixin, DeleteView):\n \"\"\"Delete view to delete a supplier.\"\"\"\n template_name = 'purchases/modals/suppliers/supplier_delete_form.html'\n model = Supplier\n success_url = reverse_lazy('purchases:supplier-list')\n success_message = 'The selected supplier is successfully deleted.'\n page_name = 'suppliers'\n access_roles = [ROLE_ADMIN, ROLE_STAFF]\n\n def delete(self, request, *args, **kwargs):\n \"\"\"Overwrites delete method to send success message.\"\"\"\n self.object = self.get_object()\n self.object.delete()\n success_url = self.get_success_url()\n messages.success(request, self.success_message)\n return redirect(success_url)\n" }, { "alpha_fraction": 0.48821547627449036, "alphanum_fraction": 0.5959596037864685, "avg_line_length": 17.5625, "blob_id": "8260cb94c3f908c0c60dfa9233544488e747411c", "content_id": "0cc7db77a067dbaa4b21a221a07cd4d75764abd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 297, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/purchases/migrations/0011_delete_batch.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-07 20:40\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('purchases', '0010_auto_20200606_1609'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='Batch',\n ),\n ]\n" }, { "alpha_fraction": 0.5417867302894592, "alphanum_fraction": 0.5994236469268799, "avg_line_length": 19.41176414489746, "blob_id": "fb4c872dca33e52a59918c42173a71bddd72015a", "content_id": "697bebf0271270ee0c15f80511c731573990681a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 347, "license_type": "no_license", "max_line_length": 58, "num_lines": 17, "path": "/orders/migrations/0007_remove_deliveryorder_status.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-06 13:09\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0006_remove_deliveryorder_lc_number'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='deliveryorder',\n name='status',\n ),\n ]\n" }, { "alpha_fraction": 0.7087307572364807, "alphanum_fraction": 0.7212032079696655, "avg_line_length": 29.266666412353516, "blob_id": "e8468ee5144ddee5b0811fe59bc1c1437c5e3022", "content_id": "84a9384959ccb8edca3c74542bf4c80fe7c2b9a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1363, "license_type": "no_license", "max_line_length": 75, "num_lines": 45, "path": "/purchases/tests/factories.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from random import uniform, choice\n\nimport factory\n\nfrom shared.models import Unit\n\nfrom purchases.models import Supplier, Product, ProductCategory, Batch\n\n\nclass SupplierFactory(factory.django.DjangoModelFactory):\n name = factory.Sequence(lambda n: f'Supplier {n}')\n city = factory.Faker('city')\n country = factory.Faker('country_code')\n\n class Meta:\n model = Supplier\n\n\nclass ProductCategoryFactory(factory.django.DjangoModelFactory):\n name = factory.Sequence(lambda n: f'Product Category {n}')\n\n class Meta:\n model = ProductCategory\n\n\nclass ProductFactory(factory.django.DjangoModelFactory):\n name = factory.Sequence(lambda n: f'Product {n}')\n category = factory.SubFactory(ProductCategoryFactory)\n unit = factory.LazyFunction(lambda: choice(Unit.objects.all()))\n\n class Meta:\n model = Product\n\n\nclass BatchFactory(factory.django.DjangoModelFactory):\n name = factory.Sequence(lambda n: f'LOT {n}')\n lc_number = factory.Sequence(lambda n: f'LC{n}')\n product = factory.SubFactory(ProductFactory)\n supplier = factory.SubFactory(SupplierFactory)\n quantity = factory.LazyFunction(lambda: round(uniform(1000, 50000), 2))\n rate = factory.LazyFunction(lambda: round(uniform(50, 300), 2))\n year = factory.LazyFunction(lambda: choice(Batch.YEAR_CHOICES)[0])\n\n class Meta:\n model = Batch\n\n" }, { "alpha_fraction": 0.574184000492096, "alphanum_fraction": 0.6275964379310608, "avg_line_length": 23.071428298950195, "blob_id": "75c42879a72d46e91bb859bf0f874c4694cbca20", "content_id": "d541ca154eb9fec456c46993841425eabba88f0e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license_type": "no_license", "max_line_length": 61, "num_lines": 28, "path": "/orders/migrations/0005_auto_20200531_1309.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-05-31 10:09\n\nfrom django.db import migrations\n\n\ndef move_lc(apps, schema_editor):\n \"\"\"\n Move a lc_number field to 'Batch' model.\n \"\"\"\n DeliveryOrder = apps.get_model('orders', 'DeliveryOrder')\n delivery_orders = DeliveryOrder.objects.all()\n\n for order in delivery_orders:\n if not order.batch.lc_number:\n order.batch.lc_number = order.lc_number\n order.batch.save()\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0004_auto_20200526_1708'),\n ('purchases', '0007_batch_lc_number')\n ]\n\n operations = [\n migrations.RunPython(move_lc)\n ]\n" }, { "alpha_fraction": 0.5931034684181213, "alphanum_fraction": 0.6285714507102966, "avg_line_length": 30.71875, "blob_id": "78700044e9b1b8b0ec5f720ad316b882a36bf0cc", "content_id": "a91bbabecfdd65810b388828ae0d19956eac6a08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 70, "num_lines": 32, "path": "/orders/migrations/0009_auto_20200607_2303.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.11 on 2020-06-07 20:03\nfrom django.db import migrations\n\ndef move_batch_model(apps, schema_editor):\n \"\"\"\n Moves the `Batch` model from the `purchases` app to the\n `orders` app.\n \"\"\"\n OldBatch = apps.get_model('purchases', 'Batch')\n NewBatch = apps.get_model('orders', 'Batch')\n batches = OldBatch.objects.all()\n for batch in batches:\n kwargs = dict(\n id=batch.pk, name=batch.name, lc_number=batch.lc_number,\n product=batch.product, supplier=batch.supplier,\n quantity=batch.quantity, rate=batch.rate, year=batch.year,\n status=batch.status, is_deleted=batch.is_deleted,\n created_at=batch.created_at, updated_at=batch.update_at\n )\n NewBatch.objects.create(**kwargs)\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('orders', '0008_batch'),\n ('purchases', '0010_auto_20200606_1609')\n ]\n\n operations = [\n migrations.RunPython(move_batch_model),\n ]\n" }, { "alpha_fraction": 0.6832493543624878, "alphanum_fraction": 0.6832493543624878, "avg_line_length": 31.742267608642578, "blob_id": "87cc2232f0e798923925e049ead33cb5f545c8c5", "content_id": "40b3fa68b5ba47c3434b171958d71666b632dae1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3176, "license_type": "no_license", "max_line_length": 72, "num_lines": 97, "path": "/accounts/views.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.views import PasswordChangeView, LoginView\nfrom django.contrib.messages.views import SuccessMessageMixin\nfrom django.shortcuts import redirect\nfrom django.urls import reverse_lazy, reverse\nfrom django.views.generic import CreateView, TemplateView, UpdateView\n\nfrom shared.constants import ROLE_SUPPLIER, DEMO, ROLE_GUEST, ROLE_ADMIN\n\nfrom .forms import UserRegistrationForm, ProfileUpdateForm\nfrom .mixins import AccountMixin\nfrom .models import CustomUser\n\n\nUser = get_user_model()\n\n\nclass CustomLoginView(LoginView):\n\n def get_success_url(self):\n \"\"\"\n Returns the user profile url if the user has not activated,\n else return the default success url.\n \"\"\"\n success_url = super().get_success_url()\n user = self.request.user\n if user.is_superuser:\n return success_url\n elif user.status == CustomUser.PENDING or user.role is None:\n return reverse('accounts:profile-update')\n else:\n return success_url\n\n\nclass UserRegistrationView(SuccessMessageMixin, CreateView):\n model = User\n form_class = UserRegistrationForm\n success_url = reverse_lazy('accounts:register-success')\n template_name = 'registration/register.html'\n\n def get_success_message(self, cleaned_data):\n if settings.ENVIRONMENT == DEMO:\n return 'Please login with your new e-mail and password.'\n return super().get_success_message(cleaned_data)\n\n def get_success_url(self):\n success_url = super().get_success_url()\n if settings.ENVIRONMENT == DEMO:\n return reverse('accounts:login')\n return success_url\n\n def form_valid(self, form):\n \"\"\"\n When the environment is `DEMO`, activate the\n user and assign him/her a staff role.\n \"\"\"\n redirect_url = super().form_valid(form)\n user = self.object\n role = ROLE_GUEST\n status = CustomUser.PENDING\n if settings.ENVIRONMENT == DEMO:\n role = ROLE_ADMIN\n status = CustomUser.ACTIVE\n user.role = role\n user.status = status\n user.save()\n return redirect_url\n\n\nclass RegistrationSuccessView(TemplateView):\n template_name = 'registration/success.html'\n\n\nclass PasswordUpdateView(SuccessMessageMixin, PasswordChangeView):\n template_name='registration/password_form.html'\n success_url = reverse_lazy('accounts:password-change')\n success_message = 'Password changed successfully.'\n page_name = 'accounts'\n access_roles = '__all__'\n\n\nclass ProfileUpdateView(SuccessMessageMixin, UpdateView):\n template_name = 'registration/profile_form.html'\n model = User\n form_class = ProfileUpdateForm\n success_url = reverse_lazy('accounts:profile-update')\n success_message = 'Your profile is updated successfully.'\n page_name = 'accounts'\n access_roles = '__all__'\n\n def get_object(self):\n return self.request.user\n\n def get_context_data(self, **kwargs):\n kwargs.update(ROLE_SUPPLIER=ROLE_SUPPLIER)\n return super().get_context_data(**kwargs)\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 23, "blob_id": "216a794d0540bb22dd53ba6287be6279f226a78c", "content_id": "90ebed371ca39839189fc3d68f989e129e0d7dec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24, "license_type": "no_license", "max_line_length": 23, "num_lines": 1, "path": "/shared/tasks.py", "repo_name": "eyobofficial/Payment-Tracker", "src_encoding": "UTF-8", "text": "# Add celery tasks here\n" } ]
90
jackpywi/Forms-anf-ModelForm-for-test
https://github.com/jackpywi/Forms-anf-ModelForm-for-test
a29be6642d251616ca2586cced179bcae3b9dcd6
9c899598324a135ee2ea1eebab8ecd03ef9c9bf6
2ea5418852fdf4421d816daea301bd6b3c14c34d
refs/heads/master
2023-04-20T18:47:45.241679
2021-05-06T13:29:31
2021-05-06T13:29:31
364,921,477
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7684210538864136, "alphanum_fraction": 0.7684210538864136, "avg_line_length": 18, "blob_id": "e1be1e70cf92afcd9267a62110df532e912e0c53", "content_id": "4b0ffeb2cf12327e7438fa3e6df164bc8683c201", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/formularze/apps.py", "repo_name": "jackpywi/Forms-anf-ModelForm-for-test", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass FormularzeConfig(AppConfig):\n name = 'formularze'\n" }, { "alpha_fraction": 0.6871508359909058, "alphanum_fraction": 0.6871508359909058, "avg_line_length": 18.88888931274414, "blob_id": "68fe52a6c0d439bb7e1faf42e22047de73e99a96", "content_id": "7e8bc82fd2979a45ef84b60551971ea168beed64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 179, "license_type": "no_license", "max_line_length": 58, "num_lines": 9, "path": "/formularze/urls.py", "repo_name": "jackpywi/Forms-anf-ModelForm-for-test", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name=\"formularze\"\n\nurlpatterns = [\n path('', views.contact),\n path('snippet', views.snippet_detail, name='snippet'),\n]\n" }, { "alpha_fraction": 0.5824634432792664, "alphanum_fraction": 0.5824634432792664, "avg_line_length": 25.58333396911621, "blob_id": "a08831353898a6fc1989573caeb3058c170474fd", "content_id": "9518205978f95ce35cd34f0a3005d06273c98dc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 958, "license_type": "no_license", "max_line_length": 59, "num_lines": 36, "path": "/formularze/views.py", "repo_name": "jackpywi/Forms-anf-ModelForm-for-test", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom .forms import ContactForm, SnippetForm\n\n\ndef contact(request):\n\n form = ContactForm()\n\n if request.method == 'POST':\n form = ContactForm(request.POST)\n\n if form.is_valid():\n name = form.cleaned_data['name']\n email = form.cleaned_data['email']\n print(name, email)\n #form = ContactForm() # clean fields\n\n context = {'form': form}\n return render(request, 'formularze/form.html', context)\n\n\ndef snippet_detail(request):\n\n form = SnippetForm()\n\n if request.method == 'POST':\n form = SnippetForm(request.POST)\n if form.is_valid():\n name = form.cleaned_data['name']\n body = form.cleaned_data['body']\n print('Valid ', name, body)\n form.save()\n #form = SnippetForm() # clean fields\n \n context = {'form': form}\n return render(request, 'formularze/form.html', context)\n\n" } ]
3
YassineRH2/test
https://github.com/YassineRH2/test
d4c93e13a6847396e687d8db1fdc4bab13814273
6af7c5828348ad7881872f2074b189bb059e9106
ce61dd7b6f827ec585ba664954166ffb32964c2c
refs/heads/master
2022-11-25T16:34:31.728699
2020-07-30T10:41:58
2020-07-30T10:41:58
283,743,855
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4910891056060791, "alphanum_fraction": 0.499009907245636, "avg_line_length": 20.95652198791504, "blob_id": "16bb3bb6c16753b953bad1d09070701b95f8c9bc", "content_id": "38943b964d34a2abeaf743675610eacf3f2a9ad0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 505, "license_type": "no_license", "max_line_length": 42, "num_lines": 23, "path": "/demo/__manifest__.py", "repo_name": "YassineRH2/test", "src_encoding": "UTF-8", "text": "{\n 'name': 'Test by YassineRH',\n 'version': '13.0',\n 'category': 'Tools',\n 'summary': 'Test for Future Projects',\n 'description': \"\"\"\n This module is just a test\n \"\"\",\n 'author': 'YassineRH',\n 'website': 'https://www.google.com',\n 'depends': ['base'],\n 'data': [\n 'views/view.xml',\n ],\n 'images': [\n 'pictures/image.jpg',\n ],\n 'demo': [],\n 'installable': True,\n 'auto_install': False,\n 'application': True,\n 'license': 'LGPL-3'\n}\n" } ]
1
ambika-qa/portfolio
https://github.com/ambika-qa/portfolio
9ac6ba9bfbb61d6f35d69ef0e7ce4511fb06b8f1
77fcdc5ca445ce4dd5555d5c2a71c5014f047509
366f18016d5dd40a0015e184e58cbcbcb9d3c910
refs/heads/master
2021-02-20T11:53:57.452889
2020-04-15T01:59:30
2020-04-15T01:59:30
245,335,557
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7876448035240173, "alphanum_fraction": 0.799227774143219, "avg_line_length": 44.70588302612305, "blob_id": "979e381b0f6eec2c1523cd09ed22fe83f3cd55c9", "content_id": "2ddeed830604a25e6c5ad085038dd93091595904", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 787, "license_type": "no_license", "max_line_length": 345, "num_lines": 17, "path": "/README.md", "repo_name": "ambika-qa/portfolio", "src_encoding": "UTF-8", "text": "# portfolio\nportfolio project\nhttp://138.68.41.35/\n\nAbout portfolio -\nPortfolio website is built by Ambika Bhat to learn website backend. I have used Django to develop backend. I have used HTML FE and also used Bootstrap libraries. Postgres database is used to store objects added to “Test Cases” and “Automation” page. This website is hosted on Digital Ocean. Gunicorn server and nginx proxy service are used to deploy.\n\nAbout automation -\nPortfolio project has been automated using Selenium and Cypress\n\n- Selenium :\nThis project uses selenium’s power to automate portfolio website. I have used TestNG automation framework.\n\n- Cypress :\nThis project uses cypress's capabilities to write automated test cases for Portfolio website.\n\nMore tools and frameworks support will be added\n" }, { "alpha_fraction": 0.6813187003135681, "alphanum_fraction": 0.6813187003135681, "avg_line_length": 25, "blob_id": "3ff98062386e7dbd77b05b306356d24ac525e01d", "content_id": "92f31434aa8673c557046d28f78d8504e879f198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 57, "num_lines": 7, "path": "/portfolio-website/blog/urls.py", "repo_name": "ambika-qa/portfolio", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('testcases', views.testcases, name='testcases'),\n path('<int:blog_id>/', views.detail, name='detail')\n]\n" }, { "alpha_fraction": 0.8491619825363159, "alphanum_fraction": 0.8491619825363159, "avg_line_length": 59, "blob_id": "573e7464982b3bb46061c220253d2ec27194c8e0", "content_id": "2c8387e73a489076b90487ed8a4d3960babab5a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 179, "license_type": "no_license", "max_line_length": 76, "num_lines": 3, "path": "/portfolio-website-automation/Selenium_Automation/ReadMe.txt", "repo_name": "ambika-qa/portfolio", "src_encoding": "UTF-8", "text": "Use VLC to play screen recording - TestPortfolioWebsite.avi\nReport generated from the automation framework - Portfolio_extentReport.html\nTest case file - TestPortfolioWebsite.java" }, { "alpha_fraction": 0.7209302186965942, "alphanum_fraction": 0.7209302186965942, "avg_line_length": 20.5, "blob_id": "e3a1271cf3f378abb03f6784ce082fdd3a326f14", "content_id": "07b4b56ca64d512240730ace2d5271e1abd45e42", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 129, "license_type": "no_license", "max_line_length": 60, "num_lines": 6, "path": "/portfolio-website/jobs/urls.py", "repo_name": "ambika-qa/portfolio", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('automation', views.automation, name='automation'),\n]\n" }, { "alpha_fraction": 0.5376623272895813, "alphanum_fraction": 0.56623375415802, "avg_line_length": 34, "blob_id": "ffa7be3b187cf592ec993917d945a3fdf25c3990", "content_id": "9c144835d7f2ff959b4a7857c3f41e24c5f914a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 385, "license_type": "no_license", "max_line_length": 49, "num_lines": 11, "path": "/portfolio-website-automation/Cypress_Automation/PortfolioTest.js", "repo_name": "ambika-qa/portfolio", "src_encoding": "UTF-8", "text": "\n/// <reference types=\"Cypress\" />\ndescribe('Portfolio test case', function() {\n it('Portfolio tab clicks', function() {\n cy.visit(\"http://138.68.41.35/\")\n cy.get('[href=\"/blog/testcases\"]').click()\n cy.get('h3').contains(\"Generic\")\n cy.get('.navbar-brand').click()\n cy.get('[href=\"/jobs/automation\"]').click()\n cy.get('h2').contains(\"GUI\")\n })\n })" }, { "alpha_fraction": 0.5146198868751526, "alphanum_fraction": 0.542397677898407, "avg_line_length": 22.586206436157227, "blob_id": "35d8244da98297edda4eac6d0a9c760b75f213b0", "content_id": "704e606edb9b860f517806bbcf7cb4fa8695451d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 684, "license_type": "no_license", "max_line_length": 70, "num_lines": 29, "path": "/portfolio-website/jobs/migrations/0002_auto_20200302_2338.py", "repo_name": "ambika-qa/portfolio", "src_encoding": "UTF-8", "text": "# Generated by Django 2.1.5 on 2020-03-02 23:38\n\nfrom django.db import migrations, models\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('jobs', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='job',\n old_name='summary',\n new_name='title',\n ),\n migrations.RemoveField(\n model_name='job',\n name='image',\n ),\n migrations.AddField(\n model_name='job',\n name='body',\n field=models.TextField(default=django.utils.timezone.now),\n preserve_default=False,\n ),\n ]\n" } ]
6
numb95/is_wordpress
https://github.com/numb95/is_wordpress
1128d0d758a69ca91c050e645ca14a6d0f4606aa
0401dd30d55abd31e987875e1f64fc8e377bf382
d609ba88ca93328c5cfb32cee20b1c29d32aa5ff
refs/heads/master
2022-12-11T10:29:29.758443
2021-06-02T13:13:09
2021-06-02T13:13:09
170,916,575
20
5
MIT
2019-02-15T19:21:51
2021-04-13T14:34:19
2021-06-02T13:13:09
Python
[ { "alpha_fraction": 0.6280992031097412, "alphanum_fraction": 0.6322314143180847, "avg_line_length": 33.57143020629883, "blob_id": "dc9ff2297e43357f9041e27b0c90c333bd4eac0d", "content_id": "87f47ded2a5ba27c1251b28d3f25b16799b7ae00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 242, "license_type": "permissive", "max_line_length": 51, "num_lines": 7, "path": "/is_wordpress/parser.py", "repo_name": "numb95/is_wordpress", "src_encoding": "UTF-8", "text": "from bs4 import BeautifulSoup\nimport re\ndef parse_data(req):\n soup = BeautifulSoup(req, 'html.parser')\n for tags in soup.find_all(\"meta\"):\n if (tags.get(\"name\", None) == 'generator'):\n return tags.get(\"content\", None)\n" }, { "alpha_fraction": 0.7020057439804077, "alphanum_fraction": 0.7086914777755737, "avg_line_length": 19.940000534057617, "blob_id": "8de61c7a60761048ce224910a1769e8baea03127", "content_id": "c6d74cf8dc73087a91bb312b01fb33ff61418e28", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1047, "license_type": "permissive", "max_line_length": 132, "num_lines": 50, "path": "/README.md", "repo_name": "numb95/is_wordpress", "src_encoding": "UTF-8", "text": "<!--\n Copyright (c) 2019 amirhossein\n \n This software is released under the MIT License.\n https://opensource.org/licenses/MIT\n-->\n# is_wordpress\nA simple (or useless) Program to check if a website is based on wordpress or not and if it's on wordpress which version does it use.\n\n# Installing \n``` pip install is-wordpress```\n\n# Usage \n```\nusage: main.py [-h] url\n\nCheck if selected website is based on wordpress or not.It also show the\nwordpress version.\n\npositional arguments:\n url URL to check the website.\n\noptional arguments:\n -h, --help show this help message and exit\n```\n\n## Docker usage\nBuild docker image\n```\n$ docker build -t is_wordpress .\n```\nNow you can simply invoke `is_wordpress` by:\n```\n$ docker run --rm is_wordpress goodarzi.net\n```\n\nOr simply run it by **docker hub**\n```\n$ docker run theyahya/is_wordpress goodarzi.net\n```\n## Example\n``` \n$ is_wordpress goodarzi.net\nWordPress 4.9.8\n```\n# Contribution\nFeel free to fork and fix problems. PRs are welcome. :heart:\n\n# Issues\nUse Issues section to report any problem.\n" }, { "alpha_fraction": 0.6697247624397278, "alphanum_fraction": 0.6811926364898682, "avg_line_length": 34.378379821777344, "blob_id": "f787d5ce789d3f1373ba8016018826326a8e235e", "content_id": "1c72e47b95dd2cfd00881e603905fd2c3dada984", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1308, "license_type": "permissive", "max_line_length": 151, "num_lines": 37, "path": "/setup.py", "repo_name": "numb95/is_wordpress", "src_encoding": "UTF-8", "text": "# Copyright (c) 2019 amirhossein\n# \n# This software is released under the MIT License.\n# https://opensource.org/licenses/MIT\n\nimport setuptools\nimport os\nthelibFolder = os.path.dirname(os.path.realpath(__file__))\nrequirementPath = thelibFolder + '/requirements.txt'\ninstall_requires = []\nif os.path.isfile(requirementPath):\n with open(requirementPath) as f:\n install_requires = f.read().splitlines()\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"is_wordpress\",\n version=\"0.0.2\",\n author=\"AmirHossein Goodarzi\",\n author_email=\"[email protected]\",\n description=\"A simple (or useless) Program to check if a website is based on wordpress or not and if it's on wordpress which version does it use.\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/numb95/is_wordpress\",\n download_url='https://github.com/numb95/is_wordpress/archive/0.0.2.tar.gz',\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n entry_points = {\n 'console_scripts': ['is_wordpress=is_wordpress.cli:main'],\n },install_requires=install_requires,\n)" }, { "alpha_fraction": 0.5989304780960083, "alphanum_fraction": 0.5989304780960083, "avg_line_length": 22.5, "blob_id": "4639d1ae23ebdaff9af291d804376f1e2e4937a9", "content_id": "7c8409aa48418bc0692e604524a778924d6ebdc5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 187, "license_type": "permissive", "max_line_length": 33, "num_lines": 8, "path": "/is_wordpress/get_requests.py", "repo_name": "numb95/is_wordpress", "src_encoding": "UTF-8", "text": "import requests\ndef get_page_requests(url):\n if (url.startswith('http')):\n pass\n else:\n url = 'http://'+url\n page_code = requests.get(url)\n return page_code.text" }, { "alpha_fraction": 0.691428542137146, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 24.14285659790039, "blob_id": "f974c780e715aec41b63db023c31218a6642ff22", "content_id": "ed208bc68464990c1a7660c45b7042440d455a3b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 175, "license_type": "permissive", "max_line_length": 50, "num_lines": 7, "path": "/is_wordpress/cli.py", "repo_name": "numb95/is_wordpress", "src_encoding": "UTF-8", "text": "# Copyright (c) 2019 amirhossein\n# \n# This software is released under the MIT License.\n# https://opensource.org/licenses/MIT\nfrom . import run\ndef main():\n print(run.run())" }, { "alpha_fraction": 0.7472527623176575, "alphanum_fraction": 0.7692307829856873, "avg_line_length": 21.75, "blob_id": "885da3dc03b69bbaca2d663684bd278dbab466da", "content_id": "59937e87f97b56581a3de691a219c7d3b61097d5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 91, "license_type": "permissive", "max_line_length": 31, "num_lines": 4, "path": "/Dockerfile", "repo_name": "numb95/is_wordpress", "src_encoding": "UTF-8", "text": "\nFROM python:3.7-alpine as build\nRUN pip install is-wordpress \n\nENTRYPOINT [\"is_wordpress\"]" }, { "alpha_fraction": 0.7183811068534851, "alphanum_fraction": 0.7183811068534851, "avg_line_length": 44.61538314819336, "blob_id": "394ddac29ece3bb275f545205e0f74eafe617411", "content_id": "0d299f3ff40eb4b498294ece056d1b8f238186d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 593, "license_type": "permissive", "max_line_length": 145, "num_lines": 13, "path": "/is_wordpress/run.py", "repo_name": "numb95/is_wordpress", "src_encoding": "UTF-8", "text": "from . import get_requests, parser\nimport sys\nimport argparse\nimport re\ndef run():\n argparser = argparse.ArgumentParser(description='Check if selected website is based on wordpress or not.It also show the wordpress version.')\n argparser.add_argument(\"url\", help='URL to check the website.')\n args = argparser.parse_args()\n website = get_requests.get_page_requests(args.url)\n if parser.parse_data(website) == None:\n return \"It's not wordpress or cannot identified\"\n if (re.findall('^WordPress.*', parser.parse_data(website))):\n return parser.parse_data(website)\n" }, { "alpha_fraction": 0.450549453496933, "alphanum_fraction": 0.6776556968688965, "avg_line_length": 15.058823585510254, "blob_id": "29f2c1fe05bc6d49330b83b4db8b5ee3bfdc4ec5", "content_id": "b07723ef14aa509d9d952f34ce40d25109044316", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 273, "license_type": "permissive", "max_line_length": 24, "num_lines": 17, "path": "/requirements-develop.txt", "repo_name": "numb95/is_wordpress", "src_encoding": "UTF-8", "text": "astroid==2.1.0\nbeautifulsoup4==4.7.1\nbs4==0.0.1\ncertifi==2018.11.29\nchardet==3.0.4\nidna==2.8\nisort==4.3.4\nlazy-object-proxy==1.3.1\nmccabe==0.6.1\npkg-resources==0.0.0\npylint==2.2.2\nrequests==2.21.0\nsix==1.12.0\nsoupsieve==1.7.3\ntyped-ast==1.3.2\nurllib3==1.26.5\nwrapt==1.11.1\n" } ]
8
dgladkov/time-tracker
https://github.com/dgladkov/time-tracker
6f010af69050e287b43dd8d6f8977431282bb3f0
72124b9c3808e1ebc788b680dcf47818bd46d228
9ea2b71b19d9a661ba2d7214fc4786702c46ebcf
refs/heads/master
2021-01-24T08:28:42.075632
2016-09-27T15:44:02
2016-09-27T15:44:02
69,466,548
0
0
null
2016-09-28T13:35:03
2016-07-29T15:42:39
2016-09-27T14:20:11
null
[ { "alpha_fraction": 0.6370656490325928, "alphanum_fraction": 0.6409266591072083, "avg_line_length": 31.375, "blob_id": "c315bec9d0dda07bf89256bd562915e1a403a822", "content_id": "1785d1e8a5bf87e7e5415fa1877ea6cc6e107b6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 259, "license_type": "no_license", "max_line_length": 66, "num_lines": 8, "path": "/time_tracker/settings/__init__.py", "repo_name": "dgladkov/time-tracker", "src_encoding": "UTF-8", "text": "from .base import * # noqa\ntry:\n from .local import * # noqa\nexcept ImportError as exc:\n message = '{} (Did you forget to create symlink to local.py?)'\n exc.args = (message.format(exc.args[0]), )\n exc.msg = message.format(exc.msg)\n raise exc\n" }, { "alpha_fraction": 0.8100000023841858, "alphanum_fraction": 0.8100000023841858, "avg_line_length": 30.25, "blob_id": "d7b0d4785b45176b597548f3d159c7fa0bf26287", "content_id": "2bbf12ca5388d5e49a806c898261e1856182a6db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "no_license", "max_line_length": 54, "num_lines": 16, "path": "/records/views.py", "repo_name": "dgladkov/time-tracker", "src_encoding": "UTF-8", "text": "from django.contrib.auth import get_user_model\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import render_to_response\nfrom rest_framework import status, generics\nfrom rest_framework.permissions import IsAuthenticated\n\nfrom .models import Record\nfrom .serializers import RecordSerializer\n\nUser = get_user_model()\n\n\nclass Records(generics.ListCreateAPIView):\n queryset = Record.objects.all()\n serializer_class = RecordSerializer\n permission_classes = (IsAuthenticated,)\n" } ]
2
pombredanne/django-spreadsheet-reports
https://github.com/pombredanne/django-spreadsheet-reports
651e1fd0b2a83cb378caf8f00dedddc35aa381ed
4299092e8f5bc98dfcb48eded40bc31da261fcda
ef7645882aed677a8783a2f9d28421f625883834
refs/heads/master
2017-06-01T11:54:22.638954
2014-12-05T08:24:25
2014-12-05T08:24:25
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8089005351066589, "alphanum_fraction": 0.8089005351066589, "avg_line_length": 46.75, "blob_id": "784177ef409d4d621952ef370447301041a2b515", "content_id": "2682f634ff96d4122c2e0f986bb1d7d5edaf09a2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 382, "license_type": "no_license", "max_line_length": 95, "num_lines": 8, "path": "/django_spreadsheet_reports/__init__.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "from .reports import Report, Column, columns, filters, Filter, groupbys, GroupBy, DateFilter, \\\n CalculatedColumn, PercentageCalculatedColumn, BooleanFilter, DecimalColumn, HiddenColumn, \\\n ChoicesColumn, PercentageDifferenceColumn\nfrom .reporting_site import site\n\n\nREPORTING_SOURCE_FILE = 'reports'\ndefault_app_config = 'django_spreadsheet_reports.autodiscover.MyAppConfig'\n" }, { "alpha_fraction": 0.6126984357833862, "alphanum_fraction": 0.6153439283370972, "avg_line_length": 26, "blob_id": "ebcdc0a8e5128b6e918ae08300885d535ba80201", "content_id": "a655e5044dcda0c11e05922d5646667e587be1bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1890, "license_type": "no_license", "max_line_length": 74, "num_lines": 70, "path": "/django_spreadsheet_reports/templatetags/reports_tags.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom django import template\nfrom django_spreadsheet_reports.models import Notice\n\n\nregister = template.Library()\n\n\ndef easy_tag(func):\n \"\"\"\n Decorator to facilitate template tag creation\n\n deal with the repetitive parts of parsing template tags\n \"\"\"\n\n def inner(parser, token):\n # print token\n try:\n return func(*token.split_contents())\n except TypeError:\n raise template.TemplateSyntaxError(\n 'Bad arguments for tag \"%s\"' % token.split_contents()[0])\n\n inner.__name__ = func.__name__\n inner.__doc__ = inner.__doc__\n return inner\n\n\nclass AppendGetNode(template.Node):\n def __init__(self, d):\n self.dict_pairs = []\n for pair in d.split(','):\n pair = pair.split('=')\n row = (pair[0], template.Variable(pair[1]))\n self.dict_pairs.append(row)\n\n def render(self, context):\n get = context['request'].GET.copy()\n for key, value in self.dict_pairs:\n get[key] = value.resolve(context)\n path = context['request'].META['PATH_INFO']\n if len(get):\n path += \"?%s\" % get.urlencode()\n return path\n\n\[email protected]()\n@easy_tag\ndef append_to_get(_tag_name, d):\n return AppendGetNode(d)\n\n\[email protected]_tag\ndef display_column(table, value, counter):\n key = table.columns[counter].accessor\n if hasattr(table.columns[key].column, 'choices'):\n d = dict(table.columns[key].column.choices)\n if value is None:\n return 'None'\n return d[value]\n return value\n\n\[email protected]_tag('django_spreadsheet_reports/notice_list.html')\ndef show_notice_list(hours_ago=72):\n cutoff = datetime.datetime.now() - datetime.timedelta(hours=hours_ago)\n notices = Notice.objects.filter(\n creation_date__gte=cutoff).order_by('-id')\n return {'notices': notices}\n" }, { "alpha_fraction": 0.4741935431957245, "alphanum_fraction": 0.4784946143627167, "avg_line_length": 31.068965911865234, "blob_id": "6cd25db6c6892747d7f037cffee828943c1a7390", "content_id": "867ff71c7494ba1a7a4131b538108cd3498979ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1860, "license_type": "no_license", "max_line_length": 84, "num_lines": 58, "path": "/django_spreadsheet_reports/templates/django_spreadsheet_reports/report.js", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "<script type=\"text/javascript\">\n// <![CDATA[\n$(document).ready(function(){\n var new_filter = \"\";\n groups = \"<ul>\";\n $(\"select#id_group_by option\").each(function(){\n groups += \"<li><a href='#'>\"+$(this).text()+\"</a></li>\";\n });\n groups += \"</ul>\";\n $(\"#groupbychoices\").html(groups);\n $(\"table.report_content tbody tr td:first-child\").css(\"cursor\", \"pointer\");\n $(\"table.report_content tbody tr td:first-child\").click(function(){\n // get selected item\n var field_name = $(\"table.report_content thead tr td:first\").text();\n /*if ((field_name == 'Date') && $('#id_Days').attr('name') == 'Days'){\n field_name = 'Days';\n //alert(\"estoy dentro\");\n }*/\n new_filter = field_name + '=' + $(this).attr(\"id\");\n\n $(\"#groupbychoices ul li a\").each(function(){\n var url = document.location.href;\n // get clicked url\n var group_selected = $(this).text();\n if (url.search('group_by') == -1){\n url += '?group_by=';\n url += group_selected;\n url = url + '&' + new_filter;\n \t url = url.replace(' ', '+');\n\t url += '&form_submitted=1&submit=Submit+Query';\n $(this).attr(\"href\", url);\n }\n else{\n // get selected group\n var previous_selected = $(\"select#id_group_by option:selected\").text();\n var old_group = 'group_by=' + previous_selected;\n url = url.replace(old_group, 'group_by='+group_selected);\n url = url + '&' + new_filter;\n\t url = url.replace(' ', '+');\n $(this).attr(\"href\", url);\n }\n \n });\n \n\n\n\n\n $.openDOMWindow({\n windowSourceID: '#groupBys',\n width: 150,\n height: 150\n });\n return false;\n });\n});\n// ]]>\n</script>\n" }, { "alpha_fraction": 0.4975564479827881, "alphanum_fraction": 0.5729578733444214, "avg_line_length": 32.06153869628906, "blob_id": "2f008fec0f3163b02dea2fb230451e27541ce73c", "content_id": "c8741d77da9b58e70b86f277384f3761bd7b7e2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4297, "license_type": "no_license", "max_line_length": 86, "num_lines": 130, "path": "/django_spreadsheet_reports/textdaterange.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "from datetime import timedelta\nfrom django.utils import timezone\nimport dateutil.parser\nimport re\n\n\nclass ParseError(RuntimeError): \n pass\n\n\nclass TextDateRange(object):\n \"\"\"\n >>> TextDateRange('2008-04-01').tuple()\n ('2008-04-01', '2008-04-01')\n \n >>> TextDateRange('2008-4-1').tuple()\n ('2008-04-01', '2008-04-01')\n\n >>> TextDateRange('2008-04-01').num_days()\n 1\n\n >>> TextDateRange('2008-04-01:2008-04-03').tuple()\n ('2008-04-01', '2008-04-03')\n\n >>> TextDateRange('2008-04-01:2008-04-03').num_days()\n 3\n \n >>> TextDateRange('2007-12-29:2008-01-02').days_list()\n ['2007-12-29', '2007-12-30', '2007-12-31', '2008-01-01', '2008-01-02']\n\n >>> TextDateRange('2008-04-01:2008-04-03', set_end_date_time=True).tuple()\n ('2008-04-01', '2008-04-03 23:59:59')\n\n >>> TextDateRange('2008-04-01:2008-04-03', set_end_date_time=True).num_days()\n 3\n\n >>> TextDateRange('2007-12-29:2008-01-02', set_end_date_time=True).days_list()\n ['2007-12-29', '2007-12-30', '2007-12-31', '2008-01-01', '2008-01-02']\n\n >>> TextDateRange('abc')\n Traceback (most recent call last):\n ...\n ParseError: Unable to parse date \"abc\"\n\n >>> TextDateRange('2008-04-03:2008-03-01')\n Traceback (most recent call last):\n ...\n ParseError: Enddate must be after the startdate\n \"\"\"\n def __init__(self, instr, set_end_date_time=False):\n tokens = instr.split(':')\n try:\n date_strings = [self._token_to_date_string(x) for x in tokens]\n if len(date_strings) == 1:\n self.start, self.end = date_strings[0], date_strings[0]\n elif len(date_strings) == 2:\n self.start, self.end = date_strings[0], date_strings[1]\n else:\n raise ParseError\n except ParseError:\n raise ParseError('Unable to parse date \"%s\"' % instr)\n if self.start > self.end:\n raise ParseError('Enddate must be after the startdate')\n if set_end_date_time:\n self.end += ' 23:59:59'\n \n def _token_to_date_string(self, token):\n daysagoregex = re.compile(r'(\\d+) ?days ?ago')\n dateregex = re.compile('^(\\d{4})-(\\d{1,2})-(\\d{1,2})$')\n if token.lower() == 'yesterday':\n return self._format_datetime(timezone.now() - timedelta(days=1))\n elif token.lower() == 'today':\n return self._format_datetime(timezone.now())\n elif daysagoregex.match(token.lower()):\n days_ago = int(daysagoregex.match(token.lower()).groups()[0])\n return self._format_datetime(timezone.now() - timedelta(days=days_ago))\n elif dateregex.match(token):\n groups = dateregex.match(token).groups()\n return \"%04d-%02d-%02d\" % (int(groups[0]), int(groups[1]), int(groups[2]))\n else:\n raise ParseError\n \n def _set_start_end_from_days_ago(self, days_ago):\n date = self._format_datetime(timezone.now() - timedelta(days=days_ago))\n self.start, self.end = date, date\n \n def days_list(self):\n format_str = '%Y-%m-%d'\n date = timezone.now().strptime(self.start, format_str)\n enddate = timezone.now().strptime(_strip_time(self.end), format_str)\n increment_by = timedelta(days=1)\n output = []\n while date <= enddate:\n output.append(self._format_datetime(date))\n date += increment_by\n return output\n \n def tuple(self):\n return self.start, self.end\n\n def num_days(self):\n d1 = timezone.now().strptime(_strip_time(self.end), '%Y-%m-%d')\n d2 = timezone.now().strptime(self.start, '%Y-%m-%d')\n return (d1 - d2).days + 1\n\n @property\n def start_dateobj(self):\n return dateutil.parser.parse(self.start)\n\n @property\n def end_dateobj(self):\n return dateutil.parser.parse(self.end)\n \n @staticmethod\n def _format_datetime(datetime):\n format_str = '%Y-%m-%d'\n return datetime.strftime(format_str)\n\n def __str__(self):\n return \"{0} -> {1}\".format(self.start, self.end)\n\n\ndef _strip_time(date_with_time):\n return date_with_time.split(' ')[0]\n \n\nif __name__ == '__main__':\n import doctest\n print(\"Running doctest . . .\")\n doctest.testmod()" }, { "alpha_fraction": 0.6900985836982727, "alphanum_fraction": 0.6918131113052368, "avg_line_length": 45.65999984741211, "blob_id": "a2df350359864fefe4546b71c1de26a2d159115b", "content_id": "18b25fe67fb53bbcffdf532a4f0d5943a275c8a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2333, "license_type": "no_license", "max_line_length": 104, "num_lines": 50, "path": "/README.txt", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "I was heavily inspired by http://code.google.com/p/django-reporting/. After playing\nwith django-reporting, I was wishing parts of it were implemented differently. And so,\ndjango-spreadsheet-reports was born.\n\nAlthough this project has been in development for a few years, it's documentation is very light.\n\nA few features provided by this are:\n\n* Ability to produce spreadsheet reports off of a user model by creating a reports.py in your app\n directories. The contents of the reports.py should look like:\n\n class UserStatsReport(django_spreadsheet_reports.Report):\n name = 'Simple User Report'\n slug = 'simple-user-report'\n model = UserStats\n\n filter_by = django_spreadsheet_reports.filters(\n django_spreadsheet_reports.DateFilter('user__date_joined'),\n django_spreadsheet_reports.Filter('user__date_joined', name='Days', multiple=True),\n )\n\n group_by = django_spreadsheet_reports.groupbys(\n 'user__date_joined',\n django_spreadsheet_reports.GroupBy('campaign__user__username', name='Affiliate'),\n django_spreadsheet_reports.GroupBy('program__name', name='Program'),\n django_spreadsheet_reports.GroupBy('referring_url', name='Referring URL'),\n django_spreadsheet_reports.GroupBy('track__track', name='Track'),\n django_spreadsheet_reports.GroupBy('tour__name', name='Tour',\n additional_columns=[\n django_spreadsheet_reports.Column('tour__url', name='Tour URL'),\n django_spreadsheet_reports.Column('tour__program__name', name='Program'),\n ]),\n )\n\n list_aggregates = django_spreadsheet_reports.columns(\n django_spreadsheet_reports.Column(Count('id'), name='Members'),\n\n* Exporting to CSV is built in\n* Sortable columns\n\nRequirements: Python>=3.4, Django>=1.5\n\nInstallation\n=============\n* pip install django-spreadsheet-reports\n* Add `django_spreadsheet_reports` to your installed apps\n* Add to your urls file: url(r'^reports/', include(django_spreadsheet_reports.site.urls)),\n* Create a reports.py in one of your app directories, and add a Report subclass in it.\n* Register your report subclass, by adding a line like this to the bottom of your reports\n file: django_spreadsheet_reports.site.register(UserStatsReport)\n" }, { "alpha_fraction": 0.5676965117454529, "alphanum_fraction": 0.5708768963813782, "avg_line_length": 42.156864166259766, "blob_id": "f61a403012722092e80292a967187265004aa1d3", "content_id": "f0cccb8d27efe0a3c231b18ec228bf25687c3b85", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4402, "license_type": "no_license", "max_line_length": 76, "num_lines": 102, "path": "/django_spreadsheet_reports/utils.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "import logging\nimport datetime\n\nfrom django.db.models import Sum\nfrom django.core.mail import send_mail\nfrom django.conf import settings\nfrom django.template.loader import render_to_string\n\nimport django_spreadsheet_reports\nfrom django_spreadsheet_reports.models import Notice\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef save_reports(report_type='daily', should_send_mail=True):\n logger.info(\"Getting %s reports\" % report_type)\n if report_type == 'daily':\n cutoff = datetime.date.today() - datetime.timedelta(days=2)\n reports = django_spreadsheet_reports.site.get_daily_reports()\n yesterday = datetime.date.today() - datetime.timedelta(days=1)\n elif report_type == 'weekly':\n cutoff = datetime.date.today() - datetime.timedelta(days=8)\n reports = django_spreadsheet_reports.site.get_weekly_reports()\n yesterday = datetime.date.today() - datetime.timedelta(days=1)\n two_weeks = datetime.date.today() - datetime.timedelta(days=15)\n else:\n logger.error(\"%s is not a valid report type\" % report_type)\n raise RuntimeError()\n count = 0\n for report in reports:\n logger.info(\"Getting stats for report %s\" % report.name)\n qs = report.notice_model.objects.filter(**report.notices_filter_by)\n if report_type == 'daily': \n qs = qs.filter(date=yesterday).values(\n report.notice_group_by).annotate(Sum(report.notice_field))\n elif report_type == 'weekly':\n qs = qs.filter(date__lte=yesterday, date__gte=cutoff).values(\n report.notice_group_by).annotate(Sum(report.notice_field))\n\n for row in qs:\n high_limit = low_limit = 0\n group_by = row[report.notice_group_by]\n val = float(row[report.notice_field+'__sum'])\n if report_type == 'daily':\n filters = {report.notice_group_by: group_by,\n 'date': cutoff}\n elif report_type == 'weekly':\n # noinspection PyUnboundLocalVariable\n filters = {report.notice_group_by: group_by,\n 'date__lte': cutoff,\n 'date__gte': two_weeks}\n else:\n raise RuntimeError()\n old_mark = report.notice_model.objects.filter(\n **report.notices_filter_by).filter(\n **filters).values(report.notice_group_by).annotate(\n Sum(report.notice_field))\n \n is_visible = True\n prev_val = 0.0\n if old_mark:\n mark = old_mark[0]\n prev_val = float(mark[report.notice_field+'__sum'])\n logger.info(\"Got prev_val of %s\" % prev_val)\n high_limit = prev_val + (prev_val * report.change_threshold)\n low_limit = prev_val - (prev_val * report.change_threshold)\n if low_limit <= val <= high_limit:\n is_visible = False\n if val < report.minimum_threshold and \\\n prev_val < report.minimum_threshold:\n is_visible = False\n \n if is_visible:\n Notice.objects.create(slug=report.slug,\n group_name=group_by,\n group_val=val,\n prev_val=prev_val,\n low_limit=low_limit,\n high_limit=high_limit)\n logger.info(\"Created notice for %s\" % group_by)\n count += 1\n logger.info(\"Created %s notices\" % count)\n\n\ndef send_new_notices_report():\n logger.info(\"sending email to staff members\")\n subject = 'New notices report'\n cutoff = datetime.datetime.now() - datetime.timedelta(hours=24)\n notices = Notice.objects.filter(creation_date__gte=cutoff)\n staff_members = [] # TODO make this a list of staff usernames\n message = render_to_string('django_spreadsheet_reports/notice_list.txt',\n {'notices': notices})\n logger.info(\"sending emails to %s staff members\" % len(staff_members))\n send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, staff_members,\n fail_silently=False)\n logger.info(\"finished\")\n\n\ndef load_from_urls():\n from django.conf import settings\n __import__(settings.ROOT_URLCONF)\n" }, { "alpha_fraction": 0.6074672341346741, "alphanum_fraction": 0.6316851377487183, "avg_line_length": 28.147058486938477, "blob_id": "69b3d2030d16395e7055bfcd8b2ce94f5b3ecde0", "content_id": "b714aeb2e33d750a2e43a3bbdb9ef9d4e8daf60a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 991, "license_type": "no_license", "max_line_length": 59, "num_lines": 34, "path": "/django_spreadsheet_reports/models.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\nclass Bookmark(models.Model):\n name = models.CharField(max_length=255)\n uri = models.CharField(max_length=4096)\n\n class Meta:\n ordering = ('name',)\n\n def __unicode__(self):\n return self.name\n\n\nclass Notice(models.Model):\n slug = models.CharField(max_length=255)\n date = models.DateField(auto_now_add=True)\n creation_date = models.DateTimeField(auto_now_add=True)\n group_name = models.CharField(max_length=255)\n group_val = models.IntegerField(default=0)\n low_limit = models.IntegerField(default=0)\n high_limit = models.IntegerField(default=0)\n prev_val = models.IntegerField(default=0)\n\n def get_change_pct(self):\n before_data = float(self.prev_val)\n after_data = float(self.group_val)\n delta = after_data - before_data\n if before_data == 0.0:\n val = after_data\n else:\n val = delta / before_data\n val = val * 100.0\n return \"%.0f\" % val\n" }, { "alpha_fraction": 0.6700000166893005, "alphanum_fraction": 0.6700000166893005, "avg_line_length": 25.263158798217773, "blob_id": "2d5db3c3a18f97df058203fc52392f56675c4009", "content_id": "5b347df14033ea2c6538860f84155cb89cf63c2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "no_license", "max_line_length": 70, "num_lines": 19, "path": "/django_spreadsheet_reports/autodiscover.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "import importlib.util\nfrom django.apps.config import AppConfig\nfrom django.conf import settings\n\ndef autodiscover():\n # Check django/contrib/admin/__init__.py to know what I'm doing :)\n for app in settings.INSTALLED_APPS:\n reports_spec = app + \".reports\"\n if importlib.util.find_spec(reports_spec) is None:\n continue\n\n __import__(reports_spec)\n\n\nclass MyAppConfig(AppConfig):\n name = 'django_spreadsheet_reports'\n\n def ready(self):\n autodiscover()\n\n" }, { "alpha_fraction": 0.647677481174469, "alphanum_fraction": 0.6494303345680237, "avg_line_length": 33.57575607299805, "blob_id": "dd271fadb08a20bee1389d5b9c761763915aa088", "content_id": "16c32e35f28daac03aaf04d1f22e52ebf798218c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "no_license", "max_line_length": 86, "num_lines": 33, "path": "/django_spreadsheet_reports/management/commands/defreports_update_daily_notes.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "import logging\nfrom optparse import make_option\n\nimport lockfile\nfrom django.core.management import base\nfrom django.db import transaction\n\nfrom django_spreadsheet_reports.utils import save_reports, load_from_urls\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(base.NoArgsCommand):\n option_list = base.NoArgsCommand.option_list + (\n make_option('-s', action='store_true', dest='silentmode',\n default=False, help='Run in silent mode'),\n make_option('--debug', action='store_true',\n dest='debugmode', default=False,\n help='Debug mode (overrides silent mode)'),\n )\n\n @transaction.commit_on_success\n def handle_noargs(self, **options):\n if not options['silentmode']:\n logging.getLogger('djangoproject').setLevel(logging.INFO)\n if options['debugmode']:\n logging.getLogger('djangoproject').setLevel(logging.DEBUG)\n lock = lockfile.FileLock('/tmp/django_spreadsheet_reports_update_daily_notes')\n lock.acquire(10)\n with lock:\n load_from_urls()\n save_reports(report_type='daily')\n" }, { "alpha_fraction": 0.6396760940551758, "alphanum_fraction": 0.6396760940551758, "avg_line_length": 35.86567306518555, "blob_id": "0a81ccd6dde2a09c59d15f3ddc6720f70b5e8968", "content_id": "d13fa11554c1065503e08a8f342e5291bc36cc17", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "no_license", "max_line_length": 96, "num_lines": 67, "path": "/django_spreadsheet_reports/reporting_site.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, url\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\n\nfrom . import models\n\n\n@staff_member_required\ndef home(request):\n context = RequestContext(request)\n context['available_reports'] = site._registered_reports\n context['bookmarks'] = models.Bookmark.objects.all()\n context['daily_reports'] = site._registered_daily_reports\n context['weekly_reports'] = site._registered_weekly_reports\n return render_to_response('django_spreadsheet_reports/home.html', context_instance=context)\n\n\ndef wrap(report):\n def wrapper(request, *args, **kwargs):\n return report.render_to_response(request)\n\n wrapper = staff_member_required(wrapper)\n return wrapper\n\n\nclass ReportingSite(object):\n _registered_reports = []\n _registered_daily_reports = []\n _registered_weekly_reports = []\n\n def register(self, report):\n if isinstance(report, type):\n report = report()\n self._registered_reports.append(report)\n\n def register_daily(self, report):\n if isinstance(report, type):\n report = report()\n self._registered_daily_reports.append(report)\n\n def get_daily_reports(self):\n return self._registered_daily_reports\n\n def register_weekly(self, report):\n if isinstance(report, type):\n report = report()\n self._registered_weekly_reports.append(report)\n\n def get_weekly_reports(self):\n return self._registered_weekly_reports\n\n def urls(self):\n urlpatterns = patterns('', url(r'^$', home, name='django_spreadsheet_reports'))\n for report in self._registered_reports:\n urlpatterns += patterns('', url(r'^%s/$' % report.slug, wrap(report),\n name='django_spreadsheet_reports-%s' % report.slug))\n for report in self._registered_daily_reports:\n urlpatterns += patterns('', url(r'^%s/$' % report.slug, wrap(report),\n name='django_spreadsheet_reports-%s' % report.slug))\n for report in self._registered_weekly_reports:\n urlpatterns += patterns('', url(r'^%s/$' % report.slug, wrap(report),\n name='django_spreadsheet_reports-%s' % report.slug))\n return urlpatterns\n\n urls = property(urls)\nsite = ReportingSite()\n" }, { "alpha_fraction": 0.4266239106655121, "alphanum_fraction": 0.4346431493759155, "avg_line_length": 22.50943374633789, "blob_id": "a4d40e24e49bdd6511d046f0c55020468d7f4e8f", "content_id": "9d943c40197155df5cc2926326badecb72bc131b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1247, "license_type": "no_license", "max_line_length": 65, "num_lines": 53, "path": "/django_spreadsheet_reports/templates/django_spreadsheet_reports/home.html", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "{% extends \"admin/base_reports.html\" %}\n{% load reports_tags %}\n\n{% block content %}\n\n<div id=\"content\" class=\"colMS\">\n\n <h1>Tracking administration</h1>\n\n <div id=\"content-main\">\n\n <div class=\"module\">\n \n <h2>Available Reports</h2>\n <ul>\n {% for report in available_reports %}\n <li><a href=\"{{report.url}}\">{{report.name}}</a></li>\n {% endfor %}\n </ul>\n \n {% if bookmarks %}\n <h2>Bookmarked Reports</h2>\n <ul>\n {% for report in bookmarks %}\n <li><a href=\"{{report.uri}}\">{{report.name}}</a></li>\n {% endfor %}\n </ul>\n {% endif %}\n\t \n\t {% if daily_reports %}\n <h2>Daily Reports</h2>\n\t <ul>\n\t {% for report in daily_reports %}\n\t\t<li><a href=\"{{report.url}}\">{{report.name}}</a></li>\n\t {% endfor %}\n\t </ul>\n\t {% endif %}\n\n\t {% if weekly_reports %}\n\t <h2>Weekly Reports</h2>\n\t <ul>\n\t {% for report in weekly_reports %}\n\t <li><a href=\"{{report.url}}\">{{report.name}}</a></li>\n\t {% endfor %}\n\t </ul>\n\t {% endif %}\n\t {% show_notice_list %}\n\n </div>\n </div>\n \n</div>\n{% endblock %} \n" }, { "alpha_fraction": 0.5017064809799194, "alphanum_fraction": 0.5139932036399841, "avg_line_length": 33.880950927734375, "blob_id": "e0b59be941cd614994e347cd4481f1491fcb14b9", "content_id": "89cbc8a12dfbd68e20d44ab36426099495d3c4a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1465, "license_type": "no_license", "max_line_length": 114, "num_lines": 42, "path": "/django_spreadsheet_reports/migrations/0001_initial.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Bookmark',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('name', models.CharField(max_length=255)),\n ('uri', models.CharField(max_length=4096)),\n ],\n options={\n 'ordering': ('name',),\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Notice',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)),\n ('slug', models.CharField(max_length=255)),\n ('date', models.DateField(auto_now_add=True)),\n ('creation_date', models.DateTimeField(auto_now_add=True)),\n ('group_name', models.CharField(max_length=255)),\n ('group_val', models.IntegerField(default=0)),\n ('low_limit', models.IntegerField(default=0)),\n ('high_limit', models.IntegerField(default=0)),\n ('prev_val', models.IntegerField(default=0)),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n ]\n" }, { "alpha_fraction": 0.5520289540290833, "alphanum_fraction": 0.5581541061401367, "avg_line_length": 31.72437286376953, "blob_id": "e59fffae7d5eadcb49a757fb8188c9a25787b5b2", "content_id": "78c33b655508a033dedcde12bdc54d47dfb69908", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14367, "license_type": "no_license", "max_line_length": 98, "num_lines": 439, "path": "/django_spreadsheet_reports/reports.py", "repo_name": "pombredanne/django-spreadsheet-reports", "src_encoding": "UTF-8", "text": "from datetime import timedelta\nimport django.forms\nfrom django.http import HttpResponse\nfrom django.utils import timezone\n\n\nclass RepChoiceField(django.forms.fields.ChoiceField):\n def validate(self, value):\n \"\"\"\n Validates that the input is in self.choices.\n \"\"\"\n pass\n\n\nclass _NamedValueObject(object):\n def __init__(self, value, name=None):\n if not name:\n if hasattr(value, 'default_alias'):\n name = value.default_alias\n else:\n name = str(value).title()\n self.name = name\n self.value = value\n\n\nclass Filter(_NamedValueObject):\n _is_a_filter = True\n\n def __init__(self, value, name=None, display_value=None, multiple=False,\n order=None):\n _NamedValueObject.__init__(self, value, name)\n self.display_value = display_value\n self.multiple = multiple\n self.order = order if order else value\n\n def filter_choices(self, qs):\n from django.db.models import Count\n\n\n values = [self.value]\n if self.display_value:\n values.append(self.display_value)\n xlist = qs.values(*values).annotate(Count('id'))\n if self.order:\n xlist = xlist.order_by(self.order)\n res = [('', '---')]\n for x in xlist:\n if self.display_value:\n res.append((x[self.value], x[self.display_value]))\n else:\n res.append((x[self.value], x[self.value]))\n return res\n\n def filter_query_set(self, qs, request):\n if self.multiple:\n val = request.GET.getlist(self.name)\n if len(val) == 0 or \"\" in val:\n return qs\n val = [x for x in val if x.strip() != '']\n if len(val) == 0:\n return qs\n else:\n include_none = False\n if 'None' in val:\n val.remove('None')\n include_none = True\n if len(val):\n args = {'%s__in' % self.value: val}\n qs = qs.filter(**args)\n if include_none:\n args = {'%s__isnull' % self.value: True}\n qs = qs.filter(**args)\n return qs\n else:\n val = request.GET.get(self.name, '')\n if val == '':\n return qs\n else:\n args = {self.value: val}\n return qs.filter(**args)\n\n\nclass BooleanFilter(_NamedValueObject):\n _is_a_filter = True\n multiple = False\n\n @property\n def _choicelist(self):\n choicelist = ['------', 'True', 'False']\n return choicelist\n\n def __init__(self, value, name=None):\n _NamedValueObject.__init__(self, value, name)\n\n def filter_choices(self, qs):\n res = []\n for x in self._choicelist:\n res.append((x, x))\n return res\n\n def filter_query_set(self, qs, request):\n try:\n val = request.GET[self.name]\n except KeyError:\n val = self._choicelist[0]\n if val == '------' or val == '':\n return qs\n boolval = True\n if val == 'True':\n boolval = True\n if val == 'False':\n boolval = False\n args = {'%s' % self.value: boolval}\n return qs.filter(**args)\n\n\nclass DateFilter(_NamedValueObject):\n _is_a_filter = True\n multiple = False\n\n @property\n def _choicelist(self):\n choicelist = ['10daysago:today', 'today', 'yesterday', '2daysago', '3daysago', '4daysago',\n '5daysago', '6daysago', '7daysago', '90daysago:today', 'all time']\n n = timezone.now()\n for i in range(12):\n n = n.replace(day=1)\n nextmonth = n + timedelta(days=31)\n lastdayofmonth = nextmonth.replace(day=1) - timedelta(days=1)\n choicelist.append(\n '{0}-{1:02}-16:{0}-{1:02}-{2:02}'.format(n.year, n.month, lastdayofmonth.day))\n choicelist.append('{0}-{1:02}-01:{0}-{1:02}-15'.format(n.year, n.month))\n choicelist.append(\n '{0}-{1:02}-01:{0}-{1:02}-{2:02}'.format(n.year, n.month, lastdayofmonth.day))\n n = n - timedelta(days=1)\n return choicelist\n\n def __init__(self, value, name=None):\n _NamedValueObject.__init__(self, value, name)\n\n def filter_choices(self, qs):\n res = []\n for x in self._choicelist:\n res.append((x, x))\n return res\n\n def filter_query_set(self, qs, request):\n from .textdaterange import TextDateRange\n try:\n val = request.GET[self.name]\n except KeyError:\n val = self._choicelist[0]\n if val == 'all time':\n return qs\n daterange = TextDateRange(val)\n args = {'%s__range' % self.value: (daterange.start, daterange.end)}\n return qs.filter(**args)\n\n\ndef filters(*values):\n result = []\n for x in values:\n if not hasattr(x, '_is_a_filter'):\n x = Filter(x)\n result.append(x)\n return result\n\n\nclass Column(_NamedValueObject):\n exists_in_db = True\n\n def _make_django_tables_column_kwargs(self):\n return dict(verbose_name=self.name)\n\n def make_django_tables_column(self):\n import django_tables2\n return django_tables2.Column(**self._make_django_tables_column_kwargs())\n\n\nclass CalculatedColumn(Column):\n exists_in_db = False\n\n def _make_django_tables_column_kwargs(self):\n vals = Column._make_django_tables_column_kwargs(self)\n vals.update(dict(data=self.value))\n return vals\n\n\nclass HiddenColumn(Column):\n exists_in_db = True\n\n def make_django_tables_column(self):\n import django_tables2\n return django_tables2.Column(visible=False,\n **self._make_django_tables_column_kwargs())\n\n\nclass ChoicesColumn(Column):\n exists_in_db = True\n\n def __init__(self, choices, *args, **kwargs):\n self.choices = choices\n super(ChoicesColumn, self).__init__(*args, **kwargs)\n\n def make_django_tables_column(self):\n import django_tables2\n a = django_tables2.Column(**self._make_django_tables_column_kwargs())\n a.choices = self.choices\n return a\n\n\nclass DecimalColumn(CalculatedColumn):\n class DecimalFloat():\n def __init__(self, val, decimal_places):\n self.val = val\n self.decimal_places = decimal_places\n\n def __str__(self):\n format = '%.' + str(self.decimal_places) + 'f'\n return format % self.val\n\n def __init__(self, val, decimal_places=2, *args, **kwargs):\n def _datafunc(row):\n data = row.data[val]\n if data is None:\n data = 0\n data = float(data)\n return self.DecimalFloat(data, decimal_places)\n\n CalculatedColumn.__init__(self, _datafunc, *args, **kwargs)\n\n\nclass PercentageCalculatedColumn(CalculatedColumn):\n class PercentFloat(float):\n def __str__(self):\n return '{0:.1%}'.format(self)\n\n class NullPercent(float):\n def __init__(self):\n float.__init__(-999)\n\n def __str__(self):\n return '--'\n\n def __init__(self, top, bottom, *args, **kwargs):\n def _datafunc(row):\n top_data = float(row.data[top])\n bottom_data = float(row.data[bottom])\n if 0 == bottom_data:\n return self.NullPercent()\n else:\n return self.PercentFloat(top_data / bottom_data)\n\n CalculatedColumn.__init__(self, _datafunc, *args, **kwargs)\n\n\nclass PercentageDifferenceColumn(CalculatedColumn):\n exists_in_db = False\n\n class PercentFloat(float):\n def __str__(self):\n return '{0:.1%}'.format(self)\n\n class NullPercent(float):\n def __init__(self):\n float.__init__(-999)\n\n def __str__(self):\n return '--'\n\n def __init__(self, before, after, *args, **kwargs):\n def _datafunc(row):\n before_data = float(row.data[before])\n after_data = float(row.data[after])\n delta = after_data - before_data\n if before_data == 0.0:\n return self.PercentFloat(after_data)\n else:\n return self.PercentFloat(delta / before_data)\n\n CalculatedColumn.__init__(self, _datafunc, *args, **kwargs)\n\n\ndef columns(*values):\n result = []\n for x in values:\n if not isinstance(x, Column):\n x = Column(x)\n result.append(x)\n return result\n\n\nclass GroupBy(_NamedValueObject):\n def __init__(self, value, name=None, additional_columns=None, order=None):\n _NamedValueObject.__init__(self, value, name)\n if additional_columns:\n # when changing code, be careful this does not result in an infinte loop\n self.additional_columns = columns(*additional_columns)\n else:\n self.additional_columns = tuple()\n self.order = order\n\n\ndef groupbys(*values):\n result = []\n for x in values:\n if not isinstance(x, GroupBy):\n x = GroupBy(x)\n result.append(x)\n return result\n\n\nclass Report(object):\n slug = None\n name = None\n model = None\n group_by = []\n list_aggregates = []\n filter_by = []\n order_by = []\n\n def render_to_response(self, request):\n from django import shortcuts, template\n from . import models\n context = template.RequestContext(request)\n formclass = self.get_form_class(request)\n if request.GET.get('form_submitted'):\n params = request.GET\n else:\n params = formclass.initial_values.copy()\n context['form'] = formclass(params)\n if context['form'].is_valid():\n context['table'] = self.get_data_table(context['form'], request.GET.get('sort', None),\n request)\n context['report_name'] = self.name\n context['request'] = request\n context['bookmarks'] = models.Bookmark.objects.all()\n if request.GET.get('submit') == 'Export to CSV':\n return self._data_table_to_csv(context['table'], self.name)\n else:\n return shortcuts.render_to_response('django_spreadsheet_reports/report.html',\n context_instance=context)\n\n def _data_table_to_csv(self, data_table, name='Report', dialect='excel'):\n \"\"\"\n Given a data table (or any object that contains an iterable 'columns'\n and 'rows' attribute), returns an HttpResponse containing the data\n serialized into a CSV file.\n \"\"\"\n import csv\n\n res = HttpResponse(mimetype='text/csv')\n res['content-disposition'] = 'attachment; filename=\"%s.csv\"' % name\n\n # even though Columns and Rows are iterable, we must cast them to lists\n # because the python csv writer loops over them using __len__ (which\n # isn't implemented), and __getattr__ (which doesn't accept indexes)\n\n writer = csv.writer(res, dialect=dialect)\n writer.writerow(list(data_table.columns))\n writer.writerows(list(row) for row in data_table.rows)\n\n return res\n\n def get_query_set(self):\n return self.model.objects\n\n def get_filtered_query_set(self, request):\n qs = self.get_query_set()\n for x in self.filter_by:\n qs = x.filter_query_set(qs, request)\n return qs\n\n def get_data_table(self, form, sort, request):\n if not form.is_valid():\n raise AssertionError(form.errors)\n annotate = {}\n for v in self.list_aggregates:\n if v.exists_in_db:\n annotate[v.name] = v.value\n groupby = self._get_current_group_by(form)\n values = [groupby.value]\n for x in groupby.additional_columns:\n if x.exists_in_db:\n values.append(x.value)\n qs = self.get_filtered_query_set(request)\n if groupby.order:\n qs = qs.order_by(groupby.order)\n else:\n qs = qs.order_by(groupby.value)\n data = qs.values(*values).annotate(**annotate)\n kwargs = {}\n if sort:\n kwargs['order_by'] = sort\n return self.get_table_class(form)(list(data), **kwargs)\n\n def _get_current_group_by(self, form):\n groupbystr = form.cleaned_data['group_by']\n for x in self.group_by:\n if x.name == groupbystr:\n return x\n raise KeyError(\"Group by '%s' cannot be found\" % groupbystr)\n\n def get_table_class(self, form):\n import django_tables2\n properties = {}\n groupby = self._get_current_group_by(form)\n properties[groupby.value] = django_tables2.Column(verbose_name=groupby.name)\n for x in groupby.additional_columns:\n properties[x.value] = x.make_django_tables_column()\n for x in self.list_aggregates:\n properties[x.name] = x.make_django_tables_column()\n return type('Mytable', (django_tables2.Table,), properties)\n\n def get_form_class(self, request):\n from django import forms\n properties = {}\n properties['form_submitted'] = forms.fields.BooleanField(widget=forms.widgets.HiddenInput)\n properties['initial_values'] = {'group_by': self.group_by[0].name, 'form_submitted': '1'}\n properties['group_by'] = forms.fields.ChoiceField(\n choices=[(x.name, x.name) for x in self.group_by])\n qs = self.get_filtered_query_set(request)\n for x in self.filter_by:\n choices = x.filter_choices(qs)\n c = forms.fields.MultipleChoiceField if x.multiple else RepChoiceField\n properties[x.name] = c(choices=choices, required=False)\n properties['initial_values'][x.name] = choices[0][0]\n\n if self.order_by:\n choices = []\n for c in self.order_by:\n choices.append((c, c + ' (ASC)'))\n choices.append(('-' + c, c + ' (DESC)'))\n properties['sort'] = RepChoiceField(choices=choices, required=False)\n return type('Myform', (forms.Form,), properties)\n\n def url(self):\n from django.core import urlresolvers\n return urlresolvers.reverse('django_spreadsheet_reports-%s' % self.slug)\n\n" } ]
13
soumya1995/bdcms
https://github.com/soumya1995/bdcms
1e9a704559f0206e0493b61de05bd7b49132a0ff
7bc84f5ff5f3e1d4342c8fdd5a49efddfa1f981c
990088e84f05a3b81c95c304d8ea602ae84143ad
refs/heads/master
2021-01-19T18:35:42.532130
2017-11-09T03:22:32
2017-11-09T03:22:32
88,366,574
0
0
null
2017-04-15T18:27:47
2017-03-19T18:41:06
2017-04-10T16:31:32
null
[ { "alpha_fraction": 0.578125, "alphanum_fraction": 0.625, "avg_line_length": 20.33333396911621, "blob_id": "0f30da032f1a29f548cda527a9d31f1b7ee953a0", "content_id": "a6cc302cb874870ede3a6b74d6112ce16a2468a4", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 64, "license_type": "permissive", "max_line_length": 54, "num_lines": 3, "path": "/css/index.php", "repo_name": "soumya1995/bdcms", "src_encoding": "UTF-8", "text": "<?php\n header( 'Location: https://haxorsoft.com/404.php' );\n?>\n" }, { "alpha_fraction": 0.5571081638336182, "alphanum_fraction": 0.5710813999176025, "avg_line_length": 28.92727279663086, "blob_id": "36c4e041c4ab494630940292985ae66e180eb4d9", "content_id": "7c5faa08923e050707aa1c09edc9e03314537575", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1646, "license_type": "permissive", "max_line_length": 170, "num_lines": 55, "path": "/cgi-bin/login.py", "repo_name": "soumya1995/bdcms", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n\nimport cgi\nimport cgitb\nimport os.environ\nimport mysql.connector\n\ndef main( ):\n cgi.enable( display = 0, logdir = \"/var/log\" )\n field_storage = cgi.FieldStorage( )\n\n print( \"Content-Type: text/html\\r\\n\" )\n\n try:\n cnx = mysql.connector.connect( user=\"root\", password=\"\", host=\"localhost\" )\n\n cursor = cnx.cursor( )\n cursor.execute( \"USE bdcms\" )\n cursor.close( )\n\n cursor = cnx.cursor( )\n cursor.execute( \"SELECT (username,md5hash) FROM Users\" )\n cursor.close( )\n\n found = false\n for username,md5hash in cursor:\n if( field_storage[ \"username\" ] == username and md5(field_storage[ \"password\" ]) == md5hash ):\n found = true\n\n if( found ):\n if( \"HTTP_COOKIE\" not in os.environ ):\n if( \"HTTP_USER_AGENT\" in os.environ and \"REMOTE_ADDR\" in os.environ ):\n print( \"Set-Cookie: session_id=%s; expires=%s\" % ( md5sum( os.environ[ \"HTTP_USER_AGENT\" ] + os.environ[ \"REMOTE_ADDR\" ] ), \"2017-03-19T17:31:39Z\" ) )\n else:\n quit( )\n\n except mysql.error.Error as err:\n if( err.errno == mysql.connector.errorcode.ER_ACCESS_DENIED_ERROR ):\n print( \"Access denied!\" )\n elif( err.errno == mysql.connector.errorcode.ER_DB_CREATE_EXISTS ):\n print( \"Database already exists!\" )\n\n \n print( \"\"\"\n<!DOCTYPE html>\n<html><head>\n<title>Login Processor</title>\n<meta http-equiv=\"refresh\" content=\"0;URL=https://bdcms.org/login.php\" />\n<meta charset=\"utf-8\" />\n</head><body>\n</body></html>\n \"\"\" )\n\nif( __name__ == '__main__' ):\n main( )\n" }, { "alpha_fraction": 0.558521568775177, "alphanum_fraction": 0.578370988368988, "avg_line_length": 30.085105895996094, "blob_id": "592e0d5fd64fbb051c7ed37580b5e3303949c146", "content_id": "6f54cf16f53a1b7f2dfe2d01e8bffe16258f6a76", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1465, "license_type": "permissive", "max_line_length": 76, "num_lines": 47, "path": "/js/sharing.js", "repo_name": "soumya1995/bdcms", "src_encoding": "UTF-8", "text": "/*\n * Copyright (C) 2016 Haxorsoft, Inc. All Rights Reserved.\n *\n * No part of this publication may be reproduced, distributed, or\n * transmitted in any form or by any means, including photocopying,\n * recording, or other electronic or mechanical methods, without the prior\n * written permission of the publisher, except in the case of brief\n * quotations embodied in critical reviews and certain other noncommercial\n * uses permitted by copyright law. For permission requests, write to the\n * publisher, addressed “Attention: Permissions Coordinator,” at the address\n * below.\n *\n * Haxorsoft, Inc\n * 10 Bay Ave\n * Huntington, NY 11743\n * www.haxorsoft.com\n */\nfunction googleplus_share( event ) {\n window.open( this.href, '', ''\n + 'menubar=no,'\n + 'toolbar=no,'\n + 'resizable=yes,'\n + 'scrollbars=yes,'\n + 'width=780,'\n + 'height=539' );\n return false;\n}\nfunction facebook_share( event ) {\n window.open( this.href, '', ''\n + 'menubar=no,'\n + 'toolbar=no,'\n + 'resizable=yes,'\n + 'scrollbars=yes,'\n + 'width=780,'\n + 'height=675' );\n return false;\n}\nfunction twitter_share( event ) {\n window.open( this.href, '', ''\n + 'menubar=no,'\n + 'toolbar=no,'\n + 'resizable=yes,'\n + 'scrollbars=yes,'\n + 'width=780,'\n + 'height=539' );\n return false;\n}\n" }, { "alpha_fraction": 0.61594557762146, "alphanum_fraction": 0.6290714740753174, "avg_line_length": 29.701492309570312, "blob_id": "4457cbf071b1f43b4298ed7e27e3682feaa697e6", "content_id": "048f036a63b101d3424779e6946f4ef794a812f8", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 2057, "license_type": "permissive", "max_line_length": 115, "num_lines": 67, "path": "/control-panel/login.php", "repo_name": "soumya1995/bdcms", "src_encoding": "UTF-8", "text": "<?php\n // vim: number ts=4 sw=4 expandtab\n if( $_COOKIE ) {\n if( strcmp( $_COOKIE[ \"session\" ], \"yes\" ) ) {\n $session_id = $_COOKIE[ \"session_id\" ];\n header( 'Location: dashboard.php' );\n }\n }\n?>\n<!DOCTYPE html>\n<html><head>\n<title></title>\n<meta charset=\"utf-8\" />\n<link type=\"text/css\" href=\"/css/fonts/font-awesome.css\" rel=\"stylesheet\" />\n<link type=\"text/css\" href=\"/css/fonts/opensans-fonts.css\" rel=\"stylesheet\" />\n<link type=\"text/css\" href=\"/css/reset.css\" rel=\"stylesheet\" />\n<link type=\"text/css\" href=\"/css/site.css\" rel=\"stylesheet\" />\n<link type=\"text/css\" href=\"/css/navigation.css\" rel=\"stylesheet\" />\n<link type=\"text/css\" href=\"/css/grid.css\" rel=\"stylesheet\" />\n<style type=\"text/css\">\nhtml {\n min-height: 100%;\n position: relative;\n}\n.panel {\n margin: 1em 0;\n margin-right: auto;\n margin-left: auto;\n background: #00f;\n padding: 1em;\n color: #fff;\n width: 40%;\n}\n#footer {\n position: absolute;\n bottom: 0;\n width: 100%;\n}\n</style>\n</head><body>\n<div class=\"navigation\">\n<div class=\"container\">\n<div class=\"header\">Control Panel</div>\n<h1 style=\"color:#fff\" class=\"align-center\">Benevolent DevOps CMS</h1>\n</div></div>\n<div class=\"text container\">\n<div class=\"panel\">\n<form method=\"post\" action=\"cgi-bin/login.py\">\n<h3 style=\"margin:0\">Username:</h3>\n<input type=\"text\" name=\"username\" placeholder=\"username\" />\n<h3 style=\"margin:0\">Password:</h3>\n<input type=\"password\" name=\"password\" />\n<div><input type=\"checkbox\" name=\"cookies\" value=\"cookies\"> Save my credentials\n<div style=\"padding:1em 0\"><input type=\"submit\" value=\"Login\" />\n<input type=\"reset\" value=\"Clear\" /></div>\n</div>\n</form>\n</div></div>\n<div id=\"footer\">\n<div class=\"container\">\n<a class=\"links\" href=\"#\">About Us</a>\n<a class=\"links\" href=\"#\">Tech Support</a>\n<a class=\"links\" href=\"#\">Privacy</a>\n<a class=\"links\" href=\"#\">Terms of Use</a>\n<p class=\"align-center small\">Copyright &copy; <?php echo date('Y'); ?> Benevolent DevOps. All Rights Reserved.</p>\n</div></div>\n</body></html>\n" }, { "alpha_fraction": 0.5755689740180969, "alphanum_fraction": 0.5800142288208008, "avg_line_length": 32.278106689453125, "blob_id": "2f30945c9f514e72eeb589205081bf89b1f974ab", "content_id": "af033525a09e42c6d4a5d551c0c29bc0e6eba6aa", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5624, "license_type": "permissive", "max_line_length": 76, "num_lines": 169, "path": "/control-panel/setup.py", "repo_name": "soumya1995/bdcms", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# Copyright 2017 Benevolent Developers.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport pymongo\nimport sys\n\nif( __name__ != '__main__' ):\n sys.exit( -1 )\nelse:\n print( \"Content-Type: text/plain\\r\\n\" )\n print( \"Connecting to mongod.. \", end='' )\n client = pymongo.MongoClient( 'localhost', 27017 )\n\n try:\n client.admin.command( 'ismaster' )\n print( \"OK\" )\n except pymongo.ConnectionFailure:\n print( \"FAIL\" )\n\n print( \"Acquiring bdcms database.. \", end='' )\n bdcms = client.bdcms\n print( \"OK\" )\n\n print( \"Acquiring ``users\\'\\' collection.. \", end='' )\n users = bdcms.users\n print( \"OK\" )\n\n print( \"Populating ``users\\'\\' collection.. \", end='' )\n bdcms.users.create_index([( 'usrid', pymongo.ASCENDING )],\n unique = True )\n many_users = [\n { 'usrid' : 0,\n 'fname' : 'Rimack',\n 'lname' : 'Zelnick',\n 'email' : '[email protected]',\n 'uname' : 'rzelnick',\n 'passw' : 'password123' },\n { 'usrid' : 1,\n 'fname' : 'Soumya',\n 'lname' : 'Das',\n 'email' : '[email protected]',\n 'uname' : 'sodas',\n 'passw' : 'pass123' },\n { 'usrid' : 2,\n 'fname' : 'Parth',\n 'lname' : 'Gupta',\n 'email' : '[email protected]',\n 'uname' : 'pgupta',\n 'passw' : 'pass345' },\n { 'usrid' : 3,\n 'fname' : 'Harkirat',\n 'lname' : 'Randhawa',\n 'email' : '[email protected]',\n 'uname' : 'kirat',\n 'passw' : 'password' } ]\n users.insert( many_users )\n\n print( \"OK\" )\n\n print( \"Acquiring ``pages\\'\\' collection.. \", end='' )\n pages = bdcms.pages\n print( \"OK\" )\n\n print( \"Populating ``pages\\'\\' collection.. \", end='' )\n bdcms.pages.create_index([( 'page_id', pymongo.ASCENDING )],\n unique = True )\n page = {\n # list of authors\n \"authors\" : [ bdcms.users.find_one({ \"uname\" : \"rzelnick\" }),\n bdcms.users.find_one({ \"uname\" : \"pgupta\" }) ],\n\n # title & subtitle\n \"title\" : \"Home\",\n \"subtitle\" : \"\",\n\n # language\n \"language\" : \"english\",\n\n # category\n \"category\" : \"homepage\",\n\n # tags\n \"tags\" : [ \"welcome\", \"hello\", \"about\", \"donations\" ],\n\n # introduction\n \"introduction\" : \"This is the homepage of Suffolk County TASC\",\n\n # paragraph1\n \"paragraph1\" : \"\"\"Our organization is dedicated in informing the\ncommunity about DUI/DWI legislation that first time offenders may\nnot know about\"\"\",\n \n # paragraph2\n \"paragraph2\" : \"\"\"This website provides useful links and information\nregarding DMV legislation additionally you may support our\norganization by donating to us\"\"\",\n\n # paragraphN\n # footer\n \"footer\" : \"Copyright &copy; Suffolk County TASC\" }\n bdcms.pages.insert( page )\n print( \"OK\" )\n\n print( \"Acquiring ``posts\\'\\' collection.. \", end='' )\n posts = bdcms.posts\n post = {\n # list of authors\n \"authors\" : [ bdcms.users.find_one({ \"uname\" : \"rzelnick\" }),\n bdcms.users.find_one({ \"uname\" : \"pgupta\" }) ],\n\n # title & subtitle\n \"title\" : \"What you should know about Interlock Ignitions\",\n \"subtitle\" : \"You thought you knew better\",\n\n # language\n \"language\" : \"english\",\n\n # category\n \"category\" : \"faq\",\n\n # tags\n \"tags\" : [ \"dmv\", \"dwi\", \"dui\", \"ignition\", \"interlock\" ],\n\n # introduction\n \"introduction\" : \"This is the homepage of Suffolk County TASC\",\n\n # paragraph1\n \"paragraph1\" : \"\"\"Our organization is dedicated in informing the\n community about DUI/DWI legislation that first time offenders may\n not know about\"\"\",\n \n # paragraph2\n \"paragraph2\" : \"\"\"This website provides useful links and information\n regarding DMV legislation additionally you may support our\n organization by donating to us\"\"\",\n\n # paragraphN\n # footer\n \"footer\" : \"Copyright &copy; Suffolk County TASC\" }\n result = bdcms.posts.insert( post )\n\n print( \"OK\" )\n\n print( \"Acquiring ``multimedia\\'\\' collection.. \", end='' )\n multimedia = bdcms.multimedia\n print( \"OK\" )\n" }, { "alpha_fraction": 0.7908496856689453, "alphanum_fraction": 0.7943098545074463, "avg_line_length": 45.44643020629883, "blob_id": "c609af55dbac53987ca1e9154062278d0e035718", "content_id": "8c1bd7623f1feb303e3dc4bfb308c567598953a5", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2601, "license_type": "permissive", "max_line_length": 226, "num_lines": 56, "path": "/README.md", "repo_name": "soumya1995/bdcms", "src_encoding": "UTF-8", "text": "# Benevolent Developers CMS\n## Product Position\nOur goal is to ultimately design a \"Content Management System\" for Suffolk\nCounty TASC in a group of four programmers, our client's client will receive\nthe latest information on Ignition Interlock and Leandra's law.\n\nOur system is divided into two logical parts: front-end and back-end. The\nfront-end compartment of our system, work such that it provides a friendly user\ninterface for our client to dynamically add/delete/update posts and pages, and\nour back-end interface interacts with the database, additionally providing\ncomputation.\n\nUnlike existing CMSs e.g Wordpress, Joomla, and Drupal. Our product offers an\nexclusive state of the art front-end and back-end logical components written by\nexperienced software developers.\n\nList of Members:\n\n* Rimack \"Mark\" Zelnick\n\nLeader and Coordinator, having contributed to the open-source community by\nfounding \"cipherchat\" the encrypted P2P communication system Mark is a\nqualified leader.\n\n* Soumya Das\n\nGroup Secretary, with an astonishing GPA of 3.9, our secretary demonstrates\ndiscipline and competency in assigning roles, meetings, and keep track of group\ndiscussions.\n\n* Parth \"Party\" Gupta\n\nLead Researcher, with intense high-energy Party comes into the group to restore\nour focus and momentum into the project. At times developing a CMS can become\ndistracting Parth then helps group with his sense of humor.\n\n* Harkirat \"Kirat\" Randhawa\n\nAssistant Researcher, teaching assistant at Stony Brook of perhaps one of the\nmost important class in the Computer Science Dept. CSE 101 by incentivizing,\nand helping new students to become acquainted to the subject.\n\n* Group No. 7\n\nIn a joint effort we are welcoming new front-end developers from Group 7,\nMaksym Trojanowski, Jacqueline Diaz, and Jacky Yue.\n\n# Instructions\nWhen developing using this repository, please do the following:\n\n* Do not push binary content into github\n* Edit ChangeLog to state your commits, and use the commit message \"See ChangeLog for details; xyz done\" listing at most one - no more than one - important feature.\n* When developing your applications here's an etiquette to follow:\n+ Create a branch with your feature name, eg \"rssgen\" for our RSS Generator. Please don't use uppercase characters, numbers or symbols in your branch name.\n+ Checkout into your branch, and work from there. Once you have done your job you should be able to auto-merge given that you added a new folder after branching, such that it doesn't collide with other file or directory names.\n+ We're using BSD 2-clause license so please include a \"copyleft\" at the top of your code.\n" }, { "alpha_fraction": 0.6197771430015564, "alphanum_fraction": 0.6309192180633545, "avg_line_length": 37.191490173339844, "blob_id": "5b6c70ad4388554aa4cfba827f3075fed30a5e72", "content_id": "eb132f0860cc1b47c584741cbe5bc327941f9788", "detected_licenses": [ "BSD-2-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3590, "license_type": "permissive", "max_line_length": 76, "num_lines": 94, "path": "/control-panel/insert.py", "repo_name": "soumya1995/bdcms", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\n# Copyright 2017 Benevolent Developers.\n# \n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n# \n# 1. Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# \n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# \n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport pymongo\nimport sys\n\ndef print_usage( ):\n print( \"\"\"\nInsert document into a collection.\n{0} [--select collection] [--from database] [--insert field=value]\n Options:\n --select collection Selects a collection from a database\n --from database Selects a database\n --insert field=value Inserts a field w/ value if field already exists\n then it's value is overwritten\n\"\"\".format( sys.argv[0] )\n sys.exit( -1 )\n\nif( __name__ != '__main__' ):\n sys.exit( -1 )\nelse:\n try:\n client = pymongo.MongoClient( 'localhost', 27017 )\n except pymongo.errors.ConnectionFailure:\n print( \"Failed to connect to mongod!\" )\n sys.exit( -1 )\n\n argv = sys.argv\n argc = len( sys.argv )\n\n for i in range( 1, argc ):\n if( argv[ i ].lower( ) == \"--select\" ):\n if( i + 1 >= argc ):\n print_usage( )\n selected_collection = argv[ i + 1 ]\n i = i + 1\n elif( argv[ i ].lower( ) == \"--from\" ):\n if( i + 1 >= argc ):\n print_usage( )\n selected_database = argv[ i + 1 ]\n i = i + 1\n elif( argv[ i ].lower( ) == \"--insert\" ):\n if( i + 1 >= argc ):\n print_usage( )\n condition = argv[ i + 1 ].split( '=' )\n field = condition[ 0 ]\n value = condition[ 1 ]\n i = i + 1\n\n # debugging\n # print( \"Selected Database {0}\".format( selected_database ) )\n # print( \"Selected Collection {0}\".format( selected_collection ) )\n # print(\"field = {0}, value = {1}\".format( field, value ) )\n\n try:\n database = client[ selected_database ]\n except pymongo.errors.InvalidName:\n print( \"No such database named {0}\".format( database_selected ) )\n sys.exit( -1 )\n\n try:\n collection = database[ selected_collection ]\n except pymongo.errors.CollectionInvalid:\n print(\"No such collection named {0}\".format(collection_selected))\n sys.exit( -1 )\n\n try:\n result = database[selected_collection].insert_one({ field : value })\n except pymongo.errors.PyMongoError:\n print(\"No such field where {0}={1}\".format( field, value ) )\n sys.exit( -1 )\n" } ]
7
tflovorn/polecalc
https://github.com/tflovorn/polecalc
962e5fcc80116b1712e951205e4d817605932db3
0d0dea47bbf540e14f9bda5f0ad61c85e4d24b0c
9640c48c63694748178370e38b5d98862de9e2a3
refs/heads/master
2021-01-15T17:07:06.432900
2012-07-16T21:17:52
2012-07-16T21:17:52
1,872,264
1
1
null
null
null
null
null
[ { "alpha_fraction": 0.7006988525390625, "alphanum_fraction": 0.7082953453063965, "avg_line_length": 27.61739158630371, "blob_id": "e8ef5de700c7306c9c93070c55c97a46ee499f32", "content_id": "fdb08af197098073d6bb22d9387af8b409dd95d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3291, "license_type": "permissive", "max_line_length": 87, "num_lines": 115, "path": "/selfconsistent.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"math\"\n\n// One-parameter scalar self-consistent equation\ntype SelfConsistentEquation interface {\n\t// return the absolute error associated with this equation under the given interface{}\n\tAbsError(args interface{}) float64\n\t// set the appropriate variable in args to value\n\tSetArguments(value float64, args interface{}) interface{}\n\t// range of possible values for SetArguments\n\tRange(args interface{}) (float64, float64, error)\n}\n\n// Return an interface{} which solves eq to tolerance of BisectionFullPrecision\nfunc Solve(eq SelfConsistentEquation, args interface{}) (interface{}, error) {\n\teqError := func(value float64) float64 {\n\t\targs = eq.SetArguments(value, args)\n\t\treturn eq.AbsError(args)\n\t}\n\tleftEdge, rightEdge, err := eq.Range(args)\n\tif err != nil {\n\t\treturn args, err\n\t}\n\tleft, right, err := FindBracket(eqError, leftEdge, rightEdge)\n\tif err != nil {\n\t\treturn args, err\n\t}\n\tsolution, err := BisectionFullPrecision(eqError, left, right)\n\tif err != nil {\n\t\treturn args, err\n\t}\n\targs = eq.SetArguments(solution, args)\n\treturn args, nil\n}\n\n// Return a slice of interface{}'s which solve eq\nfunc MultiSolve(eq SelfConsistentEquation, args interface{}) ([]interface{}, error) {\n\teqError := func(value float64) float64 {\n\t\targs = eq.SetArguments(value, args)\n\t\treturn eq.AbsError(args)\n\t}\n\tleftEdge, rightEdge, err := eq.Range(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbrackets, err := MultiBracket(eqError, leftEdge, rightEdge)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsolutions := []interface{}{}\n\tfor _, bracket := range brackets {\n\t\tleft, right := bracket[0], bracket[1]\n\t\tsolution, err := BisectionFullPrecision(eqError, left, right)\n\t\tif err != nil {\n\t\t\treturn solutions, err\n\t\t}\n\t\tsolutions = append(solutions, eq.SetArguments(solution, args))\n\t}\n\treturn solutions, nil\n}\n\n// A group of self-consistent equations which may be coupled and must all be\n// solved for the group to be considered solved.\ntype SelfConsistentSystem struct {\n\tEquations []SelfConsistentEquation\n\tTolerances []float64\n}\n\n// Solve the self-consistent system, returning the resulting interface{}\nfunc (system *SelfConsistentSystem) Solve(args interface{}) (interface{}, error) {\n\ti := 0\n\tfor !system.IsSolved(args) {\n\t\t// this should never be true: if it is, failed to iterate\n\t\tif i >= len(system.Equations) {\n\t\t\tpanic(\"self-consistent system overran bounds\")\n\t\t}\n\t\t// set args to the value that solves the equation\n\t\tnewEnv, err := Solve(system.Equations[i], args)\n\t\tif err != nil {\n\t\t\treturn args, err\n\t\t}\n\t\targs = newEnv\n\t\t// check if we need to iterate\n\t\tif !system.solvedUpTo(args, i) {\n\t\t\t// previous equations have been disturbed; restart\n\t\t\ti = 0\n\t\t} else {\n\t\t\t// ok to continue to next equation\n\t\t\ti++\n\t\t}\n\t}\n\treturn args, nil\n}\n\n// Check if the first (maxIndex + 1) equations are solved\nfunc (system *SelfConsistentSystem) solvedUpTo(args interface{}, maxIndex int) bool {\n\tfor i, eq := range system.Equations {\n\t\tif i > maxIndex {\n\t\t\tbreak\n\t\t}\n\t\tif math.Abs(eq.AbsError(args)) > system.Tolerances[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// Are all the self-consistent equations solved?\nfunc (system *SelfConsistentSystem) IsSolved(args interface{}) bool {\n\tif len(system.Equations) == 0 {\n\t\treturn true\n\t}\n\treturn system.solvedUpTo(args, len(system.Equations)-1)\n}\n" }, { "alpha_fraction": 0.6333333253860474, "alphanum_fraction": 0.6333333253860474, "avg_line_length": 9, "blob_id": "0da5d83370084a6fad180ed99d3a8049c72467be", "content_id": "4561220c8910fb089c01c23f1251b4d78974b8f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 30, "license_type": "permissive", "max_line_length": 16, "num_lines": 3, "path": "/clean", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nrm *.testignore*\n" }, { "alpha_fraction": 0.573674738407135, "alphanum_fraction": 0.617699921131134, "avg_line_length": 26.481481552124023, "blob_id": "2522e6de5df9d4fd6afa0e22319abb8a7e7cb8b7", "content_id": "85b4fe075141abccf1e28f6e751a0dad1a981304", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 2226, "license_type": "permissive", "max_line_length": 104, "num_lines": 81, "path": "/cubicspline_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"testing\"\n)\n\n// Does the cubic spline produce the expected result when interpolating over\n// only 3 points?\nfunc TestCubicSpline3Points(t *testing.T) {\n\t// constants chosen to have xs be integer values\n\tn := 3 // number of points to interpolate\t\n\tstart, stop := -10.0, 10.0\n\tsomeCubic := makeCubic(1.0, 1.0, 1.0, 1.0)\n\tstep := (stop - start) / float64(n-1)\n\txs, ys := make([]float64, n), make([]float64, n)\n\tfor i, _ := range xs {\n\t\txs[i] = start + float64(i)*step\n\t\tys[i] = someCubic(xs[i])\n\t}\n\tspline, err := NewCubicSpline(xs, ys)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tx := 1.0\n\ty, err := spline.At(x)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// expect spline coefficients as follows:\n\t// a = [0.05 -0.5], b = [0 1.5], c = [86 101], d = [-909 1]\n\tyKnown := 103.45\n\tif math.Abs(y-yKnown) > MachEpsFloat64() {\n\t\tfmt.Printf(\"a:%v b:%v c:%v d:%v\\n\", spline.a, spline.b, spline.c, spline.d)\n\t\tfmt.Printf(\"xs = %v; ys = %v\\n\", xs, ys)\n\t\tt.Fatalf(\"failed to reproduce interpolation at known value (at %f got %f, expected %f)\", x, y, yKnown)\n\t}\n}\n\n// Does the cubic spline error become small when using many points?\nfunc TestCubicSplineManyPoints(t *testing.T) {\n\taccuracy := 1e-6\n\t// constants chosen to have xs be integer values\n\tn := 10001 // number of points to interpolate\n\tstart, stop := -10.0, 10.0\n\tsomeCubic := makeCubic(1.0, 1.0, 1.0, 1.0)\n\tstep := (stop - start) / float64(n-1)\n\txs, ys := make([]float64, n), make([]float64, n)\n\tfor i, _ := range xs {\n\t\txs[i] = start + float64(i)*step\n\t\tys[i] = someCubic(xs[i])\n\t}\n\tspline, err := NewCubicSpline(xs, ys)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor i, xi := range xs {\n\t\tif i == n-1 {\n\t\t\t// don't jump out of the interpolation range\n\t\t\tcontinue\n\t\t}\n\t\tx := xi + step/2\n\t\ty, err := spline.At(x)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tyKnown := someCubic(x)\n\t\tif math.Abs((y-yKnown)/yKnown) > accuracy {\n\t\t\tt.Fatalf(\"failed to interpolate to expected accuracy (at %f got %f, expected %f)\", x, y, yKnown)\n\t\t}\n\t}\n}\n\n// Build a cubic functions with given coefficients\nfunc makeCubic(a, b, c, d float64) func(x float64) float64 {\n\tcubic := func(x float64) float64 {\n\t\treturn a*math.Pow(x, 3.0) + b*math.Pow(x, 2.0) + c*x + d\n\t}\n\treturn cubic\n}\n" }, { "alpha_fraction": 0.6694510579109192, "alphanum_fraction": 0.6909307837486267, "avg_line_length": 24.393939971923828, "blob_id": "af5c9b27670a5facae26d8b424156145b41137fd", "content_id": "2591b6dceb5c2457bc191590f3db5855b8cad7ee", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 838, "license_type": "permissive", "max_line_length": 75, "num_lines": 33, "path": "/vector_cache_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"testing\"\n\n// When a value is set in the cache, can that value be found and retrieved?\nfunc TestVectorSetSticks(t *testing.T) {\n\tkey := Vector2{0.0, 0.0}\n\tvalue := Vector2{10.0, 10.0}\n\tcache := NewVectorCache()\n\tcache.Set(key, value)\n\tif !cache.Contains(key) {\n\t\tt.Fatalf(\"VectorCache does not contain value added to it\")\n\t}\n\tgot, ok := cache.Get(key)\n\tif !ok {\n\t\tt.Fatalf(\"VectorCache failed to find value given to it\")\n\t}\n\tgotVector, ok := got.(Vector2)\n\tif !ok {\n\t\tt.Fatalf(\"VectorCache returned a value with the wrong type\")\n\t}\n\tif !value.Equals(gotVector) {\n\t\tt.Fatalf(\"VectorCache returned the wrong value\")\n\t}\n}\n\nfunc TestVectorBadSearch(t *testing.T) {\n\tkey := Vector2{0.0, 0.0}\n\tcache := NewVectorCache()\n\tif cache.Contains(key) {\n\t\tt.Fatalf(\"VectorCache reports it contains a key not given to it\")\n\t}\n}\n" }, { "alpha_fraction": 0.6607476472854614, "alphanum_fraction": 0.6626168489456177, "avg_line_length": 19.188678741455078, "blob_id": "8a4d71aac602b992fa25066548ab5a6db3b5db13", "content_id": "8dfb268953ee50291109d82e007ecd188ff0ee57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1070, "license_type": "permissive", "max_line_length": 71, "num_lines": 53, "path": "/list_cache.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\n// To be used when the expected number of keys is small and the cost of\n// calling reflect.DeepEqual on keys isn't too high.\n\nimport \"reflect\"\n\ntype ListCache struct {\n\tkeys, values []interface{}\n}\n\nfunc NewListCache() *ListCache {\n\tls := new(ListCache)\n\tls.keys = []interface{}{}\n\tls.values = []interface{}{}\n\treturn ls\n}\n\nfunc (ls *ListCache) Contains(key interface{}) bool {\n\tif ls.indexOf(key) > -1 {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc (ls *ListCache) Get(key interface{}) (interface{}, bool) {\n\tif !ls.Contains(key) {\n\t\treturn nil, false\n\t}\n\ti := ls.indexOf(key)\n\treturn ls.values[i], true\n}\n\nfunc (ls *ListCache) Set(key interface{}, value interface{}) {\n\tif !ls.Contains(key) {\n\t\t// add key to cache\n\t\tls.keys = append(ls.keys, key)\n\t\tls.values = append(ls.values, value)\n\t\treturn\n\t}\n\t// if we get here, key is already in the cache\n\ti := ls.indexOf(key)\n\tls.values[i] = value\n}\n\nfunc (ls *ListCache) indexOf(key interface{}) int {\n\tfor i, cachedKey := range ls.keys {\n\t\tif reflect.DeepEqual(key, cachedKey) {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}\n" }, { "alpha_fraction": 0.696363627910614, "alphanum_fraction": 0.7172726988792419, "avg_line_length": 34.48387145996094, "blob_id": "75d063a1a0b68aaa4109ae17c4bb748e52ee3cd4", "content_id": "1e35d5280eb5d67543256f42ca7f511d493cefa7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1100, "license_type": "permissive", "max_line_length": 100, "num_lines": 31, "path": "/kramerskronig.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"math\"\n\n// Return the real part of f = realPart + i * imagPart.\n// f must be analytic in the upper half-plane (i.e. causal).\n// left and right are the limits of integration (approximation to -+ infinity).\nfunc RealFromImaginary(imagPart Func1DError, left, right, eps float64, numPoints uint) Func1DError {\n\trealPart := func(omega float64) (float64, error) {\n\t\tintegrand := func(omegaPrime float64) (float64, error) {\n\t\t\tim, err := imagPart(omegaPrime)\n\t\t\tif err != nil {\n\t\t\t\treturn 0.0, err\n\t\t\t}\n\t\t\treturn (1 / math.Pi) * im / (omegaPrime - omega), nil\n\t\t}\n\t\treturn PvIntegral(integrand, left, right, omega, eps, numPoints)\n\t}\n\treturn realPart\n}\n\n// Kramers-Kronig equation for the imaginary part is identical to that for the\n// real part except for a minus sign.\nfunc ImaginaryFromReal(realPart Func1DError, left, right, eps float64, numPoints uint) Func1DError {\n\timaginaryPart := func(omega float64) (float64, error) {\n\t\talmost := RealFromImaginary(realPart, left, right, eps, numPoints)\n\t\talmostIm, err := almost(omega)\n\t\treturn -almostIm, err\n\t}\n\treturn imaginaryPart\n}\n" }, { "alpha_fraction": 0.6297468543052673, "alphanum_fraction": 0.6708860993385315, "avg_line_length": 29.829267501831055, "blob_id": "6d335dd7b1100a408c770bdb2f2421df8493b96f", "content_id": "940b31bc44a560a50b793d8d066678288cf3707f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1264, "license_type": "permissive", "max_line_length": 76, "num_lines": 41, "path": "/mesh_aggregates_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n// Average of Sin(kx) * Sin(ky) over Brillouin zone should be 0.\n// Check if the average found is under machine epsilon.\n// Also check if the minimum is close to -1 (arbitrary tolerance 1e-9)\nfunc TestSinSin(t *testing.T) {\n\tworker := func(k Vector2) float64 {\n\t\treturn math.Sin(k.X) * math.Sin(k.Y)\n\t}\n\tif avg := Average(128, worker); math.IsNaN(avg) || avg > MachEpsFloat64() {\n\t\tt.Fatalf(\"average of sin(kx)*sin(ky) incorrect (got %f)\", avg)\n\t}\n\tif min := Minimum(128, worker); math.IsNaN(min) || (min+1) > 1e-9 {\n\t\tt.Fatalf(\"minimum of sin(kx)*sin(ky) incorrect (got %f)\", min)\n\t}\n}\n\n// Check if DeltaBinner is working for 2 non-q-dependent delta functions\nfunc TestTwoDeltas(t *testing.T) {\n\tvar pointsPerSide uint32 = 64\n\tdeltaPoints := []float64{5.5, 10.5}\n\tdeltaTerms := func(q Vector2) ([]float64, []float64) {\n\t\tomegas := deltaPoints\n\t\tcoeffs := []float64{1.0, 1.0}\n\t\treturn omegas, coeffs\n\t}\n\tbinner := NewDeltaBinner(deltaTerms, 0.0, 15.0, 64)\n\tresult := DeltaBin(pointsPerSide, binner)\n\texpected := 1.0\n\tfor _, point := range deltaPoints {\n\t\tindex := binner.BinVarToIndex(point)\n\t\tif math.Abs(result[index]-expected) > MachEpsFloat64() {\n\t\t\tt.Fatalf(\"incorrect delta sum (%f)\", result[index])\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.6094297766685486, "alphanum_fraction": 0.676330029964447, "avg_line_length": 31.03061294555664, "blob_id": "37a5d846cf756cf570ba607b3299479e0d443b31", "content_id": "f4bed7643813d01b3a5c4930ab6d731041ae6674", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3139, "license_type": "permissive", "max_line_length": 337, "num_lines": 98, "path": "/zerotemp_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"testing\"\n\t\"reflect\"\n\t\"flag\"\n\t\"math\"\n\t\"fmt\"\n)\n\nvar cached *bool = flag.Bool(\"gc_cache\", false, \"used cached Environment for TestGc0\")\n\nfunc TestKnownZeroTempSystem(t *testing.T) {\n\tenvStr := \"{\\\"GridLength\\\":8,\\\"ImGc0Bins\\\":0,\\\"ReGc0Points\\\":0,\\\"ReGc0dw\\\":0,\\\"InitD1\\\":0.1,\\\"InitMu\\\":0.1,\\\"InitF0\\\":0.1,\\\"Alpha\\\":-1,\\\"T\\\":0,\\\"T0\\\":1,\\\"Tz\\\":0.1,\\\"Thp\\\":0.1,\\\"X\\\":0.1,\\\"DeltaS\\\":0,\\\"CS\\\":0,\\\"Superconducting\\\":false,\\\"D1\\\":0.05777149373506878,\\\"Mu\\\":-0.18330570279347042,\\\"F0\\\":0.12945949461029932,\\\"EpsilonMin\\\":-1.8}\"\n\texpectedEnv, err := EnvironmentFromString(envStr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\ttolerances := []float64{1e-6, 1e-6, 1e-6}\n\tsystem := NewZeroTempSystem(tolerances)\n\tenv, err := EnvironmentFromFile(\"zerotemp_test.json\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tenv.Initialize()\n\tsolution, err := system.Solve(*env)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsolvedEnv := solution.(Environment)\n\tif !reflect.DeepEqual(solvedEnv, *expectedEnv) {\n\t\tt.Fatalf(\"unknown solution to zero-temp system: got\\n%s, expected\\n%s\", (&solvedEnv).String(), expectedEnv.String())\n\t}\n}\n\nfunc TestGc0(t *testing.T) {\n\tcacheFileName := \"zerotemp_test_gc0_cache.json\"\n\tflag.Parse()\n\ttolerances := []float64{1e-6, 1e-6, 1e-6}\n\tsystem := NewZeroTempSystem(tolerances)\n\tenv, err := EnvironmentFromFile(\"zerotemp_test_gc0.json\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tenv.Initialize()\n\tvar solvedEnv Environment // not sure if the seperate declaration is needed\n\tif !(*cached) {\n\t\tsolution, err := system.Solve(*env)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tsolvedEnv = solution.(Environment)\n\t\tsolvedEnv.WriteToFile(cacheFileName)\n\t} else {\n\t\tcacheEnv, err := EnvironmentFromFile(cacheFileName)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tsolvedEnv = *cacheEnv\n\t}\n\tk := Vector2{0.0 * math.Pi, 0.0 * math.Pi}\n\tpoles, err := ZeroTempGreenPolePoint(solvedEnv, k)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t//if len(poles) != 4 {\n\t//\tt.Fatal(\"did not get expected number of poles\")\n\t//}\n\t//expected := []string{\"-3.8862440783169987\", \"3.86016952787911\", \"3.9111002349865496\", \"7.560058812941273\"}\n\tfor i, p := range poles {\n\t\tfmt.Printf(\"%d %v\\n\", i, p)\n\t\t//if fmt.Sprintf(\"%v\", p) != expected[i] {\n\t\t//\tt.Fatal(\"did not get expected pole value\")\n\t\t//}\n\t}\n\tfmt.Printf(\"gap=%f\\n\", ZeroTempGap(solvedEnv, k))\n\t/*\n\t\terr = ZeroTempPlotGc(solvedEnv, k, 512, \"zerotemp.gc0_k0_w0.testignore\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t*/\n\t/*\n\t\tsplit := 0.01\n\t\tpoleCurve := func(x float64) Vector2 {\n\t\t\tval := 0.5*math.Pi + split*(2*x-1)\n\t\t\treturn Vector2{val, val}\n\t\t}\n\t\tZeroTempPlotPoleCurve(solvedEnv, poleCurve, 64, \"zerotemp.testignore.polecurve.superconducting\")\n\t\tZeroTempPlotPolePlane(solvedEnv, \"zerotemp.testignore.poleplane.superconducting\", 128)\n\t\tsolvedEnv.Superconducting = false\n\t\tZeroTempPlotPoleCurve(solvedEnv, poleCurve, 64, \"zerotemp.testignore.polecurve.nonsc\")\n\t\tZeroTempPlotPolePlane(solvedEnv, \"zerotemp.testignore.poleplane.nonsc\", 64)\n\t*/\n\tPlotGcSymmetryLines(solvedEnv, 8, 256, \"zerotemp.testignore.symmetry.sc\")\n\tsolvedEnv.Superconducting = false\n\tPlotGcSymmetryLines(solvedEnv, 8, 256, \"zerotemp.testignore.symmetry.nosc\")\n}\n" }, { "alpha_fraction": 0.5898145437240601, "alphanum_fraction": 0.6094658374786377, "avg_line_length": 27.674602508544922, "blob_id": "914c67612bca8f1d4201410c2d35bc854f129619", "content_id": "a13b56a21f273cb9cd57fcd5f78443ff0c0f673a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3613, "license_type": "permissive", "max_line_length": 91, "num_lines": 126, "path": "/integrate.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n)\n\n// Integrate the cubic spline interpolation of y from x = left to x = right. \n// xs is an ordered slice of equally spaced x values.\n// ys is a slice of the corresponding y values.\n// Assume left >= xs[0] and right <= xs[len(xs)-1].\nfunc SplineIntegral(xs, ys []float64, left, right float64) (float64, error) {\n\t// if the arguments are reversed, we need a minus sign later\n\tsign := 1.0\n\tif left > right {\n\t\tsign = -1.0\n\t\tleft, right = right, left\n\t}\n\t// make the spline\n\ts, err := NewCubicSpline(xs, ys)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\txMin, xMax := s.Range()\n\t// can't integrate if left or right is outside of interpolation range\n\teps := SplineExtrapolationDistance\n\tif (xMin-left > eps) || (right-xMax > eps) {\n\t\treturn 0.0, errors.New(\"SplineIntegral error: integral arguments out of bounds\")\n\t}\n\t// k and q are the first and last indices for integration\n\tk, q := s.indexOf(left), s.indexOf(right)\n\tfirst := s.antiDeriv(k, xs[k+1]) - s.antiDeriv(k, left)\n\tlast := s.antiDeriv(q, right) - s.antiDeriv(q, xs[q])\n\t// add upp all the middle segment integrals\n\tmiddle, compensate := 0.0, 0.0\n\tfor i := k + 1; i < q; i++ {\n\t\tintegral := s.antiDeriv(i, xs[i+1]) - s.antiDeriv(i, xs[i])\n\t\tmiddle, compensate = KahanSum(integral, middle, compensate)\n\t}\n\treturn sign * (first + middle + last), nil\n}\n\n// Principal value integral of f(x) from x = a to x = b. Assume there is a \n// pole at x = w and do cubic spline integrals in the appropriate spots, \n// staying a distance eps away from the pole. Use n points for the cubic\n// spline on each side of the pole.\nfunc PvIntegral(f Func1DError, a, b, w, eps float64, n uint) (float64, error) {\n\t// can't integrate if a boundary is on top of the pole\n\tif a == w || b == w {\n\t\treturn 0.0, fmt.Errorf(\"PvIntegral error: pole (%f) equals a boundary (%f, %f)\", w, a, b)\n\t}\n\t// if the pole is within eps of a boundary, reduce eps\n\tdrop := 10.0\n\tfor w > a && w-a < eps {\n\t\teps = (w - a) / drop\n\t}\n\tfor b > w && b-w < eps {\n\t\teps = (b - w) / drop\n\t}\n\t// if the bounds were given out of order, we need a minus sign later\n\tsign := 1.0\n\tif a > b {\n\t\tsign = -1.0\n\t\ta, b = b, a\n\t}\n\t// pole is fully inside integration region\n\tif a <= w && w <= b {\n\t\t// avoid the interval [wl, wr]\n\t\twl, wr := w-eps, w+eps\n\t\t// left and right sets of x points\n\t\txls, xrs := MakeRange(a, wl, n), MakeRange(wr, b, n)\n\t\t// left and right sets of y points\n\t\tyls, yrs := make([]float64, n), make([]float64, n)\n\t\tfor i := uint(0); i < n; i++ {\n\t\t\tyl, err := f(xls[i])\n\t\t\tif err != nil {\n\t\t\t\treturn 0.0, err\n\t\t\t}\n\t\t\tyr, err := f(xrs[i])\n\t\t\tif err != nil {\n\t\t\t\treturn 0.0, err\n\t\t\t}\n\t\t\tyls[i], yrs[i] = yl, yr\n\t\t}\n\t\t// do the integrals\n\t\t// if the pole is very close to the boundary, integral ~ 0\n\t\tvar leftInt, rightInt float64\n\t\tif wl < a || FuzzyEqual(w-a, 0.0) {\n\t\t\tleftInt = 0.0\n\t\t} else {\n\t\t\tvar err error\n\t\t\tleftInt, err = SplineIntegral(xls, yls, a, wl)\n\t\t\tif err != nil {\n\t\t\t\treturn 0.0, err\n\t\t\t}\n\t\t}\n\t\tif wr > b || FuzzyEqual(b-w, 0.0) {\n\t\t\trightInt = 0.0\n\t\t} else {\n\t\t\tvar err error\n\t\t\trightInt, err = SplineIntegral(xrs, yrs, wr, b)\n\t\t\tif err != nil {\n\t\t\t\treturn 0.0, err\n\t\t\t}\n\t\t}\n\t\treturn sign * (leftInt + rightInt), nil\n\t}\n\t// pole is fully outside the integration region\n\t// x values take the entire range\n\txs := MakeRange(a, b, 2*n)\n\t// associated y values\n\tys := make([]float64, 2*n)\n\tfor i := uint(0); i < 2*n; i++ {\n\t\ty, err := f(xs[i])\n\t\tif err != nil {\n\t\t\treturn 0.0, err\n\t\t}\n\t\tys[i] = y\n\t}\n\t// only one integral to do\n\tintegral, err := SplineIntegral(xs, ys, a, b)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\treturn sign * integral, nil\n}\n" }, { "alpha_fraction": 0.6134690046310425, "alphanum_fraction": 0.6470333337783813, "avg_line_length": 30.630136489868164, "blob_id": "d3b344ca7069815f4e52b00d3ab7ff47796d546b", "content_id": "2be1d67da029a3b094ab2973af7b00ae7c2c76c0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 4618, "license_type": "permissive", "max_line_length": 123, "num_lines": 146, "path": "/cubicspline.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "// Cubic spline interpolation and integration of discrete points\n// Based on description of algorithm found at:\n// http://web.archive.org/web/20090408054627/http://online.redwoods.cc.ca.us/instruct/darnold/laproj/Fall98/SkyMeg/Proj.PDF\npackage polecalc\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nconst SplineExtrapolationDistance = 1e-6\n\n// Cubic spline is defined by the set of functions s_i given on the intervals\n// between the values of xs: s_i(x) is defined on [xs[i],xs[i+1]).\n// s_i(x) = a[i](x-xs[i])^3 + b[i](x-xs[i])^2 + c[i](x-xs[i]) + d[i]\ntype CubicSpline struct {\n\ta, b, c, d []float64 // length n - 1\n\txs []float64 // length n\n}\n\n// Return a pointer to a cubic spline interpolating y = f(x).\n// xs is an ordered slice of equally spaced x values.\n// ys is a slice of the corresponding y values.\nfunc NewCubicSpline(xs, ys []float64) (*CubicSpline, error) {\n\t// xs and ys must have the same length\n\tif len(xs) != len(ys) {\n\t\treturn nil, errors.New(\"input slices must be the same length\")\n\t}\n\t// must have at least three points\n\tif len(xs) < 3 {\n\t\treturn nil, errors.New(\"not enough points for cubic spline\")\n\t}\n\t// xs must be ordered\n\tif !inAscendingOrder(xs) {\n\t\treturn nil, errors.New(\"xs must be in ascending order\")\n\t}\n\tspline := new(CubicSpline)\n\tspline.xs = xs\n\tspline.a, spline.b, spline.c, spline.d = splineCoeffs(xs, ys)\n\treturn spline, nil\n}\n\n// Value of the interpolated function S(x) at x\n// Will panic if x is outside the interpolation range\nfunc (s *CubicSpline) At(x float64) (float64, error) {\n\txMin, xMax := s.Range()\n\teps := SplineExtrapolationDistance\n\tif (xMin-x > eps) || (x-xMax > eps) {\n\t\treturn 0.0, errors.New(\"accessing cubic spline out of bounds\")\n\t}\n\ti := s.indexOf(x)\n\treturn s.splineAt(i, x), nil\n}\n\n// Individual spline functions si(x) at index i, position x\n// Assumes i > 0 and x is in the appropriate range for si\nfunc (s *CubicSpline) splineAt(i int, x float64) float64 {\n\tdx := x - s.xs[i]\n\treturn s.a[i]*math.Pow(dx, 3.0) + s.b[i]*math.Pow(dx, 2.0) + s.c[i]*dx + s.d[i]\n}\n\n// Antiderivative of the spline functions (with integration constant = 0)\n// Makes the same assumptions as splineAt.\nfunc (s *CubicSpline) antiDeriv(i int, x float64) float64 {\n\tdx := x - s.xs[i]\n\treturn s.a[i]*math.Pow(dx, 4.0)/4 + s.b[i]*math.Pow(dx, 3.0)/3 + s.c[i]*math.Pow(dx, 2.0)/2 + s.d[i]*x\n}\n\n// Interpolation range of the spline\nfunc (s *CubicSpline) Range() (float64, float64) {\n\tn := len(s.xs)\n\treturn s.xs[0], s.xs[n-1]\n}\n\n// Return the index i such that xs[i] <= x < xs[i+1]\n// Assume x is within the bounds of the spline\n// i will be between 0 and n-2 where n is len(s.xs)\nfunc (s *CubicSpline) indexOf(x float64) int {\n\txMin, xMax := s.Range()\n\t// -1 to accomodate having one less interpolating function than the\n\t// number of points\n\tnumSplines := len(s.xs) - 1\n\tstep := (xMax - xMin) / float64(numSplines)\n\tif FuzzyEqual(xMax-xMin, 0.0) {\n\t\tpanic(\"cubic spline step size ~ 0, cannot find index\")\n\t}\n\ti := int(math.Floor((x - xMin) / step))\n\t// allow a bit of extrapolation on the endpoints\n\tif i == numSplines && xMax-x < SplineExtrapolationDistance {\n\t\treturn i - 1\n\t}\n\tif i == -1 && x-xMin < SplineExtrapolationDistance {\n\t\treturn 0\n\t}\n\treturn i\n}\n\n// Find the cubic spline coefficients corresponding to the given points\nfunc splineCoeffs(xs []float64, ys []float64) ([]float64, []float64, []float64, []float64) {\n\tn := len(xs)\n\th := xs[1] - xs[0]\n\tM := solveNaturalSplineEqn(h, ys)\n\ta, b, c, d := make([]float64, n-1), make([]float64, n-1), make([]float64, n-1), make([]float64, n-1)\n\tfor i, _ := range a {\n\t\ta[i] = (M[i+1] - M[i]) / (6 * h)\n\t\tb[i] = M[i] / 2\n\t\tc[i] = (ys[i+1]-ys[i])/h - h*(M[i+1]+2*M[i])/6\n\t\td[i] = ys[i]\n\t}\n\treturn a, b, c, d\n}\n\n// Solve the tridiagonal matrix equation for M, a slice of second derivative \n// values used in calculating the interpolating function coefficients.\nfunc solveNaturalSplineEqn(h float64, ys []float64) []float64 {\n\tM := TridiagonalSolve(splineTriDiagInit(h, ys))\n\t// natural spline condition\n\tM = PadLeftWith0(M)\n\tM = append(M, 0)\n\treturn M\n}\n\n// Initialize the tridiagonal matrix\nfunc splineTriDiagInit(h float64, ys []float64) ([]float64, []float64, []float64, []float64) {\n\tn := len(ys)\n\ta, b, c, d := make([]float64, n-1), make([]float64, n-2), make([]float64, n-1), make([]float64, n-2)\n\tfor i, _ := range a {\n\t\ta[i] = 1\n\t\tc[i] = 1\n\t}\n\tfor i, _ := range b {\n\t\tb[i] = 4\n\t\td[i] = (6 / (h * h)) * (ys[i] - 2*ys[i+1] + ys[i+2])\n\t}\n\treturn a, b, c, d\n}\n\n// check if xs is in ascending order\nfunc inAscendingOrder(xs []float64) bool {\n\tfor i, val := range xs {\n\t\tif i != 0 && xs[i-1] > val {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n" }, { "alpha_fraction": 0.6545698642730713, "alphanum_fraction": 0.6787634491920471, "avg_line_length": 22.25, "blob_id": "5285c0aa17962cbb9035e79e242b919b4c10bd0c", "content_id": "af4d7906bcddfe039f20c731946aa032d8bfe2f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 744, "license_type": "permissive", "max_line_length": 65, "num_lines": 32, "path": "/list_cache_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"testing\"\n\nfunc TestListSetSticks(t *testing.T) {\n\tkey := Vector2{0.0, 0.0}\n\tvalue := Vector2{10.0, 10.0}\n\tcache := NewListCache()\n\tcache.Set(key, value)\n\tif !cache.Contains(key) {\n\t\tt.Fatalf(\"ListCache does not contain value added to it\")\n\t}\n\tgot, ok := cache.Get(key)\n\tif !ok {\n\t\tt.Fatalf(\"ListCache failed to find value given to it\")\n\t}\n\tgotVector, ok := got.(Vector2)\n\tif !ok {\n\t\tt.Fatalf(\"ListCache returned a value with the wrong type\")\n\t}\n\tif !value.Equals(gotVector) {\n\t\tt.Fatalf(\"ListCache returned the wrong value\")\n\t}\n}\n\nfunc TestListBadSearch(t *testing.T) {\n\tkey := Vector2{0.0, 0.0}\n\tcache := NewListCache()\n\tif cache.Contains(key) {\n\t\tt.Fatalf(\"ListCache reports it contains a key not given to it\")\n\t}\n}\n" }, { "alpha_fraction": 0.6399848461151123, "alphanum_fraction": 0.6688163876533508, "avg_line_length": 26.17525863647461, "blob_id": "1b2f85d258b1f6f05a3dac8518fe267e44ca7461", "content_id": "41909eee6101325f2f159b63f5277389db3e18e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 2636, "license_type": "permissive", "max_line_length": 81, "num_lines": 97, "path": "/mesh2d.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"math\"\n\n// Return coordinate from the square mesh of lenght L corresponding to the \n// index i.\n// i=0 corresponds to (-pi, -pi); i=L-1 is (pi-step, -pi);\n// i=L is (-pi, -pi+step); i=L^2-1 is (pi-step, pi-step)\nfunc SquareAt(i uint64, L uint32) Vector2 {\n\tif i < 0 || i >= uint64(math.Pow(float64(L), 2.0)) {\n\t\t// panic here instead of returning an error since we will call\n\t\t// this function pretty often - presumably only returning one\n\t\t// variable is better for performance\n\t\tpanic(\"invalid index for square mesh\")\n\t}\n\tstart, stop := -math.Pi, math.Pi\n\tlength := stop - start\n\tstep := length / float64(L)\n\t// transform 1d index to 2d coordinate indices\n\tny := uint32(math.Floor(float64(i) / float64(L)))\n\tnx := uint32(i) - ny*L\n\t// get coordinates\n\tx := start + float64(nx)*step\n\ty := start + float64(ny)*step\n\treturn Vector2{x, y}\n}\n\ntype Callback func(k Vector2) error\ntype Acceptor func(k Vector2) bool\n\nfunc CallOnAccepted(L uint32, callback Callback, acceptor Acceptor) error {\n\tsqrtN := uint64(L)\n\tN := sqrtN * sqrtN\n\tfor i := uint64(0); i < N; i++ {\n\t\tk := SquareAt(i, L)\n\t\tif acceptor(k) {\n\t\t\terr := callback(k)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// call callback on all points in the square mesh of length L\nfunc CallOnPlane(L uint32, callback Callback) error {\n\tacceptor := func(k Vector2) bool {\n\t\treturn true\n\t}\n\treturn CallOnAccepted(L, callback, acceptor)\n}\n\n// call callback on the third quadrant only\nfunc CallOnThirdQuad(L uint32, callback Callback) error {\n\tacceptor := func(k Vector2) bool {\n\t\treturn k.X <= 0 && k.Y <= 0\n\t}\n\treturn CallOnAccepted(L, callback, acceptor)\n}\n\n// call callback on the given curve\ntype CurveGenerator func(float64) Vector2\n\nfunc CallOnCurve(curve CurveGenerator, numPoints uint, callback Callback) error {\n\txValues := MakeRange(0.0, 1.0, numPoints)\n\tfor _, x := range xValues {\n\t\tk := curve(x)\n\t\terr := callback(k)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// Scan k values along lines of high symmetry. Call callback at each point.\n// k values form a cycle: (0, 0) -> (pi, 0) -> (pi, pi) -> (0, 0)\nfunc CallOnSymmetryLines(numPoints uint, callback Callback) error {\n\txAxis := func(x float64) Vector2 {\n\t\treturn Vector2{x * math.Pi, 0.0}\n\t}\n\tyAxisShifted := func(y float64) Vector2 {\n\t\treturn Vector2{math.Pi, y * math.Pi}\n\t}\n\tequal_xy := func(x float64) Vector2 {\n\t\treturn Vector2{math.Pi - x*math.Pi, math.Pi - x*math.Pi}\n\t}\n\tcurves := []CurveGenerator{xAxis, yAxisShifted, equal_xy}\n\tfor _, curve := range curves {\n\t\terr := CallOnCurve(curve, numPoints, callback)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n" }, { "alpha_fraction": 0.6623093485832214, "alphanum_fraction": 0.6753812432289124, "avg_line_length": 19.863636016845703, "blob_id": "e5228bb47a04ce2d88d31ad023f32aa75eb8db7d", "content_id": "21d27806fc5d5388d2482990172e76e6e218e95e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 459, "license_type": "permissive", "max_line_length": 59, "num_lines": 22, "path": "/spectrum_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n// Is EpsilonMin set such that the minimum of Epsilon is 0?\nfunc TestEpsilonMin(t *testing.T) {\n\tenv, err := EnvironmentFromFile(\"environment_test.json\")\n\tenv.Initialize()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tworker := func(k Vector2) float64 {\n\t\treturn Epsilon(*env, k)\n\t}\n\tmin := Minimum(env.GridLength, worker)\n\tif math.Abs(min) > MachEpsFloat64() {\n\t\tt.Fatalf(\"minimum of Epsilon too large (%f)\", min)\n\t}\n}\n" }, { "alpha_fraction": 0.6512719988822937, "alphanum_fraction": 0.6778864860534668, "avg_line_length": 30.543209075927734, "blob_id": "f24984d6084ecd275830c8c3ef6998d8cb100f99", "content_id": "c8beb2ec0857a1cae7912af2e9951c0c933a4dc8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 2555, "license_type": "permissive", "max_line_length": 106, "num_lines": 81, "path": "/bracket.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"errors\"\n\nvar ErrorNoBracket string = \"cannot find bracket\"\n\n// (should probably set these constants through a configuration method)\n// Number of steps to take in the first attempt to find a bracket.\nconst InitialBracketNumber uint = 32\n\n// If using more steps than this to find a bracket, stop.\nconst MaxBracketNumber uint = 256 // 4 iterations from 32 (32 * 2^4)\n\n// Find all pairs of points which bracket roots of f between left and right.\nfunc MultiBracket(f Func1D, left, right float64) ([][]float64, error) {\n\treturn bracketHelper(f, left, right, InitialBracketNumber, -1)\n}\n\n// Find a pair of points which bracket a root of f between left and right.\nfunc FindBracket(f Func1D, left, right float64) (float64, float64, error) {\n\tbracket, err := bracketHelper(f, left, right, InitialBracketNumber, 1)\n\tif err != nil {\n\t\treturn 0.0, 0.0, err\n\t}\n\tbl, br := bracket[0][0], bracket[0][1]\n\treturn bl, br, err\n}\n\n// Use a number of divisions equal to bracketNum to find a root.\n// If maxBrackets <= 0, get as many brackets as possible.\nfunc bracketHelper(f Func1D, left, right float64, bracketNum uint, maxBrackets int) ([][]float64, error) {\n\tif left == right {\n\t\treturn nil, errors.New(\"bracket error: must give two distinct points to find bracket\")\n\t}\n\tif left > right {\n\t\tleft, right = right, left\n\t}\n\txs := MakeRange(left, right, bracketNum)\n\tscale := xs[1] - xs[0]\n\tbrackets := [][]float64{}\n\tfor i, _ := range xs {\n\t\t// only get as many brackets as requested\n\t\tif maxBrackets > 0 && len(brackets) >= maxBrackets {\n\t\t\treturn brackets, nil\n\t\t}\n\t\t// don't check [endpoint, endpoint+scale] bracket\n\t\tif i >= len(xs)-1 {\n\t\t\tbreak\n\t\t}\n\t\t// check function values\n\t\tfa, fb := f(xs[i]), f(xs[i+1])\n\t\tif FuzzyEqual(fb, 0.0) {\n\t\t\tbrackets = append(brackets, []float64{xs[i], xs[i+1] + scale})\n\t\t} else if FuzzyEqual(fa, 0.0) {\n\t\t\tbrackets = append(brackets, []float64{xs[i] - scale, xs[i+1]})\n\t\t}\n\t\tif !sameSign(fa, fb) {\n\t\t\tbrackets = append(brackets, []float64{xs[i], xs[i+1]})\n\t\t}\n\t}\n\t// overshot bounds if without finding bracket if we get here\n\tif bracketNum >= MaxBracketNumber {\n\t\t// too many divisions\n\t\treturn nil, errors.New(ErrorNoBracket)\n\t}\n\t// not enough brackets - try again with smaller divisions\n\tif len(brackets) == 0 {\n\t\treturn bracketHelper(f, left, right, bracketNum*2, maxBrackets)\n\t}\n\treturn brackets, nil\n}\n\n// If x and y don't have the same sign, we know they bracket a root.\nfunc sameSign(x, y float64) bool {\n\tif x >= 0 && y >= 0 {\n\t\treturn true\n\t} else if x <= 0 && y <= 0 {\n\t\treturn true\n\t}\n\treturn false\n}\n" }, { "alpha_fraction": 0.4644628167152405, "alphanum_fraction": 0.5669421553611755, "avg_line_length": 23.200000762939453, "blob_id": "fbb3627d253793de165a4c85cdb1f19c3da4433e", "content_id": "6368d0ee57b442dbca1d6b57f8c8149dfe9c4cfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 605, "license_type": "permissive", "max_line_length": 80, "num_lines": 25, "path": "/tridiagonal_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n// Simple 3x3 case for tridiagonal matrix equation\n// [4 1 0 [x1 [1\n// 1 4 1 x2 = 1\n// 0 1 4] x3] 1]\n// the solution is given by: x = [3/14 1/7 3/14]\nfunc TestTridiagonal3(t *testing.T) {\n\ta := []float64{1, 1}\n\tb := []float64{4, 4, 4}\n\tc := []float64{1, 1}\n\td := []float64{1, 1, 1}\n\tx := TridiagonalSolve(a, b, c, d)\n\texpected := []float64{3.0 / 14.0, 1.0 / 7.0, 3.0 / 14.0}\n\tfor i, val := range expected {\n\t\tif math.Abs(val-x[i]) > MachEpsFloat64() {\n\t\t\tt.Fatalf(\"tridiagonal solution failed: got (%v), expected (%v)\", x, expected)\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.6914660930633545, "alphanum_fraction": 0.7155361175537109, "avg_line_length": 36.054054260253906, "blob_id": "5faf981704230483cb76463b5a5724e064169377", "content_id": "3bf4067d309d381c8a181d29f78ab252355b18ae", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1371, "license_type": "permissive", "max_line_length": 128, "num_lines": 37, "path": "/principalvalue.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "// Interface to GSL principal value integral functionality\n// (see http://www.gnu.org/software/gsl/manual/html_node/QAWC-adaptive-integration-for-Cauchy-principal-values.html)\n// Callback passing through cgo follows the model at:\n// http://stackoverflow.com/questions/6125683/call-go-functions-from-c/6147097#6147097\npackage polecalc\n\n// #cgo LDFLAGS: -lgsl -lgslcblas\n// #include <stdlib.h>\n// #include <gsl/gsl_integration.h>\n// extern double goEvaluate(double, void*);\n//\n// static double goPvIntegral(double a, double b, double c, double epsabs, double epsrel, size_t limit, void* userdata) {\n// \tgsl_integration_workspace *w = gsl_integration_workspace_alloc(limit);\n//\tdouble result, error;\n//\tgsl_function F;\n//\tF.function = &goEvaluate;\n//\tF.params = userdata;\n//\tgsl_integration_qawc(&F, a, b, c, epsabs, epsrel, limit, w, &result, &error);\n//\tgsl_integration_workspace_free(w);\n//\treturn result;\n// }\nimport \"C\"\nimport \"unsafe\"\n\n//export goEvaluate\nfunc goEvaluate(x C.double, userdata unsafe.Pointer) C.double {\n\treq := (*Func1D)(userdata)\n\tf := *req\n\txfloat := float64(x)\n\tval := f(xfloat)\n\treturn C.double(val)\n}\n\nfunc PvIntegralGSL(f Func1D, a, b, c, epsabs, epsrel float64, limit uint16) float64 {\n\treq := unsafe.Pointer(&f)\n\treturn float64(C.goPvIntegral(C.double(a), C.double(b), C.double(c), C.double(epsabs), C.double(epsrel), C.size_t(limit), req))\n}\n" }, { "alpha_fraction": 0.7405660152435303, "alphanum_fraction": 0.7429245114326477, "avg_line_length": 14.703703880310059, "blob_id": "7adf63d0a007569c626182c77f0cd021ddfb0488", "content_id": "5ca50869203bf1e588e3f18a128722a8bba221ce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 424, "license_type": "permissive", "max_line_length": 30, "num_lines": 27, "path": "/Makefile", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "include $(GOROOT)/src/Make.inc\n\nTARG=polecalc\nGOFILES=\\\n\tbisection.go\\\n\tbracket.go\\\n\tcubicspline.go\\\n\tenvironment.go\\\n\tintegrate.go\\\n\tkramerskronig.go\\\n\tlist_cache.go\\\n\tmesh2d.go\\\n\tmesh_aggregates.go\\\n\tmpljson.go\\\n\tselfconsistent.go\\\n\tspectrum.go\\\n\tutility.go\\\n\ttridiagonal.go\\\n\tvector.go\\\n\tvector_cache.go\\\n\tzerotemp.go\\\n\tzerotemp_greens.go\\\n\tzerotemp_plots.go\nCGOFILES=\\\n\tprincipalvalue.go\n\ninclude $(GOROOT)/src/Make.pkg\n" }, { "alpha_fraction": 0.6225489974021912, "alphanum_fraction": 0.6264705657958984, "avg_line_length": 33.382022857666016, "blob_id": "dea5e084fa5af137f59ffd9608f34b69ab05e409", "content_id": "0cfb20b1643571820c8f80d05732855cd7ec3615", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3060, "license_type": "permissive", "max_line_length": 79, "num_lines": 89, "path": "/grapher.py", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "import sys\nimport json\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import FormatStrFormatter\nfrom matplotlib.font_manager import FontProperties\nfrom numpy import arange\n\n_GRAPH_DEFAULTS = {\"xlabel\":\"$x$\", \"ylabel\":\"$y$\", \"num_ticks\":5, \n \"axis_label_fontsize\":\"large\", \"tick_formatstr\":\"%.2f\",\n \"legend_fontsize\":\"large\", \"legend_loc\":0, \"legend_title\":None, \n \"graph_filepath\":None}\n\n_SERIES_DEFAULTS = {\"label\":None, \"style\":\"k.\"}\n\ndef parse_file(file_path):\n '''Return the plot representation of the JSON file specified.'''\n # -- todo : check for IOError --\n return import_json(open(file_path, 'r').read())\n\ndef import_json(json_string):\n '''Return the plot representation of the given JSON string.'''\n graph_data = json.loads(json_string)\n if isinstance(graph_data, list):\n graph_data = [_default_data(graph) for graph in graph_data]\n else:\n graph_data = _default_data(graph_data)\n return graph_data\n\ndef _default_data(graph_data):\n # graph-wide defaults\n for key, value in _GRAPH_DEFAULTS.items():\n if key not in graph_data:\n graph_data[key] = value\n # hack to give a fresh series list each time\n if \"series\" not in graph_data:\n graph_data[\"series\"] = []\n # series-specific defaults\n for series in graph_data[\"series\"]:\n for key, value in _SERIES_DEFAULTS.items():\n if key not in series:\n series[key] = value\n return graph_data\n\ndef make_graph(graph_data):\n '''Take a dictionary representing a graph or a list of such dictionaries.\n Build the graph(s), save them to file(s) (if requested), and return the\n matplotlib figures.\n\n '''\n if isinstance(graph_data, list):\n return [make_graph(some_graph) for some_graph in graph_data]\n try:\n dims = graph_data[\"dimensions\"]\n fig = plt.figure(figsize=(dims[0], dims[1]))\n except:\n fig = plt.figure()\n axes = fig.add_subplot(1, 1, 1)\n bounds = [None, None]\n for series in graph_data[\"series\"]:\n fig, axes, bounds = _graph_series(graph_data, series, fig, axes, \n bounds)\n fontprop = FontProperties(size=graph_data[\"legend_fontsize\"])\n axes.legend(loc=graph_data[\"legend_loc\"], title=graph_data[\"legend_title\"],\n prop=fontprop)\n _save_figure(graph_data, fig)\n return fig, axes\n \n\ndef _graph_series(graph_data, series, fig, axes, bounds):\n # -- todo : set ticks --\n axes.plot(_xData(series), _yData(series), series[\"style\"], \n label=series[\"label\"])\n return fig, axes, bounds\n\ndef _xData(series):\n return [point[0] for point in series[\"data\"]]\n\ndef _yData(series):\n return [point[1] for point in series[\"data\"]]\n\ndef _save_figure(graph_data, fig):\n if graph_data[\"graph_filepath\"] is None:\n return\n fig.savefig(graph_data[\"graph_filepath\"] + \".png\")\n fig.savefig(graph_data[\"graph_filepath\"] + \".eps\")\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n make_graph(parse_file(sys.argv[1]))\n" }, { "alpha_fraction": 0.6572244763374329, "alphanum_fraction": 0.6948345899581909, "avg_line_length": 28.17361068725586, "blob_id": "99071e85dea582d5e7964cb7369427c761150416", "content_id": "e48b17c88869f069b6b7d5d06c047079e7d7fb68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 4201, "license_type": "permissive", "max_line_length": 119, "num_lines": 144, "path": "/zerotemp.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"math\"\n\n// Returns the system of equations needed to solve the system at T = 0\nfunc NewZeroTempSystem(tolerances []float64) *SelfConsistentSystem {\n\teqD1 := ZeroTempD1Equation{}\n\teqMu := ZeroTempMuEquation{}\n\teqF0 := ZeroTempF0Equation{}\n\tequations := []SelfConsistentEquation{eqD1, eqMu, eqF0}\n\tsystem := &SelfConsistentSystem{equations, tolerances}\n\treturn system\n}\n\n// --- D1 equation ---\n\n// D1 = -1/(2N) \\sum_k (1 - xi(k)/E(k)) * sin(kx) * sin(ky)\nfunc ZeroTempD1AbsError(env Environment) float64 {\n\tworker := func(k Vector2) float64 {\n\t\tsx, sy := math.Sin(k.X), math.Sin(k.Y)\n\t\treturn -0.5 * (1 - Xi(env, k)/ZeroTempPairEnergy(env, k)) * sx * sy\n\t}\n\treturn env.D1 - Average(env.GridLength, worker)\n}\n\ntype ZeroTempD1Equation struct{}\n\nfunc (eq ZeroTempD1Equation) AbsError(args interface{}) float64 {\n\t//println(\"in d1\")\n\treturn ZeroTempD1AbsError(args.(Environment))\n}\n\nfunc (eq ZeroTempD1Equation) SetArguments(D1 float64, args interface{}) interface{} {\n\tenv := args.(Environment)\n\tenv.D1 = D1\n\t// Epsilon depends on D1 so we may have changed the minimum\n\tenv.EpsilonMin = EpsilonMin(env)\n\treturn env\n}\n\nfunc (eq ZeroTempD1Equation) Range(args interface{}) (float64, float64, error) {\n\treturn 0.0, 1.0, nil\n}\n\n// --- mu equation ---\n\n// x = 1/(2N) \\sum_k (1 - xi(k)/E(k))\nfunc ZeroTempMuAbsError(env Environment) float64 {\n\tworker := func(k Vector2) float64 {\n\t\treturn 0.5 * (1 - Xi(env, k)/ZeroTempPairEnergy(env, k))\n\t}\n\treturn env.X - Average(env.GridLength, worker)\n}\n\ntype ZeroTempMuEquation struct{}\n\nfunc (eq ZeroTempMuEquation) AbsError(args interface{}) float64 {\n\t//println(\"in mu\")\n\treturn ZeroTempMuAbsError(args.(Environment))\n}\n\nfunc (eq ZeroTempMuEquation) SetArguments(Mu float64, args interface{}) interface{} {\n\tenv := args.(Environment)\n\tenv.Mu = Mu\n\treturn env\n}\n\n// mu < 0 is enforced since for mu >= 0 terms with 1 / PairEnergy() can blow up\n// Factor of -2 is arbitrary, may need to be enlarged for some Environments\nfunc (eq ZeroTempMuEquation) Range(args interface{}) (float64, float64, error) {\n\tenv := args.(Environment)\n\treturn -2 * env.T0, -MachEpsFloat64(), nil\n}\n\n// --- F0 equation ---\n\n// 1/(t0+tz) = 1/N \\sum_k (sin(kx) + alpha*sin(ky))^2 / E(k)\nfunc ZeroTempF0AbsError(env Environment) float64 {\n\tworker := func(k Vector2) float64 {\n\t\tsinPart := math.Sin(k.X) + float64(env.Alpha)*math.Sin(k.Y)\n\t\treturn sinPart * sinPart / ZeroTempPairEnergy(env, k)\n\t}\n\treturn 1/(env.T0+env.Tz) - Average(env.GridLength, worker)\n}\n\ntype ZeroTempF0Equation struct{}\n\nfunc (eq ZeroTempF0Equation) AbsError(args interface{}) float64 {\n\t//println(\"in f0\", args.(Environment).Mu)\n\treturn ZeroTempF0AbsError(args.(Environment))\n}\n\nfunc (eq ZeroTempF0Equation) SetArguments(F0 float64, args interface{}) interface{} {\n\tenv := args.(Environment)\n\tenv.F0 = F0\n\treturn env\n}\n\nfunc (eq ZeroTempF0Equation) Range(args interface{}) (float64, float64, error) {\n\treturn 0.0, 1.0, nil\n}\n\n// --- energy scales and related functions ---\n\n// Holon (pair?) gap energy.\nfunc ZeroTempDelta(env Environment, k Vector2) float64 {\n\tsx, sy := math.Sin(k.X), math.Sin(k.Y)\n\treturn 4 * env.F0 * (env.T0 + env.Tz) * (sx + float64(env.Alpha)*sy)\n}\n\n// Energy of a pair of holes.\nfunc ZeroTempPairEnergy(env Environment, k Vector2) float64 {\n\txi := Xi(env, k)\n\tdelta := ZeroTempDelta(env, k)\n\treturn math.Sqrt(xi*xi + delta*delta)\n}\n\n// Energy of a singlet (?)\nfunc ZeroTempOmega(env Environment, k Vector2) float64 {\n\treturn math.Sqrt(math.Pow(env.DeltaS, 2.0) + math.Pow(env.CS, 2.0)*(2-0.5*math.Pow(math.Sin(k.X)+math.Sin(k.Y), 2.0)))\n}\n\n// Energy of a physical electron\nfunc ZeroTempElectronEnergy(env Environment, k Vector2) float64 {\n\treturn -2.0 * env.T * (math.Cos(k.X) + math.Cos(k.Y))\n}\n\n// Fermi distribution at T = 0 is H(-x), where H is a step function.\n// H(0) is taken to be 1.\nfunc ZeroTempFermi(energy float64) float64 {\n\tif energy <= 0.0 {\n\t\treturn 1.0\n\t}\n\treturn 0.0\n}\n\n// Find the minimium value of omega for which ImGc0 > 0.\nfunc ZeroTempGap(env Environment, k Vector2) float64 {\n\tminWorker := func(q Vector2) float64 {\n\t\treturn math.Abs(ZeroTempOmega(env, q) - ZeroTempPairEnergy(env, q.Sub(k)))\n\t}\n\tgap := Minimum(env.GridLength, minWorker)\n\treturn gap\n}\n" }, { "alpha_fraction": 0.5910526514053345, "alphanum_fraction": 0.6163157820701599, "avg_line_length": 25.760562896728516, "blob_id": "40c2550e984b3ccb5e4a20d556c85d03ab8631c0", "content_id": "1657d5899d35138db69e76f998f2021366d6d9b3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1900, "license_type": "permissive", "max_line_length": 99, "num_lines": 71, "path": "/bisection.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\n// Find the root of f in the interval (left, right) to precision epsilon using the bisection method\nfunc SolveBisection(f Func1D, left, right, epsilon float64) (float64, error) {\n\tif left > right {\n\t\tleft, right = right, left\n\t}\n\tvar error error\n\tfor math.Abs(right-left) > 2*epsilon {\n\t\tleft, right, error = BisectionIterate(f, left, right)\n\t\tif error != nil {\n\t\t\treturn (left + right) / 2.0, error\n\t\t}\n\t}\n\treturn (left + right) / 2.0, nil\n}\n\n// Provide the next iteration of the bisection method for f on the interval (left, right)\nfunc BisectionIterate(f Func1D, left, right float64) (float64, float64, error) {\n\tif f(left)*f(right) > 0 {\n\t\treturn left, right, errors.New(\"arguments do not bracket a root\")\n\t}\n\tmidpoint := (left + right) / 2.0\n\tfl, fm, fr := f(left), f(midpoint), f(right)\n\tif fl == 0 {\n\t\t// left side is the root\n\t\treturn left, left, nil\n\t} else if fr == 0 {\n\t\t// right side is the root\n\t\treturn right, right, nil\n\t} else if (fl > 0 && fm < 0) || (fl < 0 && fm > 0) {\n\t\t// root is in the left half\n\t\treturn left, midpoint, nil\n\t} else if (fm > 0 && fr < 0) || (fm < 0 && fr > 0) {\n\t\t// root is in the right half\n\t\treturn midpoint, right, nil\n\t}\n\t// midpoint must be the root\n\treturn midpoint, midpoint, nil\n}\n\n// Solve f for the root in interval (a, b) up to machine precision using bisection\n// Cribbed from implementation on Wikipedia page 'Bisection method'\nfunc BisectionFullPrecision(f Func1D, a, b float64) (float64, error) {\n\tfa, fb := f(a), f(b)\n\tif !((fa >= 0 && fb <= 0) || (fa <= 0 && fb >= 0)) {\n\t\t// no root bracketed\n\t\treturn 0, errors.New(\"arguments do not bracket a root\")\n\t}\n\tvar lo, hi float64\n\tif fa <= 0 {\n\t\tlo, hi = a, b\n\t} else {\n\t\tlo, hi = b, a\n\t}\n\tmid := lo + (hi-lo)/2.0\n\tfor mid != lo && mid != hi {\n\t\tif f(mid) <= 0 {\n\t\t\tlo = mid\n\t\t} else {\n\t\t\thi = mid\n\t\t}\n\t\tmid = lo + (hi-lo)/2.0\n\t}\n\treturn mid, nil\n}\n" }, { "alpha_fraction": 0.5744680762290955, "alphanum_fraction": 0.6044129133224487, "avg_line_length": 25.4375, "blob_id": "34cefb2418bcf00ff4ea04fe171bb1fd83c159a9", "content_id": "d2edce80c704c73deef4eaf17e9a3cdf6f7e1140", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1269, "license_type": "permissive", "max_line_length": 87, "num_lines": 48, "path": "/tridiagonal.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "// Solve a tridiagonal matrix equation\n// (in order to support cubic spline interpolation)\n// Based on Matlab implementation on Wikipedia\n// (http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm#Implementation_in_Matlab)\npackage polecalc\n\n// a: sub-diagonal (below main), input with length n - 1\n// b: main diagonal, input with length n\n// c: sup-diagonal (above main), input with length n - 1\n// d: right side of equation, input with length n\nfunc TridiagonalSolve(a, b, c, d []float64) []float64 {\n\tn := len(b)\n\tx := make([]float64, n)\n\t// algorithm expects these to be the same length as b\n\ta = PadLeftWith0(a)\n\tc = append(c, 0)\n\t// forward sweep: modify coefficients\n\t// first row\n\tc[0] = c[0] / b[0]\n\td[0] = d[0] / b[0]\n\t// remaining rows\n\tfor i := 1; i < n; i++ {\n\t\tid := 1 / (b[i] - c[i-1]*a[i])\n\t\tc[i] = c[i] * id\n\t\td[i] = (d[i] - d[i-1]*a[i]) * id\n\t}\n\t// back substitute: get solution\n\t// final row\n\tx[n-1] = d[n-1]\n\t// remaining rows\n\tfor i := n - 2; i >= 0; i-- {\n\t\tx[i] = d[i] - c[i]*x[i+1]\n\t}\n\treturn x\n}\n\n// Return a new slice which is expanded by adding a 0 on the 0th index\nfunc PadLeftWith0(xs []float64) []float64 {\n\tr := make([]float64, len(xs)+1)\n\tfor i, _ := range r {\n\t\tif i == 0 {\n\t\t\tr[i] = 0\n\t\t} else {\n\t\t\tr[i] = xs[i-1]\n\t\t}\n\t}\n\treturn r\n}\n" }, { "alpha_fraction": 0.5760233998298645, "alphanum_fraction": 0.6184210777282715, "avg_line_length": 15.285714149475098, "blob_id": "56362a638e36c002c11a12d56dfc7e05429ae76f", "content_id": "3a7d44237304afc5fbee68f2118c69d37c88e964", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 684, "license_type": "permissive", "max_line_length": 42, "num_lines": 42, "path": "/vector.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"fmt\"\n)\n\ntype Vector2 struct {\n\tX, Y float64\n}\n\nfunc (v Vector2) Add(u Vector2) Vector2 {\n\treturn Vector2{v.X + u.X, v.Y + u.Y}\n}\n\nfunc (v Vector2) Sub(u Vector2) Vector2 {\n\treturn Vector2{v.X - u.X, v.Y - u.Y}\n}\n\nfunc (v Vector2) Mult(s float64) Vector2 {\n\treturn Vector2{s * v.X, s * v.Y}\n}\n\nfunc (v Vector2) Dot(u Vector2) float64 {\n\treturn v.X*u.X + v.Y*u.Y\n}\n\nfunc (v Vector2) Norm() float64 {\n\treturn math.Sqrt(v.Dot(v))\n}\n\nfunc (v Vector2) NormSquared() float64 {\n\treturn v.Dot(v)\n}\n\nfunc (v Vector2) Equals(u Vector2) bool {\n\treturn v.X == u.X && v.Y == u.Y\n}\n\nfunc (v Vector2) String() string {\n\treturn fmt.Sprintf(\"(%f, %f)\", v.X, v.Y)\n}\n" }, { "alpha_fraction": 0.7108280062675476, "alphanum_fraction": 0.7265392541885376, "avg_line_length": 32.884891510009766, "blob_id": "fbb160c7f8a97a6f9659794f7264270730f3cf51", "content_id": "bf458d1594f05d5d502e49c3cd38a174160058bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 4710, "license_type": "permissive", "max_line_length": 132, "num_lines": 139, "path": "/environment.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io/ioutil\"\n\t\"math\"\n\t\"reflect\"\n)\n\n// Holds all the necessary data for evaluating functions in the cuprate system\ntype Environment struct {\n\t// program parameters\n\tGridLength uint32 // points per side in Brillouin zone; typical value ~ 64\n\tImGc0Bins uint // number of bins to use when calculating the imaginary part of the electron Green's function\n\tReGc0Points uint // number of points to use on each side of the 1/x singularity when calculating ReGc0\n\tReGc0dw float64 // distance away from the singularity to step when calculating ReGc0\n\tInitD1, // initial values for self-consistent parameters\n\tInitMu,\n\tInitF0 float64\n\n\t// system constant physical parameters\n\tAlpha int8 // either -1 (d-wave) or +1 (s-wave)\n\tT, // hopping energy for the physical electron\n\tT0, // Overall energy scale (default = 1.0)\n\tTz, // z-direction hopping energy (|tz| < 0.3 or so)\n\tThp, // Diagonal (next-nearest-neighbor) hopping energy (similar range as tz)\n\tX, // Doping / holon excess (0 < x < ~0.2)\n\tDeltaS, // spin gap\n\tCS float64 // coefficient for k deviation in omega_q\n\tSuperconducting bool // are we in the superconducting phase?\n\n\t// self-consistently determined physical parameters\n\tD1, // diagonal hopping parameter generated by two-hole process\n\tMu, // holon chemical potential\n\tF0 float64 // superconducting order parameter\n\n\t// cached value: must be reset with EpsilonMin() if D1 changes\n\tEpsilonMin float64\n}\n\n// The one-holon hopping energy Th is determined by Environment parameters\nfunc (env *Environment) Th() float64 {\n\treturn env.T0 * (1 - env.X)\n}\n\n// Spinon chemical potential\nfunc (env *Environment) Lambda() float64 {\n\treturn math.Sqrt(math.Pow(env.DeltaS, 2.0) + math.Pow(env.CS, 2.0))\n}\n\n// Set self-consistent parameters to the initial values as specified by the Environment\nfunc (env *Environment) Initialize() {\n\t// specified defaults\n\tenv.D1 = env.InitD1\n\tenv.Mu = env.InitMu\n\tenv.F0 = env.InitF0\n\t// must be determined after system is otherwise initialized\n\tenv.EpsilonMin = EpsilonMin(*env)\n}\n\nfunc (env *Environment) ZeroTempErrors() string {\n\treturn fmt.Sprintf(\"errors - d1: %f; mu: %f; f0: %f\", ZeroTempD1AbsError(*env), ZeroTempMuAbsError(*env), ZeroTempF0AbsError(*env))\n}\n\n// Convert the Environment to string by returning a JSON representation\nfunc (env *Environment) String() string {\n\tenvBytes, err := json.Marshal(env)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\tenvStr := bytes.NewBuffer(envBytes).String()\n\treturn envStr\n}\n\n// Construct an Environment from the JSON file with given path.\n// Self-consistent parameters are not set to values given by Init fields.\nfunc EnvironmentFromFile(filePath string) (*Environment, error) {\n\tfileContents, err := ioutil.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn EnvironmentFromBytes(fileContents)\n}\n\n// Convert to string and pass to EnvironmentFromBytes\nfunc EnvironmentFromString(jsonData string) (*Environment, error) {\n\tjsonBytes, err := StringToBytes(jsonData)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn EnvironmentFromBytes(jsonBytes)\n}\n\n// Construct an Environment from the given JSON byte slice.\n// Self-consistent parameters are not set to values given by Init fields.\nfunc EnvironmentFromBytes(jsonData []byte) (*Environment, error) {\n\tjsonObject := make(map[string]interface{})\n\tif err := json.Unmarshal(jsonData, &jsonObject); err != nil {\n\t\treturn nil, err\n\t}\n\treturn EnvironmentFromObject(jsonObject)\n}\n\n// Construct an Environment from the given JSON object.\n// Self-consistent parameters are not set to values given by Init fields.\nfunc EnvironmentFromObject(jsonObject map[string]interface{}) (*Environment, error) {\n\tenv := new(Environment)\n\tenvValue := reflect.Indirect(reflect.ValueOf(env))\n\tfor key, value := range jsonObject {\n\t\tfield := envValue.FieldByName(key)\n\t\tfieldType := field.Type().Name()\n\t\t// Hack to get around Unmarshal treating all numbers as \n\t\t// float64's. Will need to extend this for other types if they \n\t\t// show up in Environment (or come up with a more clever \n\t\t// solution).\n\t\tif fieldType == \"uint\" {\n\t\t\tfield.Set(reflect.ValueOf(uint(value.(float64))))\n\t\t} else if fieldType == \"uint16\" {\n\t\t\tfield.Set(reflect.ValueOf(uint16(value.(float64))))\n\t\t} else if fieldType == \"uint32\" {\n\t\t\tfield.Set(reflect.ValueOf(uint32(value.(float64))))\n\t\t} else if fieldType == \"int8\" {\n\t\t\tfield.Set(reflect.ValueOf(int8(value.(float64))))\n\t\t} else {\n\t\t\tfield.Set(reflect.ValueOf(value))\n\t\t}\n\t}\n\treturn env, nil\n}\n\n// Write the Environment to a JSON file at the given path\nfunc (env *Environment) WriteToFile(filePath string) error {\n\tif err := WriteToJSONFile(env, filePath); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n" }, { "alpha_fraction": 0.5482625365257263, "alphanum_fraction": 0.6023166179656982, "avg_line_length": 16.266666412353516, "blob_id": "36377316890d27fa0cbfb640df6903d3512909e2", "content_id": "2d2e54038ff623fd021ce190cbb821b0d6f68088", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 259, "license_type": "permissive", "max_line_length": 53, "num_lines": 15, "path": "/utility_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestMakeRange(t *testing.T) {\n\trng := MakeRange(0.0, 10.0, 11)\n\tfor i := 0; i < 11; i++ {\n\t\tif math.Abs(rng[i]-float64(i)) > MachEpsFloat64() {\n\t\t\tt.Fatal(\"incorrect range produced, got %v\", rng)\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.6525945663452148, "alphanum_fraction": 0.6824977993965149, "avg_line_length": 24.840909957885742, "blob_id": "177c8379bc27b719ff1b8e066675cc66ea4f837a", "content_id": "93612efd2d6b64effd8d952f9370e5bd63aaf86d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1137, "license_type": "permissive", "max_line_length": 102, "num_lines": 44, "path": "/bisection_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n\t\"testing/quick\"\n)\n\n// Does SolveBisection correctly solve a simple linear function?\nfunc TestLinear(t *testing.T) {\n\tmakeLinear := func(root float64) func(float64) float64 {\n\t\treturn func(x float64) float64 { return root - x }\n\t}\n\tchecker := func(root float64) bool {\n\t\tscale := math.Abs(root)\n\t\tepsilon := scale / 1e-5\n\t\tval, err := SolveBisection(makeLinear(root), root-scale, root+scale, epsilon)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn val == root\n\t}\n\tif !(checker(5) && checker(100) && checker(1e-5)) {\n\t\tt.FailNow()\n\t}\n}\n\n// Does BisectionFullPrecision correctly solve arbitrary simple linear functions to machine precision?\nfunc TestLinearFullPrecision(t *testing.T) {\n\tmakeLinear := func(root float64) func(float64) float64 {\n\t\treturn func(x float64) float64 { return root - x }\n\t}\n\tchecker := func(root float64) bool {\n\t\tscale := math.Abs(root)\n\t\tval, err := BisectionFullPrecision(makeLinear(root), root-scale, root+scale)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn val-root <= MachEpsFloat64()\n\t}\n\tif err := quick.Check(checker, nil); err != nil {\n\t\tt.Error(err)\n\t}\n}\n" }, { "alpha_fraction": 0.598870038986206, "alphanum_fraction": 0.6484619975090027, "avg_line_length": 28.5, "blob_id": "a3d36a1bdf05f12c494a415901e2b9235f051976", "content_id": "32de3f94b209e0f3fd9e307e36d591e4d3cc26e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1593, "license_type": "permissive", "max_line_length": 88, "num_lines": 54, "path": "/integrate_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n// Does the cubic spline integral produce the expected result when \n// interpolating over only 3 points?\nfunc TestCubicSplineIntegral3Points(t *testing.T) {\n\tsomeCubic := makeCubic(1.0, 1.0, 1.0, 1.0)\n\t// constants chosen to have xs be integer values\n\tn := 3 // number of points to interpolate\t\n\tstart, stop := -10.0, 10.0\n\tstep := (stop - start) / float64(n-1)\n\txs, ys := make([]float64, n), make([]float64, n)\n\tfor i, _ := range xs {\n\t\txs[i] = start + float64(i)*step\n\t\tys[i] = someCubic(xs[i])\n\t}\n\txl, xr := -9.0, 1.0\n\tval, err := SplineIntegral(xs, ys, xl, xr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\t// expect spline coefficients as follows:\n\t// a = [0.05 -0.5], b = [0 1.5], c = [86 101], d = [-909 1]\n\tvalKnown := -3747.025\n\t// 1e-15 is somewhat arbitrary\n\t// (couldn't get results to match to better accuracy)\n\tif math.Abs((val-valKnown)/valKnown) > 1e-15 {\n\t\tt.Fatalf(\"failed to reproduce integral (got %f, expected %f)\", val, valKnown)\n\t}\n}\n\n// Does the principal value integral return the correct result for a removable\n// singularity? (simulate this singularity by integrating a constant)\nfunc TestPrincipalValueRemovable(t *testing.T) {\n\tconstant := func(x float64) (float64, error) {\n\t\treturn 1.0, nil\n\t}\n\teps := 1e-9\n\ta, b := 0.0, 5.0\n\tw := (a + b) / 2.0\n\tintegral, err := PvIntegral(constant, a, b, w, eps, uint(256))\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpected := b - a\n\ttolerance := 1e-6\n\tif math.Abs(integral-expected) > tolerance {\n\t\tt.Fatalf(\"pv integral gave incorrect value (got %f, expected %f)\", integral, expected)\n\t}\n}\n" }, { "alpha_fraction": 0.6405797004699707, "alphanum_fraction": 0.6718840599060059, "avg_line_length": 22.310810089111328, "blob_id": "35b3087af10f41832f23c699fde82b91027f79e1", "content_id": "b163c663f9280abd859e4a7caba221f2e591fa14", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1725, "license_type": "permissive", "max_line_length": 77, "num_lines": 74, "path": "/utility.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"encoding/json\"\n\t\"math\"\n\t\"os\"\n\t\"strings\"\n)\n\n// One-dimensional scalar function - used for bisection and bracket\ntype Func1D func(float64) float64\ntype Func1DError func(float64) (float64, error)\n\n// Write Marshal-able object to a new file at filePath\nfunc WriteToJSONFile(object interface{}, filePath string) error {\n\tmarshalled, err := json.Marshal(object)\n\tif err != nil {\n\t\treturn err\n\t}\n\tjsonFile, err := os.Create(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif _, err := jsonFile.Write(marshalled); err != nil {\n\t\treturn err\n\t}\n\tif err := jsonFile.Close(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Machine epsilon (upper bound on error due to rounding) for float64\nfunc MachEpsFloat64() float64 {\n\treturn math.Pow(2.0, -53.0)\n}\n\n// Are x and y within MachEpsFloat64() of one another?\nfunc FuzzyEqual(x, y float64) bool {\n\treturn math.Abs(x-y) < MachEpsFloat64()\n}\n\n// Are x and y within a smallish multiple of MachEpsFloat64() of one another?\nfunc FuzzierEqual(x, y float64) bool {\n\treturn math.Abs(x-y) < (MachEpsFloat64() * 64)\n}\n\n// Convert string to byte slice\nfunc StringToBytes(str string) ([]byte, error) {\n\treader := strings.NewReader(str)\n\tbytes := make([]byte, len(str))\n\tfor seen := 0; seen < len(str); {\n\t\tn, err := reader.Read(bytes)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tseen += n\n\t}\n\treturn bytes, nil\n}\n\n// Make a set of points evenly spaced between left and right (inclusive)\nfunc MakeRange(left, right float64, num uint) []float64 {\n\tstep := (right - left) / float64(num-1)\n\tvals := make([]float64, num)\n\tfor i := 0; i < int(num); i++ {\n\t\tvals[i] = left + float64(i)*step\n\t}\n\treturn vals\n}\n\nfunc plusMinus(x, y float64) (float64, float64) {\n\treturn x + y, x - y\n}\n" }, { "alpha_fraction": 0.6014598608016968, "alphanum_fraction": 0.6437956094741821, "avg_line_length": 26.399999618530273, "blob_id": "6d562d2d2d22f6e4ce756d07b739cc34321396bd", "content_id": "dec62760e5278ce8f11de23216400b6fae973b95", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 685, "license_type": "permissive", "max_line_length": 185, "num_lines": 25, "path": "/environment_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\n// Does Environment correctly convert to and from JSON?\nfunc TestEnvironmentConvert(t *testing.T) {\n\tenvStr := \"{\\\"GridLength\\\":64,\\\"InitD1\\\":0.1,\\\"InitMu\\\":0.1,\\\"InitF0\\\":0.1,\\\"Alpha\\\":-1,\\\"T0\\\":1,\\\"Tz\\\":0.1,\\\"Thp\\\":0.1,\\\"X\\\":0.1,\\\"D1\\\":0.1,\\\"Mu\\\":0.1,\\\"F0\\\":0.1,\\\"EpsilonMin\\\":-1.8}\"\n\texpectedEnv, err := EnvironmentFromString(envStr)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\texpectedEnv.Initialize()\n\tenv, err := EnvironmentFromFile(\"environment_test.json\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tenv.Initialize()\n\tif !reflect.DeepEqual(env, expectedEnv) {\n\t\tprintln(env.String())\n\t\tt.Fatal(\"Environment does not match known value\")\n\t}\n}\n" }, { "alpha_fraction": 0.7198513150215149, "alphanum_fraction": 0.7379925847053528, "avg_line_length": 27.862661361694336, "blob_id": "19cf64a1b035cb962a9b7b247b16f67971804567", "content_id": "f31bc45f55f58b053b918afa9f10981049b2a5ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 6725, "license_type": "permissive", "max_line_length": 104, "num_lines": 233, "path": "/mesh_aggregates.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"math\"\n\n// A function which does calculations based on data passed in on cmesh and returns results through accum\ntype Consumer func(point Vector2) float64\n\n// A type which can absorb grid points and return a result\ntype GridListener interface {\n\tinitialize() GridListener\n\tgrab(point Vector2) GridListener\n\tresult() interface{}\n}\n\n// --- Accumulator ---\n// Collects values passed through grab() to find an average\ntype Accumulator struct {\n\tworker Consumer // function to average\n\tvalue float64 // sum of points seen so far\n\tcompensate float64 // used in Kahan summation to correct floating-point error\n\tpoints uint64 // number of points seen\n}\n\nfunc (accum Accumulator) initialize() GridListener {\n\taccum.value = 0.0\n\taccum.compensate = 0.0\n\taccum.points = 0\n\treturn accum\n}\n\n// Handle new data.\n// Use Kahan summation algorithm to reduce error: implementation cribbed from Wikipedia\nfunc (accum Accumulator) grab(point Vector2) GridListener {\n\tnewValue := accum.worker(point)\n\taccum.value, accum.compensate = KahanSum(newValue, accum.value, accum.compensate)\n\taccum.points += 1\n\treturn accum\n}\n\nfunc KahanSum(extraValue, oldValue, compensate float64) (float64, float64) {\n\ty := extraValue - compensate\n\tnewValue := oldValue + y\n\tnewCompensate := (newValue - oldValue) - y\n\treturn newValue, newCompensate\n}\n\n// Average of points passed in through grab()\nfunc (accum Accumulator) result() interface{} {\n\treturn accum.value / float64(accum.points)\n}\n\n// Create a new accumulator\nfunc NewAccumulator(worker Consumer) *Accumulator {\n\taccum := new(Accumulator)\n\taccum.worker = worker\n\treturn accum\n}\n\n// --- accumulator for minima ---\ntype MinimumData struct {\n\tworker Consumer // function to minimize\n\tminimum float64 // minimum value seen so far\n}\n\nfunc (minData MinimumData) initialize() GridListener {\n\tminData.minimum = math.MaxFloat64\n\treturn minData\n}\n\nfunc (minData MinimumData) grab(point Vector2) GridListener {\n\tnewValue := minData.worker(point)\n\tif newValue < minData.minimum {\n\t\tminData.minimum = newValue\n\t}\n\treturn minData\n}\n\nfunc (minData MinimumData) result() interface{} {\n\treturn minData.minimum\n}\n\nfunc NewMinimumData(worker Consumer) *MinimumData {\n\tminData := new(MinimumData)\n\tminData.worker = worker\n\treturn minData\n}\n\n// --- accumulator for maximua ---\n// it'd be nice to combine this with MaximumData but maybe would lose some\n// speed - most common (?) use case is minimizing epsilon after changing D1\ntype MaximumData struct {\n\tworker Consumer\n\tmaximum float64\n}\n\nfunc (maxData MaximumData) initialize() GridListener {\n\tmaxData.maximum = -math.MaxFloat64\n\treturn maxData\n}\n\nfunc (maxData MaximumData) grab(point Vector2) GridListener {\n\tnewValue := maxData.worker(point)\n\tif newValue > maxData.maximum {\n\t\tmaxData.maximum = newValue\n\t}\n\treturn maxData\n}\n\nfunc (maxData MaximumData) result() interface{} {\n\treturn maxData.maximum\n}\n\nfunc NewMaximumData(worker Consumer) *MaximumData {\n\tmaxData := new(MaximumData)\n\tmaxData.worker = worker\n\treturn maxData\n}\n\n// --- accumulator for (discrete approximation) delta functions ---\n\n// returns pair of slices of bin variable values and their associciated \n// coefficients which are affected at the given point\n// (for Gc0, bin variable is omega)\ntype DeltaTermsFunc func(point Vector2) ([]float64, []float64)\n\ntype DeltaBinner struct {\n\tdeltaTerms DeltaTermsFunc\n\tbinStart, binStop float64\n\tnumBins uint\n\tbins []float64 // value of the function at various omega values\n\tcompensates []float64 // compensation values for Kahan summation\n\tnumPoints uint64\n}\n\nfunc (binner DeltaBinner) initialize() GridListener {\n\tbinner.numPoints = 0\n\tfor i, _ := range binner.bins {\n\t\tbinner.bins[i] = 0.0\n\t\tbinner.compensates[i] = 0.0\n\t}\n\treturn binner\n}\n\nfunc (binner DeltaBinner) grab(point Vector2) GridListener {\n\tomegas, coeffs := binner.deltaTerms(point)\n\tfor i, omega := range omegas {\n\t\tn := binner.BinVarToIndex(omega)\n\t\tbinner.bins[n], binner.compensates[n] = KahanSum(coeffs[i], binner.bins[n], binner.compensates[n])\n\t}\n\tbinner.numPoints += 1\n\treturn binner\n}\n\nfunc (binner DeltaBinner) result() interface{} {\n\tresult := make([]float64, binner.numBins)\n\tfor i, val := range binner.bins {\n\t\tresult[i] = val / float64(binner.numPoints)\n\t}\n\treturn result\n}\n\nfunc (binner DeltaBinner) Step() float64 {\n\treturn math.Abs(binner.binStop-binner.binStart) / float64(binner.numBins)\n}\n\nfunc (binner DeltaBinner) BinVarToIndex(binVar float64) int {\n\ti := int(math.Floor((binVar - binner.binStart) / binner.Step()))\n\tif uint(i) == binner.numBins && FuzzierEqual(binVar, binner.binStop) {\n\t\treturn i - 1\n\t}\n\tif i == -1 && FuzzierEqual(binVar, binner.binStart) {\n\t\treturn 0\n\t}\n\treturn i\n}\n\nfunc (binner DeltaBinner) IndexToBinVar(index int) float64 {\n\treturn binner.binStart + binner.Step()*float64(index)\n}\n\nfunc (binner DeltaBinner) BinVarValues() []float64 {\n\tvalues := make([]float64, binner.numBins)\n\tfor i, _ := range values {\n\t\tvalues[i] = binner.IndexToBinVar(i)\n\t}\n\treturn values\n}\n\nfunc NewDeltaBinner(deltaTerms DeltaTermsFunc, binStart, binStop float64, numBins uint) *DeltaBinner {\n\tif binStart > binStop {\n\t\tbinStart, binStop = binStop, binStart\n\t}\n\tbins, compensates := make([]float64, numBins), make([]float64, numBins)\n\tbinner := &DeltaBinner{deltaTerms, binStart, binStop, numBins, bins, compensates, 0}\n\treturn binner\n}\n\n// -- utility functions --\nfunc DoGridListen(pointsPerSide uint32, listener GridListener) interface{} {\n\tlistener = listener.initialize()\n\tsqrtN := uint64(pointsPerSide)\n\tN := sqrtN * sqrtN\n\tfor i := uint64(0); i < N; i++ {\n\t\tlistener = listener.grab(SquareAt(i, pointsPerSide))\n\t}\n\treturn listener.result()\n}\n\n// Find the average over a square grid of the function given by worker.\n// Spawn number of goroutines given by numWorkers.\n// pointsPerSide is uint32 so that accum.points will fit in a uint64.\n// numWorkers is uint16 to avoid spawning a ridiculous number of processes.\n// Consumer is defined in utility.go\nfunc Average(pointsPerSide uint32, worker Consumer) float64 {\n\taccum := NewAccumulator(worker)\n\treturn DoGridListen(pointsPerSide, *accum).(float64)\n}\n\nfunc Minimum(pointsPerSide uint32, worker Consumer) float64 {\n\tminData := NewMinimumData(worker)\n\treturn DoGridListen(pointsPerSide, *minData).(float64)\n}\n\nfunc Maximum(pointsPerSide uint32, worker Consumer) float64 {\n\tmaxData := NewMaximumData(worker)\n\treturn DoGridListen(pointsPerSide, *maxData).(float64)\n}\n\n// Instead of taking a worker directly, this functions takes a *DeltaBinner\n// (to avoid passing in all the params for DeltaBinner)\nfunc DeltaBin(pointsPerSide uint32, deltaTerms *DeltaBinner) []float64 {\n\treturn DoGridListen(pointsPerSide, deltaTerms).([]float64)\n}\n" }, { "alpha_fraction": 0.6426264643669128, "alphanum_fraction": 0.6776103377342224, "avg_line_length": 25.16901397705078, "blob_id": "15acd2d6bae0fc6e9b2acd5202d70f03b47429ef", "content_id": "bc5cdbe2d7556858af4436a9dd662a763ae61c80", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 1858, "license_type": "permissive", "max_line_length": 91, "num_lines": 71, "path": "/selfconsistent_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\ntype LinearEquation struct {\n\troot float64\n\tmyVar string\n}\n\nfunc (eq LinearEquation) AbsError(args interface{}) float64 {\n\tvars := args.(map[string]float64)\n\treturn eq.root - vars[eq.myVar]\n}\n\nfunc (eq LinearEquation) SetArguments(x float64, args interface{}) interface{} {\n\tvars := (args).(map[string]float64)\n\tvars[eq.myVar] = x\n\treturn vars\n}\n\nfunc (eq LinearEquation) Range(args interface{}) (float64, float64, error) {\n\treturn eq.root - 2*eq.root, eq.root + 2*eq.root, nil\n}\n\n// Does Solve() correctly find the root of a linear equation?\nfunc TestSolve(t *testing.T) {\n\troot := 10.0\n\teq := LinearEquation{root, \"uno\"}\n\tguess := make(map[string]float64)\n\tguess[\"uno\"] = 0.0\n\tsolution, err := Solve(eq, guess)\n\tif err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\tif solution == nil {\n\t\tt.Fatalf(\"got nil solution\")\n\t}\n\tvals := solution.(map[string]float64)\n\tif math.Abs(vals[\"uno\"]-root) > MachEpsFloat64() {\n\t\tt.Fatalf(\"solution not found to expected precision\")\n\t}\n}\n\n// Does SelfConsistentSystem.Solve() correctly solve a system of non-coupled\n// linear equations?\nfunc TestSystemSolve(t *testing.T) {\n\troot1, root2 := 10.0, 20.0\n\teq1, eq2 := LinearEquation{root1, \"uno\"}, LinearEquation{root2, \"dos\"}\n\ttol1, tol2 := 1e-9, 1e-9\n\tsystem := &SelfConsistentSystem{[]SelfConsistentEquation{eq1, eq2}, []float64{tol1, tol2}}\n\targs := make(map[string]float64)\n\targs[\"uno\"] = 0.0\n\targs[\"dos\"] = 0.0\n\tsolution, err := system.Solve(args)\n\tif err != nil {\n\t\tt.Fatalf(\"error: %s\", err)\n\t}\n\tif solution == nil {\n\t\tt.Fatalf(\"got nil solution\")\n\t}\n\tvals := solution.(map[string]float64)\n\tif math.Abs(vals[\"uno\"]-root1) > MachEpsFloat64() {\n\t\tt.Fatalf(\"solution uno not found to expected precision\")\n\t}\n\tif math.Abs(vals[\"dos\"]-root2) > MachEpsFloat64() {\n\t\tt.Fatalf(\"solution dos not found to expected precision\")\n\t}\n}\n" }, { "alpha_fraction": 0.6844155788421631, "alphanum_fraction": 0.7103896141052246, "avg_line_length": 27.518518447875977, "blob_id": "ce9658a5e157a578c0b2989515f85c1d144e136e", "content_id": "e46e98676d94830bfb86bff3d2259513f40a4d3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 770, "license_type": "permissive", "max_line_length": 72, "num_lines": 27, "path": "/spectrum.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport \"math\"\n\n// Single-hole hopping energy. Minimum must be 0.\nfunc Epsilon(env Environment, k Vector2) float64 {\n\treturn EpsilonBar(env, k) - env.EpsilonMin\n}\n\n// Single-hole hopping energy without fixed minimum.\nfunc EpsilonBar(env Environment, k Vector2) float64 {\n\tsx, sy := math.Sin(k.X), math.Sin(k.Y)\n\treturn 2*env.Th()*((sx+sy)*(sx+sy)-1) + 4*(env.D1*env.T0-env.Thp)*sx*sy\n}\n\n// Find the minimum of EpsilonBar() to help in calculating Epsilon()\nfunc EpsilonMin(env Environment) float64 {\n\tworker := func(k Vector2) float64 {\n\t\treturn EpsilonBar(env, k)\n\t}\n\treturn Minimum(env.GridLength, worker)\n}\n\n// Effective hopping energy (epsilon - mu). Minimum is -mu.\nfunc Xi(env Environment, k Vector2) float64 {\n\treturn Epsilon(env, k) - env.Mu\n}\n" }, { "alpha_fraction": 0.7171671986579895, "alphanum_fraction": 0.720753014087677, "avg_line_length": 27.97402572631836, "blob_id": "3db2b6951c5eb5f7bb48e6029b5d998d1a0f681d", "content_id": "73931dd3e8f20545f6b702ea1b9127fab79bf530", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 2231, "license_type": "permissive", "max_line_length": 87, "num_lines": 77, "path": "/mpljson.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"encoding/json\"\n\t\"os\"\n\t\"os/exec\"\n)\n\nconst SERIES_KEY = \"series\"\nconst DATA_KEY = \"data\"\n\n// A map compatible with the JSON Object type\ntype jsonObject map[string]interface{}\n\n// Intermediate representation for graph data.\ntype Graph struct {\n\tgraphParameters map[string]interface{}\n\tseriesParameters []map[string]string\n\tseriesData [][][]float64\n}\n\nfunc NewGraph() *Graph {\n\tgraph := new(Graph)\n\tgraph.graphParameters = make(map[string]interface{})\n\tgraph.seriesParameters = make([]map[string]string, 0)\n\tgraph.seriesData = make([][][]float64, 0)\n\treturn graph\n}\n\n// Set the global graph parameters as given in params.\nfunc (graph *Graph) SetGraphParameters(params map[string]interface{}) {\n\tfor key, value := range params {\n\t\tgraph.graphParameters[key] = value\n\t}\n}\n\n// Add a new data series to the graph.\nfunc (graph *Graph) AddSeries(params map[string]string, data [][]float64) {\n\tgraph.seriesParameters = append(graph.seriesParameters, params)\n\tgraph.seriesData = append(graph.seriesData, data)\n}\n\n// Implements interface json.Marshaler\nfunc (graph *Graph) MarshalJSON() ([]byte, error) {\n\tjsonGraph := jsonObject{}\n\t// add global graph parameters\n\tfor key, value := range graph.graphParameters {\n\t\tjsonGraph[key] = value\n\t}\n\t// add parameters and data for each series\n\tjsonGraph[SERIES_KEY] = []jsonObject{}\n\tfor i, someSeriesParams := range graph.seriesParameters {\n\t\tnewSeriesParams := jsonObject{}\n\t\tfor key, value := range someSeriesParams {\n\t\t\tnewSeriesParams[key] = value\n\t\t}\n\t\tnewSeriesParams[DATA_KEY] = graph.seriesData[i]\n\t\tjsonGraph[SERIES_KEY] = append(jsonGraph[SERIES_KEY].([]jsonObject), newSeriesParams)\n\t}\n\tmarshalled, err := json.Marshal(jsonGraph)\n\treturn marshalled, err\n}\n\n// Constructs a plot from graph_data using matplotlib.\n// graph_data must be a list or dictionary containing objects representable\n// in JSON. Blocks until Python script is finished.\nfunc MakePlot(graphData interface{}, jsonFilePath string) error {\n\tif err := WriteToJSONFile(graphData, jsonFilePath); err != nil {\n\t\treturn err\n\t}\n\twd, _ := os.Getwd()\n\tcmd := exec.Command(\"/usr/bin/env\", \"python\", wd+\"/grapher.py\", jsonFilePath)\n\tif err := cmd.Run(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n" }, { "alpha_fraction": 0.6326276659965515, "alphanum_fraction": 0.6438356041908264, "avg_line_length": 19.075000762939453, "blob_id": "019be385ae1390934f24b64f8fa5011141943eaa", "content_id": "4bce63540d0945add3ac27fcaf86b4d43e07293a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 803, "license_type": "permissive", "max_line_length": 58, "num_lines": 40, "path": "/vector_cache.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\ntype VectorCache map[float64]map[float64]interface{}\n\nfunc NewVectorCache() *VectorCache {\n\tc := make(VectorCache)\n\treturn &c\n}\n\nfunc (c *VectorCache) Contains(k Vector2) bool {\n\tcacheX, ok := (*c)[k.X]\n\tif !ok {\n\t\treturn false\n\t}\n\t_, ok = cacheX[k.Y]\n\treturn ok\n}\n\nfunc (c *VectorCache) Get(k Vector2) (interface{}, bool) {\n\tcacheX, ok := (*c)[k.X]\n\tif !ok {\n\t\t// considering returning cacheX here instead of nil\n\t\t// Q: what would cacheX be in this case?\n\t\treturn nil, false\n\t}\n\tcachedObj, ok := cacheX[k.Y]\n\treturn cachedObj, ok\n}\n\nfunc (c *VectorCache) Set(k Vector2, obj interface{}) {\n\txCache, ok := (*c)[k.X]\n\tif !ok {\n\t\t// need to create cache for this x\n\t\tnewCache := make(map[float64]interface{})\n\t\tnewCache[k.Y] = obj\n\t\t(*c)[k.X] = newCache\n\t\treturn\n\t}\n\txCache[k.Y] = obj\n}\n" }, { "alpha_fraction": 0.5812917351722717, "alphanum_fraction": 0.6302895545959473, "avg_line_length": 19.409090042114258, "blob_id": "c5fb3d590721c37707d682c4936a337fa0f6e29a", "content_id": "4e599649d271a89381116d6588b21ec87e8e049b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 449, "license_type": "permissive", "max_line_length": 68, "num_lines": 22, "path": "/principalvalue_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\nfunc TestPrincipalValueGSLConstant(t *testing.T) {\n\tconstant := func(x float64) float64 {\n\t\treturn 1.0\n\t}\n\tepsabs := 1e-9\n\tepsrel := 1e-9\n\tlimit := uint16(2048)\n\ta, b := 0.0, 5.0\n\tc := (a + b) / 2.0\n\tintegral := PvIntegralGSL(constant, a, b, c, epsabs, epsrel, limit)\n\texpected := math.Log(math.Abs((b - c) / (a - c)))\n\tif math.Abs(integral-expected) > epsabs {\n\t\tt.Fatalf(\"tolerance exceeded\")\n\t}\n}\n" }, { "alpha_fraction": 0.5890207886695862, "alphanum_fraction": 0.6335311532020569, "avg_line_length": 32.70000076293945, "blob_id": "3a83f9b136030fe8708a8a29b815edaf72277f00", "content_id": "5fc12244ef4eebe78d0f5c843b117e9cf2dddc35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 674, "license_type": "permissive", "max_line_length": 163, "num_lines": 20, "path": "/mesh2d_test.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"math\"\n\t\"testing\"\n)\n\n// Does SquareAt produce the expected points?\nfunc TestSquareAtKnown(t *testing.T) {\n\tL, L64 := uint32(32), uint64(32) // points per side\n\tstep := 2 * math.Pi / float64(L)\n\tpoints := []Vector2{SquareAt(0, L), SquareAt(L64-1, L), SquareAt(L64, L), SquareAt(L64*L64-1, L)}\n\texpected := []Vector2{Vector2{-math.Pi, -math.Pi}, Vector2{math.Pi - step, -math.Pi}, Vector2{-math.Pi, -math.Pi + step}, Vector2{math.Pi - step, math.Pi - step}}\n\tfor i, p := range points {\n\t\te := expected[i]\n\t\tif !FuzzyEqual(p.X, e.X) || !FuzzyEqual(p.Y, e.Y) {\n\t\t\tt.Fatalf(\"square point %d is not as expected (got %v, expected %v\", i, p, e)\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.6751806139945984, "alphanum_fraction": 0.6904024481773376, "avg_line_length": 29.519685745239258, "blob_id": "173e50f1dafc476f5743605421bafda32c355a2e", "content_id": "5222bd126bacc7f9d13e8ed09b90e516a3e7e59e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 3876, "license_type": "permissive", "max_line_length": 119, "num_lines": 127, "path": "/zerotemp_plots.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nfunc ZeroTempPlotGc(env Environment, k Vector2, numOmega uint, outputPath string) error {\n\timOmegas, imCalcValues := ZeroTempImGc0(env, k)\n\timSpline, err := NewCubicSpline(imOmegas, imCalcValues)\n\tif err != nil {\n\t\treturn err\n\t}\n\timOmegaMin, imOmegaMax := imSpline.Range()\n\tomegas := MakeRange(imOmegaMin-1.0, imOmegaMax+1.0, numOmega)\n\trealValues := make([]float64, numOmega)\n\timValues := make([]float64, numOmega)\n\tfullReValues := make([]float64, numOmega)\n\tfor i := 0; i < int(numOmega); i++ {\n\t\tif omegas[i] < imOmegaMin || omegas[i] > imOmegaMax {\n\t\t\timValues[i] = 0.0\n\t\t} else {\n\t\t\tim, err := imSpline.At(omegas[i])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\timValues[i] = im\n\t\t}\n\t\tre, err := ZeroTempReGc0(env, k, omegas[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\trealValues[i] = re\n\t\tfullRe, err := FullReGc(env, k, omegas[i])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfullReValues[i] = fullRe\n\t}\n\treGraph := NewGraph()\n\timGraph := NewGraph()\n\tfullReGraph := NewGraph()\n\trePath := outputPath + \"_re\"\n\timPath := outputPath + \"_im\"\n\tfullRePath := outputPath + \"_fullRe\"\n\treGraph.SetGraphParameters(map[string]interface{}{\"graph_filepath\": rePath})\n\timGraph.SetGraphParameters(map[string]interface{}{\"graph_filepath\": imPath})\n\tfullReGraph.SetGraphParameters(map[string]interface{}{\"graph_filepath\": fullRePath})\n\treData := make([][]float64, len(omegas))\n\timData := make([][]float64, len(omegas))\n\tfullReData := make([][]float64, len(omegas))\n\tfor i, _ := range reData {\n\t\treData[i] = []float64{omegas[i], realValues[i]}\n\t\timData[i] = []float64{omegas[i], imValues[i]}\n\t\tif !math.IsNaN(fullReValues[i]) {\n\t\t\tfullReData[i] = []float64{omegas[i], fullReValues[i]}\n\t\t} else {\n\t\t\tfullReData[i] = []float64{omegas[i], 0.0}\n\t\t}\n\t}\n\treGraph.AddSeries(map[string]string{\"label\": \"re_gc0\"}, reData)\n\timGraph.AddSeries(map[string]string{\"label\": \"im_gc0\"}, imData)\n\tfullReGraph.AddSeries(map[string]string{\"label\": \"fullRe_gc0\"}, fullReData)\n\terr = MakePlot(reGraph, rePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = MakePlot(imGraph, imPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = MakePlot(fullReGraph, fullRePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// Plot im/re gc0 and re gc along lines of high symmetry in k space.\nfunc PlotGcSymmetryLines(env Environment, kPoints, numOmega uint, outputPath string) error {\n\tcallback := func(k Vector2) error {\n\t\textra := fmt.Sprintf(\"_kx_%f_ky_%f\", k.X, k.Y)\n\t\tfullPath := outputPath + extra\n\t\terr := ZeroTempPlotGc(env, k, numOmega, fullPath)\n\t\treturn err\n\t}\n\terr := CallOnSymmetryLines(kPoints, callback)\n\treturn err\n}\n\n// Plot the existence of poles throughout the k plane.\nfunc ZeroTempPlotPolePlane(env Environment, outputPath string, sideLength uint32) error {\n\tpolePlane, err := ZeroTempGreenPolePlane(env, sideLength, true)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgraphPoleData(polePlane, outputPath, &Vector2{32.0, 32.0})\n\treturn nil\n}\n\n// Plot the line of poles specified by poleCurve, which takes a float value from\n// 0 to 1 and returns a Vector2 corresponding to that value\nfunc ZeroTempPlotPoleCurve(env Environment, poleCurve func(float64) Vector2, numPoints uint, outputPath string) error {\n\tpolePoints, err := ZeroTempGreenPoleCurve(env, poleCurve, numPoints)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgraphPoleData(polePoints, outputPath, nil)\n\treturn nil\n}\n\nfunc graphPoleData(poles []GreenPole, outputPath string, dims *Vector2) {\n\tpoleData := [][]float64{}\n\tfor _, gp := range poles {\n\t\tk := gp.K\n\t\tpoleData = append(poleData, []float64{k.X, k.Y})\n\t}\n\tpoleGraph := NewGraph()\n\tparams := make(map[string]interface{})\n\tif dims != nil {\n\t\tparams[\"dimensions\"] = []float64{dims.X, dims.Y}\n\t}\n\tparams[\"graph_filepath\"] = outputPath\n\tpoleGraph.SetGraphParameters(params)\n\tpoleGraph.AddSeries(map[string]string{\"label\": \"poles\", \"style\": \"k.\"}, poleData)\n\tMakePlot(poleGraph, outputPath)\n}\n" }, { "alpha_fraction": 0.6585517525672913, "alphanum_fraction": 0.6820271015167236, "avg_line_length": 28.490842819213867, "blob_id": "cca9d52a49c50d38c99d9376da69a3e4a204625d", "content_id": "c90bfccd2623ca4e4431ec1b9e958752e805aa0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Go", "length_bytes": 8051, "license_type": "permissive", "max_line_length": 143, "num_lines": 273, "path": "/zerotemp_greens.go", "repo_name": "tflovorn/polecalc", "src_encoding": "UTF-8", "text": "package polecalc\n\nimport (\n\t\"fmt\"\n\t\"math\"\n)\n\nvar imGc0Cache = NewListCache()\n\n// --- noninteracting Green's function for the physical electron ---\n\n// -- imaginary part of noninteracting Green's function --\nfunc deltaTermsGc0(env Environment, k Vector2, q Vector2) ([]float64, []float64) {\n\tomega_q := ZeroTempOmega(env, q)\n\tE_h := ZeroTempPairEnergy(env, q.Sub(k))\n\tlambda_p, lambda_m := plusMinus(1, env.Lambda()/omega_q)\n\t// 0 in f_p & f_m is really bose function of omega_q = ZeroTempOmega(q)\n\t// since omega_q > 0 and mu < 0, bose function result is 0\n\tf_p, f_m := plusMinus(0, ZeroTempFermi(E_h))\n\tif env.Superconducting {\n\t\tc := -0.25 * math.Pi\n\t\txi := Xi(env, q.Sub(k))\n\t\txi_p, xi_m := plusMinus(1, xi/E_h)\n\t\tomegas := []float64{omega_q - E_h, omega_q + E_h, -omega_q - E_h, -omega_q + E_h}\n\n\t\tcoeffs := []float64{c * lambda_p * xi_p * f_p, c * lambda_p * xi_m * (f_m + 1), -c * lambda_m * xi_p * (f_m + 1), -c * lambda_m * xi_m * f_p}\n\t\treturn omegas, coeffs\n\t}\n\t// non-superconducting if we get here\n\tc := -0.5 * math.Pi\n\tomegas := []float64{omega_q - E_h, -omega_q - E_h}\n\tcoeffs := []float64{c * lambda_p * f_p, -c * lambda_m * (f_m + 1)}\n\treturn omegas, coeffs\n}\n\n// values for all omega are calculated simultaneously, so return two slices of \n// floats. first is omega values, second is coefficients\nfunc ZeroTempImGc0(env Environment, k Vector2) ([]float64, []float64) {\n\tvar omegaMin, omegaMax float64\n\tif env.Superconducting {\n\t\tpairWorker := func(q Vector2) float64 {\n\t\t\treturn ZeroTempPairEnergy(env, q.Sub(k))\n\t\t}\n\t\tpairEnergyMax := Maximum(env.GridLength, pairWorker)\n\t\tmaxAbsOmega := env.Lambda() + pairEnergyMax\n\t\tomegaMin, omegaMax = -maxAbsOmega-1.0, maxAbsOmega+1.0\n\t} else {\n\t\txiWorker := func(q Vector2) float64 {\n\t\t\treturn Xi(env, q.Sub(k))\n\t\t}\n\t\txiMax := Maximum(env.GridLength, xiWorker)\n\t\tmaxAbsOmega := env.Lambda() + xiMax\n\t\tomegaMin, omegaMax = -maxAbsOmega-1.0, maxAbsOmega+1.0\n\t}\n\tdeltaTerms := func(q Vector2) ([]float64, []float64) {\n\t\treturn deltaTermsGc0(env, k, q)\n\t}\n\tbinner := NewDeltaBinner(deltaTerms, omegaMin, omegaMax, env.ImGc0Bins)\n\tresult := DeltaBin(env.GridLength, binner)\n\tomegas := binner.BinVarValues()\n\treturn omegas, result\n}\n\nfunc cachedImGc0(env Environment, k Vector2) (*CubicSpline, bool) {\n\tkCacheInterface, ok := imGc0Cache.Get(env)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\tkCache := kCacheInterface.(VectorCache)\n\tspline, ok := kCache.Get(k)\n\tif ok {\n\t\treturn spline.(*CubicSpline), ok\n\t}\n\treturn nil, ok\n}\n\nfunc addToCacheImGc0(env Environment, k Vector2, spl *CubicSpline) {\n\tif !imGc0Cache.Contains(env) {\n\t\t// env not encountered yet\n\t\tkCache := *NewVectorCache()\n\t\tkCache.Set(k, spl)\n\t\timGc0Cache.Set(env, kCache)\n\t} else {\n\t\tkCacheInterface, _ := imGc0Cache.Get(env)\n\t\tkCache := kCacheInterface.(VectorCache)\n\t\tkCache.Set(k, spl)\n\t}\n}\n\nfunc getFromCacheImGc0(env Environment, k Vector2) (*CubicSpline, error) {\n\tvar imPart *CubicSpline\n\tif cache, ok := cachedImGc0(env, k); ok {\n\t\timPart = cache\n\t} else {\n\t\tvar err error\n\t\timPartOmegaVals, imPartFuncVals := ZeroTempImGc0(env, k)\n\t\timPart, err = NewCubicSpline(imPartOmegaVals, imPartFuncVals)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\taddToCacheImGc0(env, k, imPart)\n\t}\n\treturn imPart, nil\n}\n\n// implementing this the lazy way for now by interpolating ImGc0(k)\n// could also calculate ImGc0(k,omega) directly\nfunc ZeroTempImGc0Point(env Environment, k Vector2, omega float64) (float64, error) {\n\timPart, err := getFromCacheImGc0(env, k)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\tomegaMin, omegaMax := imPart.Range()\n\tif omegaMin <= omega && omega <= omegaMax {\n\t\treturn imPart.At(omega)\n\t}\n\treturn 0.0, nil\n}\n\n// -- real part of noninteracting Green's function --\nfunc ZeroTempReGc0(env Environment, k Vector2, omega float64) (float64, error) {\n\timPart, err := getFromCacheImGc0(env, k)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\tomegaMin, omegaMax := imPart.Range()\n\t// assume that Im(Gc0) is smooth near omegaPrime, so that spline\n\t// interpolation is good enough\n\tintegrand := func(omegaPrime float64) (float64, error) {\n\t\tif omegaMin <= omega && omega <= omegaMax {\n\t\t\tim, err := imPart.At(omegaPrime)\n\t\t\tif err != nil {\n\t\t\t\treturn 0.0, err\n\t\t\t}\n\t\t\treturn (1 / math.Pi) * im / (omegaPrime - omega), nil\n\t\t}\n\t\treturn 0.0, nil\n\t}\n\tintegral, err := PvIntegral(integrand, omegaMin, omegaMax, omega, env.ReGc0dw, env.ReGc0Points)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\treturn integral, nil\n}\n\n// --- full Green's function poles ---\n// find solutions to Re[1/Gc0(k,omega)] - ElectronEnergy(k) = 0\n// ==> ((ReGc0)^2 + (ImGc0)^2)*ElectronEnergy - ReGc0 = 0\n\ntype ZeroTempGreenPoleEq struct {\n\tK Vector2\n}\n\ntype ZeroTempGreenArgs struct {\n\tEnv Environment\n\tOmega float64\n}\n\nfunc (eq ZeroTempGreenPoleEq) AbsError(args interface{}) float64 {\n\tgreenArgs := args.(ZeroTempGreenArgs)\n\tenv, omega := greenArgs.Env, greenArgs.Omega\n\tReGc0, err := ZeroTempReGc0(env, eq.K, omega)\n\tif err != nil {\n\t\tpanic(\"error encountered searching for ReGc0: \" + err.Error())\n\t}\n\t/*\n\t\tImGc0, err := ZeroTempImGc0Point(env, eq.K, omega)\n\t\tif err != nil {\n\t\t\tpanic(\"error encountered searching for ImGc0: \" + err.String())\n\t\t}\n\t*/\n\tepsilon_k := ZeroTempElectronEnergy(env, eq.K)\n\t//return (ReGc0*ReGc0+ImGc0*ImGc0)*epsilon_k - ReGc0\n\treturn 1.0 - epsilon_k*ReGc0\n}\n\nfunc (eq ZeroTempGreenPoleEq) SetArguments(omega float64, args interface{}) interface{} {\n\tenv := args.(ZeroTempGreenArgs).Env\n\treturn ZeroTempGreenArgs{env, omega}\n}\n\nfunc (eq ZeroTempGreenPoleEq) Range(args interface{}) (float64, float64, error) {\n\tenv := args.(ZeroTempGreenArgs).Env\n\treturn -10.0 * env.T, 10.0 * env.T, nil\n}\n\n// return all pole omegas at a given k\nfunc ZeroTempGreenPolePoint(env Environment, k Vector2) ([]float64, error) {\n\t// find brackets for all the poles\n\t// lazy for now - only look at one solution\n\teq := ZeroTempGreenPoleEq{k}\n\tinitArgs := ZeroTempGreenArgs{env, 0.0}\n\tsolvedArgs, err := MultiSolve(eq, initArgs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsolutions := []float64{}\n\tfor _, args := range solvedArgs {\n\t\tomega := args.(ZeroTempGreenArgs).Omega\n\t\tsolutions = append(solutions, omega)\n\t}\n\treturn solutions, nil\n}\n\n// real part of the full Green's function\nfunc FullReGc(env Environment, k Vector2, omega float64) (float64, error) {\n\tReGc0, err := ZeroTempReGc0(env, k, omega)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\tImGc0, err := ZeroTempImGc0Point(env, k, omega)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\tmag := ReGc0*ReGc0 + ImGc0*ImGc0\n\tepsilon_k := ZeroTempElectronEnergy(env, k)\n\tnumer := mag * (ReGc0 - mag*epsilon_k)\n\tdenom := math.Pow(ReGc0-mag*epsilon_k, 2.0) + ImGc0*ImGc0\n\treturn numer / denom, nil\n}\n\n// --- plotting helper functions ---\n\ntype GreenPole struct {\n\tK Vector2\n\tOmega float64\n}\n\nfunc (gp GreenPole) String() string {\n\treturn fmt.Sprintf(\"k: %v; omega: %f\", gp.K, gp.Omega)\n}\n\nfunc capturePoles(env Environment, k Vector2, poles []GreenPole) ([]GreenPole, error) {\n\tkPoles, err := ZeroTempGreenPolePoint(env, k)\n\tif err != nil {\n\t\tif err.Error() == ErrorNoBracket {\n\t\t\tprintln(\"bracket error at k = \", k.String())\n\t\t\treturn poles, nil\n\t\t}\n\t\treturn poles, err\n\t} else {\n\t\tfor _, p := range kPoles {\n\t\t\tprintln(\"got pole k=\", k.String(), p)\n\t\t\tpoles = append(poles, GreenPole{k, p})\n\t\t}\n\t}\n\treturn poles, err\n}\n\n// scan the k space looking for poles; return all those found\nfunc ZeroTempGreenPolePlane(env Environment, pointsPerSide uint32, minimal bool) ([]GreenPole, error) {\n\tpoles := []GreenPole{}\n\tcallback := func(k Vector2) error {\n\t\tvar err error\n\t\tpoles, err = capturePoles(env, k, poles)\n\t\treturn err\n\t}\n\terr := CallOnThirdQuad(pointsPerSide, callback)\n\treturn poles, err\n}\n\n// Scan k values given along poleCurve, which takes a value from 0 to 1 and \n// returns a vector in k space. Return all poles found.\nfunc ZeroTempGreenPoleCurve(env Environment, poleCurve CurveGenerator, numPoints uint) ([]GreenPole, error) {\n\tpoles := []GreenPole{}\n\tcallback := func(k Vector2) error {\n\t\tvar err error\n\t\tpoles, err = capturePoles(env, k, poles)\n\t\treturn err\n\t}\n\terr := CallOnCurve(poleCurve, numPoints, callback)\n\treturn poles, err\n}\n" } ]
37
kandreb/batch9
https://github.com/kandreb/batch9
52280f1fbd0f14bed92bb4baf693c1d04bdebe0e
f5b4ccf6811482e98f61b3b19d6e6e5c3996421f
8ca5524b07d57261d4ae14e78a9959dd3b4be99c
refs/heads/master
2020-03-28T07:56:19.175260
2018-09-08T13:15:07
2018-09-08T13:15:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7142857313156128, "alphanum_fraction": 0.7857142686843872, "avg_line_length": 13, "blob_id": "8994da0bb2885b211220b59d8df2c64779b756d0", "content_id": "7005180dac8d36882be881ed172f0a324ae4625b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 28, "license_type": "no_license", "max_line_length": 18, "num_lines": 2, "path": "/README.md", "repo_name": "kandreb/batch9", "src_encoding": "UTF-8", "text": "# batch9\nProject for batch9\n" }, { "alpha_fraction": 0.7179487347602844, "alphanum_fraction": 0.7179487347602844, "avg_line_length": 18.5, "blob_id": "114eeb550e309a77e4bbd198cdad371644b1218d", "content_id": "ddcc27ecfebdd719b528d9d5e322d734447e9da1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 39, "license_type": "no_license", "max_line_length": 19, "num_lines": 2, "path": "/my_test_code.py", "repo_name": "kandreb/batch9", "src_encoding": "UTF-8", "text": "print \"Hello World\"\nprint \"A new line\"\n" } ]
2
winterconnect/Web_Programming
https://github.com/winterconnect/Web_Programming
2f6372a93d759a62a50355e78815012299287d09
e80c507f747594286ed3e8241524f483e1dfc168
7851acda56cb35b24b337da5466081c9f27c59a6
refs/heads/master
2023-02-28T12:38:38.740598
2021-02-05T03:20:48
2021-02-05T03:20:48
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5703319311141968, "alphanum_fraction": 0.5834025144577026, "avg_line_length": 12.525280952453613, "blob_id": "2117853d5fea961f0aa7f96d6f2fd26d50f33a51", "content_id": "920a8e88a3887ea71599b5fc65473185749b0b91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5764, "license_type": "no_license", "max_line_length": 386, "num_lines": 356, "path": "/html/HTML.md", "repo_name": "winterconnect/Web_Programming", "src_encoding": "UTF-8", "text": "# HTML\n\n- 가장 기본\n- 인터넷으로 데이터를 주고받을 때 사용하는 용어\n- 데이터베이스에서 SQL을 쓰는 것처럼 웹페이지에서는 HTML을 쓴다\n- 정적인 방법 / 동적인 방법\n- 동적인 방법 예: 로그인을 하면 보는 창이 달라짐\n\n\n\n- html은 index.html 이라는 메인 페이지에서 시작된다\n- 링크로 연결된다\n- 인터넷이라는 것은, html 페이지가 묶여 연결되어 있는 것이다!\n\n\n\n\n\n\n\n__\\<! >__: 주석\n\n\n\n__HTML의 기본구성__\n\n- 구글의 개발자도구를 잘 활용하자\n\n```html\n<!DOCTYPE html>\n\n<html>\n\n\t<head>\n <title>WEB1 - HTML</title>\n \t<meta charset =\"UTF-8\">\n </head>\n \n\t<body>\n\t <div>\n\t <ol>\n\t <li>cloud</li>\n\t <li>IoT</li>\n\t <li>Bigdata</li>\n\t </ol>\n\t </div>\n </body>\n</html>\n\n\n<table>\n <tr>\n\t <td>head</td>\n\t <td>98.1%</td>\n </tr>\n <tr>\n \t<td>BODY</td>\n \t<td>97.9%</td>\n </tr>\n</table>\n```\n\n\n\n\n\n__만약 이것을 파이썬으로 구현한다면? (웹크롤링)__\n\n- url request 를 보내고, html 로 response(index.html)를 받음. html 파일을 받아서 필요한 값들이 있는 부분을 확인(찾기 기능 활용)하여 추출함\n- 태그를 찾아서 내용을 추출\n\n\n\n\n\n\n\n- HTML만 쓰다보니 여러가지 불편한 점들이 생김(디자인 등)\n\n\n\n### HTML의 기본 구성요소\n\n- 태그: < > </ >\n\n- 속성: 태그 안의 성질(font, size 등)\n\n\n\n### 1. 태그\n\n> Hypertext Markup Language(HTML) is the standard markup language for creating web pages and web applications\n\n\n\n__tag의 시작과 끝__: < > </ >\n\n```html\nHypertext Markup Language(HTML) is the standard markup language for <strong> creating web pages </strong> and web applications.\n```\n\n\n\n__\\<u>__ :underbar\n\n```html\nHypertext Markup Language(HTML) is the standard markup language for <strong> creating <u>web</u> pages </strong> and web applications.\n```\n\n\n\n__\\<html> \\</head>__\n\n\n\n__\\<body> \\</body>__\n\n\n\n__\\<h1> \\<h2> ... \\<h6>__\n\n```html\n<h1> Hello World!! </h1>\n<h2> Hello World!! </h2>\n<h3> Hello World!! </h3>\n```\n\n \n\n__\\<br>__: 줄 나누기\n\n```html\nHypertext Markup Language(HTML) is the standard markup langauge for <strong> creating <u> web </w> pages </strong> and web applications. Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. <br><br> HTML describes the structure of a web page semenatically and originally included cues for the appearance of the document.\n```\n\n\n\n__\\<p> \\</p>__: 단락 나누기\n\n```html\n<h1>\n HTML\n</h1>\n<p>\nHypertext Markup Language(HTML) is the standard markup langauge for <strong> creating <u> web </w> pages </strong> and web applications. Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. <p>\n \n</p>HTML describes the structure of a web page semenatically and originally included cues for the appearance of the document.\n</p>\n```\n\n\n\n__파라미터값 넣기__\n\n__\\<p style=\"margin-top:40px;\">__\n\n```html\n<h1>\n HTML\n</h1>\n<p>\n Hypertext Markup Language(HTML) is the standard markup langauge for <strong> creating <u> web </w> pages </strong> and web applications. Web browsers receive HTML documents from a web server or from local storage and render them into multimedia web pages. </p>\n \n<p style = \"margin-top:40px;\">HTML describes the structure of a web page semenatically and originally included cues for the appearance of the document.\n</p>\n```\n\n\n\n\n\n__\\<span style=\"font-size:24px\">__\n\n- \\<h2>, \\<h3> 등 외에도 세부적인 옵션을 조절 가능 (더 많이 사용하게 됨)\n\n```html\n<span style=\"font-size:24px\">\n coding\n</span>\n```\n\n\n\n\n\n__\\<img src=\"\">__\n\n```html\n<img src=\"coding.jpg\" width = \"100%\">\n```\n\n\n\n### 목차태그\n\n__\\<li> \\</li>__:리스트 만들기\n\n```html\n<li>1.html</li>\n<li>2.CSS</li>\n<li>3.JavaScript</li>\n```\n\n\n\n__리스트의 부모태그(ul, ol)__\n\n__\\<ul> \\</ul>__: Unordered List 번호 없음\n\n```html\n<ul>\n <li>1.HTML</li>\n <li>2. CSS</li>\n <li>3. JavaScript</li>\n</ul>\n<ul>\n <li>egoing</li>\n <li>k8805</li>\n <li>youbin</li>\n</ul>\n```\n\n\n\n__\\<ol> \\</ol>__: Ordered List. 번호 생성됨\n\n```html\n<ol>HTML</ol>\n<ol>CSS</ol>\n<ol>JavaScript</ol>\n\n<ol>\n <li>HTML</li>\n <li>CSS</li>\n <li>JavaScript</li>\n</ol>\n```\n\n\n\n__\\<tr> \\</tr>__\n\n\n\n__\\<title> \\</title>__\n\n```html\n<title>WEB1 - HTML</title>\n\n<ol>\n <li>HTML</li>\n <li>CSS</li>\n <li>JavaScript</li>\n</ol>\n```\n\n\n\n__\\<link> \\</link>__\n\n\n\n__\\<a> \\</a>__\n\n```html\n<a href=\"https://www.w3.org/TR/html5/\" target=\"_blank\">Hypertext Markup Language (HTML)</a>\n```\n\n\n\n\n\n__\\<span> \\</span>__\n\n- 의미있는 태그는 아니다\n\n```\n\n```\n\n\n\n__\\<table> \\</table>__\n\n\n\n## CSS\n\n- HTML 기반, 디자인(색상, 모양, 폰트)을 편하게 하기 위한 __언어__\n\n\n\n__CSS를 작성하는 방법 2가지__\n\n1. 속성 style\n2. 태그 \\<style> \\</style>: 언어를 HTML안의 태그로 녹여서 사용하는 것\n\n\n\n__CSS를 지배하는 두가지 중요한 토대__\n\n1. 효과\n2. 선택자\n\n\n\n\n\n## Javascript\n\n- HTML 기반, 동적으로 핸들링할 때(이벤트, 액션) 사용하는 언어\n\n\n\n__\\<script> \\</script>__\n\n\n\n## Django Framework\n\n- \n\n\n\n\n\n\n\n\n\n### 실습해보기\n\n__링크를 걸어 웹페이지를 만들자__\n\n\n\n1. 링크로 연결되도록 하자 (본 파일, 각각의 웹페이지 html 생성)\n\n```html\n<html>\n <head>\n <title>WEB1 - HTML</title>\n <meta charset=\"utf-8\">\n </head>\n <body>\n <h1><a href=\"index.html\">WEB</a></h1>\n <ol>\n <li><a href=\"1.html\">HTML</a></li>\n <li><a href=\"2.html\">CSS</a></li>\n <li></li><a href=\"3.html\">JavaScript</a></ol></li>\n </ol>\n <h2>HTML이란 무엇인가?</h2>\n ...생략...\n </body>\n</html>\n```\n\n\n\n\n\n" }, { "alpha_fraction": 0.6160456538200378, "alphanum_fraction": 0.6449306607246399, "avg_line_length": 17.408245086669922, "blob_id": "acf5bdc80942062ad406a85a9c2ec8e311df82ea", "content_id": "a00e10378642eae6195660f46b4b188292481d4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18034, "license_type": "no_license", "max_line_length": 137, "num_lines": 752, "path": "/django/web_programming.md", "repo_name": "winterconnect/Web_Programming", "src_encoding": "UTF-8", "text": "# WEB PROGRAMMING\n\n> CHAPTER1 웹 프로그래밍의 이해\n>\n> ​\t1.1 웹 프로그래밍이란?\n>\n> ​\t1.2 다양한 웹 클라이언트\n>\n> ​\t1.3 HTTP 프로토콜\n>\n> ​\t1.4 URL 설계\n>\n> ​\t1.5 웹 애플리케이션 서버\n>\n> \n>\n> CHAPTER2 파이썬 웹 표준 라이브러리\n\n\n\n\n\n## 네트워크(Network)\n\n- 네트워크는 __규약(protocol)__이다\n- \"나 이제 공 던질게!\" \"나 글로브 가져올게!\" \"던진다!\" \"잘 받았어!\" 처럼 통신을 하기 위해 정해놓은 규칙들\n - 메세지를 어떻게 보내야할지 정해져있음: \"패킷\"으로 정보 저장\n - 컴퓨터는 비트로 정보 저장 (01010111...)\n - 정보를 저장해두었다 패킷을 통해 정보 전달\n\n\n\n- 예전에는 구리선으로 연결된 아날로그(주파수)\n- 주파수를 디지털화(주파수에 맞는 데이터를 전송) - 자동으로 아날로그 신호로 변환을 해주는 프로그램이 생겨나게 됨\n - ex) 아날로그(통신언어) -> \"01010101\"(컴퓨터언어) -> 안녕하세요\"(사람언어)\n - \"안녕하세요\" -> \"01010101\" -> 아날로그\n\n\n\n- 패킷\n\n - SIP(Source IP): 보내는사람 IP\n - DIP(Destination IP): 받는사람 IP\n - C(Control): 메세지의 용도 표시(송신용send, 수신용, 특별용 등), ftp, http 등을 입력\n - Port: 1~1000 까지의 포트는 규약으로 정해져있음 (ex. http 80, ftp: 21,22)\n - 나머지 칸에 데이터 저장\n\n -> 양쪽 컴퓨터가 모두 준비가 되면 네트워크 시작\n\n- 송신자가 패킷을 보내려니 너무 크면? 패킷을 자름(sip, dip는 패킷마다 표시하고 데이터는 분할하여 송신)\n\n- 수신자는 분할된 패킷을 보고, 조합하여 하나로 만들어서 다시 사용\n\n- 수신자에게 갈 때까지 패킷들은 각각 다른 스위치(=라우터)를 거치며 경로가 다양하고, 만약 분할된 데이터중 일부가 안오게 되면? 들어올 때까지 대기하게 됨\n\n\n\n- 통신의 목적? 정보 교환\n\n\n\n- __OSI 7 계층(layer)__\n\n\n\n\n\n## CHAPTER1. 웹 프로그래밍의 이해\n\n### 1.1 웹 프로그래밍이란?\n\n\n\n- 서버가 request 를 받으면 데이터베이스를 관리하는 어플리케이션이 정보를 조회한 후 html로 전송\n\n- 웹 서버, 데이터베이스 서버를 분리함(과부하 방지)\n\n- 웹프로그램을 한다는 것은? 웹서버 개발\n\n 1. 사이트 설계\n\n 2. 사이트 설계를 토대로 데이터베이스 설계\n 3. 인터페이스 설계\n\n- 장고와 같은 웹 프레임워크를 사용하여 웹 서버 개발\n\n\n\n### 1.2 다양한 웹 클라이언트\n\n#### 1.2.1 웹 브라우저를 사용하여 요청\n\n#### 1.2.2 리눅스 curl 명령어를 사용하여 요청\n\n#### 1.2.3 Telnet을 사용하여 요청\n\n#### 1.2.4 직접 만든 클라이언트로 요청\n\n```python\nimport urllib.request\nprint(urllib.request.urlopen(\"http://www.example.com\").read().decode('utf-8'))\n```\n\n\n\n\n\n### 1.3 HTTP 프로토콜\n\n>## 인터넷 (http)\n>\n>- 통신을 하면서 많은 프로토콜이 생겨나게 됨 (telnet, ftp, http 등...)\n>\n> - telnet: 서버에 접속해 메세지를 주고받는 프로토콜\n> - ftp(file transfer protocol): 파일전송 프로토콜\n> - http: \n>\n>- http의 규약: request - response\n>\n> \n>\n>- 인터넷으로 웹에 접속한다는 것은? client(pc) - server(홈페이지): html로 소통함\n>\n> - client가 http 프로토콜을 이용해서 데이터를 요청 (request)\n> - server는 반드시 대답해야 함(response): html로 만든 메세지(파일)를 전송\n> - index.html 을 갖고 있음\n> - index: 홈페이지 첫페이지 의미\n> - 서버가 index를 클라이언트에게 보내주고, 클라이언트가 이것을 해독하여 필요한 정보를 가져가고, 태그에 따라 브라우저에 표시\n>\n> \n>\n> - ex) 클라이언트가 브라우저 페이지를 요청(html로 요청) - 서버가 브라우저의 html을 전송\n> - 브라우저가 html를 해독하여 그 내용을 화면에 그대로 보여줌\n\n\n\n#### 1.3.1 HTTP 메시지의 구조\n\n#### 1.3.2 HTTP 처리 방식\n\n- 8가지가 있지만 현실적으로 가장 많이 사용하는 메소드는 GET, POST\n- request header에 들어감\n - GET 요청방식: 지정한 url의 정보를 가져오는 메서드(데이터 조회 read)\n - POST 요청방식: 리소스를 생성 (데이터 생성 create)\n\n#### 1.3.3 GET과 POST 메소드\n\n#### 1.3.4 상태 코드\n\n\n\n### 1.4 URL 설계\n\n- URL scheme: URL에 사용된 프로토콜 의미\n- netloc: 네트워크 위치. http 프로토콜은 host:port 형식으로 표현\n - host: 웹 서버의 호스트명, 도메인명 또는 IP 주소\n - port: 웹 서버 내의 서비스 포트번호. 생략시에 디폴트 포트번호 사용(http 80, https 443)\n- path: 파일이나 애플리케이션 경로\n- params: 애플리케이션에 전달될 매개변수\n- query: 질의 문자열 또는 매개변수. 앰퍼샌드(&)로 구분된 이름-값 쌍 형식으로 표현\n- fragment: 문서 내의 앵커 등 조각을 지정\n\n\n\n#### 1.4.1 URL을 바라보는 측면\n\n#### 1.4.2 간편 URL\n\n#### 1.4.3 파이썬의 우아한 URL\n\n\n\n### 1.5 웹 애플리케이션 서버\n\n\n\n#### 1.5.1. 정적페이지 vs 동적페이지\n\n> - 사용자가 페이지를 요청하는 시점에 페이지의 내용이 유지되는가 변경되는가를 구분해주는 용어\n>\n> - 동적페이지에는 프로그래밍 코드가 포함되어 있어서 페이지 요청시점에 HTML 문장을 만들어내는 것\n\n\n\n\n\n#### 1.5.3 CGI 방식의 대안기술\n\n\n\n#### 1.5.4 애플리케이션 서버 방식\n\n웹클라이언트 - 웹서버 - 웹 애플리케이션 서버\n\n\n\n#### 1.5.5 웹서버와의 역할 구분\n\n\n\n## CHAPTER2. 파이썬 웹 표준 라이브러리\n\n> 2.1 웹 라이브러리 구성\n>\n> 2.2 웹 클라이언트 라이브러리\n>\n> 2.3 웹 서버 라이브러리\n>\n> 2.4 CGI/WSGI 라이브러리\n\n\n\n\n\n### 2.1 웹 라이브러리 구성\n\n- 웹 클라이언트 프로그래밍: urllib 패키지(고수준 API 제공)\n- 웹 서버 프로그래밍: Web Framework(Django, Flask, Tornado 등)\n\n\n\n- urllib 패키지: 웹 클라이언트를 작성하는데 사용되는 모듈들이 있으며, 가장 빈번하게 사용하는 모듈\n\n- http 패키지\n\n - 서버용과 클라이언트용 라이브러리로 나누어 모듈을 담고 있음\n - 쿠키 관련 라이브러리도 서버용과 클라이언트용 모듈이 구분됨\n\n \n\n### 2.2 웹 클라이언트 라이브러리\n\n#### 2.2.1 urllib.parse 모듈\n\n- URL의 분해, 조립, 변경 및 URL 문자인코딩, 디코딩 등을 처리하는 함수 제공\n\n```python\nfrom urllib.parse import urlparse\nresult = urlparse(\"http://www.python.org:80/guido/python.html;philosophy?overall=3#n10\")\nresult\n```\n\n결과: URL 구성요소대로 파싱됨\n\n```\nParseResult(scheme='http', netloc='www.python.org:80', path='/guido/python.html', params='philosophy', query='overall=3', fragment='n10')\n```\n\n\n\n- __URL scheme__: URL에 사용된 프로토콜 의미\n- __netloc__: 네트워크 위치. http 프로토콜은 host:port 형식으로 표현\n - host: 웹 서버의 호스트명, 도메인명 또는 IP 주소\n - port: 웹 서버 내의 서비스 포트번호. 생략시에 디폴트 포트번호 사용(http 80, https 443)\n- __path__: 파일이나 애플리케이션 경로\n- __params__: 애플리케이션에 전달될 매개변수\n- __query__: 질의 문자열 또는 매개변수. 앰퍼샌드(&)로 구분된 이름=값 쌍 형식으로 표현\n- __fragment__: 문서 내의 앵커 등 조각을 지정\n\n\n\n#### 2.2.2 urllib.request 모듈\n\n> urlopen(url, data = None, [timeout])\n\n\n\n__urlopen() 함수__\n\n```python\nfrom urllib.request import urlopen\n```\n\n\n\n- GET 방식\n\n```python\nfrom urllib.request import urlopen\n\nf = urlopen(\"http://www.example.com\")\nprint(f.read(500).decode('utf-8'))\n```\n\n\n\n- POST 방식\n\n```python\n# 서버를 올리고 정보를 요청\nwinter@Winterui-MacBookPro ch2-test-server % python manage.py runserver\n\nWatching for file changes with StatReloader\nPerforming system checks...\n\nSystem check identified no issues (0 silenced).\n\nYou have 4 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth.\nRun 'python manage.py migrate' to apply them.\nJanuary 27, 2021 - 15:29:12\nDjango version 3.1.5, using settings 'mysite.settings'\nStarting development server at http://127.0.0.1:8000/\nQuit the server with CONTROL-C.\nHomeView.post()...\npython\ndjango\n홍길동\[email protected]\nhttp://google.co.kr\n[27/Jan/2021 15:29:19] \"POST / HTTP/1.1\" 200 1758\n```\n\n```python\nfrom urllib.request import urlopen\n\ndata = \"language=python&framework=django\"\nf = urlopen(\"http://127.0.0.1:8000\", bytes(data, encoding='utf-8'))\n\nprint(f.read(500).decode('utf-8'))\n```\n\n\n\n- Request 클래스로 요청 헤더 지정\n - 헤더값을 사용자가 모두 지정할 필요는 없으므로, 브라우저가 자동으로 지정하고 꼭 필요한 것만 지정\n - 헤더값이 상단에 표시됨\n\n```python\nfrom urllib.request import urlopen, Request\nfrom urllib.parse import urlencode\n\nurl = 'http://127.0.0.1:8000'\n\ndata = {\n 'name': '김석훈',\n 'email': '[email protected]',\n 'url': 'http://www.naver.com',\n}\nencData = urlencode(data)\npostData = bytes(encData, encoding='utf-8')\n\nreq = Request(url, data=postData)\nreq.add_header('Content-Type', 'application/x-www-form-urlencoded')\n\nf = urlopen(req)\n\nprint(f.info())\nprint(f.read(500).decode('utf-8'))\n```\n\n```\nDate: Wed, 27 Jan 2021 06:36:54 GMT\nServer: WSGIServer/0.2 CPython/3.9.0\nContent-Type: text/html; charset=utf-8\nX-Frame-Options: DENY\nContent-Length: 1758\nX-Content-Type-Options: nosniff\nReferrer-Policy: same-origin\n\n\n<!DOCTYPE html>\n<html lang=\"ko\">\n\n\n\n\n<head>\n\n <meta charset=\"utf-8\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n <title>ch2-test-server</title>\n\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css\">\n\n <!-- my css -->\n <link rel=\"shortcut\n```\n\n\n\n- HTTPBasicAuthHandler 클래스로 인증 요청\n\n```python\nfrom urllib.request import HTTPBasicAuthHandler, build_opener\n\n\nauth_handler = HTTPBasicAuthHandler()\nauth_handler.add_password(realm='ksh', user='shkim', passwd='shkimadmin', uri='http://127.0.0.1:8000/auth/') # OK\n# NOK. auth_handler.add_password(realm='ksh', user='shkim', passwd='shkimadmin', uri='http://127.0.0.1:8000/')\nopener = build_opener(auth_handler) # 서버 인증 자격 빌드 (인증 Key값)\nresp = opener.open('http://127.0.0.1:8000/auth/') # 서버 인증 요청\nprint(resp.read().decode('utf-8'))\n```\n\n\n\n- HTTPCookieProcessor 클래스로 쿠키 데이터를 포함하여 요청\n\n```python\nfrom urllib.request import Request, HTTPCookieProcessor, build_opener\n\n\nurl = 'http://127.0.0.1:8000/cookie/'\n\n# first request (GET) with cookie handler\n\n# 쿠키 핸들러 생성, 쿠키 데이터 저장은 디폴트로 CookieJar 객체를 사용함\ncookie_handler = HTTPCookieProcessor()\nopener = build_opener(cookie_handler)\n\nreq = Request(url)\nres = opener.open(req)\n\nprint(res.info())\nprint(res.read().decode('utf-8'))\n\n# second request (POST)\nprint(\"-------------------------------------------------------\")\n\ndata = \"language=python&framework=django\"\nencData = bytes(data, encoding='utf-8')\n\nreq = Request(url, encData)\nres = opener.open(req)\n\nprint(res.info())\nprint(res.read().decode('utf-8'))\n```\n\n\n\n- ProxyHandler 및 ProxyBasicaAuthHandler 클래스로 프록시 처리\n - proxy: \"방화벽\"이라고 생각하면 된다\n\n```python\nimport urllib.request\n\n\nurl = 'http://www.example.com'\nproxyServer = 'http://www.proxy.com:3128/'\n\n# 프록시 서버를 통해 웹서버로 요청을 보냅니다.\nproxy_handler = urllib.request.ProxyHandler({'http': proxyServer})\n\n# 프록시 서버 설정을 무시하고 웹서버로 요청을 보냅니다.\n# proxy_handler = urllib.request.ProxyHandler({})\n\n# 프록시 서버에 대한 인증을 처리합니다.\nproxy_auth_handler = urllib.request.ProxyBasicAuthHandler()\nproxy_auth_handler.add_password('realm', 'host', 'username', 'password')\n\n# 2개의 핸들러를 오프너에 등록합니다.\nopener = urllib.request.build_opener(proxy_handler, proxy_auth_handler)\n\n# 디폴트 오프너로 지정하면, urlopen() 함수로 요청을 보낼 수 있습니다.\nurllib.request.install_opener(opener)\n\n# opener.open() 대신에 urlopen()을 사용했습니다.\nf = urllib.request.urlopen(url)\n\nprint(\"geturl():\", f.geturl())\nprint(f.read(300).decode('utf-8'))\n```\n\n\n\n#### 2.2.3 urllib.request 모듈 예제\n\n```python\nfrom urllib.request import urlopen\nfrom html.parser import HTMLParser\n\n\nclass ImageParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n if tag != 'img':\n return\n if not hasattr(self, 'result'):\n self.result = []\n for name, value in attrs:\n if name == 'src':\n self.result.append(value)\n\n\ndef parse_image(data):\n parser = ImageParser()\n parser.feed(data)\n dataSet = set(x for x in parser.result)\n return dataSet\n\n\ndef main():\n url = \"http://www.google.co.kr\"\n\n with urlopen(url) as f:\n charset = f.info().get_param('charset')\n data = f.read().decode(charset)\n\n dataSet = parse_image(data)\n print(\"\\n>>>>>>>>> Fetch Images from\", url)\n print('\\n'.join(sorted(dataSet)))\n\n\nif __name__ == '__main__':\n main()\n```\n\n\n\n#### 2.2.4 http.client 모듈\n\n1. 연결객체 생성: conn = http.client.HTTPConnection(\"www.python.org\")\n2. 요청을 보냄: conn.request(\"GET\", \"/index.html\")\n3. 응답객체 생성: response = conn.getresponse()\n4. 응답 데이터를 읽음: data = response.read()\n5. 연결을 닫음: conn.close()\n\n\n\n- GET 방식 요청\n\n```python\nfrom http.client import HTTPConnection\n\nhost = 'www.example.com'\nconn = HTTPConnection(host)\n\nconn.request('GET', '/')\n\nr1 = conn.getresponse()\nprint(r1.status, r1.reason)\n\ndata1 = r1.read()\n# 일부만 읽는 경우\n# data1 = r1.read(100)\n\n# 두번째 요청에 대한 테스트\nconn.request('GET', '/')\n\nr2 = conn.getresponse()\nprint(r2.status, r2.reason)\n\ndata2 = r2.read()\nprint(data2.decode())\n\nconn.close()\n```\n\n\n\n- HEAD 방식 요청\n\n```python\nfrom http.client import HTTPConnection\n\nconn = HTTPConnection('www.example.com')\nconn.request('HEAD', '/')\n\nresp = conn.getresponse()\nprint(resp.status, resp.reason)\n\ndata = resp.read()\nprint(len(data))\nprint(data == b'')\n```\n\n\n\n- POST방식 요청\n\n```python\nfrom http.client import HTTPConnection\nfrom urllib.parse import urlencode\n\nhost = '127.0.0.1:8000'\nparams = urlencode({\n 'language': 'python',\n 'name': '김석훈',\n 'email': '[email protected]',\n})\nheaders = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'text/plain',\n}\n\nconn = HTTPConnection(host)\nconn.request('POST', '', params, headers)\nresp = conn.getresponse()\nprint(resp.status, resp.reason)\n\ndata = resp.read()\nprint(data.decode('utf-8'))\n\nconn.close()\n```\n\n\n\n- PUT 방식 요청\n\n```python\nfrom http.client import HTTPConnection\nfrom urllib.parse import urlencode\n\n\nhost = '127.0.0.1:8000'\nparams = urlencode({\n 'language': 'python',\n 'name': '김석훈',\n 'email': '[email protected]',\n})\nheaders = {\n 'Content-Type': 'application/x-www-form-urlencoded',\n 'Accept': 'text/plain',\n}\n\nconn = HTTPConnection(host)\nconn.request('PUT', '', params, headers)\nresp = conn.getresponse()\nprint(resp.status, resp.reason)\n\ndata = resp.read(300)\nprint(data.decode('utf-8'))\n\nconn.close()\n```\n\n\n\n__http.client 모듈 예제__\n\n```python\nimport os\nfrom http.client import HTTPConnection\nfrom urllib.parse import urljoin, urlunparse\nfrom urllib.request import urlretrieve\nfrom html.parser import HTMLParser\n\n\nclass ImageParser(HTMLParser):\n def handle_starttag(self, tag, attrs):\n if tag != 'img':\n return\n if not hasattr(self, 'result'):\n self.result = []\n for name, value in attrs:\n if name == 'src':\n self.result.append(value)\n\n\ndef download_image(url, data):\n\n if not os.path.exists('DOWNLOAD'):\n os.makedirs('DOWNLOAD')\n\n parser = ImageParser()\n parser.feed(data)\n dataSet = set(x for x in parser.result)\n\n for x in sorted(dataSet) :\n imageUrl = urljoin(url, x)\n basename = os.path.basename(imageUrl)\n targetFile = os.path.join('DOWNLOAD', basename)\n\n print(\"Downloading...\", imageUrl)\n urlretrieve(imageUrl, targetFile)\n\n\ndef main():\n host = \"www.google.co.kr\"\n\n conn = HTTPConnection(host)\n conn.request(\"GET\", '')\n resp = conn.getresponse()\n\n charset = resp.msg.get_param('charset')\n data = resp.read().decode(charset)\n conn.close()\n\n print(\"\\n>>>>>>>>> Download Images from\", host)\n url = urlunparse(('http', host, '', '', '', ''))\n download_image(url, data)\n\n\nif __name__ == '__main__':\n main()\n```\n\n\n\n### 2.3 웹 서버 라이브러리\n\n#### 2.3.1 간단한 웹서버\n\n```\n\n```\n\n\n\n\n\n#### 2.3.2 HTTPServer 및 BaseHTTPRequestHandler 클래스\n\n\n\n#### 2.3.3 SimpleHTTPRequestHandler\n\n\n\n#### 2.3.4 CGIHTTPRequestHandler 클래스\n\n\n\n\n\n### 2.4 CGI/WSGI 라이브러리\n\n- CGI: 서버 부하가 높아짐\n- WSGI: CGI의 단점을 해결하고 파이썬으로 애플리케이션을 좀 더 쉽게 작성할 수 있도록 웹 서버와 애플리케이션 간 연동 규격을 정의한 것\n\n\n\n#### 2.4.3 WSGI 서버의 애플리케이션 처리 과정\n\n\n\n#### 2.4.4 wsgiref.simple_server 모듈\n\n```python\nfrom wsgiref.simple_server import make_server\n\n\ndef my_app(environ, start_response):\n\n status = '200 OK'\n headers = [('Content-Type', 'text/plain')]\n start_response(status, headers)\n\n response = [b\"This is a sample WSGI Application.\"]\n\n return response\n\n\nif __name__ == '__main__':\n print(\"Started WSGI Server on port 8787...\")\n server = make_server('', 8787, my_app)\n server.serve_forever()\n```\n\n\n\n\n\n" }, { "alpha_fraction": 0.5098591446876526, "alphanum_fraction": 0.5633803009986877, "avg_line_length": 18.72222137451172, "blob_id": "c6a292d7bfdb83107aed727db4e1095f9e16f574", "content_id": "6d02bf806156461b5fb6abc31d7256ca0bd57f9a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/django/practice/root/books/migrations/0002_auto_20210204_2301.py", "repo_name": "winterconnect/Web_Programming", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.5 on 2021-02-04 14:01\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('books', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='book',\n old_name='publishers',\n new_name='publisher',\n ),\n ]\n" }, { "alpha_fraction": 0.5908206701278687, "alphanum_fraction": 0.6098794341087341, "avg_line_length": 14.029239654541016, "blob_id": "026e07968566aa127a6d2026228b22a1f7cd7a19", "content_id": "e4ced46a280cc0a03aad047edf438a60eb9cf72e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9791, "license_type": "no_license", "max_line_length": 94, "num_lines": 513, "path": "/django/Django_chapter4.md", "repo_name": "winterconnect/Web_Programming", "src_encoding": "UTF-8", "text": "# CHAPTER4. Django의 핵심 기능\n\n> 실제 프로젝트 개발을 위해 꼭 알야아할 기능 6가지 설명\n\n\n\n## 4.1 Admin 사이트 꾸미기\n\n> Admin\n>\n> - 데이터베이스에 들어있는 데이터를 쉽게 관리할 수 있도록 데이터의 CRUD(생성, 조회, 변경, 삭제) 등의 기능 제공\n> - 깔끔한 UI 제공\n\n\n\n### 4.1.1 데이터 입력 및 수정\n\n\n\n### 4.1.2 필드 순서 변경하기\n\npolls/admin.py 파일 변경\n\n```python\n# admin.py\n\nfrom django.contrib import admin\n\n# Register your models here.\n\n\nfrom django.contrib import admin\nfrom polls.models import Question, Choice\n\n# ModelAdmin 클래스를 상속받아 새로운 QuestionAdmin 클래스 정의\nclass QuestionAdmin(admin.ModelAdmin): \n fields = ['pub_date', 'question_text'] # 필드 순서 변경\n\n# admin.site.register() 함수의 두번째 인자로 QuestionAdmin 클래스 정의 \nadmin.site.register(Question, QuestionAdmin)\nadmin.site.register(Choice)\n```\n\n\n\n\n\n### 4.1.3 각 필드를 분리해서 보여주기\n\n```python\n# admin.py\n\nfrom django.contrib import admin\n\n# Register your models here.\n\n\nfrom django.contrib import admin\nfrom polls.models import Question, Choice\n\n\nclass QuestionAdmin(admin.ModelAdmin):\n fieldsets = [\n ('Question Statement', {'fields': ['question_text']}),\n ('Date Information', {'fields': ['pub_date']}),\n ]\n \nadmin.site.register(Question, QuestionAdmin)\nadmin.site.register(Choice)\n```\n\n\n\n### 4.1.4 필드 접기\n\n- admin.py 에 collapse 추가\n\n```python\n# admin.py\n\nfrom django.contrib import admin\n\n# Register your models here.\n\n\nfrom django.contrib import admin\nfrom polls.models import Question, Choice\n\n\nclass QuestionAdmin(admin.ModelAdmin):\n fieldsets = [\n ('Question Statement', {'fields': ['question_text']}),\n ('Date Information', {'fields': ['pub_date'], 'classes': ['collapse']}), # collapse 추가\n ]\n \nadmin.site.register(Question, QuestionAdmin)\nadmin.site.register(Choice)\n```\n\n\n\n### 4.1.5 외래키 관계 화면\n\n\n\n### 4.1.6 Question 및 Choice를 한 화면에서 변경하기\n\n```python\n# admin.py\n\nfrom django.contrib import admin\nfrom django.contrib import admin\nfrom polls.models import Question, Choice\n\nclass ChoiceInline(admin.StackedInline):\n model = Choice\n extra = 2 # 한번에 보여주는 Choice text의 숫자가 결정\n \nclass QuestionAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['question_text']}),\n ('Date Information', {'fields': ['pub_date'], 'classes': ['collapse']}),\n ]\n inlines = [ChoiceInline] # Choice 모델 클래스 같이보기\n \nadmin.site.register(Question, QuestionAdmin)\nadmin.site.register(Choice)\n```\n\n\n\n### 4.1.7 테이블 형식으로 보여주기\n\n- TarbularInline 으로 변경\n\n```python\n# admin.py\n\nfrom django.contrib import admin\n\n# Register your models here.\n\n\nfrom django.contrib import admin\nfrom polls.models import Question, Choice\n\n \nclass ChoiceInline(admin.TabularInline):\n model = Choice\n extra = 2\n \nclass QuestionAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['question_text']}),\n ('Date Information', {'fields': ['pub_date'], 'classes': ['collapse']}),\n ]\n inlines = [ChoiceInline] # Choice 모델 클래스 같이보기\n \nadmin.site.register(Question, QuestionAdmin)\nadmin.site.register(Choice)\n```\n\n\n\n\n\n### 4.1.8 레코드 리스트 컬럼 지정하기\n\n- admin.py 에 list_display 추가\n\n```python\nfrom django.contrib import admin\n\n# Register your models here.\n\n\nfrom django.contrib import admin\nfrom polls.models import Question, Choice\n\n \nclass ChoiceInline(admin.TabularInline):\n model = Choice\n extra = 2\n \nclass QuestionAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['question_text']}),\n ('Date Information', {'fields': ['pub_date'], 'classes': ['collapse']}),\n ]\n inlines = [ChoiceInline] # Choice 모델 클래스 같이보기\n list_display = ('question_text', 'pub_date') # 레코드 리스트 컬럼 지정\n \nadmin.site.register(Question, QuestionAdmin)\nadmin.site.register(Choice)\n```\n\n\n\n### 4.1.9 list_filter 필터\n\n- UI 화면 우측에 필터 사이드바 추가\n- 사용된 기준 필드 타입에 따라 장고가 자동으로 적절한 항목들을 보여줌\n\n\n\n### 4.1.10 search_fields\n\n- UI 화면에 검색박스 표시\n\n```python\n# admin.py\n\nfrom django.contrib import admin\n\n# Register your models here.\n\n\nfrom django.contrib import admin\nfrom polls.models import Question, Choice\n\n \nclass ChoiceInline(admin.TabularInline):\n model = Choice\n extra = 2\n \nclass QuestionAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['question_text']}),\n ('Date Information', {'fields': ['pub_date'], 'classes': ['collapse']}),\n ]\n inlines = [ChoiceInline] # Choice 모델 클래스 같이보기\n list_display = ('question_text', 'pub_date') # 레코드 리스트 컬럼 지정\n list_filter = ['pub_date']\n search_fields = ['question_text'] # 검색박스 추가 \n \nadmin.site.register(Question, QuestionAdmin)\nadmin.site.register(Choice)\n```\n\n\n\n### 4.1.11 polls/admin.py 변경 내역 정리(최종)\n\n```python\nfrom django.contrib import admin\nfrom django.contrib import admin\nfrom polls.models import Question, Choice\n \nclass ChoiceInline(admin.TabularInline):\n model = Choice\n extra = 2\n \nclass QuestionAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['question_text']}),\n ('Date Information', {'fields': ['pub_date'], 'classes': ['collapse']}),\n ]\n inlines = [ChoiceInline] # Choice 모델 클래스 같이보기\n list_display = ('question_text', 'pub_date') # 레코드 리스트 컬럼 지정\n list_filter = ['pub_date'] # 필터 사이드바 추가\n search_fields = ['question_text'] # 검색박스 추가 \n \nadmin.site.register(Question, QuestionAdmin)\nadmin.site.register(Choice)\n```\n\n\n\n\n\n### 4.1.12 Admin 사이트 템플릿 수정\n\n\n\n\n\n\n\n## 4.2 장고 파이썬 쉘로 데이터 조작하기\n\n### 4.2.1 Create - 데이터 생성/입력\n\n\n\n### 4.2.2 Read - 데이터 조회\n\nQuestion.objects.all()\n\n\n\n### 4.2.3 Update - 데이터 수정\n\n\n\n### 4.2.4 Delete - 데이터 삭제\n\nQuestion.objects.delete()\n\n\n\n### 4.2.5 polls 애플리케이션의 데이터 실습\n\n\n\n\n\n## 4.3 템플릿 시스템\n\n\n\n### 4.3.1 템플릿 변수\n\n{{ variable }}\n\n\n\n### 4.3.2 템플릿 필터\n\n{{ name|lower }} : name 변수값의 모든 문자를 소문자로 바꿔주는 필터\n\n{{ text|escape|linebreaks }} : text변수값 중에 특수문자를 이스케이프해주고 그 결과 스트링에 HTML <p> 태그를 붙임\n\n{{ bio|truncatewords:30 }}\n\n{{ list|join:\" // \" }}\n\n{{ value|default:\"nothing\" }}\n\n{{ value|length }}\n\n{{ value|striptags }}\n\n{{ value|pluralize }}\n\n\n\n\n\n### 4.3.3 템플릿 태그\n\n{% for %} 태그\n\n```\n<ul>\n{% for athlete in athlete_list %}\n\t<li>{{ athlete.name }}</li>\n{% endfor %}\n</ul>\n```\n\n\n\n{% if %} 태그\n\n```\n{% if athlete_list %}\n\tNumber of athletes: {{ athlete_list|length }}\n{% elif athlete_in_locker_room_list %}\n\tAthletes should be out of the locker room soon!\n{% else %}\n\tNo athletes.\n{% endif %}\n```\n\n\n\n{% csrf_token %} 태그\n\n\n\n{% url %}\n\n\n\n{% with %}\n\n\n\n{% load %}\n\n\n\n### 4.3.4 템플릿 주석\n\n{# #} 한줄주석\n\n{% comment %} 여러줄 주석\n\n\n\n### 4.3.5 HTML 이스케이프\n\n< (less than) : &lt\n\n\\> (greater than) : &gt\n\n\n\n### 4.3.6 템플릿 상속\n\n- 템플릿 상속을 통해 템플릿 코드를 재사용할 수 있고, 사이트의 룩앤필을 일관성 있게 보여줄 수 있음\n- 부모템플릿: 템플릿의 뼈대를 만들어주고, {% block %} 태그를 통해 하위로 상속해줄 부분을 지정\n\n\n\n\n\n## 4.4 폼 처리하기\n\n\n\n### 4.4.1 HTML 에서의 폼\n\n\n\n### 4.4.2 장고의 폼 기능\n\n\n\n### 4.4.3 폼 클래스로 폼 생성\n\n\n\n### 4.4.4 뷰에서 폼 클래스 처리\n\n\n\n### 4.4.5 폼 클래스를 템플릿으로 변환\n\n{{ form.as_table }} : \\<tr> 태그로 감싸서 테이블 셀로 렌더링\n\n{{ form.as_p }} : \\<p> 태그로 감싸도록 렌더링\n\n{{ form.as_ul }} : \\<li> 태그로 감싸도록 렌더링\n\n\n\n\n\n## 4.5 클래스형 뷰\n\n\n\n### 4.5.1 클래스형 뷰의 시작점\n\n\n\n### 4.5.2 클래스형 뷰의 장점\n\n- 효율적인 메소드 구분\n- 상속 기능 가능\n\n\n\n### 4.5.4 클래스형 제네릭 뷰\n\n\n\n### 4.5.5 클래스형 뷰에서 폼 처리\n\n\n\n\n\n## 4.6 로그 남기기\n\n### 4.6.1 로거(Logger)\n\n- 로깅시스템의 시작점으로 로그 메세지를 처리하기 위해 메세지를 담아두는 저장소\n- 로그 레벨: 로그 메세지의 중요도에 따라 자신이 어느 레벨 이상의 메세지를 처리할지에 대한 기준이 됨\n\n| 로그 레벨 | 정수값 | 설명 |\n| --------- | ------ | ------------------------------------------------------------ |\n| NOTSET | 0 | 로그 레벨의 최하위 수준<br />로거 또는 핸들러가 생성될 때도 별도 설정이 없으면 갖는 디폴트 로그 레벨 |\n| DEBUG | 10 | 디버그 용도로 사용되는 정보 |\n\n\n\n### 4.6.2 핸들러\n\n- 로거에 있는 메세지에 무슨 작업을 할지 결정하는 엔진\n\n \n\n### 4.6.3 필터\n\n- 로그 레코드가 로거에서 핸들러로 넘겨질 때, 필터를 사용해서 로그 레코드에 추가적인 제어\n\n \n\n### 4.6.4 포맷터\n\n- 로그 레코드는 최종적으로 텍스트로 표현되는데, 포멧터는 텍스트로 표현 시 사용할 포멧을 지정해줌\n\n\n\n### 4.6.5 로거 사용 및 로거 이름 계층화\n\n\n\n### 4.6.6 장고의 디폴트 로깅 설정\n\n\n\n### 4.6.7 장고의 로깅 추가 사항 정리\n\n\n\n### 4.6.8 로깅 설정\n\n#### 디폴트 설정 유지\n\n#### 디폴트 설정 무시\n\n\n\n" }, { "alpha_fraction": 0.6300433278083801, "alphanum_fraction": 0.6460755467414856, "avg_line_length": 17.099037170410156, "blob_id": "8f3a96093f80bed32252d7aeb0638ba391d399ed", "content_id": "1870188a6c80395150843be37b0f813f3bb930a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 18379, "license_type": "no_license", "max_line_length": 238, "num_lines": 727, "path": "/django/Django.md", "repo_name": "winterconnect/Web_Programming", "src_encoding": "UTF-8", "text": "# Django\n\n\n\n# CHAPTER3 Django 웹 프레임워크\n\n> 장고의 애플리케이션 개발 방식과 원리 설명\n\n\n\n## 3.1 일반적인 특징\n\n__MVC 패턴 기반 MVT(Model View Template)__\n\n- M(MODEL): 데이터 관점에서 조회, 저장 등 DB 모델링\n- V(VIEW): UI, 프로트엔드\n- C(CONTROLLER): 백엔드\n\n\n\n- 장고에서는 VIEW가 백엔드, TEMPLATE이 프론트엔드\n\n\n\n__객체 관계 매핑__\n\n- db.things.save()\n\n\n\n__자동으로 구성되는 관리자 화면__\n\n\n\n__우아한 URL 설계__\n\n\n\n__자체 템플릿 시스템__\n\n- 디자인과 로직에 대한 코딩을 분리하여 독립적으로 개발 진행\n\n\n\n__캐시 시스템__\n\n\n\n__다국어 지원__\n\n\n\n__풍부한 개발 환경__\n\n\n\n__소스 변경사항 자동 반영__\n\n\n\n\n\n## 3.3 장고에서의 애플리케이션 개발 방식\n\n> 전체 프로그램을 __프로젝트 Project__ 라고 하고, 모듈화된 단위 프로그램을 __애플리케이션 Application__ 이라 부른다\n\n\n\n### 3.3.1 MVT 패턴\n\n### 3.3.2 Model - 데이터베이스 정의\n\n- __ORM 기법(Object-Relational Mapping)__: 객체와 관계형 데이터베이스를 연결\n- 애플리케이션에서 사용할 데이터베이스를 클래스로 매핑해서 코딩\n- 모델 클래스는 models.py 파일에 정의\n\n\n\n### 3.3.3 URLconf - URL 정의\n\n- 클라이언트로 요청을 받으면 요청이 들어있는 URL을 분석\n- urls.py파일에 URL 과 처리함수(view)를 맵핑하는 파이썬 코드를 작성\n\n\n\n### 3.3.4 View - 로직 정의\n\n- 웹 요청을 받아서 해당 애플리케이션의 로직에 맞는 처리를 하고(데이터베이스 접속 등)\n- 그 결과 데이터를 HTML로 변환하기 위해 템플릿 처리를 한 후,\n- 최종 HTML로 된 응답데이터를 웹 클라이언트로 반환하는 역할\n\n\n\n- 뷰는 함수 또는 클래스의 메소드로 작성되며, 웹 요청을 받고 응답을 반환함\n\n- 보통 views.py 파일에 작성\n\n\n\n### 3.3.5 Template - 화면 UI 정의\n\n- settings.py 파일에 정의되어 있음\n- \n\n### 3.3.6 MVT 코딩 순서\n\n> 모델, 뷰, 템플릿 셋 중 무엇을 먼저 코딩해야하는 지에 대해 정해진 순서는 없음\n>\n> 화면 설계: 뷰와 템플릿 코딩으로 연결\n>\n> 테이블 설계: 모델 코딩에 반영\n\n따라서 독립적으로 개발할 수 있는 모델를 먼저 코딩, \n\n뷰와 템플릿은 서로 영향을 미치므로 모델 이후에 같이 코딩하는 것이 일반적\n\n\n\n__순서__\n\n- 프로젝트 뼈대 만들기: 프로젝트 및 앱 개발에 필요한 디렉토리와 파일 생성\n- 모델 코딩하기: 테이블 관련 사항을 개발(models.py, admin.py)\n- URLconf 코딩하기: URL 및 뷰 매핑 관계를 정의(urls.py)\n- 템플릿 코딩하기: 화면 UI 개발(templates/*.html)\n- 뷰 코딩하기: 애플리케이션 로직 개발(views.py)\n\n\n\n\n\n## 실습: 프로젝트 & 애플리케이션 개발\n\n\n\n## 3.4 애플리케이션 설계하기\n\n1. 프로젝트란? 개발 대상이 되는 전체 프로그램을 의미\n\n2. 애플리케이션이란? 프로젝트 하위의 서브 프로그램\n\n\n\n서브 프로그램인 애플리케이션을 개발하고, 이들을 모아서 프로젝트 개발을 완성!\n\n\n\n> __*개발할 애플리케이션*__\n>\n> - 설문에 해당하는 질문을 보여준 후, 질문에 포함되어 있는 답변 항목에 투표하면 결과를 알려주는 예제\n> - 3개의 페이지를 기준으로 개발한다고 가정\n> - index.html: 질문 리스트\n> - detail.html: 질문에 대한 답변 항목\n> - results.html: 질문에 따른 투표 결과\n> - 테이블: Question(질문 저장 테이블), Choice(답변 저장 테이블)\n\n\n\n\n\n## 3.5 프로젝트 뼈대 만들기\n\n- 프로젝트에 필요한 디렉토리 및 파일을 구성, 설정파일 셋팅\n- 기본테이블 생성\n- 슈퍼유저(관리자 계정) 생성\n- 프로젝트 생성 후 애플리케이션 디렉토리 및 파일 구성\n\n\n\n### 3.5.1 프로젝트 생성\n\n```\ndjango-admin startproject mysite\nmv mysite ch3\n```\n\n\n\n### 3.5.2 애플리케이션 생성\n\n```\npython3 manage.py startapp polls // polls 라는 애플리케이션 생성\n```\n\n- admin\n- apps\n- models\n- views\n- tests\n- migration/\n\n\n\n### 3.5.3 프로젝트 설정 파일 변경\n\nnotepad settings.py: 설정파일을 확인 및 수정\n\n- settings.py: 프로젝트의 전반적인 사항들을 설정해주는 곳\n\n```python\n # True면 개발모드, False면 운영모드\nDEBUG = True\n\n# runserver 기동할 서버 IP\nALLOWED_HOSTS = [ 'localhost' , '127.0.0.1' ] \n\n# Application definition\n# 생성한 polls 애플리케이션의 apps.py 파일의 PollsConfig 클래스를 프로젝트 애플리케이션에 등록\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'polls.apps.PollsConfig', # 추가\n]\n\n# Database\n# https://docs.djangoproject.com/en/3.1/ref/settings/#databases\n# 기본 SQLite3 데이터베이스 엔진을 사용하도록 설정 \n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3',\n 'NAME': BASE_DIR / 'db.sqlite3',\n }\n}\n\n# Internationalization\n# https://docs.djangoproject.com/en/3.1/topics/i18n/\n# 타임존 변경\n\nLANGUAGE_CODE = 'en-us'\n# TIME_ZONE = 'UTC'\nTIME_ZONE = 'Asia/Seoul'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n```\n\n\n\n### 3.5.4 기본 테이블 생성\n\n데이터베이스에 기본 테이블을 생성\n\n```\npython3 manage.py migrate \n```\n\n- 장고는 모든 웹 프로젝트 개발 시 반드시 사용자와 그룹 테이블이 필요하다는 가정 하에 설계\n- 따라서 테이블을 만들지 않았더라도 사용자 및 그룹 테이블 등을 만들어주기 위해 프로젝트 개발 시작 시점에 이 명령을 실행\n- 실행 결과로 SQLite3 데이터베이스 파일인 db.sqlite3 파일이 생성됨\n\n\n\n\n\n### 3.5.5 지금까지 작업 확인하기\n\n현재까지 작업을 개발용 웹 서버로 확인\n\n```\npython3 manage.py runserver 0:8000\n```\n\n\n\n1. http://localhost:8000 으로 접속\n\n2. http://localhost:8000/admin 으로 접속\n3. 슈퍼유저 생성\n\n```\npython3 manage.py createsuperuser\n```\n\n```\nwinter@Winterui-MacBookPro practice % tree /F ch3\n/F [error opening dir]\nch3\n├── db.sqlite3\n├── manage.py\n├── mysite\n│   ├── __init__.py\n│   ├── __pycache__\n│   │   ├── __init__.cpython-39.pyc\n│   │   ├── settings.cpython-39.pyc\n│   │   ├── urls.cpython-39.pyc\n│   │   └── wsgi.cpython-39.pyc\n│   ├── asgi.py\n│   ├── settings.py\n│   ├── urls.py\n│   └── wsgi.py\n└── polls\n ├── __init__.py\n ├── __pycache__\n │   ├── __init__.cpython-39.pyc\n │   ├── admin.cpython-39.pyc\n │   ├── apps.cpython-39.pyc\n │   └── models.cpython-39.pyc\n ├── admin.py\n ├── apps.py\n ├── migrations\n │   ├── __init__.py\n │   └── __pycache__\n │   └── __init__.cpython-39.pyc\n ├── models.py\n ├── tests.py\n └── views.py\n\n6 directories, 23 files\n```\n\n\n\n## 3.6 애플리케이션 개발하기 - Model 코딩\n\n- 모델작업: 데이터베이스에 테이블을 생성하는 작업\n\n> 1. notepad models.py\n> 2. notepad admins.py\n> 3. python3 manage.py makemigrations\n> 4. python3 manage.py migrate\n> 5. python3 manage.py runserver\n\n\n\n### 3.6.1 테이블 정의\n\n- polls 애플리케이션: Question, Choice 두개의 테이블 필요\n- 테이블은 models.py 파일에 정의\n\n```python\n# models.py\n\nfrom django.db import models\n\n# Create your models here.\n\nfrom django.db import models\n\nclass Question(models.Model):\n question_text = models.CharField(max_length = 200)\n pub_date = models.DateTimeField('date published')\n \n def __str__(self):\n return self.question_text\n \nclass Choice(models.Model):\n question = models.ForeignKey(Question, on_delete = models.CASCADE)\n choice_text = models.CharField(max_length = 200)\n votes = models.IntegerField(default = 0)\n \n def __str__(self):\n return self.choice_text\n```\n\n- 장고에서는 테이블을 하나의 클래스로 정의, 테이블의 컬럼은 클래스의 변수(속성)로 매핑함\n- 테이블 클래스는 django.db.models.Model 클래스를 상속받아 정의\n- 각 클래스 변수의 타입도 장고에서 미리 정의된 필드 클래스를 사용\n\n\n\n### 3.6.2 Admin 사이트에 테이블 반영\n\n- models.py 파일에서 정의한 테이블이 Admin 사이트 화면에 보이게 함\n\n- admins.py 파일에 등록해주면 됨\n\n```python\n# admin.py\n\nfrom django.contrib import admin\nfrom polls.models import Question, Choice \n# models.py 모듈에서 정의한 Question, Choice 클래스를 임포트\n\n# admin.site.register() 함수를 이용하여 임포트한 클래스를 Admin 사이트에 등록\nadmin.site.register(Question)\nadmin.site.register(Choice)\n```\n\n- 테이블을 새로 만들 때는 models.py, admin.py 두 개의 파일을 함께 수정해야함!\n\n\n\n### 3.6.3 데이터베이스 변경사항 반영\n\n```\npython3 manage.py makemigrations # 데이터베이스에 변경이 필요한 사항을 추출함\npython3 manage.py migrate \t\t\t\t# 데이터베이스에 변경사항을 반영함\n```\n\n- migration\n - 테이블 및 필드의 생성, 삭제, 병경 등과 같은 데이터베이스에 대한 변경사항을 알려주는 정보\n - 애플리케이션 디렉토리별로 migration 파일이 존재\n - makemigrations 명령에 의해 polls/migrations 디렉토리 하위에 마이그레이션 파일들이 생김\n - 이 마이그레이션 파일들을 이용해 migrate 명령으로 데이터베이스에 테이블을 만들어줌\n\n\n\n- models.py 모듈에 정의한 테이블을 migrate 명령으로 데이터베이스에 반영할 때, 장고가 사용하는 SQL 문장 확인\n\n```\nwinter@Winterui-MacBookPro ch3 % python3 manage.py sqlmigrate polls 0001\n```\n\n```\nBEGIN;\n--\n-- Create model Question\n--\nCREATE TABLE \"polls_question\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"question_text\" varchar(200) NOT NULL, \"pub_date\" datetime NOT NULL);\n--\n-- Create model Choice\n--\nCREATE TABLE \"polls_choice\" (\"id\" integer NOT NULL PRIMARY KEY AUTOINCREMENT, \"choice_text\" varchar(200) NOT NULL, \"votes\" integer NOT NULL, \"question_id\" integer NOT NULL REFERENCES \"polls_question\" (\"id\") DEFERRABLE INITIALLY DEFERRED);\nCREATE INDEX \"polls_choice_question_id_c5b4b260\" ON \"polls_choice\" (\"question_id\");\nCOMMIT;\n```\n\n\n\n\n\n### 3.6.4 지금까지 작업 확인하기\n\n현재까지 작업을 개발용 웹 서버로 확인함\n\n```\npython3 manage.py runserver\n```\n\n\n\n\n\n## 3.7 애플리케이션 개발하기 - View 및 Template 코딩\n\n- polls 애플리케이션의 3개의 페이지를 보여주기 위해 필요한 뷰와 템플릿을 코딩\n\n- 요청에서 응답까지의 처리흐름에 대한 로직 설계: 4개의 URL과 뷰가 필요하다고 판단\n\n- URL과 뷰는 1:1 관계로 매핑됨 (N:1도 가능)\n- URLconf: URL/뷰 매핑을 의미\n- urls.py 파일에 작성\n\n\n\n>__순서__\n>\n>- urls.py 작성\n>- views.index() 함수 작성\n>- views.detail() 함수 작성\n>- views.vote() 함수 작성\n>- views.results() 함수 작성\n\n\n\n### 3.7.1 URLconf 코딩\n\n__mysite/urls.py 파일 코딩__\n\n```python\n# urls.py\n\nfrom django.contrib import admin\nfrom django.urls import path\nfrom polls import views\n\n\n# URL/뷰 매핑 정의\n# URL 패턴 매칭은 위에서 아래로 진행하므로 순서에 유의\nurlpatterns = [\n path('admin/', admin.site.urls), # 장고의 Admin 사이트에 대한 URLconf는 이미 정의되어 있음\n path('polls/', views.index, name='index'),\n path('polls/<int:question_id>/', views.detail, name='detail'),\n path('polls/<int:question_id>/results/', views.results, name='results'),\n path('polls/<int:question_id>/vote/', views.vote, name='vote'),\n]\n```\n\n\n\n- mysite/settings.py 파일에 ROOT_URLCONF 항목이 정의되어 있음\n\n```python\n# settings.py\n\nROOT_URLCONF = 'mysite.urls'\n```\n\n\n\n\n\n__mysite/urls.py 와 polls/urls.py 두가지 파일로 작성__\n\n- 더 좋은 방법임!\n - URLconf 모듈을 계층적으로 구성 - 변경과 확장 용이해짐\n - 재사용이 용이해짐\n\n```python\n# mysite/urls.py\n\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('polls/', include('polls.urls')),\n]\n```\n\n\n\n```python\n# polls/urls.py\n\nfrom django.urls import path\nfrom . import views\n\napp_name = 'polls'\nurlpatterns = [\n path('', views.index, name='index'),\n path('<int:question_id>/', views.detail, name='detail'),\n path('<int:question_id>/results/', views.results, name='results'),\n path('<int:question_id>/vote/', views.vote, name='vote'), # vote 버튼을 누르면 vote() 뷰 함수가 호출됨\n]\n```\n\n\n\n### 3.7.2 뷰 함수 index() 및 템플릿 작성\n\n- 화면에 질문을 보여주는 로직을 구현하기 위해 뷰 함수와 템플릿 파일을 각각 코딩\n- 뷰 함수와 템플릿은 서로 영향을 미치므로 보통 같이 작업\n- UI 화면을 생각하면서 로직을 풀어나가는 것이 쉽기 때문에 템플릿을 먼저 코딩하는 것을 추천\n\n\n\n__템플릿 작성__\n\n```html\n<!--polls/templates/polls/index.html-->\n\n{% if latest_question_list %}\n <ul>\n {% for question in latest_question_list %}\n <li><a href = \"/polls/{{ question.id }}/\">{{ question.question_text }}</a></li>\n {% endfor %}\n </ul>\n{% else %}\n <p>No polls are available.</p>\n{% endif %}\n```\n\n\n\n__views.index() 함수 작성__\n\n- 최종적으로 클라이언트에게 응답할 데이터인 HttpResponse 객체를 반환\n\n```python\n# polls/views.py\n\nfrom django.shortcuts import render\nfrom polls.models import Question\n\ndef index(request):\n latest_question_list = Question.objects.all().order_by('-pub_date')[:5]\n context = {'latest_question_list': latest_question_list}\n return render(request, 'polls/index.html', context)\n```\n\n\n\n\n\n### 3.7.3 뷰 함수 detail() 및 폼 템플릿 작성\n\n- 템플릿 작성: detail.html\n\n```html\n<h1>{{ question.question_text }}</h1>\n\n{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}\n\n<form action=\"{% url 'polls:vote' question.id %}\" method = \"post\">\n{% csrf_token %}\n{% for choice in question.choice_set.all %}\n <input type=\"radio\" name=\"choice\" id=\"choice{{ forloop.counter }}\" value=\"{{ choice.id }}\" />\n <label for=\"choice{{ forloop.counter }}\">{{ choice.choice_text }}</label><br />\n{% endfor %}\n<input type=\"submit\" value=\"Vote\" />\n</form>\n```\n\n\n\n- views.py에 detail() 함수 작성\n\n```python\n# views.py \n\nfrom django.shortcuts import get_object_or_404, render\nfrom polls.models import Question\n\ndef index(request):\n latest_question_list = Question.objects.all().order_by('-pub_date')[:5]\n context = {'latest_question_list': latest_question_list}\n return render(request, 'polls/index.html', context)\n\ndef detail(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n return render(request, 'polls/detail.html', {'question': question})\n```\n\n\n\n### 3.7.4 뷰 함수 vote() 및 리다이렉션 작성\n\n- views.py에 vote() 뷰 함수 작성 \n\n```python\nfrom django.shortcuts import get_object_or_404, render\nfrom django.http import HttpResponseRedirect\nfrom django.urls import reverse\nfrom polls.models import Choice, Question\n\ndef index(request):\n latest_question_list = Question.objects.all().order_by('-pub_date')[:5]\n context = {'latest_question_list': latest_question_list}\n return render(request, 'polls/index.html', context)\n\ndef detail(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n return render(request, 'polls/detail.html', {'question': question})\n\ndef vote(request, question_id):\n question = get_object_or_404(Question, pk=question_id)\n try:\n selected_choice = question.choice_set.get(pk=request.POST['choice'])\n except (KeyError, Choice.DoesNotExist):\n #설문 투표 폼을 다시 보여준다\n return render(request, 'polls/detail.html', {\n 'question': question,\n 'error_message': \"You didn't select a choice.\",\n })\n else:\n selected_choice.votes += 1\n selected_choice.save()\n \n # POST 데이터를 정상적으로 처리하였으면,\n # 항상 HttpResponseRedirect를 반환하여 리다이렉션 처리함\n return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))\n```\n\n\n\n__reverse() 함수__\n\n- URL패턴명으로 URL스트링을 구할 수 있음\n\n- URLconf에 이미 정의된 URL 패턴을 활용해서 URL 스트링을 추출하는 방식이므로, 소스에 URL 스트링을 하드코딩하지 않도록 해줌\n\n\n\n\n\n### 3.7.5 뷰 함수 results() 및 템플릿 작성\n\n- results.html 입력\n\n```html\n<h1>{{ question.question_text}}</h1>\n\n<ul>\n{% for choice in question.choice_set.all %}\n <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>\n{% endfor %}\n</ul>\n\n<a href=\"{% url 'polls:detail' question.id %}\">Vote again?</a>\n```\n\n\n\n### 3.7.6 지금까지 작업 확인하기\n\n\n\n-----\n\n- 서버가 request 를 받으면 데이터베이스를 관리하는 어플리케이션이 정보를 조회한 후 html로 전송\n\n- 웹 서버, 데이터베이스 서버를 분리함(과부하 방지)\n\n- 웹프로그램을 한다는 것은? 웹서버 개발\n\n 1. 사이트 설계\n\n 2. 사이트 설계를 토대로 데이터베이스 설계\n 3. 인터페이스 설계\n\n- 장고와 같은 웹 프레임워크를 사용하여 웹 서버 개발\n\n\n\n\n\n\n\n- 데이터베이스에 바로 접속할 수 없다\n\n ex) 공공기관(주민센터)에서 공공 데이터베이스에 접속한다면, 바로 db에 접속하는 것이 아니라 인터페이스로 접속\n\n 인터페이스에 맞춰 정보들을 담아 주민센터로 접속\n\n 인터페이스의 순서는 규약으로 정해져있음 (주민센터-데이터베이스 간)\n\n- 어플리케이션에서는 __API(Application Interface)__, 웹에서는 __CGI (Common Gateway Interface)__\n\n\n\n- request: header 파일: 각종 정보를 넣어 전송\n- response header 파일\n\n\n\n" }, { "alpha_fraction": 0.646869957447052, "alphanum_fraction": 0.646869957447052, "avg_line_length": 47, "blob_id": "c731ad901d594b4ae4f7cbfbd7b9b2287f7780da", "content_id": "e8de61292cfa3049693f7cbae662eacb9aa40c91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 623, "license_type": "no_license", "max_line_length": 92, "num_lines": 13, "path": "/django/practice/root/books/urls.py", "repo_name": "winterconnect/Web_Programming", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\napp_name = 'books'\nurlpatterns = [\n path('', views.BooksModelView.as_view(), name = 'index'),\n path('book/', views.BookList.as_view(), name = 'book_list'), \n path('author/', views.AuthorList.as_view(), name = 'author_list'),\n path('publisher/', views.PublisherList.as_view(), name = 'publisher_list'),\n path('book/<int:pk>/', views.BookDetail.as_view(), name = 'book_detail'),\n path('author/<int:pk>/', views.AuthorDetail.as_view(), name = 'author_detail'),\n path('publisher/<int:pk>/', views.PublisherDetail.as_view(), name = 'publisher_detail'),\n]" } ]
6
Sayak11/Hactoberfest
https://github.com/Sayak11/Hactoberfest
82846be277991cdfbee47196411381fef788d87f
b6031966d23b143d6580867be04f980cbbeb734b
e25881ddb45d0480b74b5b84a6cb21febb928b76
refs/heads/master
2023-08-21T23:45:44.561098
2021-10-17T01:27:28
2021-10-17T01:27:28
298,512,122
0
2
MIT
2020-09-25T08:20:28
2021-10-17T01:27:16
2021-10-17T01:27:28
Java
[ { "alpha_fraction": 0.8374999761581421, "alphanum_fraction": 0.8374999761581421, "avg_line_length": 79, "blob_id": "e6c4e0fc6c31c43979bc5cbc89eae0bed17cb32e", "content_id": "5241511bfeee6ff34ad2d39ef8c8a4063e8239bb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 80, "license_type": "permissive", "max_line_length": 79, "num_lines": 1, "path": "/README.md", "repo_name": "Sayak11/Hactoberfest", "src_encoding": "UTF-8", "text": "# Following repo consists of various programs on basic competitive programming.\n" }, { "alpha_fraction": 0.524193525314331, "alphanum_fraction": 0.5322580933570862, "avg_line_length": 22.399999618530273, "blob_id": "5291667183fcca19c8b7411245542ea1176da050", "content_id": "295392f83ce21a74b6c60bfd1c942e12ade1df7e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "permissive", "max_line_length": 49, "num_lines": 10, "path": "/even_odd.py", "repo_name": "Sayak11/Hactoberfest", "src_encoding": "UTF-8", "text": "\r\n\r\ndef even_odd(x):\r\n # Todo: Code to determine & print even or odd\r\n if (x % 2) == 0:\r\n print(x,\"is Even\".format(x))\r\n else:\r\n print(x,\"is Odd\".format(x))\r\n\r\nprint(\"Enter your number\")\r\nx=int(input().strip())\r\neven_odd(x)\r\n" } ]
2
moman102/Python-Basis
https://github.com/moman102/Python-Basis
9e18c4882107b8325174effa013b883b33cbde1f
a4610a8b4fa2992df350f27ad61c6d47d575efcb
856c6c09444d3a1cce15095b949ef8070e1c241d
refs/heads/main
2023-04-12T09:48:41.785759
2021-05-06T23:42:10
2021-05-06T23:42:10
364,757,743
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5369649529457092, "alphanum_fraction": 0.5408560037612915, "avg_line_length": 16.066667556762695, "blob_id": "7d515c2aad5df599ae9976be4f93574546d65c66", "content_id": "4b1b52981c4271e031accfed71352dc3d63401c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 257, "license_type": "no_license", "max_line_length": 30, "num_lines": 15, "path": "/Practice.py", "repo_name": "moman102/Python-Basis", "src_encoding": "UTF-8", "text": "string = input(\"~ \")\n\nchars=''\nnums= []\ntotal = 0\nfor char in string:\n if char.isdigit():\n nums.append(int(char))\n total += int(char)\n else:\n chars += char\n\nprint(\"nums : \" , nums)\nprint(\"chars :\" , chars)\nprint(\"total :\",total)\n\n" }, { "alpha_fraction": 0.5600000023841858, "alphanum_fraction": 0.5600000023841858, "avg_line_length": 19, "blob_id": "1b65d06861d9be4649470d5a260c535e67b9cc8a", "content_id": "e80d168dada3baee43d5b83beee6ba4386a2f0ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 44, "num_lines": 10, "path": "/files.py", "repo_name": "moman102/Python-Basis", "src_encoding": "UTF-8", "text": "with open(\"test.txt\", \"r\") as file:\n data = file.read()\n\nprint(data)\n\nname = input(\"name : \")\nage = input(\"age : \")\n\nwith open(\"write.txt\", \"a+\") as f:\n f.write(f\"{name} is {age} years old\\n \")\n" }, { "alpha_fraction": 0.469696968793869, "alphanum_fraction": 0.469696968793869, "avg_line_length": 13.55555534362793, "blob_id": "c5bfcfe7c6b41d4b01171cc935e4722346886c66", "content_id": "783a2cb5a0bbc4a1900a8f6460d23eff81bd623c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 132, "license_type": "no_license", "max_line_length": 24, "num_lines": 9, "path": "/Math.py", "repo_name": "moman102/Python-Basis", "src_encoding": "UTF-8", "text": "a = int(input(\" a : \"))\nb = int(input(\" b : \"))\n\nprint(a + b)\nprint(a * b)\nprint(a // b)\nprint(a / b)\nprint(a ** b)\nprint(a % b)\n\n" }, { "alpha_fraction": 0.5542168617248535, "alphanum_fraction": 0.5794085264205933, "avg_line_length": 19.266666412353516, "blob_id": "572ede1f66a26a84d6ea0965933bb6d13ec6cd50", "content_id": "22eb586aa3ee078ccb51000f6063ca0d2633785e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 913, "license_type": "no_license", "max_line_length": 61, "num_lines": 45, "path": "/Lists.py", "repo_name": "moman102/Python-Basis", "src_encoding": "UTF-8", "text": "shoppingcart = [\"apple \", \"ananas \", \"mangos\", \"bread\"]\nshoppingcart.pop(2)\nprint(shoppingcart)\nshoppingcart.append(\"papaya\")\nprint(shoppingcart)\n\nshoppinglist = []\nquit = False\n\nwhile not quit:\n userInput = input(\"y to add more items , n to stop : \")\n if userInput.lower() == \"y\":\n item = input(\"enter item :\")\n shoppinglist.append(item)\n elif userInput.lower() == \"n\":\n quit = True\n else:\n print(\"Invalid input\")\n\nprint(\"your shopping list contains : \", shoppinglist)\n\nlist = [\"z\",\"a\" , \"b\" , \"c\" , \"d\"]\nlist.sort()\nfor item in list:\n if item == 'd':\n print(list.index('d'))\n print(item)\n\nAlex = {\n \"firstname \": \"Alex \",\n \"Matrikel nr \": \"266186\",\n \"Age\": \"22\",\n \"sex\":\"M\"\n}\n\nprint(Alex[\"firstname \"],Alex[\"Matrikel nr \"])\nAlex[\"Tel\"] = \"123456789\"\n\nprint(Alex)\n\nfor n in Alex.values():\n print(n)\n\ntuple1 = (\"ALex\" , \"123\")\nprint(tuple1)\n\n" }, { "alpha_fraction": 0.5336700081825256, "alphanum_fraction": 0.5538720488548279, "avg_line_length": 15.971428871154785, "blob_id": "a1f9ddaf3af6dfb019c23d82916b273264c1c993", "content_id": "e13abcaad16acbb6f5b4235072cec23ef4ebe060", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 44, "num_lines": 35, "path": "/loops.py", "repo_name": "moman102/Python-Basis", "src_encoding": "UTF-8", "text": "bestehquote = int(input(\" bestehquote : \"))\nnote = int(input(\"student note : \"))\n\nif note >= bestehquote:\n print(\"Bestanden !\")\n\nelif note < bestehquote:\n print(\"nicht bestanden !\")\n\n\nfor i in range(1,51, 10):\n print(i)\n\nstring = \"This is a String !\"\ntcount = 0\nfor char in string:\n if char.lower()=='t':\n tcount = tcount +1\n\nprint(\"t count is :\" , tcount)\n\nx = 0\n\nwhile x <= 5:\n print(x)\n x = x + 1\nisCharA = False\n\ny = 0\nwhile not isCharA :\n if string[y].lower() == 'a':\n print(f\"A exist at Index {y}\")\n isCharA = True\n else :\n y = y + 1\n" }, { "alpha_fraction": 0.5439093708992004, "alphanum_fraction": 0.5694050788879395, "avg_line_length": 15.350000381469727, "blob_id": "793bb1d80a6359d1c2e93cf9351289fca4572bd3", "content_id": "1a9c8474e2c46023b7b6e82822a19d8847e7ceaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 28, "num_lines": 20, "path": "/first.py", "repo_name": "moman102/Python-Basis", "src_encoding": "UTF-8", "text": "print(\"Hello World !\")\r\nprint(\" /|\")\r\nprint(\" / |\")\r\nprint(\" / |\")\r\nprint(\"/___|\")\r\n\r\n\r\npi = 3.14\r\nprint(pi)\r\nname = \"° Python °\"\r\nprint(name)\r\na = int(pi)\r\nprint(a)\r\nprint(type(a))\r\ntest_string = \"stringtest\"\r\nprint(test_string[0])\r\nprint(test_string[2:6])\r\nprint(test_string[6:10])\r\nprint(test_string.upper())\r\nprint(test_string.isupper())\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.5911949872970581, "alphanum_fraction": 0.6006289124488831, "avg_line_length": 16.66666603088379, "blob_id": "76512e86f154bc3aa61c3bfd70ba777cfa2cb372", "content_id": "c9329f7e2c811898e6f1b665843c39d0245549c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "no_license", "max_line_length": 33, "num_lines": 18, "path": "/functions.py", "repo_name": "moman102/Python-Basis", "src_encoding": "UTF-8", "text": "def areaOfTriangle(base, height):\n return base * height * 1 / 2\n\n\nb = int(input(\"b : \"))\nh = int(input(\"h : \"))\n\narea = areaOfTriangle(b, h)\nprint(area)\n\ndef isPalendrome(var):\n if var == var[::-1]:\n return True\n else:\n return False\n\nprint(isPalendrome(\"refer\"))\nprint(isPalendrome(\"refere\"))\n" }, { "alpha_fraction": 0.8085106611251831, "alphanum_fraction": 0.8085106611251831, "avg_line_length": 22.5, "blob_id": "3f6e86b1512cb05751bfc1e9484673476c24d0b4", "content_id": "8b6a0e2f686e87bd749a4bf328183653b17a89f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 47, "license_type": "no_license", "max_line_length": 36, "num_lines": 2, "path": "/README.md", "repo_name": "moman102/Python-Basis", "src_encoding": "UTF-8", "text": "# Python-\nmy learning progressions with Python\n" } ]
8
ErfanPY/Insta-Finder
https://github.com/ErfanPY/Insta-Finder
67708279571a4e8ee536b2322d9feffe64a83af6
bedc8be0a41c46a8858a35c53a68f8f5a8a0deeb
53ee4b24c05f40089d409fe11f5c317a06f58f79
refs/heads/master
2022-01-30T13:01:01.820162
2022-01-16T20:05:20
2022-01-16T20:05:20
239,370,035
0
1
MIT
2020-02-09T20:32:55
2020-02-10T20:44:13
2020-02-10T21:06:32
Python
[ { "alpha_fraction": 0.5611674785614014, "alphanum_fraction": 0.5700682997703552, "avg_line_length": 31.86394500732422, "blob_id": "bd2173a38dc6474ebb888146bae0dcd7773c4da2", "content_id": "6847b6c65d7b7037e5e5e1c592dd00b30114b046", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4831, "license_type": "permissive", "max_line_length": 146, "num_lines": 147, "path": "/main.py", "repo_name": "ErfanPY/Insta-Finder", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport os\nimport instaloader\nfrom dotenv import loadenv\nfrom sightengine.client import SightengineClient\n\nloadenv()\n\nusername = os.environ.get(\"INSTA_USERNAME\")\npassword = os.environ.get(\"INSTA_PASSWORD\")\n\nif not username:\n print(\"Please put Instagram Username and Password in INSTA_USERNAME, INSTA_PASSWORD environment variables.\"\n exit(1)\n\ninstaClient = instaloader.Instaloader()\ninstaClient.login(username, password)\n\nsight_key = os.environ.get(\"SIGHT_KEY\")\nsight_hash = os.environ.get(\"SIGHT_HASH\")\n\nif not sight_key:\n print(\"Please put sightengine api key, hash in SIGHT_KEY, SIGHT_HASH environment variables.\")\n exit(1)\n\napiClient = SightengineClient(sight_key, sight_hash)\n\nclass node ():\n def __init__(self, userPro, viewer):\n self.viewer = viewer\n self.qualuty = 0\n self.posts = []\n self.users = []\n \n if type(userPro) == str :\n self.username = userPro\n self.profile = instaloader.Profile.from_username(viewer.context, userPro)\n else:\n self.username = userPro.username\n self.profile = userPro\n \n if debug : print('Node ({}) Made'.format(self.username))\n\n def calcFitScroe(self, gender='male', num=10, adult=1, nude=0):\n self.fitScore = 0\n inum = 0\n \n for post in self.profile.get_posts():\n if inum >= num : break\n output = apiClient.check('nudity','face-attributes').set_url('{}'.format(post.url))\n try :\n attr = output['faces'][0]['attributes']\n except:\n print('NO FACE DETECTED')\n continue\n \n ageScore = (1*adult)+(-1*adult)* attr['minor']\n nudeScore = (1*nude)+(-1*nude)* output['nudity']['safe']\n try :\n if output['nudity']['partial_tag']:nusescore = 1\n except :\n pass\n \n imgFitScore = (attr[gender] + ageScore + nudeScore)/3\n \n self.fitScore += imgFitScore\n self.posts.append({post:[output, imgFitScore]})\n\n inum += 1\n if debug : print('Image Score:{} \\ngender{}:{} adult{}:{} nude{}:{}\\n{}\\n'.format(\n imgFitScore, gender, attr[gender], adult, ageScore, nude, nudeScore, post.url))\n \n self.fitScore /= num\n return self.fitScore\n \n def expandNode (self, option, num):\n if 'folower' in option :\n self.followers = self.profile.get_followers()\n for follower in self.followees:\n if debug :print('Expanding By Followers')\n \n if len(self.users) >= num:\n break\n usersNode = node(follower, self.viewer)\n users.append(userNode)\n\n if 'folowing' in option :\n self.followees = self.profile.get_followees()\n for followee in self.followees:\n if debug :print('Expanding By Followees')\n \n if len(self.users) >= num:\n break\n usersNode = node(followee, self.viewer)\n users.append(userNode)\n \n if 'tag' in option :\n for post in self.profile.get_tagged_posts():\n if debug :print('Expanding By Tag')\n \n self.posts.append(post)\n \n if len(self.users) >= num:\n break\n for user in post.tagged_users :\n if user != self.username :\n userNode = node(user, self.viewer)\n self.users.append(userNode) \n\n return self.users[:num]\n\nif __name__ == \"__main__\":\n seed_username = os.environ.get(\"SEED_USERNAME\")\n if not seed_username:\n print(\"Please set SEED_USERNAME in environmet variables.\")\n exit(1)\n\n testNode = node(, instaClient)\n fitScore = testNode.calcFitScroe(gender=os.environ.get(\"SEED_GENDER\"), num=4, adult=1, nude=1)\n if fitScore >= 0.45:\n testNode.expandNode('tag folowing', 10)\n \n\n#TODO:\n'''\n1_get page posts\n2_send to picture detect api\n3_get folowee if is high score\n'''\n#TOTEST\n'''\nPost.location\n\nfor post in L.get_hashtag_posts('cat'):\n # post is an instance of instaloader.Post\n L.download_post(post, target='#cat')\n\n#Profile.from_id(L.context, USERID)\n#post = Post.from_shortcode(L.context, SHORTCODE)\n'''\n#API\n'''\n# if you haven't already, install the SDK with \"pip install sightengine\"\nfrom sightengine.client import SightengineClient\nclient = SightengineClient('1169033501', '7ymikLMsYSdhYpjVA2xd')\noutput = client.check('nudity','celebrities','faces','scam','face-attributes').set_url('https://sightengine.com/assets/img/examples/example7.jpg')\n'''\n" }, { "alpha_fraction": 0.6952381134033203, "alphanum_fraction": 0.6984127163887024, "avg_line_length": 21.5, "blob_id": "f5a25506628c2eb38dea68de8f6b4b6703d71913", "content_id": "550cbca3f77013c1f9285f18dc0de20aa472d476", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 315, "license_type": "permissive", "max_line_length": 93, "num_lines": 14, "path": "/README.md", "repo_name": "ErfanPY/Insta-Finder", "src_encoding": "UTF-8", "text": "# Insta Finder\n Expand your social network ;)\n\n Using a seed username on Instagram, the script will retrieve all followers of that person. \n If they pass the rating test, then they will be used as seed for further network expansion.\n \n# Usage\n ```\n mv .env.example .env \n vim .env\n ```\n ```\n python3 main.py\n ```\n" }, { "alpha_fraction": 0.7801046967506409, "alphanum_fraction": 0.7801046967506409, "avg_line_length": 30.83333396911621, "blob_id": "b9259e106bf1448f69bfaed75b7e9c0e7a088ce9", "content_id": "3c8df1bd3076004b6120fa9e1dbe2d7d1f0523a1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 191, "license_type": "permissive", "max_line_length": 40, "num_lines": 6, "path": "/.env.example", "repo_name": "ErfanPY/Insta-Finder", "src_encoding": "UTF-8", "text": "INSTA_USERNAME=<YOUR_INSTAGRAM_USERNAME>\nINSTA_PASSWORD=<YOUR_INSTAGRAM_PASSWORD>\nSIGHT_KEY=<YOUR_SIGHT_KEY>\nSIGHT_HASH=<YOUR_SIGHT_HASH>\nSEED_USERNAME=<YOUR_SEED_USERNAME>\nSEED_GENDER=<YOUR_SEED_GENDER>\n" } ]
3
Mythologyli/WeChat-Push
https://github.com/Mythologyli/WeChat-Push
e04501c514a5b75b5c8617c53757e5589e285596
1c843389c7dfabbfa315359664b61bd7ec26e9d8
630a51021f2dc59d6b17117bf2d0350ebbf8b21c
refs/heads/main
2023-06-15T02:41:03.616648
2022-05-27T15:22:43
2022-05-27T15:22:43
387,978,469
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4897504448890686, "alphanum_fraction": 0.4955436587333679, "avg_line_length": 25.399999618530273, "blob_id": "bf973e088783b05594c922511f05bcb4e14468b8", "content_id": "787d73f510f1bed7760218350f60c0a1d2963dfc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2352, "license_type": "permissive", "max_line_length": 111, "num_lines": 85, "path": "/wechatpusher.py", "repo_name": "Mythologyli/WeChat-Push", "src_encoding": "UTF-8", "text": "import requests\nimport json\n\n\nclass WeChatPusher:\n \"\"\"企业微信推送\"\"\"\n\n def __init__(self, corpid, agentid, corpsecret):\n # 企业ID\n self.corpid = corpid\n\n # 企业应用ID\n self.agentid = agentid\n\n # 应用的凭证密钥\n self.corpsecret = corpsecret\n\n # access_token\n self.access_token = ''\n\n # access_token 获取调用接口\n self.token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?'\n\n # 应用消息发送接口\n self.send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='\n\n # 请求 session\n self.sess = requests.Session()\n\n def _get_token(self):\n \"\"\"获取 access_token\"\"\"\n\n res = self.sess.get(self.token_url + 'corpid=' + self.corpid + '&corpsecret=' + self.corpsecret).json()\n\n if res['errcode'] != 0:\n return res['errcode']\n\n self.access_token = res['access_token']\n\n return 0\n\n def send(self, title, description='', url='', btntxt='', user='@all'):\n \"\"\"应用消息发送\"\"\"\n\n if description == '':\n description = title\n\n if url == '':\n url = 'https://github.com/Mythologyli/WeChatPusher'\n\n if self.access_token == '':\n res_get = self._get_token() # 更新 access_token\n if res_get != 0:\n return res_get\n\n data = {\n 'touser': user,\n 'toparty': '@all',\n 'totag': '@all',\n 'msgtype': 'textcard',\n 'agentid': self.agentid,\n 'textcard': {\n 'title': title,\n 'description': description,\n 'url': url,\n 'btntxt': btntxt\n },\n 'safe': 0,\n 'enable_id_trans': 0,\n 'enable_duplicate_check': 0,\n 'duplicate_check_interval': 1800\n }\n\n res = self.sess.post(url=(self.send_url + self.access_token), json=data).json()\n\n if res['errcode'] != 0: # 可能由 access_token 过期造成\n res_get = self._get_token() # 更新 access_token\n if res_get != 0:\n return res_get\n\n res = self.sess.post(url=(self.send_url + self.access_token), json=data).json()\n\n return res['errcode']\n else:\n return 0\n" }, { "alpha_fraction": 0.5677530169487, "alphanum_fraction": 0.5694682598114014, "avg_line_length": 19.821428298950195, "blob_id": "d0496ae8e5263b2f5b15a731dd8395b572508533", "content_id": "2143517ca70d9548e4e58accc5bee493bf132acb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 659, "license_type": "permissive", "max_line_length": 63, "num_lines": 28, "path": "/test.py", "repo_name": "Mythologyli/WeChat-Push", "src_encoding": "UTF-8", "text": "import os\nimport json\n\nfrom wechatpusher import WeChatPusher\n\n\ndef main():\n # 读取配置文件\n if os.path.exists('./config.json'):\n configs = json.loads(open('./config.json', 'r').read())\n corpid = configs[\"corpid\"]\n agentid = configs[\"agentid\"]\n corpsecret = configs[\"corpsecret\"]\n else:\n print('配置文件 config.json 不存在!')\n return\n\n push = WeChatPusher(corpid, agentid, corpsecret)\n\n res = push.send('发送消息测试')\n if res == 0:\n print('发送消息成功!')\n else:\n print('发送消息失败!错误代码:', res)\n\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.688524603843689, "alphanum_fraction": 0.7147541046142578, "avg_line_length": 21.629629135131836, "blob_id": "1f5edf9faa4d23d0851496a5ac9640355d5cf729", "content_id": "64402bdf6329b348849fdeadcc1299014d6ddf4f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1088, "license_type": "permissive", "max_line_length": 98, "num_lines": 27, "path": "/README.md", "repo_name": "Mythologyli/WeChat-Push", "src_encoding": "UTF-8", "text": "# WeChatPusher\n\n企业微信应用消息推送\n\n## 功能\n\n+ 发送文本卡片消息\n\n## 测试方法\n\n+ 使用 config.json.templ 文件为模版创建 config.json 文件,填写企业ID、企业应用ID、应用的凭证密钥\n+ 运行 ``python3 test.py``\n\n## 使用方法\n\n+ ``from wechatpusher import WeChatPusher``\n+ 创建实例 ``WeChatPusher(corpid, agentid, corpsecret)``\n+ 使用 push 方法发送文本卡片消息\n \n 必选参数:\n + title: 标题,不超过 128 个字节,超过会自动截断\n \n 可选参数有:\n + description: 描述,不超过 512 个字节,超过会自动截断。默认与标题一致\n + url: 点击后跳转的链接。最长 2048 字节,请确保包含了协议头(http/https)。默认为 https://github.com/Mythologyli/WeChatPusher\n + btntxt: 按钮文字。默认为“详情”,不超过 4 个文字,超过自动截断\n + user: 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持 1000 个)。特殊情况:指定为 @all,则向关注该企业应用的全部成员发送。默认为 @all" } ]
3
MineRobber9000/symfilesorter
https://github.com/MineRobber9000/symfilesorter
061da382ba408d7f708727ceafbad9109d2ff544
c9c19b222d49a9f99154dc61116790c6d72efc19
82c5c4ea6cd51c145754dc9af69f1c42fd79963d
refs/heads/master
2021-09-02T06:57:45.193012
2017-12-31T06:49:57
2017-12-31T06:49:57
115,847,401
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7578125, "alphanum_fraction": 0.7578125, "avg_line_length": 35.57143020629883, "blob_id": "e5dd52380f6244890e840a277bc890455762afc1", "content_id": "69fe7ba2b881d494048c59b3ae332bae27cb5d58", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 64, "num_lines": 7, "path": "/main.py", "repo_name": "MineRobber9000/symfilesorter", "src_encoding": "UTF-8", "text": "import symfile,argparse\nparser = argparse.ArgumentParser(description=\"Sorts a symfile.\")\nparser.add_argument(\"symfile\",help=\"Symfile to sort.\")\nargs = parser.parse_args()\nsym = symfile.SymFile(args.symfile)\nwith open(args.symfile,\"w\") as f:\n\tsym.output(f)\n" } ]
1
lujb/sevabot
https://github.com/lujb/sevabot
866cf95f9296cfdffca6f769674834ad48ea3674
ee2fa665674c19a4d1abd364aacccb9ec0ba3857
8f4da9034ce535e2f75fe9fd860a824adae54d32
refs/heads/master
2021-01-16T22:23:21.659029
2013-11-06T02:31:31
2013-11-06T02:31:31
13,977,199
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6542056202888489, "alphanum_fraction": 0.6604361534118652, "avg_line_length": 18.625, "blob_id": "74b77106688012969403ea156e841b37c47a621a", "content_id": "2fcaf0e9c6411e6ea70720a3d31304ddd2ed84d2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 321, "license_type": "permissive", "max_line_length": 50, "num_lines": 16, "path": "/modules/list.py", "repo_name": "lujb/sevabot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nlist all subscribers\n\"\"\"\nimport sys\nsys.path.append('/home/skype/webots')\nimport bbsbot\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\nbbsbot.init_db()\n\nprint 'Current subscribers:'\nfor sid, sname, bbsid in bbsbot.get_subscribers():\n print sid + \" <--> \" + bbsid\n\n\n \n" }, { "alpha_fraction": 0.5627906918525696, "alphanum_fraction": 0.5767441987991333, "avg_line_length": 18.545454025268555, "blob_id": "5edd23a9df768879eb3c6c9255390a42f5fc971f", "content_id": "d87836256ac1779b386f8fa6be338546bcf4811a", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "permissive", "max_line_length": 69, "num_lines": 22, "path": "/modules/joke.py", "repo_name": "lujb/sevabot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#-*-coding:utf-8-*-\n\nimport urllib2\nimport re\nimport time\nimport random\n\nkey = time.strftime('%Y-%m-%d')\n\n\ndef random_joke():\n r = urllib2.urlopen('http://feed.feedsky.com/qiushi', timeout=60)\n p = r.read()\n r = re.findall('&lt;p&gt;([\\s]+)([^\\t]+)&lt;br/&gt;', p)\n if r:\n\tres, n = re.subn(\"&lt;br/&gt;\", \" \", random.choice(r)[1])\n return res\n else:\n\treturn 'None'\n\nprint random_joke()\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 10.25, "blob_id": "0f83713e4eba84bd698b8a8fc0c14ba57a55ec43", "content_id": "fcc22b3d619388bdb97168e469e11e6c0fd7e89e", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 102, "license_type": "permissive", "max_line_length": 26, "num_lines": 8, "path": "/modules/roll.sh", "repo_name": "lujb/sevabot", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nRANGE=101\n\nnumber=$RANDOM\nlet \"number %= $RANGE\"\n\necho \"掷出了 $number 上限为 100\"\n" }, { "alpha_fraction": 0.7026143670082092, "alphanum_fraction": 0.7124183177947998, "avg_line_length": 18.125, "blob_id": "0073f9c1f14a1f649d4cf0c3ed0050b8b99264ea", "content_id": "7e65ec6891ed5b9b544723ac63f79bcd4aa4a7fd", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "permissive", "max_line_length": 57, "num_lines": 16, "path": "/modules/unsubscribe.py", "repo_name": "lujb/sevabot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nunsubscribe bbs notification\n\"\"\"\nimport os, sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\nsys.path.append('/home/skype/webots')\nimport bbsbot\n\nusername = unicode(os.environ[\"SKYPE_USERNAME\"], 'utf-8')\n\nbbsbot.delete_subscriber(username)\nprint '取消订阅成功!'\n" }, { "alpha_fraction": 0.5429184436798096, "alphanum_fraction": 0.665772557258606, "avg_line_length": 41.3636360168457, "blob_id": "a0bcaeea94ecd0f38d3d760d48ff2904bca9b9d8", "content_id": "ba9a276520dfc33eb53dbf14a708eb053d055034", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1908, "license_type": "permissive", "max_line_length": 401, "num_lines": 44, "path": "/modules/chat.py", "repo_name": "lujb/sevabot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n#-*-coding:utf-8-*-\n\nimport requests\nimport random\nimport sys\n\nurl_chat = 'http://www.simsimi.com/func/req?msg=%s&lc=ch'\nh_accept = \"application/json, text/javascript, */*; q=0.01\" \nh_xrw = \"XMLHttpRequest\" \nh_ua = \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36\"\nh_cookie = \"sagree=true; selected_nc=ch; JSESSIONID=C2BD358F72447923A47338265045B62D; AWSELB=15E16D030EBAAAB8ACF4BD9BB7E0CA8FB501388662640BCEC6E9C54E70B150AA8514D30E844A0F6781F3C00BEC43069730243F418119D4A1660F073D105DD873991975B881; __utma=119922954.1581747215.1382876735.1382876756.1382964833.3; __utmb=119922954.2.10.1382964833; __utmc=119922954; __utmz=119922954.1382876735.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)\" \nh_referer = \"http://www.simsimi.com/talk.htm\" \n\nclass Bot:\n\n def __init__(self):\n self.session = requests.Session()\n self.init_session()\n\n def init_session(self):\n self.session.headers.update({'User-Agent': h_ua})\n self.session.get('http://www.simsimi.com/talk.htm')\n self.session.headers.update({'Referer': h_referer})\n self.session.headers.update({'Accept': h_accept})\n self.session.headers.update({'X-Requested-With': h_xrw})\n self.session.headers.update({'Cookie': h_cookie})\n\n def chat(self, message='hello'):\n\ttry:\n\t res = self.session.get(url_chat % message)\n\t answer = res.json()['response'].encode('utf-8')\n\t if answer == 'SimSimi is tired, I only can speak 200 time a day. Please visit again tomorrow. See ya~ ':\n\t\treturn random.choice(['hehe', '。。。', '-_-!', '=。='])\n\t return answer\n\texcept Exception, e:\n\t return random.choice(['|hehe', '|。。。', '|-_-!', '|=。='])\n\t\n \nbot = Bot()\nif len(sys.argv) >1:\n print bot.chat(\" \".join(sys.argv[1:]))\nelse:\n print bot.chat(\"我什么也不想说\")+\" (eg: !chat 钓鱼岛是中国的)\"\n" }, { "alpha_fraction": 0.625931441783905, "alphanum_fraction": 0.6423248648643494, "avg_line_length": 20.645160675048828, "blob_id": "8ec3894126edc584b759fa3d37a9f60f5be01ff5", "content_id": "dd136be42425961e8817e38547fbbad66416b3c1", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "permissive", "max_line_length": 61, "num_lines": 31, "path": "/modules/subscribe.py", "repo_name": "lujb/sevabot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nsubscribe bbs notification\n\"\"\"\nimport os, sys\n\nreload(sys)\nsys.setdefaultencoding('utf-8')\nsys.path.append('/home/skype/webots')\nimport bbsbot\n\nusername = unicode(os.environ[\"SKYPE_USERNAME\"], 'utf-8')\nfullname = unicode(os.environ[\"SKYPE_FULLNAME\"], 'utf-8')\n\ndef u(string):\n unicode(string, 'utf-8')\n\nif len(sys.argv) == 2:\n bbsid = unicode(sys.argv[1], 'utf-8')\n ret = bbsbot.insert_subscriber(username, fullname, bbsid)\n if ret == 0:\n\tprint u'订阅成功!'\n elif ret == 1:\n\tprint u'你已经订阅了--'\n elif ret == 2:\n\tprint u'成功修改订阅信息!'\n else:\n\tprint u'神秘的未知错误!'\nelse:\n print u'参数错误! (eg: !subscribe BBS_ID)'\n" }, { "alpha_fraction": 0.2848167419433594, "alphanum_fraction": 0.2848167419433594, "avg_line_length": 27.939393997192383, "blob_id": "10fb4129e9eb42545e5604ce762b98ef52a59a0e", "content_id": "dee0f8ab4c54ce2f9362f0b509711fff78f5ea77", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1083, "license_type": "permissive", "max_line_length": 47, "num_lines": 33, "path": "/modules/help.sh", "repo_name": "lujb/sevabot", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\necho \"可用命令列表:\"\necho \"=======================================\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!chat [MSG]\"\necho \" 机器人聊天\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!joke\"\necho \" 笑话\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!list\"\necho \" 查询当前订阅用户\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!ping\"\necho \" 网络测试\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!roll\"\necho \" 人品测试\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!sad\"\necho \" 别那么悲伤\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!subscribe BBSID\"\necho \" 订阅论坛提醒,BBSID为bbs.rytong.com中的uid\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!unsubscribe\"\necho \" 取消订阅论坛提醒\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"!weather [CITY]\"\necho \" 天气查询,默认查询北京\"\necho \"+++++++++++++++++++++++++++++++++++++++\"\necho \"========================================\"\n" } ]
7
VelDia/Cult_game
https://github.com/VelDia/Cult_game
3fed628c35b8cd3656076fd05939b15bd3023acc
9b95f0c4140727d86adf13a006bdfe90e52ae159
f63e83d1bca5f606759818829e1112f94f73895b
refs/heads/master
2022-12-15T19:15:38.653968
2020-09-16T18:19:33
2020-09-16T18:19:33
292,243,344
2
0
null
2020-09-02T09:47:25
2020-09-13T14:26:22
2020-09-16T18:19:34
Python
[ { "alpha_fraction": 0.6010100841522217, "alphanum_fraction": 0.6273849606513977, "avg_line_length": 22.766666412353516, "blob_id": "8b8df8d1e324b8dceb6d8f9765ea65b5cb410438", "content_id": "896559e7ec5eb96e8694d1c98c8f684c19fa461f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3564, "license_type": "no_license", "max_line_length": 88, "num_lines": 150, "path": "/Tutorial.py", "repo_name": "VelDia/Cult_game", "src_encoding": "UTF-8", "text": "# Tutorial part\n\nfrom Characters import People, NPC, MainCharacter, Character\nfrom character_data import*\n#from random import randint, choice\n\n#================================================\n#\t\t\t\t Tutorial NPC\n#================================================\n\nnpc1 = NPC('Andrew', 27, 1, 50, 0)\nnpc2 = NPC('Bob', 32, 1, 50, 0)\nnpc3 = NPC('Alina', 20, 0, 50, 0)\n\n#================================================\n#================================================\n\n\n\n#================================================\n#\t\t\t\t First visit\n#================================================\n'''\ndef FirstVisit():\n\tMainCharacter.greeting()\n\tnpc1.greeting()\n\n\twhile True:\n\t\tanswear = bool(input('Enter your action'))\n\n\t\tif answear == 'q':\n\t\t\tanswear = input('Enter your last action')\n\t\t\tif answear == '0':\n\t\t\t\tMainCharacter.finish_phrase(True)\n\t\t\t\tnpc1.farewell(answear)\n\n\t\t\tif answear == '1':\n\t\t\t\tMainCharacter.finish_phrase(False)\n\t\t\t\tnpc1.farewell(answear)\n\t\t\tbreak\n\t\telse:\n\t\t\tif answear == '0':\n\t\t\t\tMainCharacter.recruitment(True)\n\t\t\t\tnpc1.phrase(answear)\n\n\t\t\tif answear == '1':\n\t\t\t\tMainCharacter.recruitment(False)\n\t\t\t\tnpc1.phrase(answear)\n\n\tif npc1.motivation > 90:\n\t\tprint('Perfect you have first member in your cult!')\n\telse:\n\t\tprint('Damn! He\\'s so strong try harder!!!')\n\t\t#FirstVisit()\n'''\n\ndef Visit():\n\tMainCharacter.greeting()\n\tnpc1.greeting()\n\tnpc1.showStats()\n\t#bool bad1 = False, bad2 = False, bad3 = False\n\tbad1 = MainCharacter.recruitment(characterRecruitmentSoft,characterRecruitmentSoftBad)\n\tnpc1.phrase(bad1)\n\tnpc1.showStats()\n\tbad2 = MainCharacter.recruitment(characterRecruitmentHard, characterRecruitmentHardBad)\n\tnpc1.phrase(bad2)\n\tnpc1.showStats()\n\tbad3 = MainCharacter.recruitment(characterFinishPhrase, characterFinishPhraseBad)\n\tnpc1.farewell(bad3)\n\tnpc1.showStats()\n\tif npc1.motivation <= 50:\n\t\tprint('You lost... The person didn`t believe you.')\n\telif npc1.motivation > 50 and npc1.motivation < 90:\n\t\tprint('Congrats, you`ve got a new believer.')\n\t\tMainCharacter.add_believer()\n\telif npc1.motivation >= 90:\n\t\tprint('Heh, you were good enough to get a worshipper.')\n\t\tMainCharacter.add_believer()\n\tprint('The amount of believers:', MainCharacter.believers)\n\t\t\n'''\ndef SecondVisit():\n\tMainCharacter.greeting()\n\tnpc2.greeting()\n\n\twhile True:\n\t\tanswear = input('Enter your action')\n\n\t\tif answear == 'q':\n\t\t\tanswear = input('Enter your last action')\n\t\t\tif answear == '0':\n\t\t\t\tMainCharacter.finish_phrase(1)\n\t\t\t\tnpc2.farewell(answear)\n\n\t\t\tif answear == '1':\n\t\t\t\tMainCharacter.finish_phrase(0)\n\t\t\t\tnpc2.farewell(answear)\n\t\t\tbreak\n\t\telse:\n\t\t\tif answear == '0':\n\t\t\t\tMainCharacter.recruitment(1)\n\t\t\t\tnpc2.phrase(answear)\n\n\t\t\tif answear == '1':\n\t\t\t\tMainCharacter.recruitment(0)\n\t\t\t\tnpc2.phrase(answear)\n\n\tif npc2.motivation > 90:\n\t\tprint('Perfect you have first member in your cult!')\n\telse:\n\t\tprint('Damn! He\\'s so strong try harder!!!')\n\t\tSecondVisit()\n\n\n\ndef ThirdVisit():\n\tMainCharacter.greeting()\n\tnpc3.greeting()\n\n\twhile True:\n\t\tanswear = input('Enter your action')\n\n\t\tif answear == 'q':\n\t\t\tanswear = input('Enter your last action')\n\t\t\tif answear == '0':\n\t\t\t\tMainCharacter.finish_phrase(1)\n\t\t\t\tnpc3.farewell(answear)\n\n\t\t\tif answear == '1':\n\t\t\t\tMainCharacter.finish_phrase(0)\n\t\t\t\tnpc3.farewell(answear)\n\t\t\tbreak\n\t\telse:\n\t\t\tif answear == '0':\n\t\t\t\tMainCharacter.recruitment(1)\n\t\t\t\tnpc3.phrase(answear)\n\n\t\t\tif answear == '1':\n\t\t\t\tMainCharacter.recruitment(0)\n\t\t\t\tnpc3.phrase(answear)\n\n\tif npc3.motivation > 90:\n\t\tprint('Perfect you have first member in your cult!')\n\telse:\n\t\tprint('Damn! He\\'s so strong try harder!!!')\n\t\tThirdVisit()\n\n'''\n\nVisit()" }, { "alpha_fraction": 0.7315521836280823, "alphanum_fraction": 0.7315521836280823, "avg_line_length": 64.58333587646484, "blob_id": "f06560f46e6599f0a8976ec241fc240a1942a0e1", "content_id": "377302efd9502c214ecf51c91a88dd1f564f2492", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 146, "num_lines": 12, "path": "/character_data.py", "repo_name": "VelDia/Cult_game", "src_encoding": "UTF-8", "text": "# File with Сharacter phrases\n\ncharacterGreeting = ['Oh, hi', 'What\\'s up?', 'With God to you I come']\n\ncharacterRecruitmentSoft = ['Lets talk about religion', 'Wanna see something cool?', 'Would you mind to go to our church?']\ncharacterRecruitmentSoftBad = ['I need people for making cult', 'Join our religion', 'Hey, I see you\\'re rich, enough would ya join our religion']\n\ncharacterRecruitmentHard = ['Okey, so you have to visit our church', 'You`ll find all answers in our church', 'Join our church to feel happy']\ncharacterRecruitmentHardBad = ['You must come']\n\ncharacterFinishPhrase = ['We will wait for ya!', 'God will be proud of you']\ncharacterFinishPhraseBad = ['We will wait for your money!', 'God in need of you and $$$', 'Hope you will come with somebody to our religion']" }, { "alpha_fraction": 0.6314179301261902, "alphanum_fraction": 0.6511040329933167, "avg_line_length": 27.373584747314453, "blob_id": "a0ca06420edc66bc112d2e8e9c81d64461d86f4e", "content_id": "f008b36c0e1204bf86bf567919a8c0154da5dee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7518, "license_type": "no_license", "max_line_length": 179, "num_lines": 265, "path": "/Characters.py", "repo_name": "VelDia/Cult_game", "src_encoding": "UTF-8", "text": "# Main Character logic\n# And NPC logic\n\nfrom random import choice, randint\n#from Tutorial import Visit\nfrom character_data import characterGreeting\nfrom npc_data import*\nimport time, threading\n#================================================\n#\t\t\t Main Character logic\n#================================================\nclass People:\n\tdef __init__(self, name, gender, age, picture):\n\t\tself.name = name\n\t\tself.gender = gender\n\t\tself.age = age\n\t\tself.picture = picture\n\n\tdef GetName(self):\n\t\tName = input(\"Enter character name: \")\n\t\treturn Name\n\t\n\tdef GetGender(self):\n\t\tGender = int(input(\"Enter your gender: (\\\"0\\\" for female, \\\"1\\\" for male, \\\"9\\\" for a random gender) \"))\n\t\tif Gender == 9:\n\t\t\tGender = randint(0,1)\n\t\tif Gender == 0:\n\t\t\tstrGender = 'female'\n\t\telif Gender == 1:\n\t\t\tstrGender = 'male'\t\n\t\telse:\n\t\t\tprint('Error: wrong gender initialization...')\n\t\treturn strGender\n\n\tdef get_picture(self, age, gender):\n\t\tif gender == 0:\n\t\t\tprint(\"female\") #enter/search the folder with girl`s pictures\n\t\telif gender == 1:\n\t\t\tprint(\"male\") #enter/search the folder with boy`s pictures\n\t\tif age < 30:\n\t\t\tprint(\"young person\")\n\t\t\t#find and attach the picture of the young person\n\t\telif age >= 30 and age <=50:\n\t\t\tprint(\"middle-aged person\")\n\t\t\t#find and attach the picture of the middle-aged person\n\t\telse: \n\t\t\t#or elif age >= 50:... and then else: print(\"Unable to attach the picture\")\n\t\t\tprint(\"old person\")\n\t\t\t#find and attach the picture of the old person\n\nclass Character(People):\n\n\tbelievers = 0\n\tlevel = 0\n\tmoney = 0\n\n\tdef __init__(self, name, age, gender, money, charisma, energy, level, believers, picture):\n\t\tPeople.__init__(self, name, gender, age, picture)\n\t\tself.money = money\n\t\tself.charisma = charisma\n\t\tself.energy = energy\n\t\tself.level = level\n\t\tself.believers = believers\n\t\tself.picture = picture\n\n\t\t\"\"\"\n\t\t\n\t\t[name] - name of character (Player choose at the beginning)\n\t\t[age] - age of character (at the beginning equals to 21)\n\t\t[gender] - gender of a character (0 - female or 1 - male)\n\t\t[money] - amount of money that character have (at the beginning equals to 0)\n\t\t[charisma] - level of charisma of character (at the beginning equals to 0)\n\t\t[energy] - level of energy of character (at the beginning equals to 100)\n\t\t#[element] - element of character (0, 1, 2) == (rock, paper, scissors)\n\t\t[level] - literally, the level of the character, which indicates how much stages the main character has gone through...\n\t\t[believers] - the amount of people, who believe in religion of the character\n\t\t\n\t\t\"\"\"\n\t\n\t\t\t\n\tdef greeting(self):\n\t\tprint(choice(characterGreeting))\n\n\tdef recruitment(self, ListOfPhrases, ListOfPhrasesBad):\n\t\tprint('1.',choice(ListOfPhrases))\n\t\tprint('2.',choice(ListOfPhrasesBad))\n\t\tansw = int(input('Choose the answer: '))\n\t\tif answ == 1:\n\t\t\tbad = False\n\t\telif answ == 2:\n\t\t\tbad = True\n\t\telse:\n\t\t\tprint('Something went wrong try again')\n\t\treturn bad\n\t'''\n\tdef recruitment(self, bad):\n\t\tif bad == True:\n\t\t\tprint(choice(characterRecruitmentSoftBad))\n\t\telse:\n\t\t\tprint(choice(characterRecruitmentSoft))\n\n\n\tdef finish_phrase(self, bad):\n\t\tif bad == True:\n\t\t\tprint(choice(characterFinishPhraseBad))\n\t\telse:\n\t\t\tprint(choice(characterFinishPhrase))\n\t'''\t\n\tdef add_believer(self):\n\t\tself.believers += 1\n\n\tdef level_up(self):\n\t\tself.level += 1\n\n#================================================\n#\t\t\tCreating Main Character\n#================================================\n'''\ndef aTutorial():\n\tglobal MainCharacter\n\tMainCharacter = Character(Character.GetName(Character), 21, Character.GetGender(Character), 0, 100, 0, 0, 0, Character.get_picture(Character, 21, Character.GetGender(Character)))\n\tVisit()\n'''\n\ndef SkipTutorial():\n\t# actions with MainCharacter characteristics\n\t# Add soon\n\tpass\n\n#================================================\n#================================================\n\nMainCharacter = Character('Default name', 21, 0, 0, 50, 100, 1, 0, 0)\n\n#================================================\n#\t\t\t\t\tNPC logic\n#================================================\n\nclass NPC(People):\n\n\tdef __init__(self, name, age, gender, motivation, picture):\n\t\tPeople.__init__(self, name, gender, age, picture)\n\t\tself.motivation = motivation\n\n\t\t\"\"\"\n\t\t[name] - NPC name\n\t\t[age] - NPC age (from 18 to 80)\n\t\t[gender] - gender of NPC (smart random) (0 - female, 1 - male)\n\t\t[charisma] - level of charisma of character (smart random)\n\t\t[motivation] - motivation to listen to Main Character (smart random)\n\t\t#[element] - element of character (0, 1, 2) == (rock, paper, scissors)\n\t\t[picture] - the number of the picture which will be shown on the screen when the NPC is shown\n\n\t\t\"\"\"\n\t\n\tdef greeting(self):\t\n\t\tprint(choice(npcGreeting) + ' I\\'m ' + self.name)\n\n\tdef phrase(self, bad):\n\t\tif bad == True:\n\t\t\tprint(choice(npcAnswearBad))\n\t\t\tself.motivation -= randint(5, 10) # Need to add smart random parameters\n\t\telse:\n\t\t\tprint(choice(npcAnswear))\n\t\t\tself.motivation += randint(5, 10) # Here too\n\n\n\tdef farewell(self, bad):\n\t\tif bad == True:\n\t\t\tprint(choice(npcFarewellBad))\n\t\t\tself.motivation -= randint(1, 5) # Here too\n\t\telse:\n\t\t\tprint(choice(npcFarewell))\n\t\t\tself.motivation += randint(1, 5) # Here too\n\t\n\tdef showStats(self):\n\t\tprint('Name:', self.name)\n\t\tprint('Age:', self.age)\n\t\tprint('Motivation:', self.motivation)\n\n\n# Need to dislocate it\ndef SmartRandom(level):\t# For creating appropriate NPC\n\t\"\"\"\n\tSmartRandom\n\n\tArgs:\n\t\tlevel (int): takes level from 0 to 4 (easy, medium, hard, extreme, ureal)\n\n\tReturns:\n\t\ttuple: ready for creating new class 'NPC' member data \n\t\"\"\"\t\n\n\tif level == 0:\t# Easy\n\t\tMIN_charisma = 0\n\t\tMAX_charisma = MainCharacter.charisma + 2\n\n\t\tMIN_motivation = 50\n\t\tMAX_motivation = 70\n\n\telif level == 1:\t# Medium\n\t\tMIN_charisma = MainCharacter.charisma \n\t\tMAX_charisma = MainCharacter.charisma + 5\n\n\t\tMIN_motivation = 50\n\t\tMAX_motivation = 60\n\n\telif level == 2:\t# Hard\n\t\tMIN_charisma = MainCharacter.charisma + 5\n\t\tMAX_charisma = MainCharacter.charisma + 15\n\n\t\tMIN_motivation = 30\n\t\tMAX_motivation = 50\n\n\telif level == 3:\t# Extreme\n\t\tMIN_charisma = MainCharacter.charisma + 15\n\t\tMAX_charisma = MainCharacter.charisma + 35\n\n\t\tMIN_motivation = 20\n\t\tMAX_motivation = 40\n\n\telif level == 4:\t# Unreal\n\t\tMIN_charisma = MainCharacter.charisma + 35\n\t\tMAX_charisma = MainCharacter.charisma + 65\n\n\t\tMIN_motivation = 0\n\t\tMAX_motivation = 30\n\t\n\tage = randint(18, 80)\n\tgender = randint(0, 1)\n\tcharisma = randint(MIN_charisma, MAX_charisma)\n\tmotivation = randint(MIN_motivation, MAX_motivation)\t\n\n\tif gender == 0:\n\t\tname = choice(npcFemaleNames)\n\telse:\n\t\tname = choice(npcMaleNames)\n\n\treturn name, age, gender, charisma, motivation\n\nclass worshipper(People):\n\n\tdef __init__(self, name, age, gender, charisma, motivation, picture, newcomers_per_time, all_newcomers = 0):\n\t\tPeople.__init__(self, name, gender, age, picture)\n\t\tself.charisma = charisma\n\t\tself.newcomers_per_time = newcomers_per_time \n\t\tself.all_newcomers = all_newcomers\n\n\t\t'''\n\n\t\t[charisma] - the koeficient of successful recruition (1 to 10)\n\t\t[newcomers_per_time] - the amount of people the worshipper assigns per some time (initially 1 to 10)\n\t\t[all_newcomers] - the amount of people the worshipper has ever assigned\n\t\t\n\t\t'''\n\n\tdef autoRecruitment(self):\n\t\tself.all_newcomers += self.charisma * self.newcomers_per_time\n\t\tprint(str(self.name) + ' has already recrited ' + str(int(self.all_newcomers)) + ' believers and has just added +' + str(self.newcomers_per_time * self.charisma))\n\t\tthreading.Timer(10, self.autoRecruitment).start()\n\n#aTutorial()\n\n#w1 = worshipper('John', 21, 1, 7, 100, 0, 1)\n#w1.autoRecruitment()" }, { "alpha_fraction": 0.5986732840538025, "alphanum_fraction": 0.5986732840538025, "avg_line_length": 49.25, "blob_id": "6aaab89a59fc43cd6dd9f1758c3ffaaa72f25104", "content_id": "e4f132db3ab9cf54049ec26799c451deedb7da1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 603, "license_type": "no_license", "max_line_length": 128, "num_lines": 12, "path": "/npc_data.py", "repo_name": "VelDia/Cult_game", "src_encoding": "UTF-8", "text": "# File with NPC phrases\n\nnpcMaleNames = ['John', 'Boris', 'Andrew', 'Emmet', 'Eliot', 'Bob', 'Steve', 'Tony', 'Michel', 'Peter', 'Frank', 'George']\nnpcFemaleNames = ['Lara', 'Emma', 'Natasha', 'Scarlet', 'Helen', 'Linda', 'Rachel', 'Tina', 'Sofi', 'Clara', 'Eleonor', 'Sonya']\n\nnpcGreeting = ['Hello', 'Main respecturen', 'Hi MF!', 'Oh, hi']\n\nnpcAnswear = ['Yes', 'Why not, yeah', 'Ok', 'Hell yeah']\nnpcAnswearBad = ['No', 'No! Never', 'Emmm, no', 'What?!']\n\nnpcFarewell = ['Have a nice day!', 'Thanks, good bye', 'Bye', \"Good bye\"]\nnpcFarewellBad = ['Get hell outa here!', '*Door slaps*', 'Fuck off!']\n" }, { "alpha_fraction": 0.7486631274223328, "alphanum_fraction": 0.7486631274223328, "avg_line_length": 40.51852035522461, "blob_id": "2ee44e554aa2ffcfb86ac58e9108159a77dcc678", "content_id": "2a03eb37a87d6bcef226f258cc337e288c21d5e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1122, "license_type": "no_license", "max_line_length": 202, "num_lines": 27, "path": "/README.md", "repo_name": "VelDia/Cult_game", "src_encoding": "UTF-8", "text": "# :video_game: Cult_game\n\nProject to test knowledges and for practicing skills. Also this is all just for fun.\n\n## :warning: Warning (Disclaimer)\n##### This project does not want to hurt someone's feelings or whatever, if you don't like it - you're free to go by your way. \n##### Don't like swearing or you're religious or your cat don't appreciate this or anything in the world, we don't even care.\n\n## :bulb: Idea\n\nCult_game it's a game where you can create your own religion, or recreate already existed once. Written in Python from scratch with a small idea that came one night: \"Why not?\".\n\n## :page_facing_up: About \n\nWanted to test yourself as 'God' you're welcome. Create your own religion, cult, fanclub or whatever you want to name it. Test your skills as leader of your own religion and try to beat other religions.\n\n## :hammer: Developing\n\nGame in development, just right now.\n\nAdditional info will be added soon...\n\n## :octocat: Contributing\n\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.\n\nPlease make sure to update tests as appropriate. \n" }, { "alpha_fraction": 0.6241217851638794, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 17.54347801208496, "blob_id": "3718e34530d89160255e4f6691bc63cf3b19f32b", "content_id": "55708b3d7da4475daad376bec9d740611dae953d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 854, "license_type": "no_license", "max_line_length": 70, "num_lines": 46, "path": "/Web_GUI_test.py", "repo_name": "VelDia/Cult_game", "src_encoding": "UTF-8", "text": "import eel\nimport pickle\n\nfileName = 'data'\nfileExistsFlag = False\n\neel.init('web')\n\ntry:\n\tinfile = open(fileName,'rb')\n\tuser_info = pickle.load(infile)\n\tinfile.close()\n\tprint(user_info)\n\tfileExistsFlag = True\nexcept IOError:\n\tprint(\"Enter data please\")\n\n\[email protected]\ndef get_info(name, gender, age):\n\tif str(name) == '' or age == '':\n\t\tname = 'User'\n\t\tage = 18\n\n\tage = int(age)\n\n\tif gender == \"Male\":\n\t\tuser_info = (str(name), age, 1)\n\telse:\n\t\tuser_info = (str(name), age, 0)\n\n\toutfile = open(fileName,'wb')\n\tpickle.dump(user_info, outfile)\n\toutfile.close()\n\t\n\tprint(\"Name = \" + name)\n\tprint(\"Gender = \" + gender)\n\tprint(\"Age = \" + str(age))\n\ntry:\n\tif fileExistsFlag == True:\n\t\teel.start('html/main.html', host='localhost', size=(500, 500))\n\telse:\n\t\teel.start('html/start_page.html', host='localhost', size=(500, 500))\nexcept:\n\tprint(\"End of program\")\n\n" }, { "alpha_fraction": 0.5465313196182251, "alphanum_fraction": 0.5888324975967407, "avg_line_length": 23.58333396911621, "blob_id": "b72807aaa23c4b50e3a42b7f622c2190f65fdfc8", "content_id": "37256189b6d7353ac0f867dfb7e67561f1b7b0cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 591, "license_type": "no_license", "max_line_length": 84, "num_lines": 24, "path": "/Perlin_noise/Playing_perlin.py", "repo_name": "VelDia/Cult_game", "src_encoding": "UTF-8", "text": "from perlin import PerlinNoiseFactory\nimport PIL.Image\n\nsize = 800\nres = 40\nframes = 1\nframeres = 5\nspace_range = size//res\nframe_range = frames//frameres\n\npnf = PerlinNoiseFactory(3, octaves=3, tile=(space_range, space_range, frame_range))\n\nfor t in range(frames):\n img = PIL.Image.new('L', (size, size))\n for x in range(size):\n for y in range(size):\n n = pnf(x/res, y/res, t/frameres)\n\n img.putpixel((x, y), int((n + 1) / 2 * 255 + 0.5))\n\n \n print( int((n + 1) / 2 * 255 + 0.5))\n img.save(\"noiseframe{:03d}.png\".format(t))\n print(t)\n\n" } ]
7
aguilar-gomez/gemmaForNonModel
https://github.com/aguilar-gomez/gemmaForNonModel
393c8d2c452c95528628acfd4e31f9ac1196e169
df2bfdf7f3a0464712b15546499c5343c2353244
e360a3cbc61e5d98d9c5cb8ca3a1f549e7077af6
refs/heads/main
2023-02-17T01:42:36.180356
2021-01-19T22:24:19
2021-01-19T22:24:19
331,124,216
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6734693646430969, "alphanum_fraction": 0.706632673740387, "avg_line_length": 25.727272033691406, "blob_id": "ddb3a84c45914ebc8f97d0af4355d410ac2784b3", "content_id": "d37fe60a044703f61485835b1c7924ffbb2418ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1176, "license_type": "no_license", "max_line_length": 85, "num_lines": 44, "path": "/merge_chr_map.py", "repo_name": "aguilar-gomez/gemmaForNonModel", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Author : Diana Aguilar\n'''script to modify map file, for assemblies with too many scaffolds for plink\nConvert scaffolds to a single giant chromosome\nExample:\nchr1 1-10\nchr2 1-9\nchr3 1-8\nTo:\nchr1-10\nchr1 11-19\nchr1 20-27\n\nUse merge_chr_map.py mapfile reference.fasta.fai merged.mapfile easy_remapfile\n'''\nimport sys\nimport pandas as pd\n\nfilename=sys.argv[1]\nfasta_fai=sys.argv[2]\noutfilename=sys.argv[3]\neasy_remap=sys.argv[4]\n\nchrs=pd.read_csv(fasta_fai,header=None,sep=\"\\t\")\nchrs[\"start_pos\"]=chrs[1].cumsum()-chrs[1]\n#Dictionary with cumpos to access cum pos easy_access_cum[\"start_pos\"][\"chr#\"]\neasy_access_cum=chrs[[0,\"start_pos\"]].set_index([0]).to_dict()\n\n#Open files\noutfile= open(outfilename,\"w+\")\nremapfile= open(easy_remap,\"w+\")\ninfile = open(filename, \"r\")\n\nfor line in infile:\n\tcolumn=line.split(\"\\t\")\n\tchr_and_pos=column[1].split(\":\")\n\tchrom=chr_and_pos[0]\n\tnewposition=int(chr_and_pos[1])+easy_access_cum[\"start_pos\"][chrom]\n\toutfile.write('\\t'.join([\"1\",\"chr1:\"+str(newposition),\"0\",str(newposition)])+\"\\n\")\n\tremapfile.write('\\t'.join([\"chr1:\"+str(newposition),chrom+\":\"+chr_and_pos[1]])+\"\\n\")\n\ninfile.close()\noutfile.close()\nremapfile.close()\n" }, { "alpha_fraction": 0.7166882157325745, "alphanum_fraction": 0.7270374894142151, "avg_line_length": 26.60714340209961, "blob_id": "8e70112e5b8e8560a9a601aa83f47bde7eb1b682", "content_id": "60d0a40660119e44b0c88ad572d6aa2f2a07f11d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 773, "license_type": "no_license", "max_line_length": 100, "num_lines": 28, "path": "/mergechr_rs.py", "repo_name": "aguilar-gomez/gemmaForNonModel", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Author : Diana Aguilar\n'''script to modify association with gemma results, for assemblies with too many scaffolds for plink\nConvert scaffolds to a single giant chromosome, re map to original names\n\nUse re_map_names.py result_association easy_remapfile result_asso_original_chr\n'''\nimport sys\nimport pandas as pd\n\nfilename=sys.argv[1]\neasy_remap=sys.argv[2]\noutfilename=sys.argv[3]\n\nchrs=pd.read_csv(easy_remap,header=None,sep=\"\\t\")\n#Dictionary with map positions [\"giant_chr_rs\"]=\"original_rs\"\neasy_remap_dic=chrs[[0,1]].set_index([1]).to_dict()\n\noutfile= open(outfilename,\"w+\")\ninfile = open(filename, \"r\")\n\nfor line in infile:\n\trs=line.split(\"\\n\")[0]\n\tmerged_rs=easy_remap_dic[0][rs]\n outfile.write(merged_rs+\"\\n\")\n\ninfile.close()\noutfile.close()\n" }, { "alpha_fraction": 0.6874443292617798, "alphanum_fraction": 0.6999109387397766, "avg_line_length": 32.02941131591797, "blob_id": "dd714fd21057d5679bb312b9f2f54596d3eee382", "content_id": "7df477d89869f75a37751d3297b6fba82f667a9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 172, "num_lines": 34, "path": "/remap_names.py", "repo_name": "aguilar-gomez/gemmaForNonModel", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# Author : Diana Aguilar\n'''script to modify association with gemma results, for assemblies with too many scaffolds for plink\nConvert scaffolds to a single giant chromosome, re map to original names\n\nUse re_map_names.py result_association easy_remapfile result_asso_original_chr\n'''\nimport sys\nimport pandas as pd\n\nfilename=sys.argv[1]\neasy_remap=sys.argv[2]\noutfilename=sys.argv[3]\n\nchrs=pd.read_csv(easy_remap,header=None,sep=\"\\t\")\n#Dictionary with map positions [\"giant_chr_rs\"]=\"original_rs\"\neasy_remap_dic=chrs[[0,1]].set_index([0]).to_dict()\n\noutfile= open(outfilename,\"w+\")\ninfile = open(filename, \"r\")\n#first line header\nnext(infile)\noutfile.write(\"\\t\".join([\"chr\",\"rs\",\"ps\",\"n_mis\",\"n_obs\",\"allele1\",\"allele0\",\"af\",\"beta\",\"se\",\"p_wald\",\"p_lrt\",\"p_score\",\"original_rs\",\"original_chr\",\"original_pos\"])+\"\\n\")\n\nfor line in infile:\n\tcolumn=line.split(\"\\t\")\n\trs_format=column[1]\n\toriginal_rs=easy_remap_dic[1][rs_format]\n\tchr_and_pos=original_rs.split(\":\")\n outfile.write('\\t'.join(column[:-1]+[column[-1].rstrip(),original_rs,chr_and_pos[0],chr_and_pos[1]])+\"\\n\")\n\n\ninfile.close()\noutfile.close()\n" } ]
3
trunkboy/django-multi-storage
https://github.com/trunkboy/django-multi-storage
005108112a7b94d5478d275c7c7e67b10b3c6f20
f1627f5bb01eaae06a178c323190d2ccf6fba44f
215849b334fc30ed397a06315b5087567be25c81
refs/heads/main
2023-01-01T06:41:36.611841
2020-10-20T16:41:42
2020-10-20T16:41:42
305,724,052
0
0
Apache-2.0
2020-10-20T13:51:39
2020-10-20T13:05:14
2020-10-20T13:05:11
null
[ { "alpha_fraction": 0.7188311815261841, "alphanum_fraction": 0.7194805145263672, "avg_line_length": 31.787233352661133, "blob_id": "9d8be07aeaffd8e2b4fca9494d585d763dad6656", "content_id": "aabb7a58083df706cb54ea6bb81e6e234aff13f4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1540, "license_type": "permissive", "max_line_length": 105, "num_lines": 47, "path": "/storage/schema/mutation.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "import logging\nfrom django.core.exceptions import ValidationError\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.gis.db import models\nfrom django.db.models import Q\n\nimport django_filters\nimport graphene\nfrom graphene_django import DjangoObjectType\n\n# models defination\nfrom core.models import (\n BusinessDetailsAndCategoryGrouping,\n Category,\n FollowerFollowedMapping,\n)\n\n# get Nodes definitions\nfrom core.schema.node import (\n FollowerFollowedMappingFilter, FollowerFollowedMappingNode\n)\n\n# Get an instance of a logger\nlogger = logging.getLogger(__name__)\n\n# class CreateOrUpdateFollowerFollowedMapping(graphene.relay.ClientIDMutation):\n# follower_followed_mapping = graphene.Field(FollowerFollowedMappingNode)\n\n# class Input:\n# followed = graphene.Int(required=True)\n# follow = graphene.Int(default=1)\n\n# def mutate_and_get_payload(root, info, **input):\n# user = info.context.user\n# followerFollowedMapping, _ = FollowerFollowedMapping.objects.update_or_create(\n# follower = user,\n# followed = get_user_model().objects.get(id=input.get('followed')),\n# defaults = {\n# 'follow': bool(int(input.get('follow')))\n# }\n# )\n# return CreateOrUpdateFollowerFollowedMapping(follower_followed_mapping=followerFollowedMapping)\n\nclass Mutation(graphene.AbstractType):\n # create_or_update_follower = CreateOrUpdateFollowerFollowedMapping.Field()\n pass\n # update_user = UpdateUser.Field()" }, { "alpha_fraction": 0.6572022438049316, "alphanum_fraction": 0.6620498895645142, "avg_line_length": 29.744680404663086, "blob_id": "14429050161e961e056bcb045de9c4cce82f1b50", "content_id": "ff19d1026413e48a0c8aba099a8514a17b5fef98", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1444, "license_type": "permissive", "max_line_length": 84, "num_lines": 47, "path": "/storage/google_storage.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "# GCP storege functions which is used accross the site\n# Imports the Google Cloud client library\nfrom google.cloud import storage\nimport datetime\n\n# Instantiates a client\nstorage_client = storage.Client.from_service_account_json('config/gcp_storage.json')\n\ndef upload_blob(bucket_name, source_file, destination_blob_name):\n \"\"\"Uploads a file to the bucket.\"\"\"\n # bucket_name = \"your-bucket-name\"\n # source_file_name = \"local/path/to/file\"\n # destination_blob_name = \"storage-object-name\"\n \n # bucket to upload\n bucket = storage_client.bucket(bucket_name)\n # final name of the blob\n blob = bucket.blob(destination_blob_name)\n #upload the bolb\n # result = blob.upload_from_filename(source_file_name)\n result = blob.upload_from_file(\n source_file,\n content_type=str(source_file.content_type))\n print(result)\n print(\n \"File {} uploaded to {}\".format(\n source_file, destination_blob_name\n )\n )\n return True\n\ndef generate_download_signed_url_v4(bucket_name, blob_name):\n \"\"\"\n Generates a v4 signed URL for downloading a blob.\n \"\"\"\n bucket = storage_client.bucket(bucket_name)\n blob = bucket.blob(blob_name)\n\n url = blob.generate_signed_url(\n version=\"v4\",\n # This URL is valid for 15 minutes\n expiration=datetime.timedelta(minutes=30),\n # Allow GET requests using this URL.\n method=\"GET\",\n )\n\n return url" }, { "alpha_fraction": 0.4989010989665985, "alphanum_fraction": 0.5670329928398132, "avg_line_length": 20.66666603088379, "blob_id": "4e395eaa65a47f3b142fed3960fc9bc7b39ab0d7", "content_id": "0d2d5f63410ddc8b127662919e141d97ea772e39", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 455, "license_type": "permissive", "max_line_length": 47, "num_lines": 21, "path": "/storage/migrations/0005_auto_20200416_1355.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.5 on 2020-04-16 08:25\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('storage', '0004_auto_20200416_1353'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='filestorage',\n name='connection_name',\n ),\n migrations.RemoveField(\n model_name='filestorage',\n name='driver_name',\n ),\n ]\n" }, { "alpha_fraction": 0.558223307132721, "alphanum_fraction": 0.5594237446784973, "avg_line_length": 32.45783233642578, "blob_id": "86cec802e73332063e0ed753a8a0e6619416e5f0", "content_id": "89aa94ea3bfafb7c7b450fe3aa1dac7aa455a01e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8330, "license_type": "permissive", "max_line_length": 131, "num_lines": 249, "path": "/storage/helper.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\n\nimport hashlib\nimport json\n\ntry:\n import libcloud\nexcept ImportError:\n raise ImproperlyConfigured(\"Could not load libcloud\")\n\n\ntry:\n from django.utils.six.moves.urllib.parse import urljoin\nexcept ImportError:\n string_types = str\n from urllib.parse import urljoin\n\nfrom storage.models import (\n FileStorage,\n FileTransactionLogs\n)\n\nprovider_mapper = {\n 'google_storage' : libcloud.DriverType.STORAGE.GOOGLE_STORAGE,\n}\n\nclass Storage:\n '''\n Storage class to abstract the storage function accross the multiple service providers\n '''\n # hold the drive then main connection the provider\n driver = None\n # hold the provider data\n provider = settings.STORAGE_PROVIDERS['default']\n # hold the bucket data\n bucket = None\n\n # initilize the class\n def __init__(self, provider_name=None):\n \"\"\"Establish the connection.\n\n __init__ establish the connection with the provider and connect to the bucket.\n\n Parameters\n ----------\n provider_name : string\n it should be the configuration key which is defined in the settings file\n\n Returns\n -------\n None\n It updated the object connection parameter\n\n Raises\n ------\n ImproperlyConfigured\n When the configuration is not proper\n\n\n Examples\n --------\n >>> s=Storage('default')\n \"\"\"\n # check if the provider name is in the list or none\n if provider_name is not None:\n # build the provider dict\n self.provider = settings.STORAGE_PROVIDERS[provider_name]\n \n try:\n # load the connection driver\n cls = libcloud.get_driver(libcloud.DriverType.STORAGE, provider_mapper[self.provider['type']])\n except Exception as e:\n # if connection driver is not found, raise an expection\n raise ImproperlyConfigured(\"Unable to find libcloud driver type %s: %s\" %(provider_mapper[self.provider['type']], e))\n \n try:\n # make the connection with the platform, pass the username and secret\n self.driver = cls(\n key=self.provider['user'],\n secret=self.provider['secret']\n )\n # connect to the bucket, only one bucket connection is allowed per connection\n self.bucket = self.driver.get_container(self.provider['bucket'])\n except Exception as e:\n # if connection to bucket is not established then raise an expection \n raise ImproperlyConfigured(\"Unable to create libcloud driver type %s: %s\" %(provider_mapper[self.provider['type']], e))\n\n def hash_file(self, file_data, hash_algo=None):\n \"\"\"Hash the file\n\n Funtion to generate the hash sha3_512 hash of the given file\n\n Parameters\n ----------\n file_data : File\n The File which need to be hashed, it should be inMemory file\n hash_algo : string\n Name of the hashing algorithm need to be use\n (supported algorithms : md5,)\n\n Returns\n -------\n srting\n Hash digest of the file\n\n Raises\n ------\n AttributeError\n The ``Raises`` section is a list of all exceptions\n that are relevant to the interface.\n \"\"\"\n # Create the hash object\n file_hash = hashlib.sha3_512() \n # Open the file to read it's bytes\n for f in file_data.chunks(): \n # Update the hash\n file_hash.update(f) \n\n # Retun the hexadecimal digest of the hash\n return (file_hash.hexdigest()) \n \n def list_container_objects(self):\n '''\n Return a list of objects for the given (in setting) container.\n '''\n return self.driver.list_container_objects(self.bucket)\n \n def list_containers(self):\n '''\n Return a list of containers.\n '''\n return self.driver.list_containers()\n\n def save_file(self, request, file):\n # create the return object \n reply = {\n \"status\" : False,\n \"error\" : 'None',\n \"file\" : None, \n }\n \n # create hash of the file \n file_hash = self.hash_file(file)\n\n # upload the file \n try:\n server_reply = self.upload_object(file=file, file_name=file_hash)\n except Exception as e:\n # update the error and return\n reply['error'] = \"error Uploading the file :\" + str(e)\n return reply\n\n # try saving the file related data to DB \n try:\n file_data = FileStorage.objects.create(\n hashed_name = self.hash_file(file),\n original_name = file.name,\n original_meta_data = file.content_type,\n original_size = file.size,\n original_charset = file.charset, \n bucket_raw = self.bucket,\n bucket_name = self.bucket.name,\n server_reply = server_reply,\n )\n except Exception as e:\n # update the error and return\n reply['error'] = \"error Saving file data in DB :\" + str(e)\n return reply\n\n # try saving the file transaction log \n try:\n FileTransactionLogs.objects.create(\n file = file_data,\n user = request.user,\n remark = 'File uploaded',\n )\n except Exception as e:\n # update the error and return\n reply['error'] = \"error Saving file transaction data :\" + str(e)\n return reply\n \n reply['file'] = file_data\n reply['status'] = True\n return reply \n\n def upload_object(self, file, file_name):\n '''\n upload the file to bucket\n '''\n return self.driver.upload_object_via_stream(\n iterator=file.chunks(), \n container=self.bucket,\n object_name=file_name,\n extra={\n 'meta_data': {\n 'content_type': file.content_type,\n }\n }\n )\n\n def get_object_url(self, object_data=None, object_id=None, object_hash=None):\n '''\n Return the object URL based on the id of the object from the storage table\n '''\n object_details = None\n # get the object from the database\n try:\n if object_data is not None:\n object_details = object_data\n elif object_id is not None:\n object_details = FileStorage.objects.get(id=object_id)\n elif object_hash is not None: \n object_details = FileStorage.objects.get(hashed_name=object_hash)\n except Exception as e:\n error = \"No object found\" + str(e)\n print(error)\n\n # connect to the object bucket\n if self.mount_driver_from_bucket_name(bucket_name=object_details.bucket_name):\n print('bucket connected')\n else:\n error = \"No bucket found\"\n print(error)\n\n # get the object \n object_blob = self.driver.get_object(container_name=self.bucket.name, object_name=object_details.hashed_name)\n \n # get the object URL\n try:\n url = self.driver.get_object_cdn_url(object_blob)\n except NotImplementedError as e:\n object_path = '{}/{}'.format(self.bucket.name, object_blob.name)\n if 's3' in self.provider['type']:\n base_url = 'https://%s' % self.driver.connection.host\n url = urljoin(base_url, object_path)\n elif 'google' in self.provider['type']:\n url = urljoin('https://storage.googleapis.com', object_path)\n else:\n raise e\n # return the URL\n return url\n\n def mount_driver_from_bucket_name(self, bucket_name):\n for provider in settings.STORAGE_PROVIDERS:\n if settings.STORAGE_PROVIDERS[provider]['bucket'] == bucket_name:\n self.__init__(provider_name=provider)\n return True\n return False" }, { "alpha_fraction": 0.5258525609970093, "alphanum_fraction": 0.5566556453704834, "avg_line_length": 26.545454025268555, "blob_id": "f5c2c9446f307a6c8ec8591ac8e9dd700ba5aabb", "content_id": "287c31799fbe90e6be4cc292720356f4014f9b70", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 909, "license_type": "permissive", "max_line_length": 62, "num_lines": 33, "path": "/storage/migrations/0004_auto_20200416_1353.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.5 on 2020-04-16 08:23\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('storage', '0003_filestorage_server_reply'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='filestorage',\n old_name='bucket',\n new_name='bucket_name',\n ),\n migrations.AddField(\n model_name='filestorage',\n name='bucket_raw',\n field=models.CharField(max_length=255, null=True),\n ),\n migrations.AddField(\n model_name='filestorage',\n name='connection_name',\n field=models.CharField(max_length=255, null=True),\n ),\n migrations.AddField(\n model_name='filestorage',\n name='driver_name',\n field=models.CharField(max_length=255, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.8034682273864746, "alphanum_fraction": 0.8034682273864746, "avg_line_length": 18.33333396911621, "blob_id": "4b9a15b2d0569c917775c2cc6ec353271720e5f0", "content_id": "da1dde3bb8c263bda1405c177f7d53380cd1b9b4", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 173, "license_type": "permissive", "max_line_length": 62, "num_lines": 9, "path": "/storage/schema/query.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "import graphene\nfrom graphene_django.filter import DjangoFilterConnectionField\n\nfrom storage.schema.node import (\n ImageNode\n)\n\nclass Query(graphene.ObjectType):\n pass" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 20.35714340209961, "blob_id": "e327ec2944453c28197b9ae1245522b1befb4c30", "content_id": "e9dd4ca9b92d3638a3b297931abaef2c3972153d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 300, "license_type": "permissive", "max_line_length": 70, "num_lines": 14, "path": "/storage/urls.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "'''\n storage module URL Configuration\n'''\n\nfrom django.urls import include, path\nfrom storage.views import (\n FileDownload,\n FileUpload\n)\n\nurlpatterns = [\n path('upload', FileUpload.as_view(), name='file_upload'),\n path('url/<int:fid>', FileDownload.as_view(), name='file_upload'),\n]\n\n" }, { "alpha_fraction": 0.7768595218658447, "alphanum_fraction": 0.7768595218658447, "avg_line_length": 22.200000762939453, "blob_id": "1f38b487671c24760f30f161e332474d443dc2e5", "content_id": "020d6d6eec6cac4dc1d955c79efe8469ea39a819", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 121, "license_type": "permissive", "max_line_length": 78, "num_lines": 5, "path": "/README.rst", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "# django-multi-storage\r\n\r\nSeemless integration of multiple storages backend for High Performance storage\r\n\r\nIt's a WIP.\r\n" }, { "alpha_fraction": 0.5254902243614197, "alphanum_fraction": 0.5686274766921997, "avg_line_length": 22.18181800842285, "blob_id": "e8193bd47dd7c165fcd77d4bbb88b78208d8481a", "content_id": "0dbbf24f06e836376f1bc7675df16c1e2a911986", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "permissive", "max_line_length": 64, "num_lines": 22, "path": "/storage/migrations/0002_auto_20200415_1845.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.5 on 2020-04-15 13:15\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('storage', '0001_initial'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='filestorage',\n name='hashed_id',\n ),\n migrations.AlterField(\n model_name='filestorage',\n name='hashed_name',\n field=models.CharField(max_length=255, unique=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5801402926445007, "alphanum_fraction": 0.5963302850723267, "avg_line_length": 43.119049072265625, "blob_id": "1362475773b9b8ed87dcfab478feb04aab3b1cd3", "content_id": "8023de0424d62b9636395521b662bc7db02b5ccf", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1853, "license_type": "permissive", "max_line_length": 121, "num_lines": 42, "path": "/storage/migrations/0001_initial.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "# Generated by Django 3.0.5 on 2020-04-14 15:25\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='FileStorage',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('hashed_id', models.CharField(max_length=255)),\n ('hashed_name', models.CharField(max_length=255)),\n ('original_name', models.CharField(max_length=255)),\n ('original_meta_data', models.TextField(null=True)),\n ('original_size', models.IntegerField(help_text='The size, in bytes, of the uploaded file.', null=True)),\n ('original_charset', models.CharField(max_length=255, null=True)),\n ('bucket', models.CharField(max_length=255, null=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ],\n ),\n migrations.CreateModel(\n name='FileTransactionLogs',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('remark', models.TextField(null=True)),\n ('file', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='storage.FileStorage')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6250962018966675, "alphanum_fraction": 0.6250962018966675, "avg_line_length": 27.2608699798584, "blob_id": "5a315816ec2226c47eee63efaabfde5a291ee9d5", "content_id": "97a1475382f0ab6fc078606dfea84a4357f9aa40", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1299, "license_type": "permissive", "max_line_length": 94, "num_lines": 46, "path": "/storage/storage.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.core.exceptions import ImproperlyConfigured\nfrom django.core.files.storage import Storage\n\n\nclass MultiStorage(Storage):\n '''\n Base Storage class to abstract the storage function accross the multiple service providers\n '''\n\n # hold the drive then main connection the provider\n driver = None\n # hold the provider data\n provider = settings.STORAGE_PROVIDERS['default']\n # hold the bucket data\n bucket = None\n\n def __init__(self, provider_name=None):\n \"\"\"Establish the connection.\n\n __init__ establish the connection with the provider and connect to the bucket.\n\n Parameters\n ----------\n provider_name : string\n it should be the configuration key which is defined in the settings file\n\n Returns\n -------\n None\n It updated the object connection parameter\n\n Raises\n ------\n ImproperlyConfigured\n When the configuration is not proper\n\n\n Examples\n --------\n >>> s=Storage('default')\n \"\"\"\n # check if the provider name is in the list or none\n if provider_name is not None:\n # build the provider dict\n self.provider = settings.STORAGE_PROVIDERS[provider_name]" }, { "alpha_fraction": 0.6479290127754211, "alphanum_fraction": 0.6532544493675232, "avg_line_length": 23.852941513061523, "blob_id": "b590b26f8d2187e903e18c9424c53ef4fb3044a3", "content_id": "deeff4cba50390d945f1d6f5823a7803b52abf6a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1690, "license_type": "permissive", "max_line_length": 72, "num_lines": 68, "path": "/storage/schema/node.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "import json\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.gis.db import models\n\nimport django_filters\nimport graphene\nfrom graphene_django import DjangoObjectType\nfrom graphene_django.converter import convert_django_field\n\nfrom storage.models import (\n FileStorage,\n FileTransactionLogs\n)\n\nfrom storage.helper import (\n Storage\n)\n\n# File Node\nclass FileNode(graphene.Interface):\n '''\n Defines the custom file node\n\n it accepts the file id to view the file and its related details\n '''\n id = graphene.ID(required=True)\n url = graphene.String()\n\n def resolve_id(self, info):\n return self.hashed_name\n \n def resolve_url(self, info):\n storage = Storage()\n return storage.get_object_url(object_id=self.id)\n\n# Image node\nclass ImageNode(graphene.ObjectType):\n '''\n Defines the custom Image node, it extends the File Node\n\n it accepts the file id to view the Image and its related details\n '''\n class Meta:\n interfaces = (graphene.relay.Node, FileNode)\n \n url_200 = graphene.String()\n def resolve_url_200(self, info):\n '''\n url of the 200 byte implimation of the image\n '''\n return \"URL comming soon\"\n\n# Video node\nclass VideoNode(graphene.ObjectType):\n '''\n Defines the custom Video node, it extends the File Node\n\n it accepts the file id to view the Video and its related details\n '''\n class Meta:\n interfaces = (graphene.relay.Node, FileNode)\n \n stream_url = graphene.String()\n def resolve_stream_url(self, info):\n '''\n Streaming Url\n '''\n return \"URL comming soon\"\n" }, { "alpha_fraction": 0.5730970501899719, "alphanum_fraction": 0.582360029220581, "avg_line_length": 27.21176528930664, "blob_id": "f04d57880bb6a4813306b85357f8cab66c223401", "content_id": "6d44739d002050b0cf8908b1802529ad565e59b3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2483, "license_type": "permissive", "max_line_length": 84, "num_lines": 85, "path": "/storage/s3_storage.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "# AWS S3 storage functions which is used accross the site\r\n# Imports the AWS Boto3 library\r\n\r\nimport boto3\r\nfrom botocore.exceptions import ClientError\r\nimport datetime\r\n\r\n# Create a client for s3\r\ns3_client = boto3.client('s3')\r\n\r\n def upload_to_s3(bucket_name, source_file, destination_name=None):\r\n \"\"\"Upload a file to an S3 bucket\r\n\r\n :param source_file: File to upload\r\n :param bucket_name: Bucket to upload to\r\n :param object_name: S3 object name. If not specified then file_name is used\r\n :return: True if file was uploaded, else False\r\n \"\"\"\r\n\r\n # If S3 object_name was not specified, use file_name\r\n if destination_name is None:\r\n destination_name = file_name\r\n\r\n try:\r\n response = s3_client.upload_file(source_file, bucket_name, destination_name)\r\n print(\r\n \"File {} uploaded to bucket {} at {}\".format(\r\n source_file, bucket_name, destination_name\r\n )\r\n )\r\n except ClientError as e:\r\n print(e)\r\n return False\r\n\r\n return True\r\n\r\n\r\n\r\n\r\ndef create_presigned_url_s3(bucket_name, object_name, expiration=3600):\r\n \"\"\"Generate a presigned URL to share an S3 object\r\n\r\n bucket_name: string\r\n object_name: string\r\n expiration: Time in seconds for the presigned URL to remain valid\r\n :return: Presigned URL as string. If error, returns None.\r\n \"\"\"\r\n\r\n # Generate a presigned URL for the S3 object\r\n try:\r\n response = s3_client.generate_presigned_url('get_object',\r\n Params={'Bucket': bucket_name,\r\n 'Key': object_name},\r\n ExpiresIn=expiration)\r\n except ClientError as e:\r\n print(e)\r\n return None\r\n\r\n # The response contains the presigned URL\r\n return response\r\n\r\n\r\n## Listing all objects in the Bucket\r\ndef list_files_in_bucket(bucket_name):\r\n \"\"\"\r\n List all files in bucket\r\n \"\"\"\r\n try:\r\n response = client.list_objects_v2(\r\n Bucket= bucket_name\r\n )\r\n except ClientError as e:\r\n print(e)\r\n return None\r\n\r\n for key in response['Contents']:\r\n print('-> {}'.format(key['Key']))\r\n\r\n\r\ndef download_from_s3(bucket_name, object_name, file_name):\r\n try:\r\n s3_client.download_file(bucket_name, object_name, file_name)\r\n except ClientError as e:\r\n print(e)\r\n return None\r\n" }, { "alpha_fraction": 0.6077908277511597, "alphanum_fraction": 0.6157950758934021, "avg_line_length": 36.47999954223633, "blob_id": "5a300db9fbe65f63e8e1b7d4963732d8140caf2e", "content_id": "ff1cf6d077037e9e7a12019b9c2213a1fe6259c1", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1874, "license_type": "permissive", "max_line_length": 87, "num_lines": 50, "path": "/storage/views.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\n\nfrom rest_framework.views import APIView\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom storage.helper import Storage\n\nclass FileUpload(APIView):\n permission_classes = [IsAuthenticated]\n def post(self, request):\n '''\n basic funtion to upload the file\n\n need to pass the file upload location (mainly the bucket name) too\n '''\n storage = None\n # check name data is provided or not\n if request.POST:\n # mount the bucket specified in request\n storage = Storage(request.POST['name'])\n else:\n # mount the default bucket\n storage = Storage()\n # check file data is provided\n if request.FILES:\n # file data is provided then proced the upload the file\n file_data = request.FILES['file']\n # upload the file\n file_details = storage.save_file(request=request, file=file_data)\n # return the file hash\n if file_details['status']:\n return Response({\"file\": file_details['file'].hashed_name}, status=200)\n else:\n return Response({\"error\": file_details['error']}, status=400)\n else:\n # file is not provided so return the error code\n return Response({\"error\": \"Unsupported Media Type\"}, status=415) \n \n # By default return the method is not allowed as something is wrong\n return Response({\"error\": \"Method Not allowed\"}, status=405)\n \nclass FileDownload(APIView):\n '''\n Download the file from the server based on the fid which is provided\n '''\n def get(self, request, fid):\n storage = Storage()\n storage.get_object_url(object_id=fid)\n return Response({\"file\": 'ok'}, status=200)\n" }, { "alpha_fraction": 0.7116843461990356, "alphanum_fraction": 0.7230652570724487, "avg_line_length": 47.85185241699219, "blob_id": "220c866d5412c33513292c3c22d8ee7a98e6c84a", "content_id": "4f0851a0755edf343bbf64e6e4ccb4af3d82b213", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1318, "license_type": "permissive", "max_line_length": 131, "num_lines": 27, "path": "/storage/models.py", "repo_name": "trunkboy/django-multi-storage", "src_encoding": "UTF-8", "text": "from django.contrib.auth import get_user_model\n\nfrom django.contrib.gis.db import models\n\nclass FileStorage(models.Model):\n '''\n Stored the data and location related to the files uploaded to the buckets\n '''\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n hashed_name = models.CharField(max_length=255, unique=True) # unique name for the file after hashing use for identification\n original_name = models.CharField(max_length=255)\n original_meta_data = models.TextField(null=True)\n original_size = models.IntegerField(null=True, help_text='The size, in bytes, of the uploaded file.')\n original_charset = models.CharField(max_length=255, null=True)\n bucket_raw = models.CharField(max_length=255, null=True)\n bucket_name = models.CharField(max_length=255, null=True)\n server_reply = models.TextField(null=True) # server reply after storing the object\n\nclass FileTransactionLogs(models.Model):\n '''\n Stored the file storage and its transaction logs\n '''\n file = models.ForeignKey(FileStorage, on_delete=models.CASCADE)\n user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)\n created_at = models.DateTimeField(auto_now_add=True)\n remark = models.TextField(null=True)" } ]
15
bkrusz/Substitution_Cipher
https://github.com/bkrusz/Substitution_Cipher
2314aba503a34260a6b1c502593f3983b1fee6b8
ffbafa1a8e22843afb0d18d5389158df7da699bd
d60a548a0df97913c0c885569315b6f7278df058
refs/heads/main
2023-07-26T10:02:41.214448
2021-09-12T16:27:38
2021-09-12T16:27:38
405,691,492
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8333333134651184, "alphanum_fraction": 0.8333333134651184, "avg_line_length": 35, "blob_id": "c1d30af6a18b5c9cbf7946bc1614a53cffdf5439", "content_id": "24e240a999c60565f38d4f8d9b6dde575da372be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 72, "license_type": "no_license", "max_line_length": 49, "num_lines": 2, "path": "/README.md", "repo_name": "bkrusz/Substitution_Cipher", "src_encoding": "UTF-8", "text": "# Substitution_Cipher\n A simple implementation of a substitution cipher\n" }, { "alpha_fraction": 0.5713626146316528, "alphanum_fraction": 0.5806004405021667, "avg_line_length": 39.092594146728516, "blob_id": "5dc3d8ab88a4da05626615eeb112f1c8564a0243", "content_id": "3cca26b8440cfafb11e59c80c444034ed79d6053", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2165, "license_type": "no_license", "max_line_length": 120, "num_lines": 54, "path": "/Substitution_Cipher.py", "repo_name": "bkrusz/Substitution_Cipher", "src_encoding": "UTF-8", "text": "alphabet_lower=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\nalphabet_upper=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']\ndef cipher_array(array, key):\n cipher_array=[0]*len(array)\n key_count=0\n for i in range(len(array)):\n if key_count >= len(key):\n key_count=0\n cipher_array[i]=alphabet_upper.index(key[key_count].upper())\n key_count=key_count+1\n return cipher_array\n\ndef decipher(array, cipher_array):\n deciphered_array=['']*len(array)\n for i in range(len(array)):\n if array[i].isupper():\n deciphered_array[i]=alphabet_upper[(alphabet_upper.index(array[i])-cipher_array[i])%26]\n else:\n deciphered_array[i]=alphabet_lower[(alphabet_lower.index(array[i])-cipher_array[i])%26]\n return deciphered_array\n\ndef cipher(array, cipher_array):\n ciphered_array=['']*len(array)\n for i in range(len(array)):\n if array[i].isupper():\n ciphered_array[i]=alphabet_upper[(alphabet_upper.index(array[i])+cipher_array[i])%26]\n else:\n ciphered_array[i]=alphabet_lower[(alphabet_lower.index(array[i])+cipher_array[i])%26]\n return ciphered_array\n\ndef print_array(array):\n for i in range(len(array)):\n print(array[i],end=\"\")\n print(\"\")\n\noption=input(\"To cipher, input 1. To decipher, input 0. To quit, input q: \")\nwhile option!='q':\n if option=='1':\n text=input(\"Text to be ciphered: \")\n key=input(\"Key to cipher with: \")\n new_cipher_array=cipher_array(text, key)\n print_array(cipher(text, new_cipher_array))\n option=input(\"To cipher, input 1. To decipher, input 0. To quit, input q: \")\n elif option=='0':\n cipher=input(\"Text to be deciphered: \")\n key=input(\"Key to decipher with: \")\n new_cipher_array=cipher_array(cipher, key)\n print_array(decipher(cipher, new_cipher_array))\n option=input(\"To cipher, input 1. To decipher, input 0. To quit, input q: \")\n else:\n print(\"Unkown input. Try again.\")\n text=\"\"\n key=\"\"\n cipher=\"\"\n" } ]
2
liamhan0905/OpenCV-SimpleProjects
https://github.com/liamhan0905/OpenCV-SimpleProjects
bc62b3269397064cf83045875a018c86021372b0
bf745acecf8476cf01c34a834334865830042f13
09a233bbf1468aebaffc94b95230f8112b0b0e91
refs/heads/master
2022-07-15T09:11:19.793581
2020-05-11T23:41:26
2020-05-11T23:41:26
262,675,805
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5464268326759338, "alphanum_fraction": 0.6105979681015015, "avg_line_length": 28.811594009399414, "blob_id": "535a4eafc48e98729fb3a9534117b6182f065ee9", "content_id": "58e616b043f9fdc2114a56743bcc384ebdda7d6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2057, "license_type": "no_license", "max_line_length": 109, "num_lines": 69, "path": "/Project1: Virtual Paint/project.py", "repo_name": "liamhan0905/OpenCV-SimpleProjects", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\nframeWidth = 640\nframeHeight = 480\ncap = cv2.VideoCapture(0)\ncap.set(3,frameWidth)\ncap.set(4,frameHeight)\ncap.set(10,150) #brightness\n\nmyColors = [[\"red\",0,137,111,23,255,255], #red\n [\"blue\",104,57,91,122,255,255], #blue\n ['green',53,63,0,95,165,175]] #green\n\n#BGR Format\nmyColorValues = [[0,0,255],\n [255,0,0],\n [0,255,0]]\n\nmyPoints = [] #[x,y,colorIndex]\n\n\ndef findColor(img,myColors,myColorValues):\n imgHSV = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n count = 0\n newPoints = []\n for color in myColors:\n lower = np.array(color[1:4])\n upper = np.array(color[4:7])\n mask = cv2.inRange(imgHSV,lower,upper)\n x,y = getContours(mask)\n cv2.circle(imgResult,(x,y),10, myColorValues[count],cv2.FILLED)\n if x!=0 and y!=0:\n newPoints.append([x,y,count])\n count += 1\n # cv2.imshow(color[0],mask) #uncomment to view the masks\n return newPoints\n\ndef getContours(img):\n contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n x,y,w,h = 0,0,0,0\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if area > 500:\n # cv2.drawContours(imgResult, cnt, -1, (255, 0, 0), thickness=3) # uncomment to view the contour\n peri = cv2.arcLength(cnt,True)\n approx = cv2.approxPolyDP(cnt,0.02*peri,True) # find corners\n x,y,w,h = cv2.boundingRect(approx)\n return x+w,y+h//2\n\ndef drawOnCanvas(myPoints,myColorValues):\n for point in myPoints:\n cv2.circle(imgResult, (point[0],point[1]), 10, myColorValues[point[2]], cv2.FILLED)\n\n\nwhile True:\n success, img = cap.read()\n imgResult = img.copy()\n newPoints = findColor(img,myColors,myColorValues)\n if len(newPoints) != 0:\n for newPoint in newPoints:\n myPoints.append(newPoint)\n if len(myPoints) != 0:\n drawOnCanvas(myPoints,myColorValues)\n\n cv2.imshow(\"Video\",imgResult)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n" }, { "alpha_fraction": 0.7596899271011353, "alphanum_fraction": 0.7777777910232544, "avg_line_length": 54.28571319580078, "blob_id": "8a0dc56cda4a25af9e440fb7230e205c5fa3e081", "content_id": "9fadc5324f5666abbc2a4db6be7a7582240e8522", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 387, "license_type": "no_license", "max_line_length": 143, "num_lines": 7, "path": "/README.md", "repo_name": "liamhan0905/OpenCV-SimpleProjects", "src_encoding": "UTF-8", "text": "# OpenCV-SimpleProjects\n\n### DISCLOSURE: These projects belong to \"Murtaza's Workshop - Robotics and AI\"\n\nThis repo consists of three simple projects that were found in \"Learn Opencv in 3 hours with Python from Murtazaa's Workshop - Robotics and AI\"\n\nHere is the [link](https://www.youtube.com/watch?v=WQeoO7MI0Bs&t=6344s) that consists lectures on openCV as well as the three projects.\n" }, { "alpha_fraction": 0.6536661386489868, "alphanum_fraction": 0.7815912365913391, "avg_line_length": 70.11111450195312, "blob_id": "2127d38a8d5535ded4b74b9f98d715b216b594ba", "content_id": "10bb138bb111e15e51b075a16f5e921e43d46d13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 641, "license_type": "no_license", "max_line_length": 260, "num_lines": 9, "path": "/Project1: Virtual Paint/README.md", "repo_name": "liamhan0905/OpenCV-SimpleProjects", "src_encoding": "UTF-8", "text": "### DISCLOSURE: This project belongs to \"Murtaza's Workshop - Robotics and AI\"\n\nIn this project, I learned to read images from the webcam, mask the image (for specific color) and then find the contour of the masked image. For every frame, the tip of the pen coordinate of the contour is used to draw out the trajectory of the pen movement. \n\n[Demo-Video](https://www.youtube.com/watch?v=8SpA_c7OlnU&feature=youtu.be)\n\n![mask](https://user-images.githubusercontent.com/44885838/81487585-7567eb00-9213-11ea-8f32-3d6342671aff.JPG)\n\n![mask2](https://user-images.githubusercontent.com/44885838/81487588-78fb7200-9213-11ea-93f9-e210b573c654.JPG)\n\n" }, { "alpha_fraction": 0.7849056720733643, "alphanum_fraction": 0.7849056720733643, "avg_line_length": 86.33333587646484, "blob_id": "10d1a9859ac907d22cd2e2b61f2fead08c4dd79b", "content_id": "989d97b7b9f68225305d079308c9557bdc33303e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 265, "license_type": "no_license", "max_line_length": 185, "num_lines": 3, "path": "/Project3: Number Plate Detection/README.md", "repo_name": "liamhan0905/OpenCV-SimpleProjects", "src_encoding": "UTF-8", "text": "DISCLOSURE: This project belongs to \"Murtaza's Workshop - Robotics and AI\"\n\nIn this project, I learned to detect the license plate using the webcam (I used images instead of using actual car license plate). Casscade classifier was used to find the licene plate.\n\n\n\n" }, { "alpha_fraction": 0.6007181406021118, "alphanum_fraction": 0.6434470415115356, "avg_line_length": 30.647727966308594, "blob_id": "7490e53db2aa3c5617939d5e82b4a45f298f6c39", "content_id": "6364746d2393442e772f665de11b92ae1f7e67ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2785, "license_type": "no_license", "max_line_length": 104, "num_lines": 88, "path": "/Project2: Document Scanner/project.py", "repo_name": "liamhan0905/OpenCV-SimpleProjects", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\n\nwidthImg = 480\nheightImg = 640\ncap = cv2.VideoCapture(0)\ncap.set(3,widthImg)\ncap.set(4,heightImg)\ncap.set(10,150) #brightness\n\ndef preProcessing(img):\n imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n imgBlur = cv2.GaussianBlur(imgGray,(5,5),1)\n # cv2.imshow(\"blur\", imgBlur)\n imgCanny = cv2.Canny(imgBlur,30,90)\n # cv2.imshow(\"canny\", imgCanny)\n kernel = np.ones((5,5))\n imgDilation = cv2.dilate(imgCanny,kernel, iterations = 2)\n # cv2.imshow(\"dilation\", imgDilation)\n imgErode = cv2.erode(imgDilation,kernel,iterations = 1 )\n # cv2.imshow(\"erode\", imgErode)\n imgThres = imgErode\n return imgThres\n\ndef getContours(img):\n biggest = np.array([])\n maxArea = 0\n contours,hierarchy = cv2.findContours(img,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n for cnt in contours:\n area = cv2.contourArea(cnt)\n\n if area > 100000:\n cv2.drawContours(imgContour, cnt, -1, (255, 0, 0), thickness=2) # -1 to draw on all contour\n peri = cv2.arcLength(cnt,True)\n # print(peri)\n approx = cv2.approxPolyDP(cnt,0.02*peri,True) # find corners\n # print(len(approx))\n if area > maxArea and len(approx == 4):\n biggest = approx\n maxArea = area\n # print(biggest)\n cv2.drawContours(imgContour, biggest, -1, (0, 0, 255), thickness=10) # -1 to draw on all contour\n return biggest\n\ndef reorder(myPoints):\n myPoints = myPoints.reshape((4,2))\n newPoints = np.zeros((4,1,2),np.int32)\n add = myPoints.sum(1)\n # print(\"add\",add)\n # print(\"min\",myPoints[np.argmin(add)])\n newPoints[0] = myPoints[np.argmin(add)]\n newPoints[3] = myPoints[np.argmax(add)]\n\n diff = np.diff(myPoints, axis=1)\n newPoints[1] = myPoints[np.argmin(diff)]\n newPoints[2] = myPoints[np.argmax(diff)]\n\n return newPoints\n\ndef getWarp(img,biggest):\n # print(biggest)\n biggest = reorder(biggest)\n pts1 = np.float32(biggest)\n pts2 = np.float32([[0, 0], [widthImg, 0], [0, heightImg], [widthImg, heightImg]])\n matrix = cv2.getPerspectiveTransform(pts1, pts2)\n imgOutput = cv2.warpPerspective(img, matrix, (widthImg, heightImg))\n\n imgCropped = imgOutput[10:imgOutput.shape[0]-10,10:imgOutput.shape[1]-10]\n imgCropped = cv2.resize(imgCropped,(widthImg,heightImg))\n\n return imgCropped\n\n\nwhile True:\n success, img = cap.read()\n img = cv2.resize(img,(widthImg,heightImg))\n imgContour = img.copy()\n imgThresh = preProcessing(img)\n biggest = getContours(imgThresh)\n imgWarped = getWarp(img,biggest)\n\n cv2.imshow(\"Original Img\", img)\n cv2.imshow(\"Original Img with Contour\", imgContour)\n cv2.imshow(\"Video\",imgWarped)\n\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n" }, { "alpha_fraction": 0.72052401304245, "alphanum_fraction": 0.7991266250610352, "avg_line_length": 90.5999984741211, "blob_id": "55d11506398727b2dbad0273b33db52bf0381620", "content_id": "8f4f3f8d2f3fbeda3d5e51fe9dde9d96c88bdbfb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 458, "license_type": "no_license", "max_line_length": 270, "num_lines": 5, "path": "/Project2: Document Scanner/README.md", "repo_name": "liamhan0905/OpenCV-SimpleProjects", "src_encoding": "UTF-8", "text": "DISCLOSURE: This project belongs to \"Murtaza's Workshop - Robotics and AI\"\n\nIn this project, I learned to read images from the webcam, find the contour and corners of the desired image. Then the warped image was extracted from the orinal image. This tool can be useful when the user requires to view a specific feature/part of the original image.\n\n![warp](https://user-images.githubusercontent.com/44885838/81525252-edfca380-9308-11ea-89e5-c766d0021ac4.JPG)\n" } ]
6
haregali/woofcryption
https://github.com/haregali/woofcryption
31b2ae5be2bd52436d51d2fdec3fcf35d2497ad1
dc39c381aacb3cc9948c35bdd96103fc25fc8b27
a7b858b09b7edd4bc67cc2833cbdf62439c0a180
refs/heads/master
2021-06-09T05:32:30.952410
2016-11-08T00:38:35
2016-11-08T00:38:35
73,133,648
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.47035956382751465, "alphanum_fraction": 0.49368318915367126, "avg_line_length": 39.2400016784668, "blob_id": "b58a5c410bc677b86d0456b7a3d418bb4447634f", "content_id": "5871ce396eb143708cb49ee4ce92e9c61945b8ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1029, "license_type": "no_license", "max_line_length": 156, "num_lines": 25, "path": "/woofgen.py", "repo_name": "haregali/woofcryption", "src_encoding": "UTF-8", "text": "from random import randint\r\n\r\nlistWoof = ['wOOf', 'WOoF', 'wOOF', 'Woof', 'wOof', 'WoOf', 'wooF', 'woOF', 'WooF', 'woOf', 'woof', 'WOOf', 'WOOF', 'WOof', 'wOoF', 'WoOF']\r\nlistChar = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j',\r\n'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+','/','=']\r\ndictHash = dict()\r\nranInt1 = 0\r\nranInt2 = 0\r\nwoofString = ''\r\n\r\nk = 0\r\nwhile k < len(listChar):\r\n woofString = listWoof[randint(0,15)]\r\n while len(woofString) != 8:\r\n woofStr = listWoof[randint(0,15)]\r\n if woofStr not in woofString:\r\n woofString = woofString + woofStr\r\n if woofString not in dictHash.values():\r\n dictHash[listChar[k]] = woofString\r\n k = k+1\r\n else:\r\n k = k-1\r\nreverse = dict((v,k) for k, v in dictHash.iteritems())\r\nprint(\"Original: \" + str(dictHash) + \"\\n\")\r\nprint(\"Reverse(for decoding): \" + str(reverse))" }, { "alpha_fraction": 0.7979093790054321, "alphanum_fraction": 0.8060395121574402, "avg_line_length": 70.75, "blob_id": "52d20a8b78e3d1ae16c25383269a6cb19a443b0a", "content_id": "a338589e9102ae9608b7acaa7272b7dd8ea31a6e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 861, "license_type": "no_license", "max_line_length": 271, "num_lines": 12, "path": "/README.md", "repo_name": "haregali/woofcryption", "src_encoding": "UTF-8", "text": "# woofcryption\nThis is a project inspired by quackcryption but is a Python implementation and the entire encryption/decryption process is done in about 40 lines of code\n\nwoofgen.py- if you would like a unique dictionary this program will generate one for you\nwoofcryption.py- main file that uses 128 bit AES encryption converted into base64 then a hashtable is used to find the corresponding coded 'woofwoof'\n\n\n---USAGE---\n\njust run woofcryption.py using python or chmod it into an executable, then follow the prompts(do note that it is case-sensitive so enter it as it is in the prompt.\n\nFor woofgen.py run using python or chmod it into an executable, then just copy and paste the output. the dictionary following the Original tag is pasted into the corresponding dict in woofcryption and the reverse tag is pasted into the corresponding dict in woofcryption.\n" } ]
2
Wallruzz9114/fastapi-backend
https://github.com/Wallruzz9114/fastapi-backend
7576d2631394d90a436323313e8f1db120c5c353
37986e4dfec815b867286c00e1edd8ee642f0f67
4f5c38662ae1346f777e166bfe9aa2e2362e0035
refs/heads/master
2023-04-28T14:06:56.863429
2021-05-05T15:19:26
2021-05-05T15:19:26
364,585,982
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.40909090638160706, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 14, "blob_id": "cad4d9eae8cf44caa88c40598b8f0af224fcd7f8", "content_id": "f321e688a79b938505cc268911612c7c2043b94b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 44, "license_type": "no_license", "max_line_length": 15, "num_lines": 3, "path": "/project/requirements.txt", "repo_name": "Wallruzz9114/fastapi-backend", "src_encoding": "UTF-8", "text": "fastapi==0.63.0\nuvicorn==0.13.4\nyapf==0.31.0" }, { "alpha_fraction": 0.7171717286109924, "alphanum_fraction": 0.7171717286109924, "avg_line_length": 32, "blob_id": "7995b3665cea4e5373d357a4965bf850300d5dee", "content_id": "f1967e3785a1998cdf279dc0f9af85b7d3211dd2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 92, "num_lines": 18, "path": "/project/app/main.py", "repo_name": "Wallruzz9114/fastapi-backend", "src_encoding": "UTF-8", "text": "from fastapi import Depends, FastAPI\n\nfrom app.config import Settings, get_settings\n\napp = FastAPI()\n\n\n# Take note of settings: Settings = Depends(get_settings).\n# Here, the Depends function is a dependency that declares another dependency, get_settings.\n# Put another way, Depends depends on the result of get_settings.\n# The value returned, Settings, is then assigned to the settings parameter.\[email protected]('/ping')\ndef pong(settings: Settings = Depends(get_settings)):\n return {\n \"ping\": \"pong!\",\n \"environment\": settings.environment,\n \"testing\": settings.testing\n }\n" } ]
2
developer-md/Desktop-Assistant
https://github.com/developer-md/Desktop-Assistant
50fb79c04de00ba6fdfce8ce4a6864a72bd4172a
a36c798ada59028e045c042f0b8f19db3b84ff68
f8ea512000fb53e8b815ea9990f7dd43bb9db08a
refs/heads/master
2023-05-14T08:11:21.481209
2021-06-12T17:23:57
2021-06-12T17:23:57
277,158,110
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5410507321357727, "alphanum_fraction": 0.5645997524261475, "avg_line_length": 35.90048599243164, "blob_id": "99e19213e3e0b7a7a562885546b48bfa3502668c", "content_id": "c3e1a511e3b726fd26f043462dabe69649d5dc36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15627, "license_type": "no_license", "max_line_length": 182, "num_lines": 412, "path": "/main.py", "repo_name": "developer-md/Desktop-Assistant", "src_encoding": "UTF-8", "text": "import speech_recognition as sr #for taking input from microphone and recognize it\r\nimport datetime #for date time \r\nimport random #for choosen random values from given values\r\nimport webbrowser #for open and access web\r\nimport wikipedia #for access wikipedia\r\nimport os #for access files \r\nimport pyaudio #for taking input from microphone\r\nimport pyttsx3 #for converting text into speech\r\nimport smtplib #for sending mail\r\nimport tkinter as tk #for creating GUI\r\nfrom PIL import Image, ImageTk #for GUI\r\nfrom tkinter import Menu,Label,Button,Entry,Scrollbar,messagebox #for GUI\r\nimport time #for access wait function\r\nimport keyboard #enter auto input\r\nimport pyautogui #control keyboard automatic\r\n#from selenium import webdriver \r\n#from selenium.webdriver.support.ui import WebDriverWait \r\n#from selenium.webdriver.support import expected_conditions as EC \r\n#from selenium.webdriver.common.keys import Keys \r\n#from selenium.webdriver.common.by import By\r\nimport pywhatkit #for accessing youtube and whatsapp\r\n\r\n#making instance of pyttsx3\r\nen=pyttsx3.init() \r\nen.setProperty('rate',180)\r\n\r\n#getting details of current voice\r\nvoices = en.getProperty('voices') \r\n\r\n#changes voices. o for male\r\n#en.setProperty('voice', voices[0].id) \r\n\r\n#changes voices. 1 for female\r\nen.setProperty('voice', voices[1].id) \r\n\r\n#global vairiables\r\nglobal email\r\nglobal password\r\n\r\n#dictionary of mail addresses\r\nmail={\"jyoti\":\"[email protected]\",\r\n\"md\":\"[email protected]\",\r\n\"shubham\":\"[email protected]\"}\r\n\r\n#dictionary of whatsapp contacts\r\ncontacts={\"jyoti\":\"+9189###99032\",\r\n\"shubham\":\"+9193####2443\",\r\n\"md\":\"+919######951\"}\r\n\r\n\r\n#speak function which speak the text comes in it.\r\ndef speak(audio):\r\n en.say(audio)\r\n en.runAndWait()\r\n\r\ndef Ex():\r\n\texit()\r\n\r\n\r\n\r\n\r\n#take funtion record your audio and return back to in form of text\r\ndef take():\r\n\tr= sr.Recognizer()\r\n\twith sr.Microphone() as source:\r\n\t\tspeak(\"speak up\")\r\n\t\tprint(\"Listening.....\")\r\n\t\tr.adjust_for_ambient_noise(source, duration=1)\r\n\t\tr.pause_threshold=1\r\n\t\taudio = r.listen(source)\r\n\ttry:\r\n\t\tprint(\"recognizing..\")\r\n\t\tqr= r.recognize_google(audio)\r\n\t\tprint(qr)\r\n\texcept Exception as e:\r\n\t\tprint(e)\r\n\t\tspeak(\"sorry, say that again please..\")\r\n\t\treturn \"None\"\r\n\treturn qr\r\n\r\n#function for destroying GUI\r\ndef quit():\r\n\tglobal email\r\n\tglobal password\r\n\temail=e.get()\r\n\tpassword=e1.get()\r\n\tif email==\"\" or password==\"\":\r\n\t\tmessagebox.showerror('Error','Oops enter mail & password')\r\n\telse:\r\n\t\troot.destroy()\r\n\r\n\r\n#function for Help GUI\r\ndef aboutme():\r\n rot=tk.Tk()\r\n rot.title(\"panda-the assistant app\")\r\n rot.geometry(\"1300x900\")\r\n rot.resizable(0,0)\r\n rot.config(background=\"white\")\r\n scrollbar = Scrollbar(rot)\r\n scrollbar.pack(side=tk.RIGHT, fill=tk.Y)\r\n l4=Label(rot,text=\" Commands Description\",font=(\"Times\",15,\"bold\"),bg=\"white\")\r\n l4.pack(anchor=tk.W,pady=(10,0))\r\n l5=Label(rot,text=\" name tell own name\",font=(\"Times\",15),bg=\"white\")\r\n l5.pack(anchor=tk.W,padx=(10,0))\r\n l6=Label(rot,text=\" open google open google for you\",font=(\"Times\",15),bg=\"white\")\r\n l6.pack(anchor=tk.W,padx=(10,0))\r\n l7=Label(rot,text=\" open youtube open youtube for you\",font=(\"Times\",15),bg=\"white\")\r\n l7.pack(anchor=tk.W,padx=(10,0))\r\n l8=Label(rot,text=\" wikipedia ------- search wikipedia, eg:wikipedia dogs\",font=(\"Times\",15),bg=\"white\")\r\n l8.pack(anchor=tk.W,padx=(10,0))\r\n l9=Label(rot,text=\" search search anything in google\",font=(\"Times\",15),bg=\"white\")\r\n l9.pack(anchor=tk.W,padx=(10,0))\r\n l10=Label(rot,text=\" location find any location on map\",font=(\"Times\",15),bg=\"white\")\r\n l10.pack(anchor=tk.W,padx=(10,0))\r\n l11=Label(rot,text=\" yourself tell about herself\",font=(\"Times\",15),bg=\"white\")\r\n l11.pack(anchor=tk.W,padx=(10,0))\r\n l12=Label(rot,text=\" time tell current time\",font=(\"Times\",15),bg=\"white\")\r\n l12.pack(anchor=tk.W,padx=(10,0))\r\n l13=Label(rot,text=\" how are you talk about herself\",font=(\"Times\",15),bg=\"white\")\r\n l13.pack(anchor=tk.W,padx=(10,0))\r\n l14=Label(rot,text=\" play music play music for you, songs must be here D:/song\",font=(\"Times\",15),bg=\"white\")\r\n l14.pack(anchor=tk.W,padx=(10,0))\r\n l15=Label(rot,text=\" notepad open notepad & ask for writing something\",font=(\"Times\",15),bg=\"white\")\r\n l15.pack(anchor=tk.W,padx=(10,0))\r\n l16=Label(rot,text=\" my computer open my computer\",font=(\"Times\",15),bg=\"white\")\r\n l16.pack(anchor=tk.W,padx=(10,0))\r\n l17=Label(rot,text=\" month tell current month name\",font=(\"Times\",15),bg=\"white\")\r\n l17.pack(anchor=tk.W,padx=(10,0))\r\n l18=Label(rot,text=\" mail send Email\",font=(\"Times\",15),bg=\"white\")\r\n l18.pack(anchor=tk.W,padx=(10,0))\r\n l19=Label(rot,text=\" shutdown shutdown your system\",font=(\"Times\",15),bg=\"white\")\r\n l19.pack(anchor=tk.W,padx=(10,0))\r\n l20=Label(rot,text=\" restart Restart your system\",font=(\"Times\",15),bg=\"white\")\r\n l20.pack(anchor=tk.W,padx=(10,0))\r\n l21=Label(rot,text=\" day tell today's day\",font=(\"Times\",15),bg=\"white\")\r\n l21.pack(anchor=tk.W,padx=(10,0))\r\n l22=Label(rot,text=\" exit Shutdown herself\",font=(\"Times\",15),bg=\"white\")\r\n l22.pack(anchor=tk.W,padx=(10,0))\r\n l23=Label(rot,text=\" play in youtube play anything in youtube\",font=(\"Times\",15),bg=\"white\")\r\n l23.pack(anchor=tk.W,padx=(10,0))\r\n l24=Label(rot,text=\" use whatsapp sent messages on whatsapp\",font=(\"Times\",15),bg=\"white\")\r\n l24.pack(anchor=tk.W,padx=(10,0))\r\n\r\n\r\n#function for show about developer \r\ndef aboutdeveloper():\r\n about=tk.Tk()\r\n about.title(\"panda-the assistant app\")\r\n about.geometry(\"920x720\")\r\n about.resizable(0,0)\r\n about.config(background=\"black\")\r\n label=Label(about,text=\"Oops!\\n404\\nNot Found\",font=(\"Times\",15,\"bold\"),bg=\"black\",fg=\"white\")\r\n label.pack(pady=(200,10))\r\n\r\n\r\n#function for saving mail and password\r\ndef submit():\r\n\tglobal email\r\n\tglobal password\r\n\temail=e.get()\r\n\tpassword=e1.get()\r\n\tif email==\"\" or password==\"\":\r\n\t\tmessagebox.showerror('Error','Oops enter mail & password')\r\n\telse:\r\n\t\tmessagebox.showinfo('success','Added successfully')\r\n\r\ndef show():\r\n\tglobal email\r\n\tglobal password\r\n\tprint(email)\r\n\tprint(password)\r\n\r\n\r\n\r\n#function for sending mail \r\ndef sendemail(to,content):\r\n\tglobal email\r\n\tglobal password\r\n\tsvr=smtplib.SMTP('smtp.gmail.com',587)\r\n\tsvr.ehlo()\r\n\tsvr.starttls()\r\n\tsvr.login(email,password)\r\n\tsvr.sendmail(password,to,content)\r\n\tsvr.close()\r\n\r\n\r\n#create main GUI\r\nroot=tk.Tk()\r\nroot.title(\"panda-the assistant app\")\r\n#root.iconbitmap('logo1.ico')\r\nroot.geometry(\"1100x800\")\r\nroot.resizable(0,0)\r\nroot.config(background=\"white\")\r\n\r\n#creating menu bar\r\nmenubar=Menu(root)\r\n\r\n#help option\r\nhelpmenu=Menu(menubar,tearoff=0)\r\nhelpmenu.add_command(label=\"About me\",command=aboutme)\r\nmenubar.add_cascade(label=\"Help\",menu=helpmenu)\r\n\r\n#About option\r\naboutmenu=Menu(menubar,tearoff=0)\r\naboutmenu.add_command(label=\"About developer\",command=aboutdeveloper)\r\nmenubar.add_cascade(label=\"About\",menu=aboutmenu)\r\n\r\n#exit option\r\nexitmenu=Menu(menubar,tearoff=0)\r\nexitmenu.add_command(label=\"Exit\",command=Ex)\r\nmenubar.add_cascade(label=\"Exit\",menu=exitmenu)\r\n\r\n#put menubar in GUI\r\nroot.config(menu=menubar)\r\n\r\n\r\n#main icon at top of GUI\r\nimg = ImageTk.PhotoImage(Image.open(\"icon2.png\")) # PIL solution\r\nl1=Label(root,image=img,border=0)\r\nl1.pack(pady=(10,10))\r\n\r\n#label for email\r\nl2=Label(root,text=\"Email:\",border=0,font=(\"consalis\",15),bg=\"white\",fg=\"black\")\r\nl2.pack(pady=(10,10))\r\n\r\n#input email\r\ne=Entry(root,width=25,font=(\"consalis\",11),bd=2,insertbackground=\"black\")\r\ne.pack(pady=(10,10))\r\n\r\n#label for password\r\nl3=Label(root,text=\"Password:\",border=0,font=(\"consalis\",15),bg=\"white\",fg=\"black\")\r\nl3.pack(pady=(10,10))\r\n\r\n#input password\r\ne1=Entry(root,show=\"*\",width=25,font=(\"consalis\",11),bd=2,insertbackground=\"black\")\r\ne1.pack(pady=(10,10))\r\n\r\n#button for submit the email and password\r\nb1=Button(text=\"submit\",font=(\"times\",12),command=submit,width=10,border=2,bg=\"skyblue\")\r\nb1.pack(pady=(10,10))\r\n\r\n\r\n#put a Label\r\nnote=Label(root,text=\"Note: Before you start go in help upper left corner\\nbecause after clicking on start it will disapear.\",font=(\"consalis\",10),bg=\"white\",fg=\"red\")\r\nnote.pack(pady=(10,10))\r\n\r\n#create a start button with image\r\nimg1 = ImageTk.PhotoImage(Image.open(\"start2.png\")) # PIL solution\r\nb=Button(text=\"\",image=img1,border=0,command=quit)\r\nb.pack(pady=(30,10))\r\n\r\n#put a label\r\nfooter=Label(root,text=\"click to start\",border=0,font=(\"consalis\",15),bg=\"white\",fg=\"blueviolet\")\r\nfooter.pack(pady=(10,10))\r\n\r\n#put a Label\r\nl=Label(root,text=\"developed by team triangle:\",width=100,font=(\"consalis\",20),bg=\"black\",fg=\"gold\")\r\nl.pack(pady=(20,10))\r\n\r\n\r\n#start GUI\r\nroot.mainloop()\r\n\r\n\r\ncommand=\"\"\r\n\r\n\r\n#main loop\r\nwhile True:\r\n\ttime.sleep(1)\r\n\tcommand=take().lower()\r\n\tif \"name\" in command or \"who are you\" in command:\r\n\t\ts=[\"my name is pandaa\",\"sir, I am pandaa\",\"my names pandaa\"]\r\n\t\thr=int(datetime.datetime.now().hour)\r\n\t\tif hr>=0 and hr<12:\r\n\t\t\tspeak(\"good morining\")\r\n\t\telif hr>=12 and hr<18:\r\n\t\t\tspeak(\"good afternoon\")\r\n\t\telif hr>=18 and hr<20:\r\n\t\t\tspeak(\"good evening\")\r\n\t\telse:\r\n\t\t\tspeak(\"good night\")\r\n\t\tspeak(random.choice(s))\r\n\r\n\telif \"open google\" in command:\r\n\t\twebbrowser.open(\"google.com\")\r\n\t\ttime.sleep(1)\r\n\t\tspeak(\"opening google\")\r\n\telif \"open youtube\" in command:\r\n\t\twebbrowser.open(\"youtube.com\")\r\n\t\ttime.sleep(1)\r\n\t\tspeak(\"opening youtube\")\r\n\telif \"wikipedia\" in command:\r\n\t\tcommand=command.replace(\"wikipedia\",\"\")\r\n\t\tspeak(\"searching wikipedia\")\r\n\t\tresult=wikipedia.summary(command,sentences=2)\r\n\t\tspeak(\"according to wikipedia\")\t\r\n\t\tprint(result)\r\n\t\tspeak(result)\r\n\telif \"search\" in command:\r\n\t\tspeak(\"what do you want to search for?\")\r\n\t\ts=take()\r\n\t\turl='https://google.com/search?q='+s\r\n\t\twebbrowser.get().open(url)\r\n\t\ttime.sleep(2)\r\n\t\tspeak(f\"Here is result what I found for {s}\")\r\n\telif \"location\" in command:\r\n\t\tspeak(\"what do you want to search for?\")\r\n\t\ts=take()\r\n\t\turl='https://google.nl/maps/place/'+s+'/&amp;'\r\n\t\twebbrowser.get().open(url)\r\n\t\ttime.sleep(3)\r\n\t\tspeak(f\"Here is result what i found for {s}\")\r\n\telif \"time\" in command:\r\n\t\ttime=datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n\t\tspeak(f\"sir, the time is {time}\")\r\n\telif \"day\" in command:\r\n\t\td=datetime.datetime.now().strftime(\"%A\")\r\n\t\tspeak(f\"Today is {d}\")\r\n\telif \"date\" in command:\r\n\t\tc=datetime.datetime.now().strftime(\"%d\")\r\n\t\tv=datetime.datetime.now().strftime(\"%B\")\r\n\t\tspeak(f\"Today's date is {c}\")\r\n\t\tspeak(v)\r\n\telif \"month\" in command:\r\n\t\tm=datetime.date.now().strftime(\"%B\")\r\n\t\tspeak(f\"month is {m}\")\r\n\telif \"yourself\" in command:\r\n\t\tspeak(\"hello sir, my name is pandaa. I'am your personal assistant. I'am developed by developer MD. How may I help you sir\")\r\n\telif \"how are you\" in command or \"what's up\" in command or \"how's you\" in command:\r\n\t\ts=[\"I am fine\",\"I'am good.\",\"I don't want to talk.\",\"I am so tired pleases leave me alone.\",\"today I'am so bored\",\"don't talk to me\"]\r\n\t\tspeak(random.choice(s))\r\n\telif \"notepad\" in command:\r\n\t\tpath=\"C:\\\\Windows\\\\notepad.exe\"\r\n\t\tos.startfile(path)\r\n\t\tspeak(\"opening notepad\")\r\n\t\tspeak(\"Are you want write somthing\")\r\n\t\tq=take().lower()\r\n\t\tif \"yes\" in q:\r\n\t\t\tspeak(\"Okay tell me what should I write for you\")\r\n\t\t\ttime.sleep(1)\r\n\t\t\tcontent=take()\r\n\t\t\tkeyboard.write(content)\r\n\t\t\tspeak(\"Are want to save this\")\r\n\t\t\tq=take().lower()\r\n\t\t\tif \"yes\" in q:\r\n\t\t\t\tpyautogui.hotkey('ctrl','s')\r\n\t\t\t\tname=[\"new\",\"first\",\"test\",\"testing file\",\"tested\",\"neww\"]\r\n\t\t\t\tkeyboard.write(random.choice(name))\r\n\t\t\t\tpyautogui.press('enter')\r\n\t\t\t\tspeak(\"your file is saved\")\r\n\t\telse:\r\n\t\t\tspeak(\"okay...\")\r\n\telif \"my computer\" in command:\r\n\t\tpath=\"C:\\\\Windows\\\\explorer.exe\"\r\n\t\tos.startfile(path)\r\n\t\ttime.sleep(1)\r\n\t\tspeak(\"opening my computer\")\r\n\telif \"play music\" in command:\r\n\t\tdir=\"D:\\\\song\"\r\n\t\tsong=os.listdir(dir)\r\n\t\tspeak(\"enjoy....I found something new for you it will start soon.\")\r\n\t\tos.startfile(os.path.join(dir,random.choice(song)))\r\n\telif \"mail\" in command:\r\n\t\ttry:\r\n\t\t\tspeak(\"whom you want to send mail\")\r\n\t\t\tv=take().lower()\r\n\t\t\tspeak(\"what should I say\")\r\n\t\t\tcontent=take()\r\n\t\t\tto=mail.get(v)\r\n\t\t\tsendemail(to,content)\r\n\t\t\tspeak(\"email has been sent\")\r\n\t\texcept Exception as e:\r\n\t\t\tprint(e)\r\n\t\t\tspeak(\"sorry,something went wrong\")\r\n\telif \"shutdown\" in command:\r\n\t\tspeak(\"are you sure\")\r\n\t\tans=take().lower()\r\n\t\tif \"yes\" in ans:\r\n\t\t\tspeak(\"okay sure sir, byee. have a good day\")\r\n\t\t\tos.system(\"shutdown /s /t 1\")\r\n\telif \"restart\" in command:\r\n\t\tspeak(\"are you sure\")\r\n\t\tans=take().lower()\r\n\t\tif \"yes\" in ans:\r\n\t\t\tspeak(\"okay sure sir,\")\r\n\t\t\tos.system(\"shutdown /r /t 1\")\r\n\telif \"play in youtube\" in command:\r\n\t\tspeak(\"what you want to play\")\r\n\t\tv=take()\r\n\t\tpywhatkit.playonyt(v)\r\n\telif \"open whatsapp\" in command:\r\n\t\twebbrowser.open(\"webwhatsapp.com\")\r\n\t\ttime.sleep(1)\r\n\t\tspeak(\"opening whatsapp\")\r\n\telif \"use whatsapp\" in command:\r\n\t\tspeak(\"whom you want to send message\")\r\n\t\tcc=take().lower()\r\n\t\tspeak(\"what is the message\")\r\n\t\tmsg=take()\r\n\t\tcon=contacts.get(cc)\r\n\t\th=datetime.datetime.now().hour\r\n\t\tm=datetime.datetime.now().minute\r\n\t\tm=m+2\r\n\t\tspeak(\"It will take nearly two minutes for setup whatsapp\")\r\n\t\tpywhatkit.sendwhatmsg(con,msg,h,m)\t\t\r\n\t\ttime.sleep(116)\r\n\t\tspeak(\"message successfully sent\")\r\n\telif \"exit\" in command:\r\n\t\tspeak(\"sure sir, byeee. have a good day\")\r\n\t\texit()\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.7832897901535034, "alphanum_fraction": 0.8067885041236877, "avg_line_length": 24.53333282470703, "blob_id": "502db25106a377e82c56fcbeda0941d4208d11d8", "content_id": "c6ae62656709884b423b00bb24d5ec748f09463b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 383, "license_type": "no_license", "max_line_length": 98, "num_lines": 15, "path": "/README.md", "repo_name": "developer-md/Desktop-Assistant", "src_encoding": "UTF-8", "text": "# Desktop-Assistant\ndesktop assistant in python AI based\nTo run python code first check you must have following modules if you don't have then install it.\nexample:- pip install modulename\n\n1) speechrecognition\n2)pyttsx3\n3)pyaudio\n4)wikipedia\n5)PIL\n6)keyboard\n7)pyautogui\n8)pywhatkit\n\nafter running the app you must go in help section for detais about commands of this assistant app.\n" } ]
2
maiana-hanshaw/cswr
https://github.com/maiana-hanshaw/cswr
3d59513e453f99c5ecae1eec9482386025f70f11
84d0e3130a896d8d39dac40b7cbe1307773dfc1a
1208ee6191ed21cc68b5bf2ded98b6836906399f
refs/heads/master
2022-12-01T19:14:58.489327
2020-08-03T22:55:45
2020-08-03T22:57:50
284,810,857
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5144243240356445, "alphanum_fraction": 0.5657697319984436, "avg_line_length": 35.33333206176758, "blob_id": "4337e9bf3d67b38503b3f44e3b084862c237a2bd", "content_id": "3904a8e95ada063c1f72658492f386df8761aa57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11335, "license_type": "no_license", "max_line_length": 171, "num_lines": 312, "path": "/soundings/4_Output_Data_to_Excel/convert_uv2xls.py", "repo_name": "maiana-hanshaw/cswr", "src_encoding": "UTF-8", "text": "### NAME: convert_uv2xls.py\n\n### MODIFICATION HISTORY: Written by Maiana Hanshaw for Python (03/28/2020);\n\n### PURPOSE: To calculate our own shear values from various datasets and put them into excel format.\n\n### RESTRICTIONS: Data has to be in the UV format as shown below:\n#Project: \t\t\t\tVSE-2018\n#Platform ID/Location: \tNWS: KBMX\n#Date/Time (UTC): \t\t20180328/2306\n#Latitude/Longitude: \t33.18000/-86.78300\n#Altitude (masl): \t\t174.0\n#---------------------------------------------\n#HEIGHT(masl) WSPD(m/s) WDIR U(m/s) V(m/s)\n# 174.0 5.1 159.4 -1.8 4.8\n\n###############################################################################\n\nimport os # operating system library\nimport pandas as pd # pandas library for dictionary and data frames\nfrom openpyxl.workbook import Workbook\nfrom openpyxl.styles import Font, Alignment, Border, NamedStyle, Side\n\n###### UPDATE THIS ######\ndirectory_in = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/CSU/UV_Files\" # location of UV text files\ndirectory_out = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO\" # location to output excel file\nfile_out = \"RELAMPAGO_CSU_IOP04_UV.xlsx\"\ndirectory_in_problemfile = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/CSU/UV_Files\" # location of sounding file problem list\nproblem_file_name = \"Problem_Files.txt\"\ninvalid_value = -9999\n#########################\n\ndef get_iop(date):\n\n iop = \"\"\n # PECAN\n if int(date) == 20150624 or int(date) == 20150625:\n iop = \"15\"\n if int(date) == 20150705 or int(date) == 20150706:\n iop = \"20\"\n if int(date) == 20150712 or int(date) == 20150713:\n iop = \"27\"\n\n # VSE-2017\n if int(date) == 20170327 or int(date) == 20170328:\n iop = \"1B\"\n if int(date) == 20170405 or int(date) == 20170406:\n iop = \"3B\"\n if int(date) == 20170430 or int(date) == 20170501:\n iop = \"4C\"\n \n # VSE-2018\n if int(date) == 20180328 or int(date) == 20180329:\n iop = \"2A\"\n if int(date) == 20180403 or int(date) == 20180404:\n iop = \"3\"\n if int(date) == 20180406 or int(date) == 20180407:\n iop = \"4\"\n\n # RELAMPAGO \n if int(date) == 20181102:\n iop = \"1\"\n if int(date) == 20181105:\n iop = \"2\"\n if int(date) == 20181106:\n iop = \"3\" \n if int(date) == 20181110:\n iop = \"4\" \n if int(date) == 20181111 or int(date) == 20181112:\n iop = \"5\" \n if int(date) == 20181117:\n iop = \"6\" \n if int(date) == 20181121:\n iop = \"7\" \n if int(date) == 20181122:\n iop = \"8\" \n if int(date) == 20181125:\n iop = \"9\" \n if int(date) == 20181126:\n iop = \"10\"\n if int(date) == 20181129:\n iop = \"11\"\n if int(date) == 20181130:\n iop = \"12\"\n if int(date) == 20181204:\n iop = \"13\"\n if int(date) == 20181205:\n iop = \"14\"\n if int(date) == 20181210:\n iop = \"15\"\n if int(date) == 20181211:\n iop = \"16\"\n if int(date) == 20181213 or int(date) == 20181214:\n iop = \"17\"\n if int(date) == 20181215:\n iop = \"18\"\n if int(date) == 20181216:\n iop = \"19\"\n\n return iop\n\n#########################\n\ndef get_files_from_directory(directory_in):\n\n selected_files = []\n for root, dirs, files in os.walk(directory_in):\n if root == directory_in:\n for file in files:\n if \"UV\" in file:\n selected_files += [file]\n return selected_files\n\n#########################\n \ndef open_file_and_split_into_lines(file_in):\n file_lines = []\n with open (os.path.join(directory_in, file_in), \"r\") as myfile:\n for file_line in myfile: \n file_lines.append(file_line)\n return file_lines\n\n#########################\n \ndef get_list_of_problem_files(directory_in, problem_file_name):\n\n file_lines = [] \n if os.path.exists(os.path.join(directory_in, problem_file_name)):\n with open (os.path.join(directory_in, problem_file_name), \"r\") as myfile:\n for file_line in myfile: \n file_lines.append(file_line)\n return file_lines\n\n#########################\n\ndef uv_at_h0(height_values, u_values, v_values): \n\n # If -9999 at the lowest height, look to the next height\n non_invalid_inds = [ind for ind in range(len(height_values)) if (u_values[ind] != invalid_value and v_values[ind] != invalid_value)] \n first_valid_ind = non_invalid_inds[0]\n \n u0 = u_values[first_valid_ind]\n v0 = v_values[first_valid_ind]\n h0 = height_values[first_valid_ind]\n \n return u0, v0, h0\n\n#########################\n\ndef uv_at_closest_height(height_values, altitude_level, u_values, v_values):\n\n if altitude_level > height_values[-1]:\n height_closest = \"\"\n height_index = \"\"\n u_height_closest = \"\"\n v_height_closest = \"\"\n \n else: \n height_closest = height_values[min(range(len(height_values)), key=lambda i: abs(height_values[i]-altitude_level))]\n height_index = height_values.index(height_closest)\n u_height_closest = u_values[height_index]\n v_height_closest = v_values[height_index]\n \n if u_height_closest == -9999 or v_height_closest == -9999:\n height_closest_range_min = height_values[min(range(len(height_values)), key=lambda i: abs(height_values[i]-(altitude_level - 50)))]\n height_closest_range_max = height_values[min(range(len(height_values)), key=lambda i: abs(height_values[i]-(altitude_level + 50)))]\n height_index_range_min = height_values.index(height_closest_range_min)\n height_index_range_max = height_values.index(height_closest_range_max)\n \n h_values_range = height_values[height_index_range_min: height_index_range_max]\n u_values_range = u_values[height_index_range_min: height_index_range_max]\n v_values_range = v_values[height_index_range_min: height_index_range_max]\n\n height_closest_range = [] \n for ind in range(len(h_values_range)):\n if u_values_range[ind] == -9999 or v_values_range[ind] == -9999:\n continue\n height_closest_range.append(h_values_range[ind])\n if height_closest_range == []:\n height_closest = \"\"\n height_index = \"\"\n u_height_closest = \"\"\n v_height_closest = \"\"\n else:\n height_closest = height_closest_range[min(range(len(height_closest_range)), key=lambda i: abs(height_closest_range[i]-altitude_level))]\n height_index = height_values.index(height_closest)\n u_height_closest = u_values[height_index]\n v_height_closest = v_values[height_index]\n \n return height_closest, height_index, u_height_closest, v_height_closest\n \n#########################\n\ndef parse_info_from_uv_file(file_in):\n\n print(file_in) \n\n # Extract site information\n file_lines = open_file_and_split_into_lines(file_in)\n \n project = file_lines[0].split(\":\", 1)[1].strip()\n name = file_lines[1].split(\":\", 1)[1].strip()\n date = file_lines[2].split(\":\", 1)[1].strip().split(\"/\")[0]\n t = file_lines[2].split(\":\", 1)[1].strip().split(\"/\")[1]\n time = t[0:2] + \":\" + t[2:4]\n lat = file_lines[3].split(\":\", 1)[1].strip().split(\"/\")[0]\n lon = file_lines[3].split(\":\", 1)[1].strip().split(\"/\")[1]\n altitude = float(file_lines[4].split(\":\", 1)[1].strip())\n \n # Get IOP #\n iop = get_iop(date) \n \n #########################\n\n # Extract data header and data into a dictionary and then a data frame\n data_d = pd.read_csv(os.path.join(directory_in, file_in), sep=\"\\s{1,}\", engine=\"python\", header=6, usecols=[\"HEIGHT(masl)\", \"U(m/s)\", \"V(m/s)\"]).to_dict(orient=\"list\")\n data_df = pd.DataFrame.from_dict(data_d, orient='columns').astype(float).sort_index() # convert dictionary to a data frame with float numbers\n\n # Get Height in MAGL not MASL \n data_df[\"HEIGHT(masl)\"] -= altitude # remove initial altitude to height values to get MAGL\n data_df.columns = [\"HEIGHT(magl)\", \"U(m/s)\", \"V(m/s)\"]\n\n h_list = data_df[\"HEIGHT(magl)\"].values.tolist()\n u_list = data_df[\"U(m/s)\"].values.tolist()\n v_list = data_df[\"V(m/s)\"].values.tolist()\n\n # Get u and v values at different heights\n u0, v0, h0 = uv_at_h0(h_list, u_list, v_list)\n\n h1, h1_ind, u1, v1 = uv_at_closest_height(h_list, 1000, u_list, v_list)\n h3, h3_ind, u3, v3 = uv_at_closest_height(h_list, 3000, u_list, v_list)\n h6, h6_ind, u6, v6 = uv_at_closest_height(h_list, 6000, u_list, v_list)\n h8, h8_ind, u8, v8 = uv_at_closest_height(h_list, 8000, u_list, v_list)\n h9, h9_ind, u9, v9 = uv_at_closest_height(h_list, 9000, u_list, v_list)\n \n #########################\n \n file_lines = get_list_of_problem_files(directory_in_problemfile, problem_file_name)\n problem = \"\"\n for ind in range(len(file_lines)):\n if name in file_lines[ind] and date in file_lines[ind] and t in file_lines[ind]:\n problem += file_lines[ind].split(\":\", 1)[1]\n \n #If first height is > 15m, note it as a problem\n if h0 > 15:\n problem += \"PROBLEM: U0, V0 from height (magl) = \" + '{:.1f}'.format(h0)\n\n ######################### \n \n # Get data in the right format for writing to excel:\n header_values = [\"IOP\", \"Date\", \"Time\", \"Site\", \"Lat\", \"Lon\", \"U0\", \"V0\", \"U1\", \"V1\", \"U3\", \"V3\", \"V6\", \"V6\", \"U8\", \"V8\", \"U9\", \"V9\", \"Sounding Issues\"]\n data_values = [iop, date, time, name, lat, lon, u0, v0, u1, v1, u3, v3, u6, v6, u8, v8, u9, v9, problem]\n\n return header_values, data_values\n\n#########################\n\ndef write_data_to_xlsx_worksheet(workbook, worksheet, data_values, row_number):\n\n c = 1\n for data in data_values:\n worksheet.cell(row=row_number, column=c).value = data\n c += 1\n \n return workbook\n \n#########################\n\ndef format_xlsx_worksheet(workbook, worksheet, header_values, number_of_rows):\n\n # Header\n header = NamedStyle(name=\"header\")\n header.font = Font(name=\"Calibri\", size=14, bold=True)\n header.border = Border(bottom=Side(border_style=\"medium\"))\n header.alignment = Alignment(horizontal=\"center\")\n\n c = 1\n for header_name in header_values:\n worksheet.cell(row=2, column=c).value = header_name\n c += 1\n \n for cell in worksheet[\"2:2\"]:\n cell.style = header\n \n # Data\n data_style = NamedStyle(name=\"data_style\")\n data_style.font = Font(name=\"Calibri\", size=14, bold=False)\n data_style.alignment = Alignment(horizontal=\"center\")\n\n for row in worksheet.iter_rows(3,number_of_rows):\n for cell in row:\n cell.style = data_style\n \n return workbook\n\n###############################################################################\n\nfiles_to_process = get_files_from_directory(directory_in)\nnumber_of_rows = len(files_to_process) + 2\nwb = Workbook()\nws = wb.active\nrow_number = 3\n\nfor file in files_to_process:\n header_values, data_values = parse_info_from_uv_file(file)\n write_data_to_xlsx_worksheet(wb, ws, data_values, row_number)\n row_number += 1\n\nformat_xlsx_worksheet(wb, ws, header_values, number_of_rows)\nwb.save(os.path.join(directory_out, file_out))\n\n###############################################################################" }, { "alpha_fraction": 0.5707204937934875, "alphanum_fraction": 0.5925827622413635, "avg_line_length": 37.82817840576172, "blob_id": "340d2c2f78f2693f5ad75bea97624b3d1de47b83", "content_id": "a07a550b82da8ed6c9bbc9c3339ad00bb851fc9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11298, "license_type": "no_license", "max_line_length": 148, "num_lines": 291, "path": "/soundings/3_Process_RunSoundings_in_SHARPpy/sharppy_process_soundings.py", "repo_name": "maiana-hanshaw/cswr", "src_encoding": "UTF-8", "text": "\"\"\"\nSHARPpy: Plotting a sounding with indices and a hodograph\n================================================\n\"\"\"\n### NAME: sharppy_process_soundings.py\n\n### MODIFICATION HISTORY: Original code provided as an example by SHARPpy creators.\n# Modified by Maiana Hanshaw (03/25/2020) to:\n# - read in multiple SPC files and batch process them\n# - output SKEW-Ts to a specific folder\n# - output indices to text files in a specific folder\n# - rename the files to our convention\n\n###############################################################################\n\n#import os # operating system library\n#import pandas as pd # pandas library for dictionary and data frames\n#import re # regular expressions library\n\n###### UPDATE THIS ######\ndirectory_in = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/CSU/SPC_Files\" # location of \"SPC\" sounding data files\ndirectory_out_skewt = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/CSU/SHARPpy/SkewTs\" # location to output SHARPpy Skew-Ts\ndirectory_out_indices = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/CSU/SHARPpy/Indices\" # location to output SHARPpy Indices\n#########################\n\nimport os # operating system library\nfrom datetime import datetime\n\nstart_time = datetime.now()\n\ndef get_files_from_directory(directory_in):\n\n selected_files = []\n for root, dirs, files in os.walk(directory_in):\n if root == directory_in:\n for file in files:\n if \"SPC\" in file:\n selected_files += [file]\n return selected_files\n\n#########################\n\ndef open_file_and_split_into_lines(file_in):\n file_lines = []\n with open (os.path.join(directory_in, file_in), \"r\") as myfile:\n for file_line in myfile: \n file_lines.append(file_line)\n return file_lines\n\n#########################\n\nimport warnings # Silence the warnings from SHARPpy\nwarnings.filterwarnings(\"ignore\")\nimport sharppy.plot.skew as skew\nfrom matplotlib.ticker import ScalarFormatter, MultipleLocator\nfrom matplotlib.collections import LineCollection\nimport matplotlib.transforms as transforms\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib import gridspec\nfrom sharppy.sharptab import winds, utils, params, thermo, interp, profile\nfrom sharppy.io.spc_decoder import SPCDecoder\n\ndef decode(filename):\n\n dec = SPCDecoder(filename)\n\n if dec is None:\n raise IOError(\"Could not figure out the format of '%s'!\" % filename)\n\n # Returns the set of profiles from the file that are from the \"Profile\" class.\n profs = dec.getProfiles()\n stn_id = dec.getStnId()\n\n for k in list(profs._profs.keys()):\n all_prof = profs._profs[k]\n dates = profs._dates\n for i in range(len(all_prof)):\n prof = all_prof[i]\n new_prof = profile.create_profile(pres=prof.pres, hght=prof.hght, tmpc=prof.tmpc, dwpc=prof.dwpc, wspd=prof.wspd, \\\n wdir=prof.wdir, strictQC=False, profile='convective', date=dates[i])\n return new_prof, dates[i], stn_id\n \n#########################\n \ndef create_directory_out(directory_out): # Check if directory exists, and if not, make it\n if not os.path.exists(directory_out):\n os.makedirs(directory_out)\n\n#########################\n \n# To plot a reduced number of wind barbs so that they are actually visible: \ndef pressure_interval(p,u,v,upper,lower,spacing):\n\n intervals = list(range(upper,lower,spacing))\n ix = []\n for center in intervals:\n index = (np.abs(p-center)).argmin()\n if index not in ix:\n ix.append(index)\n\n return p[ix],u[ix],v[ix]\n\n############################################################################### \n\nfiles_to_process = get_files_from_directory(directory_in)\ncreate_directory_out(directory_out_skewt)\ncreate_directory_out(directory_out_indices)\n\nfor file in files_to_process:\n\n FILENAME = os.path.join(directory_in, file)\n print(\"\\n\" + file) \n \n #########################\n\n # Get lat and lon \n file_lines = open_file_and_split_into_lines(FILENAME)\n latlon_line = file_lines[1].split()\n latlon = latlon_line[2].split(\",\")\n lat = latlon[0]\n lon = latlon[1]\n \n #########################\n\n prof, time, location = decode(FILENAME)\n end_time = datetime.now()\n print(\"Decode Function: {}\".format(end_time - start_time))\n \n #########################\n \n # Bounds of the pressure axis \n pb_plot=1050\n pt_plot=100\n dp_plot=10\n plevs_plot = np.arange(pb_plot,pt_plot-1,-dp_plot)\n # Open up the SPC text file with the data in columns\n file_title = file.strip(\"SPC_\").strip(\".txt\").replace(\"_\", \" \")\n title = file_title + ' (Observed)'\n\n # Set up the figure in matplotlib.\n plt.ioff()\n fig = plt.figure(figsize=(14, 14))\n gs = gridspec.GridSpec(4,4, width_ratios=[1,5,1,1])\n ax = plt.subplot(gs[0:3, 0:2], projection='skewx')\n skew.draw_title(ax, title)\n ax.grid(True)\n plt.grid(True)\n\n # Plot the background variables\n presvals = np.arange(1000, 0, -10)\n\n ax.semilogy(prof.tmpc[~prof.tmpc.mask], prof.pres[~prof.tmpc.mask], 'r', lw=2)\n ax.semilogy(prof.dwpc[~prof.dwpc.mask], prof.pres[~prof.dwpc.mask], 'g', lw=2)\n ax.semilogy(prof.vtmp[~prof.dwpc.mask], prof.pres[~prof.dwpc.mask], 'r--')\n ax.semilogy(prof.wetbulb[~prof.dwpc.mask], prof.pres[~prof.dwpc.mask], 'c-')\n\n # Plot the parcel trace, but this may fail. If it does so, inform the user.\n try:\n ax.semilogy(prof.mupcl.ttrace, prof.mupcl.ptrace, 'k--')\n except:\n print(\"Couldn't plot parcel traces...\")\n\n # Highlight the 0 C and -20 C isotherms.\n l = ax.axvline(0, color='b', ls='--')\n l = ax.axvline(-20, color='b', ls='--')\n\n # Disables the log-formatting that comes with semilogy\n ax.yaxis.set_major_formatter(ScalarFormatter())\n ax.set_yticks(np.linspace(100,1000,10))\n ax.set_ylim(1050,100)\n\n # Plot the hodograph data.\n inset_axes = skew.draw_hodo_inset(ax, prof)\n skew.plotHodo(inset_axes, prof.hght, prof.u, prof.v, color='r')\n\n #########################\n\n # Calculate fewer wind barbs and create sub-plots\n\n # Draw the wind barbs axis and everything that comes with it.\n ax.xaxis.set_major_locator(MultipleLocator(10))\n ax.set_xlim(-50,50)\n ax2 = plt.subplot(gs[0:3,2])\n ax3 = plt.subplot(gs[3,0:3])\n skew.plot_wind_axes(ax2)\n #skew.plot_wind_barbs(ax2, prof.pres, prof.u, prof.v) # all the wind barbs (usually too many to see pattern)\n\n # Reduce the number of data points to use for the wind barbs\n p_less, u_less, v_less = pressure_interval(prof.pres, prof.u, prof.v, 0, 1050, 25)\n skew.plot_wind_barbs(ax2, p_less, u_less, v_less) \n\n srwind = params.bunkers_storm_motion(prof)\n gs.update(left=0.05, bottom=0.05, top=0.95, right=1, wspace=0.025)\n\n #########################\n\n # Calculate indices to be shown.\n p1km = interp.pres(prof, interp.to_msl(prof, 1000.))\n p3km = interp.pres(prof, interp.to_msl(prof, 3000.))\n p6km = interp.pres(prof, interp.to_msl(prof, 6000.))\n p8km = interp.pres(prof, interp.to_msl(prof, 8000.))\n p9km = interp.pres(prof, interp.to_msl(prof, 9000.))\n sfc = prof.pres[prof.sfc]\n sfc_1km_shear = winds.wind_shear(prof, pbot=sfc, ptop=p1km)\n sfc_3km_shear = winds.wind_shear(prof, pbot=sfc, ptop=p3km)\n sfc_6km_shear = winds.wind_shear(prof, pbot=sfc, ptop=p6km)\n sfc_8km_shear = winds.wind_shear(prof, pbot=sfc, ptop=p8km)\n sfc_9km_shear = winds.wind_shear(prof, pbot=sfc, ptop=p9km)\n srh3km = winds.helicity(prof, 0, 3000., stu = srwind[0], stv = srwind[1])\n srh1km = winds.helicity(prof, 0, 1000., stu = srwind[0], stv = srwind[1])\n scp = params.scp(prof.mupcl.bplus, prof.right_esrh[0], prof.ebwspd)\n stp_cin = params.stp_cin(prof.mlpcl.bplus, prof.right_esrh[0], prof.ebwspd, prof.mlpcl.lclhght, prof.mlpcl.bminus)\n stp_fixed = params.stp_fixed(prof.sfcpcl.bplus, prof.sfcpcl.lclhght, srh1km[0], utils.comp2vec(prof.sfc_6km_shear[0], prof.sfc_6km_shear[1])[1])\n ship = params.ship(prof)\n\n #########################\n\n # A routine to perform the correct formatting when writing the indices out to the figure.\n def fmt(value, fmt='int'):\n if fmt == 'int':\n try:\n val = int(value)\n except:\n val = str(\"M\")\n else:\n try:\n val = round(value,1)\n except:\n val = \"M\"\n return val\n\n # Create a dictionary that is a collection of all of the indices we want.\n # The dictionary includes the index name, the actual value, and the units.\n indices = {'SBCAPE': [fmt(prof.sfcpcl.bplus), 'J/kg'],\\\n 'MLCAPE': [fmt(prof.mlpcl.bplus), 'J/kg'],\\\n 'MUCAPE': [fmt(prof.mupcl.bplus), 'J/kg'],\\\n 'MLLCL': [fmt(prof.mlpcl.lclhght), 'm AGL'],\\\n 'SBLCL': [fmt(prof.sfcpcl.lclhght), 'm AGL'],\\\n '0-1 km SRH': [fmt(srh1km[0]), 'm2/s2'],\\\n '0-3 km SRH': [fmt(srh3km[0]), 'm2/s2'],\\\n '0-1 km Shear': [fmt(utils.comp2vec(sfc_1km_shear[0], sfc_1km_shear[1])[1]), 'kts'],\\\n '0-3 km Shear': [fmt(utils.comp2vec(sfc_3km_shear[0], sfc_3km_shear[1])[1]), 'kts'],\\\n '0-6 km Shear': [fmt(utils.comp2vec(sfc_6km_shear[0], sfc_6km_shear[1])[1]), 'kts'],\\\n '0-8 km Shear': [fmt(utils.comp2vec(sfc_8km_shear[0], sfc_8km_shear[1])[1]), 'kts'],\\\n '0-9 km Shear': [fmt(utils.comp2vec(sfc_9km_shear[0], sfc_9km_shear[1])[1]), 'kts']}\n\n #########################\n\n # List the indices within the indices dictionary on the side of the plot.\n trans = transforms.blended_transform_factory(ax.transAxes,ax.transData)\n\n # Write out all of the indices to the figure.\n string = ''\n keys = np.sort(list(indices.keys()))\n x = 0\n counter = 0\n for key in keys:\n string = string + key + ': ' + str(indices[key][0]) + ' ' + indices[key][1] + '\\n'\n if counter < 3:\n counter += 1\n continue\n else:\n counter = 0\n ax3.text(x, 1, string, verticalalignment='top', transform=ax3.transAxes, fontsize=11)\n ax3.text(x, 1, string, verticalalignment='top', transform=ax3.transAxes, fontsize=11)\n string = ''\n x += 0.3\n ax3.text(x, 1, string, verticalalignment='top', transform=ax3.transAxes, fontsize=11)\n ax3.set_axis_off()\n\n #########################\n\n # Save the figure.\n gs.tight_layout(fig)\n file_out_skewt = file.replace(\"SPC\", \"SkewT\").strip(\"txt\") + \"jpg\" # create output file name\n plt.savefig(os.path.join(directory_out_skewt, file_out_skewt), bbox_inches='tight', dpi=180)\n plt.close(fig)\n\n # Add lat and lon to indices dictionary.\n indices.update({\"Lat\": lat, \"Lon\": lon})\n\n # Write the indices to a text file.\n file_out_ind = file.replace(\"SPC\", \"Indices\") # create output file name\n with open(os.path.join(directory_out_indices, file_out_ind), \"w+\") as f: \n f.write(str(indices))\n \n end_time = datetime.now() \n print(\"Duration: {}\".format(end_time - start_time))\n\n###############################################################################" }, { "alpha_fraction": 0.5090968608856201, "alphanum_fraction": 0.5369865894317627, "avg_line_length": 40.724998474121094, "blob_id": "f8e52f4f6d29ee9318476804e70c7477b7ba899f", "content_id": "a59fa7935cce66f36fb7686a83f702ef838a37ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18358, "license_type": "no_license", "max_line_length": 199, "num_lines": 440, "path": "/soundings/2_Convert_IndividualSoundings_to_SPCforSHARPpy/convert_uah2spc.py", "repo_name": "maiana-hanshaw/cswr", "src_encoding": "UTF-8", "text": "### NAME: convert_uah2spc.py\n\n### MODIFICATION HISTORY: Written by Maiana Hanshaw for Python (03/22/2020);\n\n### PURPOSE: To read in atmospheric sounding data from UAH, which is in its own format,\n# and output into \"SPC\" file format, which SHARPpy can read and simulate.\n\n### RESTRICTIONS:\n## INCOMING UAH data needs to be in the format as shown below:\n\n#VORTEX-SE 2017 UAH Radiosonde Data\n#20170328, 0051 UTC, Brownsferry, AL, 201 m\n#latitude (deg), longitude (deg),time (sec),height (m MSL),pressure(mb),temp (deg C),RH (%),dewpoint (deg C),Calculated wind speed (kts),Calculated wind direction (deg)\n#34.73705, -87.12219, 0:52:2, 223.0, 984.3, 17.13, 86.1, 14.83, 8.2, 127 \n#34.73712, -87.1223, 0:52:5, 242.0, 982.16, 17.43, 84.85, 14.9, 8.0, 116 \n#34.73717, -87.12242, 0:52:8, 261.0, 979.9, 17.61, 83.4, 14.82, 14.2, 165 \n#%END%\n\n## OUTGOING data needs to be in the \"SPC\" file format as shown below:\n\n#%TITLE%\n# SCOUT1 181110/1659 -31.72817,-63.84490\n# \n# LEVEL HGHT TEMP DWPT WDIR WSPD\n#-------------------------------------------------------------------\n#%RAW%\n# 963.20, 311.40, 35.00, 19.34, 196.00, 13.61\n# 962.80, 315.00, 34.26, 18.68, 196.10, 13.63\n#%END%\n\n## More restrictions: - cannot have an initial pressure of -9999\n# - cannot have duplicate values of height or pressure\n# - height cannot be decreasing, and pressure cannot be increasing\n# - cannot have a space in site/vehicle name in header\n\n### SPC files need bad data to be in the format \"-9999\", although the UAH data does not have QC flags\n### Although no flags exist in the UAH data, I have attempted to add some based on info from the log notes\n\n###############################################################################\n\nimport os # operating system library\nimport pandas as pd # pandas library for dictionary and data frames\nimport re # regular expressions library\nimport math # math library\n\n###### UPDATE THIS ######\ndirectory_in = \"C:/Users/Maiana/Downloads/Soundings/VSE-2017/Data/UAH\" # location of UAH sounding data files\ndirectory_out = \"C:/Users/Maiana/Downloads/Soundings/VSE-2017/Data/UAH/SPC_Files\" # location to output \"SPC\" sounding data files\ninvalid_value = \"-9999\"\n#########################\n\ndef get_files_from_directory(directory_in):\n\n selected_files = []\n for root, dirs, files in os.walk(directory_in):\n if root == directory_in:\n for file in files:\n if \"upperair\" in file:\n selected_files += [file]\n return selected_files\n\n#########################\n\ndef open_file_and_split_into_lines(file_in):\n file_lines = []\n with open (os.path.join(directory_in, file_in), \"r\") as myfile:\n for file_line in myfile: \n file_lines.append(file_line)\n return file_lines\n\n#########################\n \ndef height_increasing(height, index, h, altitude): \n higher = True\n if invalid_value not in height: \n if index == 0:\n previous_height = altitude\n if -2 <= (float(height) - previous_height) <= 0:\n higher = True\n if (float(height) - previous_height) < -2:\n higher = False \n if index != 0:\n previous_height = h[index - 1] \n if invalid_value in previous_height:\n higher = height_increasing(height, index -1, h, altitude)\n else:\n higher = height > previous_height \n return higher\n\n########################\n \ndef pressure_decreasing(pressure, index, p): \n lower = True\n if invalid_value not in pressure: \n if index != 0:\n previous_pressure = p[index - 1] \n if invalid_value in previous_pressure:\n lower = pressure_decreasing(pressure, index -1, p)\n else:\n lower = pressure < previous_pressure \n return lower\n\n########################\n \ndef calculate_dewpoint(t_value, rh_value):\n dewpoint = 243.04*(math.log(rh_value/100)+((17.625*t_value)/(243.04+t_value)))/(17.625-math.log(rh_value/100)-((17.625*t_value)/(243.04+t_value)))\n return dewpoint\n\n#########################\n\ndef parse_info_from_uah_file(file_in):\n\n print(file_in) \n \n # Extract site info from file name for both the \"SPC\" format site header and the new file name\n site_info = re.split(r'[_.\\s]\\s*', file_in)\n \n # Get site id/name\n inst_id = site_info[1]\n location = site_info[4]\n name = inst_id + \":\" + location\n \n # Get date and time\n dt = site_info[3]\n file_name_date = dt[0:8]\n date = dt[2:8]\n time = dt[8:12]\n \n # Get lat and lon\n file_lines = open_file_and_split_into_lines(file_in)\n latlon = file_lines[3].split()\n lt = float(latlon[0].strip(\",\"))\n lat = '{:.5f}'.format(lt)\n ln = float(latlon[1].strip(\",\"))\n lon = '{:.5f}'.format(ln)\n \n # Get initial height (as data sometimes has height starting at 0 m AGL and not at m aMSL)\n alt_line = file_lines[1].replace(\" \",\"\").split(\",\")\n alt = alt_line[4].rstrip()\n altitude = float(alt[:-1])\n\n ########################\n \n # Different header formats exist, so extract data depending on which you have \n if \"height (m MSL)\" in file_lines[2] and \"dewpoint (deg C)\" in file_lines[2] and \"Calculated\" in file_lines[2]:\n col_headers = [\"height (m MSL)\", \"pressure(mb)\", \"temp (deg C)\", \"dewpoint (deg C)\", \"Calculated wind speed (kts)\", \"Calculated wind direction (deg)\"]\n elif \"height (m MSL)\" in file_lines[2] and \"dewpoint (deg C)\" in file_lines[2] and \"Calculated\" not in file_lines[2]:\n col_headers = [\"height (m MSL)\", \"pressure(mb)\", \"temp (deg C)\", \"dewpoint (deg C)\", \"wind speed (kts)\", \"wind direction (deg)\"]\n elif \"height (m AGL)\" in file_lines[2]:\n col_headers = [\"height (m AGL)\", \"pressure(mb)\", \"temp (deg C)\", \"dewpoint (deg C)\", \"wind speed (kts)\", \"wind direction (deg)\"]\n elif \"height (m MSL)\" in file_lines[2] and \"dewpoint (deg C)\" not in file_lines[2]:\n col_headers = [\"height (m MSL)\", \"pressure(mb)\", \"temp (deg C)\", \"RH (%)\", \"wind speed (kts)\", \"wind direction (deg)\"]\n\n # Extract data header and data into a dictionary and then a data frame\n data_d = pd.read_csv(os.path.join(directory_in, file_in), sep=\",\", engine=\"python\", header=2, skipfooter=1, usecols=col_headers).to_dict(orient=\"list\")\n data_df = pd.DataFrame.from_dict(data_d, orient='columns').astype(float).sort_index() # convert dictionary to a data frame with float numbers\n\n # Standardize column headers \n if \"Calculated\" in file_lines[2]:\n data_df.columns = [\"Height (masl)\", \"Pressure (mb)\", \"Temp (C)\", \"DWPT (C)\", \"WSPD (kts)\", \"WDIR (deg)\"]\n elif \"height (m MSL)\" in file_lines[2] and \"dewpoint (deg C)\" in file_lines[2] and \"Calculated\" not in file_lines[2]:\n data_df.columns = [\"Height (masl)\", \"Pressure (mb)\", \"Temp (C)\", \"DWPT (C)\", \"WSPD (kts)\", \"WDIR (deg)\"] \n elif \"height (m AGL)\" in file_lines[2]:\n data_df[\"height (m AGL)\"] += altitude # add initial altitude to height values\n data_df.columns = [\"Height (masl)\", \"Pressure (mb)\", \"Temp (C)\", \"DWPT (C)\", \"WSPD (kts)\", \"WDIR (deg)\"]\n # This is a complicated one that does not have dewpoint, so it needs to be calculated from RH\n elif \"height (m MSL)\" in file_lines[2] and \"dewpoint (deg C)\" not in file_lines[2]:\n data_df.columns = [\"Height (masl)\", \"Pressure (mb)\", \"Temp (C)\", \"RH (%)\", \"WSPD (kts)\", \"WDIR (deg)\"]\n \n # Get data into lists\n h_list = data_df[\"Height (masl)\"].values.tolist()\n p_list = data_df[\"Pressure (mb)\"].values.tolist() \n t_list = data_df[\"Temp (C)\"].values.tolist()\n ws_list = data_df[\"WSPD (kts)\"].values.tolist() \n wd_list = data_df[\"WDIR (deg)\"].values.tolist()\n if \"dewpoint (deg C)\" in file_lines[2]:\n dp_list = data_df[\"DWPT (C)\"].values.tolist()\n elif \"dewpoint (deg C)\" not in file_lines[2]:\n rh_list = data_df[\"RH (%)\"].values.tolist()\n rh_temp = [\"%.2f\"%item for item in rh_list]\n dp_list = []\n for ind in range(len(data_df)):\n dp_value = calculate_dewpoint(t_list[ind], rh_list[ind])\n dp_list.append(dp_value)\n\n ######################## \n \n # Format numbers to varying decimal places\n p_temp = [\"%.2f\"%item for item in p_list] \n h_temp = [\"%.2f\"%item for item in h_list]\n t_temp = [\"%.2f\"%item for item in t_list]\n dp_temp = [\"%.2f\"%item for item in dp_list]\n wd_temp = [\"%.2f\"%item for item in wd_list]\n ws_temp = [\"%.2f\"%item for item in ws_list] \n \n # Create new variables and put in good data\n p = []\n h = []\n t = []\n dp = []\n wd = []\n ws = []\n flag = \"\"\n for ind in range(len(data_df)):\n \n # Correct some bad data as noted in the log notes\n ## For VSE-2017\n if file_in == \"upperair.UAH_Sonde.201703271505.Huntsville_AL.txt\":\n if ind == 0:\n p_temp[0] = \"990.80\" # launch pressure taken from 1700 sounding at this site, as it was previously incorrectly SL pressure\n else:\n p_temp[ind] = invalid_value\n flag = \"BAD PRESSURES\"\n \n # If wind speed is 0, set wind direction to -9999\n if float(ws_temp[ind]) == 0.00:\n wd_temp[ind] = invalid_value\n \n # Add \"-9999\" if data is missing (-9999.0)\n if invalid_value in p_temp[ind]:\n p.append(\"{0:>8s}\".format(invalid_value))\n else:\n p.append(\"{0:>8s}\".format(str(p_temp[ind])))\n \n if invalid_value in h_temp[ind]:\n h.append(\"{0:>10s}\".format(invalid_value))\n else:\n h.append(\"{0:>10s}\".format(str(h_temp[ind]))) \n \n if invalid_value in t_temp[ind]:\n t.append(\"{0:>10s}\".format(invalid_value))\n else:\n t.append(\"{0:>10s}\".format(str(t_temp[ind])))\n \n if \"dewpoint (deg C)\" in file_lines[2]:\n if invalid_value in dp_temp[ind]:\n dp.append(\"{0:>10s}\".format(invalid_value))\n else:\n dp.append(\"{0:>10s}\".format(str(dp_temp[ind]))) \n elif \"dewpoint (deg C)\" not in file_lines[2]:\n if invalid_value in rh_temp[ind]:\n dp.append(\"{0:>10s}\".format(invalid_value))\n else:\n dp.append(\"{0:>10s}\".format(str(dp_temp[ind])))\n \n if invalid_value in wd_temp[ind]:\n wd.append(\"{0:>10s}\".format(invalid_value))\n else:\n wd.append(\"{0:>10s}\".format(str(wd_temp[ind])))\n \n if invalid_value in ws_temp[ind]:\n ws.append(\"{0:>10s}\".format(invalid_value))\n else:\n ws.append(\"{0:>10s}\".format(str(ws_temp[ind])))\n \n ########################\n\n # Check if pressure values are decreasing, and if not, make values -9999\n for index in range(len(data_df)):\n lower = pressure_decreasing(p[index], index, p)\n \n if not lower:\n p[index] = \"{0:>10s}\".format(invalid_value)\n h[index] = \"{0:>10s}\".format(invalid_value)\n t[index] = \"{0:>10s}\".format(invalid_value)\n dp[index] = \"{0:>10s}\".format(invalid_value)\n wd[index] = \"{0:>10s}\".format(invalid_value)\n ws[index] = \"{0:>10s}\".format(invalid_value)\n\n # Check if height values are increasing, and if not, make values -9999\n for index in range(len(data_df)):\n higher = height_increasing(h[index], index, h, altitude)\n \n if not higher:\n p[index] = \"{0:>10s}\".format(invalid_value)\n h[index] = \"{0:>10s}\".format(invalid_value)\n t[index] = \"{0:>10s}\".format(invalid_value)\n dp[index] = \"{0:>10s}\".format(invalid_value)\n wd[index] = \"{0:>10s}\".format(invalid_value)\n ws[index] = \"{0:>10s}\".format(invalid_value)\n \n # Sometimes the last wind value is super funky, so check it and make ws and wd -9999 if necessary\n for ind in range(len(data_df)):\n if ind == (len(data_df)-1):\n wind = ws[ind]\n previous_wind = ws[ind-1]\n if wind > previous_wind * 3:\n ws[ind] = \"{0:>10s}\".format(invalid_value)\n wd[ind] = \"{0:>10s}\".format(invalid_value)\n \n ########################\n\n # Put the data together \n spc_data_list = [] # create empty list to fill with correctly spaced data \n\n for ind in range(len(data_df)):\n if \"-9999\" in p[ind]:\n continue\n if p[ind] == p[ind-1]:\n continue\n pressure = p[ind]\n height = h[ind]\n temp = t[ind]\n dwpt = dp[ind]\n wdir = wd[ind]\n wspd = ws[ind] \n \n spc_string = \"{},{},{},{},{},{}\".format(pressure, height, temp, dwpt, wdir, wspd) # create the new string for each row\n spc_data_list.append(spc_string) # add each row into the new list \n \n spc_data = \"\\n\".join(spc_data_list) # join all the elements together again into a string\n\n #########################\n \n # Get info that could be problematic \n if spc_data_list != []:\n h_line = spc_data_list[0].split()\n h_init = float(h_line[1].strip(\",\"))\n else:\n h_init = altitude\n flag += \"FILE COMPLETELY EMPTY\"\n \n # Add a problem flag if the pressure difference is > 20mb\n missing_interpolated = \"\" \n pressure = []\n for ind in range(len(spc_data_list)):\n line = spc_data_list[ind].split()\n pressure.append(float(line[0].strip(\",\")))\n \n for ind in range(len(pressure)):\n if ind != 0:\n pressure_current = pressure[ind]\n pressure_previous = pressure[ind-1]\n pressure_diff = pressure_current - pressure_previous\n if pressure_diff <= -20:\n diff_string = '{:.1f}'.format(pressure_diff)\n missing_interpolated += \"PROBLEM (Missing/Interpolated) = \" + \"Diff: \" + diff_string\n\n ########################\n \n # Add relevant information to a dictionary\n sounding_file_dict = {}\n \n sounding_file_dict[\"file_in\"] = file_in\n sounding_file_dict[\"inst_id\"] = inst_id\n sounding_file_dict[\"location\"] = location\n sounding_file_dict[\"site_name\"] = name\n sounding_file_dict[\"date\"] = date\n sounding_file_dict[\"time\"] = time\n sounding_file_dict[\"file_name_date\"] = file_name_date\n sounding_file_dict[\"lat\"] = lat\n sounding_file_dict[\"lon\"] = lon\n sounding_file_dict[\"alt\"] = altitude\n sounding_file_dict[\"h_init\"] = h_init\n sounding_file_dict[\"flag\"] = flag\n sounding_file_dict[\"missing\"] = missing_interpolated\n sounding_file_dict[\"data\"] = spc_data\n \n return sounding_file_dict\n\n#########################\n\ndef output_to_spc_format(sounding_file_dict):\n\n # Construct site header\n site_header = \" {} {}/{} {},{}\".format(sounding_file_dict[\"site_name\"], sounding_file_dict[\"date\"], sounding_file_dict[\"time\"], sounding_file_dict[\"lat\"], sounding_file_dict[\"lon\"])\n\n # Construct data header in \"SPC\" format\n pressure = \"LEVEL\"\n height = \"HGHT\"\n temp = \"TEMP\"\n dwpt = \"DWPT\"\n wdir = \"WDIR\"\n wspd = \"WSPD\"\n\n data_header = \" {} {} {} {} {} {}\".format(pressure, height, temp, dwpt, wdir, wspd)\n\n ########################\n \n # Add file_name and data to a dictionary which will then be printed out to text files\n spc_dict = {}\n \n file_out = \"SPC_{}_{}_{}_{}.txt\".format(sounding_file_dict[\"inst_id\"], sounding_file_dict[\"location\"], sounding_file_dict[\"file_name_date\"], sounding_file_dict[\"time\"]) # create output file name\n\n whole_file = (\"%TITLE%\" + \"\\n\" + site_header + \"\\n\\n\" + data_header + \"\\n\"\n + \"-------------------------------------------------------------------\"\n + \"\\n\" + \"%RAW%\" + \"\\n\" + sounding_file_dict[\"data\"] + \"\\n\" + \"%END%\")\n\n spc_dict.update({file_out: whole_file}) # append file name (key) and data (value) to dictionary\n \n return spc_dict\n\n#########################\n \ndef create_directory_out(directory_out): # Check if directory exists, and if not, make it\n if not os.path.exists(directory_out):\n os.makedirs(directory_out)\n\n#########################\n \ndef write_to_spc_files(dictionary): # Write dictionary items to files\n for name, data in dictionary.items():\n with open(os.path.join(directory_out, name), \"w+\") as f:\n f.write(data)\n \n#############################################################################\n \nfiles_to_process = get_files_from_directory(directory_in)\ncreate_directory_out(directory_out)\n\nfor file in files_to_process:\n sounding_file_dict = parse_info_from_uah_file(file)\n spc_dict = output_to_spc_format(sounding_file_dict)\n\n # Incrementally append problem file names to a text file\n problem = \"\"\n alt_diff = sounding_file_dict[\"h_init\"] - sounding_file_dict[\"alt\"]\n if alt_diff >= 5:\n alt_diff_string = '{:.1f}'.format(alt_diff)\n problem += \"Problem (Alt. Diff >= 5) = \" + alt_diff_string\n \n if sounding_file_dict[\"flag\"] != \"\":\n problem += \"Problem (Flag) = \" + sounding_file_dict[\"flag\"]\n \n if sounding_file_dict[\"missing\"] != \"\":\n problem += sounding_file_dict[\"missing\"]\n\n if problem != \"\":\n with open(os.path.join(directory_out, \"Problem_Files_UAH.txt\"), \"a+\") as f: \n f.seek(0) # move cursor to the start of file \n data = f.read(100) # if file is not empty then append '\\n'\n if len(data) > 0:\n f.write(\"\\n\")\n # Append text to the end of the file\n f.write(file + \": \" + problem)\n \n # Write converted files to text files\n write_to_spc_files(spc_dict)\n\n#############################################################################" }, { "alpha_fraction": 0.5053322315216064, "alphanum_fraction": 0.5209187865257263, "avg_line_length": 39.66666793823242, "blob_id": "d7e5a1d2dfd429c99ac619b342cccbf3c8ed62c3", "content_id": "11acab78075f9e4e5590d95f1782451ee8042ae2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1219, "license_type": "no_license", "max_line_length": 129, "num_lines": 30, "path": "/soundings/Misc/copy_hgtfiles.py", "repo_name": "maiana-hanshaw/cswr", "src_encoding": "UTF-8", "text": "### NAME: copy_hgtfiles.py\n\n### MODIFICATION HISTORY: Written by Maiana Hanshaw for Python (03/14/2020)\n\n### PURPOSE: To extract all the CSWR \"HGT\" files for a given project into one folder.\n\n###############################################################################\n\nimport os # operating system library\nimport shutil # sh utilities library\n\n###### UPDATE THIS ######\ndirectory_in = \"C:/Users/Maiana/Desktop/Downloads/Soundings/RELAMPAGO/soundings-20200314\" # location of sounding data\ndirectory_out = \"C:/Users/Maiana/Desktop/Downloads/Soundings/RELAMPAGO/HGT_Files\" # location to output \"HGT\" sounding data files\n#########################\n\ndef copy_hgtfiles_to_directory(directory_in):\n if not os.path.exists(directory_out):\n os.makedirs(directory_out)\n for root, dirs, files in os.walk(directory_in):\n for file in files:\n # if \"IOP04\" in root:\n if \"Hgt\" in file:\n shutil.copy2(root + \"/\" + file, directory_out)\n \n###############################################################################\n \nfiles_to_copy = copy_hgtfiles_to_directory(directory_in)\n\n###############################################################################" }, { "alpha_fraction": 0.5161459445953369, "alphanum_fraction": 0.5425189137458801, "avg_line_length": 38.374629974365234, "blob_id": "68e250e882a2be847c4eda4d5af455e3b1bd81b1", "content_id": "66e537615ab0dca4cf9d08afc637cfa95c85f5ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13347, "license_type": "no_license", "max_line_length": 238, "num_lines": 339, "path": "/soundings/2_Optional_Extract_UVData_for_ShearAnalyses/extract_uah2uv.py", "repo_name": "maiana-hanshaw/cswr", "src_encoding": "UTF-8", "text": "### NAME: extract_uah2uv.py\n\n### MODIFICATION HISTORY: Written by Maiana Hanshaw for Python (03/22/2020);\n\n### PURPOSE: To extract U and V wind components from UAH, which is in its own format.\n\n### RESTRICTIONS:\n## INCOMING UAH data needs to be in the format as shown below:\n\n#VORTEX-SE 2017 UAH Radiosonde Data\n#20170328, 0051 UTC, Brownsferry, AL, 201 m\n#latitude (deg), longitude (deg),time (sec),height (m MSL),pressure(mb),temp (deg C),RH (%),dewpoint (deg C),Calculated wind speed (kts),Calculated wind direction (deg)\n#34.73705, -87.12219, 0:52:2, 223.0, 984.3, 17.13, 86.1, 14.83, 8.2, 127 \n#34.73712, -87.1223, 0:52:5, 242.0, 982.16, 17.43, 84.85, 14.9, 8.0, 116 \n#34.73717, -87.12242, 0:52:8, 261.0, 979.9, 17.61, 83.4, 14.82, 14.2, 165 \n#%END%\n\n## OUTGOING data will be a text file in the format:\n\n#Project: PECAN\n#Platform ID/Location: \tMP1: OU\n#Date/Time (UTC): \t\tCLAMPS/20150713\n#Latitude/Longitude: \t43.50500/-91.85000\n#Altitude (masl): \t\t418.0\n#---------------------------------------------\n#HEIGHT(masl) WSPD(m/s) WDIR U(m/s) V(m/s)\n# 421.8 10.7 164 -3.0 10.3\n\n### Although no flags exist in the UAH data, I have attempted to add some based on info from the log notes\n# and added these as -9999.\n\n###############################################################################\n\nimport os # operating system library\nimport pandas as pd # pandas library for dictionary and data frames\nimport re # regular expressions library\nimport math # math library\n\n###### UPDATE THIS ######\nproject = \"VSE-2018\"\ndirectory_in = \"C:/Users/Maiana/Downloads/Soundings/VSE-2018/Data/UAH\" # location of UAH sounding data files\ndirectory_out = \"C:/Users/Maiana/Downloads/Soundings/VSE-2018/Data/UAH/UV_Files\" # location to output \"UV\" text files\ninvalid_value = \"-9999\"\n#########################\n\ndef get_files_from_directory(directory_in):\n\n selected_files = []\n for root, dirs, files in os.walk(directory_in):\n if root == directory_in:\n for file in files:\n if \"upperair\" in file:\n selected_files += [file]\n return selected_files\n\n#########################\n\ndef open_file_and_split_into_lines(file_in):\n file_lines = []\n with open (os.path.join(directory_in, file_in), \"r\") as myfile:\n for file_line in myfile: \n file_lines.append(file_line)\n return file_lines\n\n#########################\n \ndef height_increasing(height, index, h, altitude): \n higher = True\n if invalid_value not in height: \n if index == 0:\n previous_height = altitude\n if -2 <= (float(height) - previous_height) <= 0:\n higher = True\n if (float(height) - previous_height) < -2:\n higher = False \n if index != 0:\n previous_height = h[index - 1] \n if invalid_value in previous_height:\n higher = height_increasing(height, index -1, h, altitude)\n else:\n higher = height > previous_height \n return higher\n\n########################\n\ndef parse_info_from_uah_file(file_in):\n\n print(file_in) \n\n # Extract site info for site header from file name, and construct into \"UV\" format\n site_info = re.split(r'[_.\\s]\\s*', file_in)\n \n # Get site id/name\n inst_id = site_info[1]\n location = site_info[4]\n name = inst_id + \": \" + location\n \n # Get date and time\n dt = site_info[3]\n date = dt[0:8]\n time = dt[8:12]\n \n # Get lat and lon\n file_lines = open_file_and_split_into_lines(file_in)\n latlon = file_lines[3].split()\n lt = float(latlon[0].strip(\",\"))\n lat = '{:.5f}'.format(lt)\n ln = float(latlon[1].strip(\",\"))\n lon = '{:.5f}'.format(ln)\n \n # Get initial height (as data sometimes has height starting at 0 m AGL and not at m aMSL)\n alt_line = file_lines[1].replace(\" \",\"\").split(\",\")\n alt = alt_line[4].rstrip()\n altitude = float(alt[:-1])\n\n ########################\n\n # Different header formats exist, so extract data depending on which you have \n if \"height (m MSL)\" in file_lines[2] and \"Calculated\" in file_lines[2]:\n col_headers = [\"height (m MSL)\", \"Calculated wind speed (kts)\", \"Calculated wind direction (deg)\"]\n elif \"height (m MSL)\" in file_lines[2] and \"Calculated\" not in file_lines[2]:\n col_headers = [\"height (m MSL)\", \"wind speed (kts)\", \"wind direction (deg)\"]\n elif \"height (m AGL)\" in file_lines[2]:\n col_headers = [\"height (m AGL)\", \"wind speed (kts)\", \"wind direction (deg)\"]\n\n # Extract data header and data into a dictionary and then a data frame\n data_d = pd.read_csv(os.path.join(directory_in, file_in), sep=\",\", engine=\"python\", header=2, skipfooter=1, usecols=col_headers).to_dict(orient=\"list\")\n data_df = pd.DataFrame.from_dict(data_d, orient='columns').astype(float).sort_index() # convert dictionary to a data frame with float numbers\n\n # Standardize column headers \n if \"height (m MSL)\" in file_lines[2]:\n data_df.columns = [\"Height (masl)\", \"WSPD (kts)\", \"WDIR (deg)\"] \n elif \"height (m AGL)\" in file_lines[2]:\n data_df[\"height (m AGL)\"] += altitude # add initial altitude to height values\n data_df.columns = [\"Height (masl)\", \"WSPD (kts)\", \"WDIR (deg)\"]\n\n # Convert variables to list\n h_temp = [\"%.1f\"%item for item in data_df[\"Height (masl)\"].values.tolist()]\n ws_temp = data_df[\"WSPD (kts)\"].values.tolist()\n wd_temp = data_df[\"WDIR (deg)\"].values.tolist()\n u_temp = [float(invalid_value)] * len(ws_temp)\n v_temp = [float(invalid_value)] * len(ws_temp)\n \n # Create new variables, put in good data, and replace bad data values with invalid value: \"-9999\"\n h = []\n ws = []\n wd = []\n u = []\n v = [] \n for ind in range(len(data_df)):\n # If wind speed is 0, set wind direction to -9999\n if float(ws_temp[ind]) == 0.00:\n wd_temp[ind] = float(invalid_value)\n \n # Add \"-9999\" if data is missing (-9999.0)\n if h_temp[ind] == invalid_value:\n h.append(\"{:>8}\".format(str(invalid_value)))\n else:\n h.append(\"{:>8}\".format(str(h_temp[ind])))\n \n if ws_temp[ind] == invalid_value:\n ws.append(\"{0:>11}\".format(invalid_value))\n else:\n ws_temp[ind] = ws_temp[ind] / 1.94384 # knots to m/s\n ws_value = '{:.1f}'.format(ws_temp[ind])\n ws.append(\"{0:>11}\".format(str(ws_value)))\n \n if wd_temp[ind] == invalid_value:\n wd.append(\"{:>8}\".format(invalid_value))\n else:\n wd_value = '{:.1f}'.format(wd_temp[ind])\n wd.append(\"{:>8}\".format(str(wd_value)))\n \n # Sometimes the last wind value is super funky, so check it and make ws and wd -9999 if necessary\n for ind in range(len(data_df)):\n if ind == (len(data_df)-1):\n wind = ws[ind]\n previous_wind = ws[ind-1]\n if wind > previous_wind * 3:\n ws[ind] = \"{0:>11s}\".format(invalid_value)\n wd[ind] = \"{0:>8s}\".format(invalid_value)\n \n # Calculate u and v\n for ind in range(len(ws_temp)): \n # If wind speed is 0, set u and v to 0 also\n if float(ws[ind]) == 0.0:\n u.append(\"{:>6}\".format(str(\"0.00\")))\n v.append(\"{:>7}\".format(str(\"0.00\"))) \n # Otherwise continue to add flags\n elif float(ws[ind]) != 0.0 and (invalid_value in ws[ind] or invalid_value in wd[ind]):\n u.append(\"{:>7}\".format(invalid_value))\n v.append(\"{:>7}\".format(invalid_value))\n else:\n u_value = -ws_temp[ind] * math.sin(math.radians(wd_temp[ind]))\n u_temp[ind] = '{:.2f}'.format(u_value)\n u.append(\"{:>7}\".format(str(u_temp[ind])))\n\n v_value = -ws_temp[ind] * math.cos(math.radians(wd_temp[ind]))\n v_temp[ind] = '{:.2f}'.format(v_value)\n v.append(\"{:>7}\".format(str(v_temp[ind])))\n \n #########################\n\n # Check if height values are increasing, and if not, make values -9999\n for index in range(len(data_df)):\n higher = height_increasing(h[index], index, h, altitude)\n \n if not higher:\n h[index] = \"{0:>8s}\".format(invalid_value)\n ws[index] = \"{0:>11s}\".format(invalid_value)\n wd[index] = \"{0:>8s}\".format(invalid_value)\n u[index] = \"{0:>6s}\".format(invalid_value)\n v[index] = \"{0:>7s}\".format(invalid_value)\n \n ######################## \n \n # Put the data together\n uv_data_list = [] # create empty list to fill with correctly spaced data\n \n for ind in range(len(data_df)):\n if \"-9999\" in h[ind]:\n continue\n if h[ind] == h[ind-1]:\n continue\n height = h[ind]\n wspd = ws[ind]\n wdir = wd[ind]\n u_wind = u[ind]\n v_wind = v[ind]\n \n uv_string = \"{} {} {} {} {}\".format(height, wspd, wdir, u_wind, v_wind) # create the new string for each row\n uv_data_list.append(uv_string) # add each row into the new list\n\n uv_data = \"\\n\".join(uv_data_list) # join all the elements together again into a string\n\n #########################\n\n # Get info that could be problematic\n flag = \"\"\n if uv_data_list != []:\n h_line = uv_data_list[0].split()\n h_init = float(h_line[0])\n else:\n h_init = altitude\n flag = \"FILE COMPLETELY EMPTY\"\n \n # Add relevant information to a dictionary\n sounding_file_dict = {}\n \n sounding_file_dict[\"file_in\"] = file_in\n sounding_file_dict[\"inst_id\"] = inst_id\n sounding_file_dict[\"location\"] = location\n sounding_file_dict[\"site_name\"] = name\n sounding_file_dict[\"date\"] = date\n sounding_file_dict[\"time\"] = time\n sounding_file_dict[\"lat\"] = lat\n sounding_file_dict[\"lon\"] = lon\n sounding_file_dict[\"alt\"] = altitude\n sounding_file_dict[\"h_init\"] = h_init\n sounding_file_dict[\"flag\"] = flag\n sounding_file_dict[\"data\"] = uv_data\n \n return sounding_file_dict\n\n#########################\n\ndef output_to_uv_format(sounding_file_dict):\n\n # Construct site header\n site_header = (\"Project: \" + \"\\t\\t\\t\\t{}\" + \"\\n\" + \"Platform ID/Location: \" + \"\\t{}\" + \"\\n\" + \"Date/Time (UTC): \" + \"\\t\\t{}/{}\" + \"\\n\" + \"Latitude/Longitude: \" + \"\\t{}/{}\" + \"\\n\" \n + \"Altitude (masl): \" + \"\\t\\t{}\").format(project, sounding_file_dict[\"site_name\"], sounding_file_dict[\"date\"], sounding_file_dict[\"time\"], sounding_file_dict[\"lat\"], sounding_file_dict[\"lon\"], sounding_file_dict[\"alt\"])\n\n # Construct data header\n height = \"HEIGHT(masl)\"\n wspd = \"WSPD(m/s)\"\n wdir = \"WDIR\"\n u_header = \"U(m/s)\"\n v_header = \"V(m/s)\"\n \n data_header = \"{} {} {} {} {}\".format(height, wspd, wdir, u_header, v_header)\n \n ########################\n\n # Add file_name and data to a dictionary which will then be printed out to text files\n uv_dict = {}\n \n file_out = \"UV_{}_{}_{}_{}.txt\".format(sounding_file_dict[\"inst_id\"], sounding_file_dict[\"location\"], sounding_file_dict[\"date\"], sounding_file_dict[\"time\"]) # create output file name\n \n whole_file = site_header + \"\\n\" + \"---------------------------------------------\" + \"\\n\" + data_header + \"\\n\" + sounding_file_dict[\"data\"]\n\n uv_dict.update({file_out: whole_file}) # append file name (key) and data (value) to dictionary\n \n return uv_dict\n\n#########################\n \ndef create_directory_out(directory_out): # Check if directory exists, and if not, make it\n if not os.path.exists(directory_out):\n os.makedirs(directory_out)\n\n#########################\n \ndef write_to_uv_files(dictionary): # Write dictionary items to files\n for name, data in dictionary.items():\n with open(os.path.join(directory_out, name), \"w+\") as f:\n f.write(data)\n \n#############################################################################\n \nfiles_to_process = get_files_from_directory(directory_in)\ncreate_directory_out(directory_out)\n\nfor file in files_to_process:\n sounding_file_dict = parse_info_from_uah_file(file)\n uv_dict = output_to_uv_format(sounding_file_dict)\n\n # Incrementally append problem file names to a text file\n problem = \"\"\n alt_diff = sounding_file_dict[\"h_init\"] - sounding_file_dict[\"alt\"]\n if alt_diff >= 5:\n alt_diff_string = '{:.1f}'.format(alt_diff)\n problem += \"Problem (Alt. Diff >= 5) = \" + alt_diff_string\n \n if sounding_file_dict[\"flag\"] != \"\":\n problem += \"Problem = \" + sounding_file_dict[\"flag\"]\n\n if problem != \"\":\n with open(os.path.join(directory_out, \"Problem_Files_UAH.txt\"), \"a+\") as f: \n f.seek(0) # move cursor to the start of file \n data = f.read(100) # if file is not empty then append '\\n'\n if len(data) > 0:\n f.write(\"\\n\")\n # Append text to the end of the file\n f.write(file + \": \" + problem)\n \n # Write converted files to text files \n write_to_uv_files(uv_dict)\n\n#############################################################################" }, { "alpha_fraction": 0.4371577501296997, "alphanum_fraction": 0.4869774281978607, "avg_line_length": 37.597938537597656, "blob_id": "c6feecd707c577e93749905dc752a7103360ba01", "content_id": "205c58b1c33060639fd36f8b9c1210187c7f38c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7487, "license_type": "no_license", "max_line_length": 131, "num_lines": 194, "path": "/soundings/1_Split_SingleCLS_to_IndividualEOLs/split_cls2eol_relampago.py", "repo_name": "maiana-hanshaw/cswr", "src_encoding": "UTF-8", "text": "### NAME: split_cls2eol_relampago.py\n\n### MODIFICATION HISTORY: Written by Maiana Hanshaw (05/09/2020);\n\n### PURPOSE: To split (parse) sounding data in EOL format that comes in combined\n# \".cls\" files and need to be split into individual sounding text files,\n# ultimately to output into \"SPC\" file format, which SHARPpy can read and simulate.\n\n### RESTRICTIONS:\n## INCOMING data needs to be in the NCAR EOL \".cls\" file format as shown below:\n\n#Data Type: GAUS SOUNDING DATA/Ascending\n#Project ID: PECAN\n#Release Site Type/Site ID: IOP 15\n#Release Location (lon,lat,alt): 098 57.05'W, 40 30.93'N, -98.951, 40.516, 668.9\n#UTC Release Time (y,m,d,h,m,s): 2015, 06, 25, 00:01:01\n#...\n#/\n#Nominal Release Time (y,m,d,h,m,s):2015, 06, 25, 00:01:01\n# Time Press Temp Dewpt RH Ucmp Vcmp spd dir Wcmp Lon Lat Ele Azi Alt Qp Qt Qrh Qu Qv QdZ\n# sec mb C C % m/s m/s m/s deg m/s deg deg deg deg m code code code code code code\n#------ ------ ----- ----- ----- ------ ------ ----- ----- ----- -------- ------- ----- ----- ------- ---- ---- ---- ---- ---- ----\n# -1.0 936.3 29.7 22.3 64.0 -1.9 -4.7 5.1 22.1 999.0 -98.951 40.516 999.0 999.0 658.0 1.0 1.0 1.0 1.0 1.0 9.0\n# 0.0 936.2 29.7 21.8 61.6 -0.9 -4.1 4.2 11.8 3.0 -98.951 40.516 999.0 999.0 658.7 1.0 1.0 1.0 1.0 1.0 99.0\n#....\n#3907.0 89.3 -62.8 -89.1 2.5 -0.8 -6.9 6.9 6.6 5.7 -98.155 40.428 999.0 999.0 17348.2 1.0 1.0 1.0 1.0 1.0 99.0\n#3908.0 89.2 -62.8 -89.1 2.5 -0.8 -6.8 6.8 7.1 5.7 -98.155 40.428 999.0 999.0 17354.1 1.0 1.0 1.0 1.0 1.0 99.0\n#Data Type: GAUS SOUNDING DATA/Ascending\n#Project ID: PECAN\n#Release Site Type/Site ID: IOP 15\n#....\n\n## OUTGOING data just needs to be data for individual soundings.\n\n###############################################################################\n\nimport os # operating system library\nimport re # regular expressions library\n\n###### UPDATE THIS ######\ndirectory_in = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/CLS_Files\" # location of \"CLS\" sounding data files\ndirectory_out = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/EOL_Files\" # location to output \"EOL\" sounding data files\nextension = \"cls\"\n#########################\n\ndef get_files_from_directory_by_extension(directory_in, extension):\n\n selected_files = []\n for root, dirs, files in os.walk(directory_in):\n if root == directory_in:\n for file in files:\n if \".\" + extension in file:\n selected_files += [file] \n return selected_files\n \n########################\n\ndef open_file_and_split_into_lines(file_in):\n file_lines = []\n with open (os.path.join(directory_in, file_in), \"r\") as myfile:\n for file_line in myfile: \n file_lines.append(file_line)\n return file_lines\n\n#########################\n\ndef process_single_file(file_in):\n \n print(file_in)\n file_lines = open_file_and_split_into_lines(file_in) \n \n new_soundings = []\n line_num = 0\n pattern = re.compile(\"Data Type\")\n for line in file_lines:\n line_num += 1\n if pattern.search(line) != None:\n new_soundings.append(line_num)\n\n sounding_dict = {} # create dictionary to append all file names and data to\n\n # Split merged data set into individual data chunks\n l = len(new_soundings)\n for i in range(l):\n \n ind_data = []\n if i < l-1:\n start = new_soundings[i] - 1\n end = new_soundings[i+1]\n ind_data = file_lines[start:end-1]\n ind_data_string = \"\".join(ind_data)\n # Continue until you reach the end of the original file\n if i == l-1:\n start = new_soundings[i] - 1\n end = len(file_lines)\n ind_data = file_lines[start:end]\n ind_data_string = \"\".join(ind_data)\n\n # Get date/time information for file name \n dt = ind_data[4].split()\n y = \"\"\n m = \"\"\n d = \"\"\n for i, v in enumerate(dt):\n if i == 4:\n y = v.strip(\",\")\n if i == 5:\n m = v.strip(\",\")\n if i == 6:\n d = v.strip(\",\")\n if i == 7:\n time = v.replace(\":\",\"\")[0:4]\n date = y + m + d\n\n # Get Institution ID, Site ID, and Location information for file name \n inst_id = \"\"\n site_id = \"\"\n location = \"\"\n if \"GTS\" in ind_data[0]:\n inst_id = \"GTS\"\n site_id = \"\"\n split = ind_data[2].split(\":\",1)\n split2 = split[1].split(\",\",1)\n location = split2[0].replace(\" \",\"\")\n if \"ARM\" in ind_data[0]:\n inst_id = \"ARM\"\n split = ind_data[2].split(\":\",1)\n split2 = split[1].split(\",\",1)\n split3 = split2[0].split(\":\")\n site_id = split3[0].strip()\n location = split3[1].replace(\" \",\"\")\n if \"CSWR\" in ind_data[0]:\n inst_id = \"CSWR\"\n split = ind_data[2].split(\":\",1)\n site_id = split[1].strip().replace(\" \",\"\")\n location = \"\"\n if \"CSU\" in ind_data[0]:\n inst_id = \"CSU\"\n site_id = \"\"\n location = \"\"\n if \"UIUC\" in ind_data[0]:\n inst_id = \"UIUC\"\n split = ind_data[2].split(\":\",1)\n split2 = split[1].strip().replace(\" \",\"\")\n site_id = split2[4]\n location = \"\"\n if \"INPE\" in ind_data[0]:\n inst_id = \"INPE\"\n site_id = \"\"\n split = ind_data[2].split(\":\",1)\n split2 = split[1].split(\",\",1)\n location = split2[0].replace(\" \",\"\")\n\n # Create output file name\n if site_id == \"\" and location == \"\":\n file_out = \"EOL_{}_{}_{}.txt\".format(inst_id, date, time)\n elif site_id == \"\" and location != \"\":\n file_out = \"EOL_{}_{}_{}_{}.txt\".format(inst_id, location, date, time)\n elif site_id != \"\" and location == \"\":\n file_out = \"EOL_{}_{}_{}_{}.txt\".format(inst_id, site_id, date, time)\n elif site_id != \"\" and location != \"\":\n file_out = \"EOL_{}_{}_{}_{}_{}.txt\".format(inst_id, site_id, location, date, time)\n\n sounding_dict.update({file_out: ind_data_string}) \n\n return sounding_dict\n \n#########################\n \ndef create_directory_out(directory_out): # Check if directory exists, and if not, make it\n if not os.path.exists(directory_out):\n os.makedirs(directory_out)\n\n#########################\n \ndef write_to_eol_files(dictionary): # Write dictionary items to files\n for name, data in dictionary.items():\n with open(os.path.join(directory_out, name), \"w+\") as f:\n f.write(data)\n \n#############################################################################\n \nfiles_to_process = get_files_from_directory_by_extension(directory_in, extension)\n\nfor file in files_to_process:\n sounding_dict = process_single_file(file)\n \n for key in sounding_dict.keys():\n print(key)\n \n create_directory_out(directory_out)\n write_to_eol_files(sounding_dict)\n\n#############################################################################" }, { "alpha_fraction": 0.4745994508266449, "alphanum_fraction": 0.5322391390800476, "avg_line_length": 32.67434310913086, "blob_id": "261d38e5ae61a0eaa9c636942e4c43187cc18bcf", "content_id": "b3ec6cecaaa58475d72787f3b08fb0f090fdcd43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10236, "license_type": "no_license", "max_line_length": 206, "num_lines": 304, "path": "/soundings/4_Output_Data_to_Excel/convert_sharppy2xls_indices.py", "repo_name": "maiana-hanshaw/cswr", "src_encoding": "UTF-8", "text": "### NAME: convert_sharppy2xls_indices.py\n\n### MODIFICATION HISTORY: Written by Maiana Hanshaw for Python (03/27/2020);\n\n### PURPOSE: To get the SHARPpy output indices and put them into excel format.\n\n###############################################################################\n\nimport os # operating system library\nimport re # regular expressions library\nfrom openpyxl.workbook import Workbook\nfrom openpyxl.styles import Font, Alignment, Border, NamedStyle, Side\n\n###### UPDATE THIS ######\ndirectory_in = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/CSU/SHARPpy/Indices\" # location of SHARPpy Indices text files\ndirectory_out = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO\" # location to output excel file\nfile_out = \"RELAMPAGO_CSU_IOP04_Indices.xlsx\"\ndirectory_in_problemfile = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/CSU/SPC_Files\" # location of sounding file problem list\nproblem_file_name = \"Problem_Files.txt\"\n#########################\n\ndef get_iop(date):\n\n iop = \"\"\n # PECAN\n if int(date) == 20150624 or int(date) == 20150625:\n iop = \"15\"\n if int(date) == 20150705 or int(date) == 20150706:\n iop = \"20\"\n if int(date) == 20150712 or int(date) == 20150713:\n iop = \"27\"\n\n # VSE-2017\n if int(date) == 20170327 or int(date) == 20170328:\n iop = \"1B\"\n if int(date) == 20170405 or int(date) == 20170406:\n iop = \"3B\"\n if int(date) == 20170430 or int(date) == 20170501:\n iop = \"4C\"\n \n # VSE-2018\n if int(date) == 20180328 or int(date) == 20180329:\n iop = \"2A\"\n if int(date) == 20180403 or int(date) == 20180404:\n iop = \"3\"\n if int(date) == 20180406 or int(date) == 20180407:\n iop = \"4\"\n \n # RELAMPAGO \n if int(date) == 20181102:\n iop = \"1\"\n if int(date) == 20181105:\n iop = \"2\"\n if int(date) == 20181106:\n iop = \"3\" \n if int(date) == 20181110:\n iop = \"4\" \n if int(date) == 20181111 or int(date) == 20181112:\n iop = \"5\" \n if int(date) == 20181117:\n iop = \"6\" \n if int(date) == 20181121:\n iop = \"7\" \n if int(date) == 20181122:\n iop = \"8\" \n if int(date) == 20181125:\n iop = \"9\" \n if int(date) == 20181126:\n iop = \"10\"\n if int(date) == 20181129:\n iop = \"11\"\n if int(date) == 20181130:\n iop = \"12\"\n if int(date) == 20181204:\n iop = \"13\"\n if int(date) == 20181205:\n iop = \"14\"\n if int(date) == 20181210:\n iop = \"15\"\n if int(date) == 20181211:\n iop = \"16\"\n if int(date) == 20181213 or int(date) == 20181214:\n iop = \"17\"\n if int(date) == 20181215:\n iop = \"18\"\n if int(date) == 20181216:\n iop = \"19\"\n\n return iop\n\n#########################\n\ndef get_files_from_directory(directory_in):\n\n selected_files = []\n for root, dirs, files in os.walk(directory_in):\n if root == directory_in:\n for file in files:\n if \"Indices\" in file:\n selected_files += [file]\n return selected_files\n\n#########################\n \ndef get_list_of_problem_files(directory_in, problem_file_name):\n\n file_lines = [] \n if os.path.exists(os.path.join(directory_in, problem_file_name)):\n with open (os.path.join(directory_in, problem_file_name), \"r\") as myfile:\n for file_line in myfile: \n file_lines.append(file_line)\n return file_lines\n \n#########################\n\ndef parse_info_from_indices_file(file_in):\n\n print(file_in) \n\n # Extract site info from file name\n site_info = re.split(r'[_.\\s]\\s*', file_in)\n \n # Get site id/name\n if \"RELAMPAGO\" in directory_in:\n name = site_info[2]\n inst_id = name\n \n else: \n inst_id = site_info[1]\n if len(site_info) == 5:\n name = site_info[1]\n if len(site_info) == 6:\n name = site_info[1] + \": \" + site_info[2]\n if len(site_info) == 7:\n name = site_info[1] + \": \" + site_info[2] + \" \" +site_info[3]\n \n # Get date and time\n if \"RELAMPAGO\" in directory_in:\n date = site_info[1]\n t = site_info[3]\n time = t[0:2] + \":\" + t[2:4]\n\n else: \n if len(site_info) == 5:\n date = site_info[2]\n t = site_info[3]\n time = t[0:2] + \":\" + t[2:4]\n if len(site_info) == 6:\n date = site_info[3]\n t = site_info[4]\n time = t[0:2] + \":\" + t[2:4]\n if len(site_info) == 7:\n date = site_info[4]\n t = site_info[5]\n time = t[0:2] + \":\" + t[2:4]\n \n # Get IOP #\n iop = get_iop(date)\n\n #########################\n\n # Convert indices text file to dictionary: \n with open(os.path.join(directory_in, file_in),'r') as f:\n indices_dict = eval(f.read())\n \n # Get data into new variables and convert to different units if necessary (eg. knots to m/s for wind speed):\n lat = \"\"\n lon = \"\"\n srh_1km = \"\"\n srh_3km = \"\"\n srh_1km_abs = \"\"\n srh_3km_abs = \"\"\n cape_sb = \"\"\n cape_ml = \"\"\n cape_mu = \"\"\n lcl_sb = \"\"\n lcl_ml = \"\"\n shear_1km = \"\"\n shear_3km = \"\"\n shear_6km = \"\"\n shear_8km = \"\"\n shear_9km = \"\"\n # Check if missing values (\"M\" exist also:\n if \"M\" not in indices_dict[\"Lat\"]:\n lat = indices_dict[\"Lat\"]\n if \"M\" not in indices_dict[\"Lon\"]:\n lon = indices_dict[\"Lon\"]\n if \"M\" not in str(indices_dict[\"0-1 km SRH\"][0]):\n srh_1km = indices_dict[\"0-1 km SRH\"][0]\n srh_1km_abs = abs(srh_1km)\n if \"M\" not in str(indices_dict[\"0-3 km SRH\"][0]):\n srh_3km = indices_dict[\"0-3 km SRH\"][0] \n srh_3km_abs = abs(srh_3km)\n if \"M\" not in str(indices_dict[\"SBCAPE\"][0]):\n cape_sb = indices_dict[\"SBCAPE\"][0] \n if \"M\" not in str(indices_dict[\"MLCAPE\"][0]):\n cape_ml = indices_dict[\"MLCAPE\"][0] \n if \"M\" not in str(indices_dict[\"MUCAPE\"][0]):\n cape_mu = indices_dict[\"MUCAPE\"][0] \n if \"M\" not in str(indices_dict[\"SBLCL\"][0]):\n lcl_sb = indices_dict[\"SBLCL\"][0] \n if \"M\" not in str(indices_dict[\"MLLCL\"][0]):\n lcl_ml = indices_dict[\"MLLCL\"][0]\n if \"M\" not in str(indices_dict[\"0-1 km Shear\"][0]):\n shear_1km = \"{:.1f}\".format(indices_dict[\"0-1 km Shear\"][0] / 1.94384) # convert to m/s \n if \"M\" not in str(indices_dict[\"0-3 km Shear\"][0]):\n shear_3km = \"{:.1f}\".format(indices_dict[\"0-3 km Shear\"][0] / 1.94384) # convert to m/s \n if \"M\" not in str(indices_dict[\"0-6 km Shear\"][0]):\n shear_6km = \"{:.1f}\".format(indices_dict[\"0-6 km Shear\"][0] / 1.94384) # convert to m/s \n if \"M\" not in str(indices_dict[\"0-8 km Shear\"][0]):\n shear_8km = \"{:.1f}\".format(indices_dict[\"0-8 km Shear\"][0] / 1.94384) # convert to m/s \n if \"M\" not in str(indices_dict[\"0-9 km Shear\"][0]):\n shear_9km = \"{:.1f}\".format(indices_dict[\"0-9 km Shear\"][0] / 1.94384) # convert to m/s \n \n #########################\n \n file_lines = get_list_of_problem_files(directory_in_problemfile, problem_file_name)\n problem = \"\"\n for ind in range(len(file_lines)):\n if inst_id in file_lines[ind] and date in file_lines[ind] and t in file_lines[ind]:\n problem = file_lines[ind].split(\": \", 1)[1]\n \n ######################### \n \n # Get data in the right format for writing to excel: \n header_values = [\"0-1 km\", \"0-3 km\", \"ABS 0-1\", \"ABS 0-3\", \"SB\", \"ML\", \"MU\", \"SB\", \"ML\", \"0-1 km\", \"0-3 km\", \"0-6 km\", \"0-8 km\", \"0-9 km\", \"IOP\", \"Date\", \"Time\", \"Site\", \"Lat\", \"Lon\", \"Sounding Issues\"]\n data_values = [srh_1km, srh_3km, srh_1km_abs, srh_3km_abs, cape_sb, cape_ml, cape_mu, lcl_sb, lcl_ml, shear_1km, shear_3km, shear_6km, shear_8km, shear_9km, iop, date, time, name, lat, lon, problem]\n\n return header_values, data_values\n\n#########################\n\ndef write_data_to_xlsx_worksheet(workbook, worksheet, data_values, row_number):\n\n c = 1\n for data in data_values:\n worksheet.cell(row=row_number, column=c).value = data\n c += 1\n \n return workbook\n \n#########################\n\ndef format_xlsx_worksheet(workbook, worksheet, header_values, number_of_rows):\n\n # Header 1\n worksheet.merge_cells('A1:D1')\n worksheet['A1'].value = \"SHARPpy SRH\"\n worksheet.merge_cells('E1:G1')\n worksheet['E1'].value = \"SHARPpy CAPE\"\n worksheet.merge_cells('H1:I1')\n worksheet['H1'].value = \"SHARPpy LCL\"\n worksheet.merge_cells('J1:N1')\n worksheet['J1'].value = \"SHARPpy SHEAR\"\n \n header1 = NamedStyle(name=\"header1\")\n header1.font = Font(name=\"Calibri\", size=14, bold=True)\n header1.alignment = Alignment(horizontal=\"center\")\n \n for cell in worksheet[\"1:1\"]:\n cell.style = header1 \n\n # Header 2\n header2 = NamedStyle(name=\"header2\")\n header2.font = Font(name=\"Calibri\", size=14, bold=True)\n header2.border = Border(bottom=Side(border_style=\"thick\"))\n header2.alignment = Alignment(horizontal=\"center\")\n\n c = 1\n for header_name in header_values:\n worksheet.cell(row=2, column=c).value = header_name\n c += 1\n \n for cell in worksheet[\"2:2\"]:\n cell.style = header2\n \n # Data\n data_style = NamedStyle(name=\"data_style\")\n data_style.font = Font(name=\"Calibri\", size=14, bold=False)\n data_style.alignment = Alignment(horizontal=\"center\")\n\n for row in worksheet.iter_rows(3,number_of_rows):\n for cell in row:\n cell.style = data_style\n \n return workbook\n\n###############################################################################\n\nfiles_to_process = get_files_from_directory(directory_in)\nnumber_of_rows = len(files_to_process) + 2\nwb = Workbook()\nws = wb.active\nrow_number = 3\n\nfor file in files_to_process:\n header_values, data_values = parse_info_from_indices_file(file)\n write_data_to_xlsx_worksheet(wb, ws, data_values, row_number)\n row_number += 1\n\nformat_xlsx_worksheet(wb, ws, header_values, number_of_rows)\nwb.save(os.path.join(directory_out, file_out))\n\n###############################################################################" }, { "alpha_fraction": 0.49325326085090637, "alphanum_fraction": 0.522061824798584, "avg_line_length": 37.401554107666016, "blob_id": "63e7d345a93590f6e4b750e557437a56078f7a2e", "content_id": "8897c061f8cb487941d8d8af694a45ce3577eb71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14822, "license_type": "no_license", "max_line_length": 202, "num_lines": 386, "path": "/soundings/2_Convert_IndividualSoundings_to_SPCforSHARPpy/convert_hgt2spc.py", "repo_name": "maiana-hanshaw/cswr", "src_encoding": "UTF-8", "text": "### NAME: convert_hgt2spc.py\n\n### MODIFICATION HISTORY: Written by Maiana Hanshaw for Python (03/22/2020)\n\n### PURPOSE: To read in CSWR quality-controlled atmospheric sounding data in \"HGT\" file\n# format and output into \"SPC\" file format, which SHARPpy can read and simulate.\n\n### RESTRICTIONS:\n## INCOMING data needs to be in the \"Hgt\" file format as shown below:\n\n# STN DATE GMT HTS LAT LON\n#SCOUT1 20181110 1659 311 -31.72817 -63.84490\n#NLVL =2137\n# P HT TC TD DIR SPD QP QH QT QD QW LON LAT\n# 963.2 311.4 35.00 19.34 196.00 7.00 1 1 1 1 1 -63.84490 -31.72817\n# 962.8 315.0 34.26 18.68 196.10 7.01 1 1 1 1 1 -63.84489 -31.72820\n\n## OUTGOING data needs to be in the \"SPC\" file format as shown below:\n\n#%TITLE%\n# SCOUT1 181110/1659 -31.72817,-63.84490\n# \n# LEVEL HGHT TEMP DWPT WDIR WSPD\n#-------------------------------------------------------------------\n#%RAW%\n# 963.20, 311.40, 35.00, 19.34, 196.00, 13.61\n# 962.80, 315.00, 34.26, 18.68, 196.10, 13.63\n#%END%\n\n## More restrictions: - cannot have an initial pressure of -9999\n# - cannot have duplicate values of height or pressure\n# - height cannot be decreasing, and pressure cannot be increasing\n# - cannot have a space in site/vehicle name in header\n\n### QUALITY CONTROL FLAGS: SPC files need bad data to be in the format \"-9999.00\"\n# QP = Pressure\n# QH = Height\n# QT = Temp\n# QD = Dew Point\n# QW = Wind\n\n# 3 = questionable/maybe - including these values for now\n# 4 = objectively BAD\n# 5 = visually BAD\n# 9 = MISSING\n\n###############################################################################\n\nimport os # operating system library\nimport pandas as pd # pandas library for dictionary and data frames\nimport re # regular expressions library\n\n###### UPDATE THIS ######\ndirectory_in = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/HGT_Files\" # location of \"Hgt\" sounding data files\ndirectory_out = \"C:/Users/Maiana/Downloads/Soundings/RELAMPAGO/SPC_Files\" # location to output \"SPC\" sounding data files\ninvalid_value = \"-9999\"\n#########################\n\ndef get_files_from_directory(directory_in):\n\n selected_files = []\n for root, dirs, files in os.walk(directory_in):\n if root == directory_in:\n for file in files:\n if \"Hgt\" in file:\n selected_files += [file]\n return selected_files\n\n########################\n \ndef open_file_and_split_into_lines(file_in):\n file_lines = []\n with open (os.path.join(directory_in, file_in), \"r\") as myfile:\n for file_line in myfile: \n file_lines.append(file_line)\n return file_lines\n\n#########################\n \ndef height_increasing(height, index, h, altitude): \n higher = True\n if invalid_value not in height: \n if index == 0:\n previous_height = altitude\n if -2 <= (float(height) - previous_height) <= 0:\n higher = True\n if (float(height) - previous_height) < -2:\n higher = False \n if index != 0:\n previous_height = h[index - 1] \n if invalid_value in previous_height:\n higher = height_increasing(height, index -1, h, altitude)\n else:\n higher = height > previous_height \n return higher\n\n########################\n \ndef pressure_decreasing(pressure, index, p): \n lower = True\n if invalid_value not in pressure: \n if index != 0:\n previous_pressure = p[index - 1] \n if invalid_value in previous_pressure:\n lower = pressure_decreasing(pressure, index -1, p)\n else:\n lower = pressure < previous_pressure \n return lower\n\n########################\n\ndef parse_info_from_hgt_file(file_in):\n \n print(file_in)\n \n # Extract vehicle info for vehicle header from file name\n vehicle_info = re.split(r'[_.\\s]\\s*', file_in)\n \n # Get vehicle id/name\n vehicle = vehicle_info[2]\n \n # Get date and time\n d = vehicle_info[1]\n date = d[2:9]\n time = vehicle_info[3] \n\n # Get lat and lon\n file_lines = open_file_and_split_into_lines(file_in)\n latlon = file_lines[1].split()\n lat = \"\"\n lon = \"\"\n for i, v in enumerate(latlon):\n if i == 4:\n lt = float(v.strip(\",\"))\n lat = '{:.5f}'.format(lt)\n if i == 5:\n ln = float(v.strip(\",\"))\n lon = '{:.5f}'.format(ln)\n \n # Get initial altitude\n alt_line = file_lines[1].split()\n altitude = float(alt_line[3])\n\n ########################\n\n # Extract data header and data into a dictionary and then a data frame \n data_d = pd.read_csv(os.path.join(directory_in, file_in), sep=\"\\s{1,}\", engine=\"python\", header=3, usecols=[\"P\", \"HT\", \"TC\", \"TD\", \"DIR\", \"SPD\", \"QP\", \"QH\", \"QT\", \"QD\", \"QW\"]).to_dict(orient=\"list\")\n data_df = pd.DataFrame.from_dict(data_d, orient='columns').astype(float).sort_index() # convert dictionary to a data frame with float numbers\n\n # Format numbers to 2 decimal places\n p_temp = [\"%.2f\"%item for item in data_df[\"P\"].values.tolist()]\n h_temp = [\"%.2f\"%item for item in data_df[\"HT\"].values.tolist()]\n t_temp = [\"%.2f\"%item for item in data_df[\"TC\"].values.tolist()]\n dp_temp = [\"%.2f\"%item for item in data_df[\"TD\"].values.tolist()]\n wd_temp = [\"%.2f\"%item for item in data_df[\"DIR\"].values.tolist()]\n ws_temp = data_df[\"SPD\"].values.tolist() # will be formatted later after converting to knots\n \n # Create new variables, put in good data, and replace bad data values with \"-9999\"\n p = []\n h = []\n t = []\n dp = []\n wd = []\n ws = []\n for ind in range(len(data_df)):\n # If wind speed is 0, set wind direction to -9999\n if float(ws_temp[ind]) == 0.00:\n wd_temp[ind] = invalid_value \n \n # Add \"-9999\" if QC flags are missing (9), visually bad (5), or objectively bad (4)\n if data_df[\"QP\"][ind] == 9 or data_df[\"QP\"][ind] == 5 or data_df[\"QP\"][ind] == 4:\n p.append(\"{0:>8s}\".format(invalid_value))\n else:\n p.append(\"{0:>8s}\".format(str(p_temp[ind])))\n \n if data_df[\"QH\"][ind] == 9 or data_df[\"QH\"][ind] == 5 or data_df[\"QH\"][ind] == 4:\n h.append(\"{0:>10s}\".format(invalid_value))\n else:\n h.append(\"{0:>10s}\".format(str(h_temp[ind]))) \n \n if data_df[\"QT\"][ind] == 9 or data_df[\"QT\"][ind] == 5 or data_df[\"QT\"][ind] == 4:\n t.append(\"{0:>10s}\".format(invalid_value))\n else:\n t.append(\"{0:>10s}\".format(str(t_temp[ind])))\n \n if data_df[\"QD\"][ind] == 9 or data_df[\"QD\"][ind] == 5 or data_df[\"QD\"][ind] == 4:\n dp.append(\"{0:>10s}\".format(invalid_value))\n else:\n dp.append(\"{0:>10s}\".format(str(dp_temp[ind]))) \n \n if data_df[\"QW\"][ind] == 9 or data_df[\"QW\"][ind] == 5 or data_df[\"QW\"][ind] == 4:\n wd.append(\"{0:>10s}\".format(invalid_value))\n ws.append(\"{0:>10s}\".format(invalid_value))\n else:\n wd.append(\"{0:>10s}\".format(str(wd_temp[ind])))\n ws_value = '{:.2f}'.format(float(ws_temp[ind]) * 1.94384) # convert wind speed to knots\n ws.append(\"{0:>10s}\".format(str(ws_value))) \n \n ########################\n \n # Check if pressure values are decreasing, and if not, make values -9999\n for index in range(len(data_df)):\n lower = pressure_decreasing(p[index], index, p)\n \n if not lower:\n p[index] = \"{0:>10s}\".format(invalid_value)\n h[index] = \"{0:>10s}\".format(invalid_value)\n t[index] = \"{0:>10s}\".format(invalid_value)\n dp[index] = \"{0:>10s}\".format(invalid_value)\n wd[index] = \"{0:>10s}\".format(invalid_value)\n ws[index] = \"{0:>10s}\".format(invalid_value)\n \n # Check if height values are increasing, and if not, make values -9999\n for index in range(len(data_df)):\n higher = height_increasing(h[index], index, h, altitude)\n \n if not higher:\n p[index] = \"{0:>10s}\".format(invalid_value)\n h[index] = \"{0:>10s}\".format(invalid_value)\n t[index] = \"{0:>10s}\".format(invalid_value)\n dp[index] = \"{0:>10s}\".format(invalid_value)\n wd[index] = \"{0:>10s}\".format(invalid_value)\n ws[index] = \"{0:>10s}\".format(invalid_value)\n \n ########################\n\n # Put the data together \n spc_data_list = [] # create empty list to fill with correctly spaced data \n\n for ind in range(len(data_df)):\n if \"-9999\" in p[ind]:\n continue\n if p[ind] == p[ind-1]:\n continue\n pressure = p[ind]\n height = h[ind]\n temp = t[ind]\n dwpt = dp[ind]\n wdir = wd[ind]\n wspd = ws[ind] \n \n spc_string = \"{},{},{},{},{},{}\".format(pressure, height, temp, dwpt, wdir, wspd) # create the new string for each row\n spc_data_list.append(spc_string) # add each row into the new list \n \n spc_data = \"\\n\".join(spc_data_list) # join all the elements together again into a string\n\n ########################\n \n # Get info that could be problematic\n flag = \"\"\n if spc_data_list != []:\n h_line = spc_data_list[0].split()\n h_init = float(h_line[1].strip(\",\"))\n else:\n h_init = altitude\n flag = \"FILE COMPLETELY EMPTY\"\n \n h_flag_0 = data_df[\"QH\"][0]\n h_flag_100 = data_df[\"QH\"][100]\n \n # Add a problem flag if the pressure difference is > 20mb\n missing_interpolated = \"\" \n pressure = []\n for ind in range(len(spc_data_list)):\n line = spc_data_list[ind].split()\n pressure.append(float(line[0].strip(\",\")))\n \n for ind in range(len(pressure)):\n if ind != 0:\n pressure_current = pressure[ind]\n pressure_previous = pressure[ind-1]\n pressure_diff = pressure_current - pressure_previous\n if pressure_diff <= -20:\n diff_string = '{:.1f}'.format(pressure_diff)\n missing_interpolated += \"PROBLEM (Missing/Interpolated) = \" + \"Diff: \" + diff_string\n\n ########################\n \n # Add relevant information to a dictionary\n sounding_file_dict = {}\n \n sounding_file_dict[\"file_in\"] = file_in\n sounding_file_dict[\"vehicle_name\"] = vehicle\n sounding_file_dict[\"date\"] = date\n sounding_file_dict[\"time\"] = time\n sounding_file_dict[\"lat\"] = lat\n sounding_file_dict[\"lon\"] = lon\n sounding_file_dict[\"alt\"] = altitude\n sounding_file_dict[\"h_init\"] = h_init\n sounding_file_dict[\"flag\"] = flag\n sounding_file_dict[\"h_flag_0\"] = h_flag_0\n sounding_file_dict[\"h_flag_100\"] = h_flag_100\n sounding_file_dict[\"missing\"] = missing_interpolated\n sounding_file_dict[\"data\"] = spc_data\n \n return sounding_file_dict \n \n#########################\n \ndef output_to_spc_format(sounding_file_dict):\n\n # Construct vehicle header\n vehicle_header = \" {} {}/{} {},{}\".format(sounding_file_dict[\"vehicle_name\"], sounding_file_dict[\"date\"], sounding_file_dict[\"time\"], sounding_file_dict[\"lat\"], sounding_file_dict[\"lon\"])\n\n # Construct data header in \"SPC\" format\n pressure = \"LEVEL\"\n height = \"HGHT\"\n temp = \"TEMP\"\n dewpt = \"DWPT\"\n wdir = \"WDIR\"\n wspd = \"WSPD\"\n\n data_header = \" {} {} {} {} {} {}\".format(pressure, height, temp, dewpt, wdir, wspd)\n\n ######################## \n \n # Add file_name and data to a dictionary which will then be printed out to text files \n spc_dict = {}\n \n file_in = sounding_file_dict[\"file_in\"]\n file_out = file_in.replace(\"Hgt\", \"SPC\") + \".txt\" # create output file name\n\n whole_file = (\"%TITLE%\" + \"\\n\" + vehicle_header + \"\\n\\n\" + data_header + \"\\n\"\n + \"-------------------------------------------------------------------\"\n + \"\\n\" + \"%RAW%\" + \"\\n\" + sounding_file_dict[\"data\"] + \"\\n\" + \"%END%\")\n\n spc_dict.update({file_out: whole_file}) # append file name (key) and data (value) to dictionary\n \n return spc_dict\n\n#########################\n \ndef create_directory_out(directory_out): # Check if directory exists, and if not, make it\n if not os.path.exists(directory_out):\n os.makedirs(directory_out)\n\n#########################\n \ndef write_to_spc_files(dictionary): # Write dictionary items to files\n for name, data in dictionary.items():\n with open(os.path.join(directory_out, name), \"w+\") as f:\n f.write(data)\n \n#############################################################################\n \nfiles_to_process = get_files_from_directory(directory_in)\ncreate_directory_out(directory_out)\n\nfor file in files_to_process:\n sounding_file_dict = parse_info_from_hgt_file(file)\n spc_dict = output_to_spc_format(sounding_file_dict)\n \n # Incrementally append problem file names to a text file\n problem = \"\"\n alt_diff = sounding_file_dict[\"h_init\"] - sounding_file_dict[\"alt\"]\n if alt_diff >= 5:\n alt_diff_string = '{:.1f}'.format(alt_diff)\n problem += \"Problem (Alt. Diff >= 5) = \" + alt_diff_string\n \n h_flag_string = \"\" \n if sounding_file_dict[\"h_flag_0\"] and sounding_file_dict[\"h_flag_100\"] == 4:\n h_flag_string = \"4 THROUGHOUT\"\n elif sounding_file_dict[\"h_flag_0\"] == 4 and sounding_file_dict[\"h_flag_100\"] != 4:\n h_flag_string = \"4 INITIALLY\" \n if h_flag_string != \"\":\n problem += \"Problem (QH Flag) = \" + h_flag_string\n \n if sounding_file_dict[\"flag\"] != \"\":\n problem += \"Problem = \" + sounding_file_dict[\"flag\"]\n \n if sounding_file_dict[\"missing\"] != \"\":\n problem += sounding_file_dict[\"missing\"]\n\n if problem != \"\":\n with open(os.path.join(directory_out, \"Problem_Files.txt\"), \"a+\") as f: \n f.seek(0) # move cursor to the start of file \n data = f.read(100) # if file is not empty then append '\\n'\n if len(data) > 0:\n f.write(\"\\n\")\n # Append text to the end of the file\n f.write(file + \": \" + problem)\n\n # Write converted files to text files\n write_to_spc_files(spc_dict)\n\n#############################################################################" } ]
8
joycepang28/password-retry
https://github.com/joycepang28/password-retry
cc9c3077a167b37473b77aa0e54b870648e1b1c7
6fc7e017e4436cc0ecb3f366b87cefc3c184d20d
d1003ad51ad5a4c362a3e59d748c7c52835cd535
refs/heads/main
2023-06-05T16:17:07.934036
2021-06-22T12:25:00
2021-06-22T12:25:00
379,247,657
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6322314143180847, "alphanum_fraction": 0.6425619721412659, "avg_line_length": 21.904762268066406, "blob_id": "9c2885981ac43dfaf55ff912474077dbb0fbec9d", "content_id": "29066ca98181f6cce02d9b1a7bff755f6e35eba3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 572, "license_type": "no_license", "max_line_length": 71, "num_lines": 21, "path": "/password.py", "repo_name": "joycepang28/password-retry", "src_encoding": "UTF-8", "text": "# 密码重试程序\n# password = 'a123456'\n# 让使用者重复输入密码\n# 最多输入3次\n# 如果正确 就印出 \"Login successfully!\"\n# 如果不正确 就印出 \"Your password is wrong! You have__times chance remaining!\"\n\npassword = 'a123456'\ni = 3 # 剩余机会\nwhile i > 0:\n\ti = i - 1\n\tpwd = input('Please input your password: ')\n\tif pwd == password:\n\t\tprint('Login successfully!')\n\t\tbreak # 逃出回圈\n\telse:\n\t\tprint('Password is wrong!')\n\t\tif i > 0:\n\t\t\tprint('You have ', i, 'chances')\n\t\telse:\n\t\t\tprint('No more chance! Your account is locked!')\n\n\n\n" } ]
1
cl4u2/gwlist
https://github.com/cl4u2/gwlist
62a5e97818321842eb800da7cc2367f032c78977
f3800eef9a62dd8f5991dee961fb5356d25fe3c8
d14d24c1468c68374d8f0c72face491c88d77b2a
refs/heads/master
2020-05-26T19:06:07.299328
2014-09-17T10:24:55
2014-09-17T10:24:55
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.515539288520813, "alphanum_fraction": 0.5347349047660828, "avg_line_length": 28.54054069519043, "blob_id": "56cbd4daed8989fecb26607dce820c6693aca614", "content_id": "e5a912ed5ee6d459b28125f6e17e7583482664a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1094, "license_type": "no_license", "max_line_length": 84, "num_lines": 37, "path": "/gws.py", "repo_name": "cl4u2/gwlist", "src_encoding": "UTF-8", "text": "from lxml import etree\nimport binascii\nimport sys\n\nif len(sys.argv) < 2:\n print \"Usage: %s <pdml.xml>\" % sys.argv[0]\n sys.exit(1)\n\npdmlfile = sys.argv[1]\ntree = etree.parse(pdmlfile)\n\noriginatorset = set()\n\nfor f in tree.xpath('/pdml/packet/proto[@name=\"olsr\"]/field[@name=\"olsr.message\"]'):\n o = \"\"\n for e in f:\n propname = e.get(\"name\").replace(\".\",\"_\")\n propvalue = e.get(\"show\")\n if propname == \"olsr_message_type\" and propvalue != \"4\":\n break\n if propname == \"olsr_origin_addr\":\n o = propvalue\n elif propname == \"olsr_network_addr\":\n if propvalue == \"0.0.0.0\":\n originatorset.add(o)\n\noriginatorlist = list(originatorset)\n\nfor o in originatorlist:\n print \"echo '----->' %s\" % o\n if o.split('.')[0] == \"172\" or \".\".join(o.split('.')[:3]) == \"10.0.1\":\n # special subnets\n oregex = \"\\.\".join(o.split('.')) + \"\\\\b.*\\|\"\n else:\n # other subnets, assume /24\n oregex = \"\\.\".join(o.split('.')[:3]) + \"\\..*/.*\\|\"\n print \"egrep '%s' gestioneindirizzi.txt\" % oregex\n\n" } ]
1
mitsuk-maksim/python
https://github.com/mitsuk-maksim/python
8e0082cf02d08821c75f5a86833fc972968681f1
0f483705ef4f449318e90b37be05abb42e6cd0bd
92bcd34bb3d2b2dbe68500449c3ee608451be07f
refs/heads/master
2020-06-14T01:36:28.980801
2019-07-02T11:58:40
2019-07-02T11:58:40
194,853,342
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8155339956283569, "alphanum_fraction": 0.8300970792770386, "avg_line_length": 67.66666412353516, "blob_id": "c82713bc4358ff164aec26ec8ea86ae066329575", "content_id": "59ac2e73c3d431d787858dacad2621538f98e4e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 374, "license_type": "no_license", "max_line_length": 92, "num_lines": 3, "path": "/README.md", "repo_name": "mitsuk-maksim/python", "src_encoding": "UTF-8", "text": "Здесь присутсвуют 2 задачи: друзья, номера. Обе взяты с тестирования на стажировку в Яндекс.\nУсловие задачи номера, содержит 3 фотографии; друзья содержит 1 фотографию.\nКод соответственно также прилагается\n" }, { "alpha_fraction": 0.5889798998832703, "alphanum_fraction": 0.609828770160675, "avg_line_length": 39.96875, "blob_id": "bf6cc95e5d84b88dc1f8dc79808bc08b1b912fb0", "content_id": "747921b2be4359749e86c770e9cb4f778d8965c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1901, "license_type": "no_license", "max_line_length": 147, "num_lines": 32, "path": "/друзья.py", "repo_name": "mitsuk-maksim/python", "src_encoding": "UTF-8", "text": "n=int(input())\r\na=[]\r\nfor i in range(n): \r\n row = input().split()\r\n for i in range(len(row)):\r\n row[i] = int(row[i])\r\n a.append(row)\r\n\r\nq=0\r\nsm=[0]*n*n #массив, в котором хранятся всевозможные варианты встреч. Из всех вариантов необходимо будет выбрать максимальный\r\nfor i in range(n):\r\n '''\r\nсчитаем что a[i][] - главный человек, а все остальные под него подстраиватются\r\nтаким образом перебираем всех людей в a[i][], считая что все остальные люди подстраиваются под этого человека\r\nзаписываем в sm[q] самого a[i][] человека, также тех, сколько доверили ему свой голос, т.е. a[i][2],\r\nа также всех a[j][] кто придет во временной промежуток, когда будет присутсвовать a[i][],\r\nтакже тех, сколько доверили ему свой голос, т.е. a[j][2]\r\n'''\r\n sm[q]=a[i][2]+1 \r\n for j in range(n): #процесс сравнения временного интервала\r\n if ((a[j][0]<=a[i][1] and a[j][1]>a[i][0]) or (a[j][1]<=a[i][1] and a[j][1]>=a[i][0]) or (a[j][0]<=a[i][0] and a[j][1]>=a[i][0])) and i!=j:\r\n # print('кол-во друзей2',a[j][2])\r\n sm[q]=sm[q]+1+a[j][2]\r\n # print('sm[q]',sm[q])\r\n q+=1\r\n#print(sm)\r\nif n==1: #если был всего 1 человек, то результатом будет он сам + сколько людей ему доверилось\r\n print(a[0][2]+1)\r\nelse: #иначе вывести максимальный элемент из массива sm\r\n print(max(sm))\r\n\r\n#print(a)\r\n" }, { "alpha_fraction": 0.4165087938308716, "alphanum_fraction": 0.436265230178833, "avg_line_length": 29.767240524291992, "blob_id": "37737afed9e0298832cceda395cfe4d25d012ba3", "content_id": "6198d1d0912b3bdf6b4ef3a714650a3a4831418a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4201, "license_type": "no_license", "max_line_length": 93, "num_lines": 116, "path": "/номера.py", "repo_name": "mitsuk-maksim/python", "src_encoding": "UTF-8", "text": "'''массив из номеров. Добавляем туда только числа.\r\nв элементе будем хранить целый номер\r\n2й матрице в нем надо хранить на индексах\r\ni,0 - код страны\r\ni,1 - код оператора\r\ni,2 - номер который точно есть\r\ni,3 - всего цифр в номере\r\ni,4 - кол-во Х\r\ni,5 - оператор\r\nзатем в цикле проверять удовлетворяет номер или нет\r\n'''\r\ndef fun_num(a,num,n,j):\r\n a[j]=''\r\n for i in range(n):\r\n if num[i].isdigit():\r\n a[j]+=str(num[i])\r\n return(a) \r\n\r\ndef pars_shabl(a,shabl,n,j): #парсинг шаблона\r\n i=0\r\n # print('n=',n)\r\n #a[j][3]+=str(n)\r\n a[j][3]=0\r\n a[j][4]=0\r\n while i<n:\r\n if shabl[i]=='+':\r\n while shabl[i+1]!=' ':\r\n i+=1\r\n a[j][0]+=str(shabl[i])\r\n a[j][3]+=1\r\n #заполнили код страны\r\n i+=3\r\n while shabl[i]!=')':\r\n a[j][1]+=str(shabl[i])\r\n i+=1\r\n a[j][3]+=1\r\n i+=2\r\n while shabl[i]!='X':\r\n a[j][2]+=str(shabl[i])\r\n i+=1\r\n a[j][3]+=1\r\n while shabl[i]=='X':\r\n # print(shabl[i])\r\n #print(i)\r\n a[j][3]+=1\r\n a[j][4]+=1\r\n i+=1\r\n while i<n:\r\n a[j][5]+=shabl[i]\r\n i+=1 \r\n return(a)\r\n\r\n\r\ndef res(result,mas,matrix,i,m): #сравнение входных данных с шаблоном (через срез)\r\n for j in range(m):\r\n # print(\"номер: \",mas[i])\r\n result=''\r\n n=0\r\n # print(\"кол-во цифр: \",len(mas[i]),matrix[j][3])\r\n if len(mas[i])==matrix[j][3]:\r\n # print(\"код страны: \",mas[i][n:len(matrix[j][0])],matrix[j][0])\r\n if mas[i][n:len(matrix[j][0])]==matrix[j][0]:\r\n result+='+'+matrix[j][0]\r\n n+=len(matrix[j][0])\r\n # print(\"код оператора: \",mas[i][n:n+len(matrix[j][1])],matrix[j][1])\r\n if mas[i][n:n+len(matrix[j][1])]==matrix[j][1]:\r\n result+=' ('+matrix[j][1]\r\n n+=len(matrix[j][1])\r\n # print(\"код1: \", matrix[j][3],mas[i][n:n+len(matrix[j][2])],matrix[j][2])\r\n if matrix[j][3]!='' and mas[i][n:n+len(matrix[j][2])]==matrix[j][2]:\r\n result+=') '+matrix[j][2]\r\n n+=len(matrix[j][2])\r\n # print(\"код2: \",len(mas[i][n:]),matrix[j][4]) \r\n if len(mas[i][n:])==matrix[j][4]:\r\n result+=mas[i][n:]+matrix[j][5]\r\n # print('найдено')\r\n break\r\n # print(result)\r\n return(result)\r\n \r\n\r\n\r\n\r\n\r\nn=input()\r\nif n.isdigit() and int(n)<=100 and int(n)>=1: #проверка входных данных\r\n n=int(n)\r\n mas_num=['*']*n\r\n for i in range (n):\r\n num=input()\r\n fun_num(mas_num,num,len(num),i)\r\n #у нас есть массив только из чисел\r\n#print(mas_num)\r\n \r\n#создаем матрицу\r\n m=input()\r\n if m.isdigit() and int(m)<=1000 and int(m)>=1:\r\n m=int(m)\r\n matrix_shablon=[]\r\n for i in range(m):\r\n matrix_shablon.append(['']*6)\r\n for i in range (m):\r\n shabl=input()\r\n pars_shabl(matrix_shablon,shabl,len(shabl),i)\r\n\r\n\r\n #print(matrix_shablon) матрица, в которой хранится информация о шаблоне \r\n res_mas=['']*n\r\n for i in range(n):\r\n #print('i: ',i)\r\n res_mas[i]=res(res_mas[i],mas_num,matrix_shablon,i,m)\r\n print(res_mas[i])\r\n else:print()\r\nelse: print()\r\n#print(res_mas)\r\n#прогоняем mas_num смотрим по длине массиве, выбираем по этой длине возможный шаблон\r\n\r\n \r\n\r\n" } ]
3
elcapitankyle/stg
https://github.com/elcapitankyle/stg
8109368bc1284fe8b20213146136b3cf940d60ff
17ab18273dad9b24be02b8705e4ef391572c8fab
8e1bca06cdb2aa1f95e6a202c984ff43cbd27879
refs/heads/master
2021-03-14T05:27:57.791312
2020-03-23T03:55:56
2020-03-23T03:55:56
246,740,488
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6595091819763184, "alphanum_fraction": 0.6656441688537598, "avg_line_length": 25.1200008392334, "blob_id": "3e1bdc22e5603e0e74085e2a9405beb6d9453dbe", "content_id": "10ce25c89ae844f78f6c4cbeefcbff0825e07530", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 652, "license_type": "no_license", "max_line_length": 68, "num_lines": 25, "path": "/challenge2/challenge2.py", "repo_name": "elcapitankyle/stg", "src_encoding": "UTF-8", "text": "import unittest\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass Challenge2(unittest.TestCase):\n\n def setUp(self):\n self.driver = webdriver.Chrome(\"../chromedriver.exe\")\n\n def tearDown(self):\n self.driver.close()\n\n def test_Challenge2(self):\n self.driver.get(\"https://www.copart.com\")\n searchInput = self.driver.find_element_by_id(\"input-search\")\n searchInput.send_keys(\"exotics\")\n searchInput.send_keys(Keys.RETURN)\n self.driver.implicitly_wait(10)\n assert \"Porsche\" in self.driver.page_source\n\n\nif __name__ == '__main__':\n unittest.main()" } ]
1
evanslify/gitgrab
https://github.com/evanslify/gitgrab
7c159e7cd0692e9d32eac390f7470ec95155869f
3bbe89edc31993e0eaca937c1b1e6eb8cc8b298b
67de3a55a0eb1d6bc4860f83e16885c441b0cd7f
refs/heads/master
2021-01-10T12:09:05.912872
2015-09-11T09:02:17
2015-09-11T09:02:17
44,380,980
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.544910192489624, "alphanum_fraction": 0.544910192489624, "avg_line_length": 25.83333396911621, "blob_id": "24b0e1825821154a7d8e3f261646105d933d7ce6", "content_id": "e2f3aa4133d3cf54a6be592bf1adba0d393d4c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 835, "license_type": "no_license", "max_line_length": 74, "num_lines": 30, "path": "/grab/spiders/grabber.py", "repo_name": "evanslify/gitgrab", "src_encoding": "UTF-8", "text": "# working :(\r\n\r\nimport scrapy\r\n\r\n\r\nclass grabber(scrapy.Spider):\r\n name = 'grabber'\r\n\r\n def __init__(self, *args, **kwargs):\r\n super(grabber, self).__init__(*args, **kwargs)\r\n self.target_url = kwargs.get('url')\r\n if self.target_url == None:\r\n raise Exception('No URL entered.')\r\n\r\n def start_requests(self):\r\n yield scrapy.Request(url='file://\\/dev/null', callback=self.parse)\r\n\r\n # yield scrapy.Request(url='', callback=self.parse)\r\n # def get(self, response)j:\r\n # return\r\n\r\n # start_urls = []\r\n\r\n # def __init__(self, *args, **kwargs):\r\n # super(testwget, self).__init__(*args, **kwargs)\r\n # self.start_urls = [kwargs.get('start_url')]\r\n\r\n def parse(self, response):\r\n items = {'file_urls': [self.target_url]}\r\n return items\r\n" }, { "alpha_fraction": 0.5802231431007385, "alphanum_fraction": 0.5844555497169495, "avg_line_length": 27.877777099609375, "blob_id": "1b84dc7185306dc6d30729b21b27b2d425e6ecda", "content_id": "f30aba46e20c26a19ec034f8cd7d841c8cedef9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2599, "license_type": "no_license", "max_line_length": 80, "num_lines": 90, "path": "/grab/pipelines.py", "repo_name": "evanslify/gitgrab", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nfrom scrapy.utils.project import get_project_settings\nfrom scrapy.pipelines.files import FilesPipeline\nimport time\nimport scrapy\nimport shlex\nimport os\nimport getpass\nfrom subprocess import Popen\n\n\ndef call_timeout(cmd, timeout):\n start = time.time()\n p = Popen(cmd)\n while time.time() - start < timeout:\n if p.poll() is not None:\n return True\n time.sleep(0.1)\n p.kill()\n # return False\n raise OSError('command timed out')\n\n\nclass GrabPipeline(object):\n def process_item(self, item, spider):\n return item\n\n\nclass NFSPipeline(FilesPipeline):\n\n def __init__(self, *args, **kwargs):\n super(NFSPipeline, self).__init__(*args, **kwargs)\n settings = get_project_settings()\n self.ip = settings['NFS_SERVER']\n self.resource = settings['NFS_RESOURCE']\n self.store_dir = settings['FILES_STORE']\n self.port = settings['NFS_PORT']\n self.protocol = settings['NFS_PROTOCOL']\n\n def get_media_requests(self, item, info):\n self.check_nfs()\n\n for file_url in item['file_urls']:\n yield scrapy.Request(file_url)\n\n \"\"\"\n We shall check(by steps):\n 1. Whether this NFS server is online.\n 2. Does this folder exists?\n 2. Is this folder mounted?\n 3. If NFS is not mounted, mount it to FILES_STORE in settings. \"\"\"\n\n def check_nfs(self):\n command = shlex.split('showmount -d %s --no-headers' % self.ip)\n if call_timeout(command, 10):\n return self.check_dir()\n\n def check_if_mount(self):\n if not os.path.ismount(self.store_dir):\n return self.mount_nfs()\n else:\n return\n\n def check_dir(self):\n try:\n os.makedirs(self.store_dir)\n except OSError:\n if not os.path.isdir(self.store_dir):\n raise\n return self.check_if_mount()\n\n def mount_nfs(self):\n username = getpass.getuser()\n cmd = (\n 'sudo mount -t nfs -o owner={username},proto={protocol},port={port}'\n ' {ip}:{resource} {store_dir}').format(**{\n 'username': username,\n 'port': self.port,\n 'protocol': self.protocol,\n 'ip': self.ip,\n 'resource': self.resource,\n 'store_dir': self.store_dir})\n if call_timeout(shlex.split(cmd), 10):\n return\n" } ]
2
arnabd64/classifier-comparison-1
https://github.com/arnabd64/classifier-comparison-1
078a67fbfe89043c57c5302c42cd903891021558
38e845679b7f934f7514425b6f945ccb282050c0
d3a6575fd569b5ccb7a8e95da46af8b835212b63
refs/heads/main
2023-06-07T01:19:32.225905
2021-06-21T06:01:54
2021-06-21T06:01:54
378,575,211
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7256944179534912, "alphanum_fraction": 0.7413194179534912, "avg_line_length": 24.065217971801758, "blob_id": "09984990e307d516730f793d814324746557d1d1", "content_id": "28993d3430d82f4b33e1415191fac1d4a9f4c515", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 122, "num_lines": 46, "path": "/README.md", "repo_name": "arnabd64/classifier-comparison-1", "src_encoding": "UTF-8", "text": "# Comparing Binary Classification Models\n\n## Instructions\n\n- To view the notebook, please click `notebook.ipynb` in the above section.\n\n- To see the Python script, click on `script.py`. \n\n- To download the dataset using Browser, click on `SUV_Purchase` --> Right Click on `Raw` --> Click on `Save Link As`. \n\n- To import this dataset in python, use:\n\n```python\nimport pandas as pd\ndf = pd.read_csv('https://raw.githubusercontent.com/arnabd64/classifier-comparison-1/main/SUV_Purchase.csv')\n```\n\n- To import this dataset in R, use:\n\n```r\ndf <- read.csv('https://raw.githubusercontent.com/arnabd64/classifier-comparison-1/main/SUV_Purchase.csv')\n```\n\n## About notebook\n\nThe aim of this notebook is to provide a simple comparison between several classification models. The models included are:\n\n1. Logistic Regression\n\n2. k-Nearest Neighbors\n\n3. Decision Tree Classifier\n\n4. Random Forest Classifier\n\n5. Naive Bayes Classifier\n\n6. Support Vector Machines\n\n## About me\n\n- [LinkedIn](https://github.com/arnabd64/resume/blob/main/linkedin.com/in/arnab-dhar)\n\n- [GitHub](https://github.com/arnabd64)\n\n- [Resume on GitHub](https://github.com/arnabd64/resume)" }, { "alpha_fraction": 0.6915490031242371, "alphanum_fraction": 0.7033455967903137, "avg_line_length": 32.367740631103516, "blob_id": "1e96ba7b09ecdd56776ab12ffc5efc451aa42dae", "content_id": "fca0e72591df9d0b85e2411a55d4ae057df7d932", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5171, "license_type": "no_license", "max_line_length": 91, "num_lines": 155, "path": "/scipt.py", "repo_name": "arnabd64/classifier-comparison-1", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\n\n\nfrom sklearn.metrics import classification_report, confusion_matrix\nfrom sklearn.metrics import roc_curve, auc\n\ndf = pd.read_csv(\"SUV_Purchase.csv\")\ndf.head()\n\ndf.info()\n# Class Names\nclass_names = {'Not Purchased':0, 'Purchased':1}\n# Remove User ID\ndf.drop('User ID', axis = 1, inplace = True)\n# Encoding Gender\ndf.replace({'Male':1, 'Female':0}, inplace = True)\n# Featire Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc = StandardScaler()\ndf[['Age','EstimatedSalary']] = sc.fit_transform(df.loc[:, ['Age','EstimatedSalary']])\n\n# variable Separation\nX = df.drop('Purchased', axis = 1).values\ny = df.loc[:, 'Purchased'].values\n\n# Train test Split\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2)\n\n# PCA for dimensionality reduction\nfrom sklearn.decomposition import PCA\npca = PCA(n_components = 2)\nX_train = pca.fit_transform(X_train)\nX_test = pca.transform(X_test)\n## results of \nprint('Variance Captured by PCA')\nfor i in np.arange(pca.n_components_):\n print(\"PC{0:d}: {1:.1f}%\".format(i+1, 100*pca.explained_variance_ratio_[i]))\n\n\ndef AUC_ROC(model,X_train, X_test, y_train, y_test) :\n # Training Data\n y_train_prob = model.predict_proba(X_train)\n fpr1, tpr1, thres1 = roc_curve(y_train, y_train_prob[:,1], pos_label = 1)\n auc1 = auc(fpr1, tpr1)\n # testing Data\n y_test_prob = model.predict_proba(X_test)\n fpr2, tpr2, thres2 = roc_curve(y_test, y_test_prob[:,1], pos_label = 1)\n auc2= auc(fpr2, tpr2)\n #plotting\n plt.figure(figsize = (8,6))\n plt.plot(fpr1, tpr1, label = \"Training: AUC-ROC = {0:.3f}\".format(auc1),\n color = \"tab:orange\")\n plt.plot(fpr2, tpr2, label = \"Testing: AUC-ROC = {0:.3f}\".format(auc2),\n color = 'tab:blue')\n plt.plot(fpr1, fpr1, label = \"FPR = TPR\", color = 'black', linewidth=0.5)\n plt.xlabel('False Positive Rate (FPR)')\n plt.ylabel('True Positive Rate (TPR)')\n plt.title(\"ROC Curve for \" + model.__class__.__name__)\n plt.legend(loc = \"lower right\")\n plt.grid(which = 'both', axis = 'both')\n plt.show()\n pass\n\ndef cm_Heatmap(y_true, y_pred, class_name = np.unique(y_train)) :\n # Confusion Matrix\n cm = confusion_matrix(y_true, y_pred)\n cm = pd.DataFrame(cm, columns = class_name, index = class_name)\n # Plotting\n plt.figure(figsize = (8,6))\n sns.heatmap(cm, annot = True, annot_kws = {'size': 20}, fmt = 'd', cmap = 'Greens')\n plt.xlabel('Observed Class')\n plt.ylabel('Predicted Class')\n plt.title('Confusion Matrix')\n plt.show()\n pass\n\n\n# Logistic Regression\nfrom sklearn.linear_model import LogisticRegression\n## Training the model\nlog_reg = LogisticRegression()\nlog_reg.fit(X_train, y_train)\n# Training report\nprint(classification_report(y_train, log_reg.predict(X_train), target_names = class_names))\n\n# test data\ncm_Heatmap(y_test, log_reg.predict(X_test), class_names)\n# Classification report\nprint(classification_report(y_test, log_reg.predict(X_test), target_names = class_names))\n# AUC-ROC\nAUC_ROC(log_reg, X_train, X_test, y_train, y_test)\n\n# k-NearestNeighbours\nfrom sklearn.neighbors import KNeighborsClassifier\n## Training model\nknn = KNeighborsClassifier(n_neighbors = 5)\nknn.fit(X_train, y_train)\n# Training report\nprint(classification_report(y_train, knn.predict(X_train)))\n\n# test data\ncm_Heatmap(y_test, knn.predict(X_test), class_names)\n# Classification report\nprint(classification_report(y_test, knn.predict(X_test), target_names = class_names))\n# AUC-ROC\nAUC_ROC(knn, X_train, X_test, y_train, y_test)\n\n# Decision Tree\nfrom sklearn.tree import DecisionTreeClassifier\n## Training model\ndtc = DecisionTreeClassifier(max_depth = 4)\ndtc.fit(X_train, y_train)\n## Trainign report\nprint(classification_report(y_train, dtc.predict(X_train), target_names = class_names))\n\n# test data\ncm_Heatmap(y_test, dtc.predict(X_test), class_names)\n# Classification report\nprint(classification_report(y_test, dtc.predict(X_test), target_names = class_names))\n# AUC-ROC\nAUC_ROC(dtc, X_train, X_test, y_train, y_test)\n\n# Random Forest Classifier\nfrom sklearn.ensemble import RandomForestClassifier\n## Training model\nrfc = RandomForestClassifier(n_estimators = 50, max_depth = 3)\nrfc.fit(X_train, y_train)\n# Training report\nprint(classification_report(y_train, rfc.predict(X_train), target_names = class_names))\n\n# test data\ncm_Heatmap(y_test, rfc.predict(X_test), class_names)\n# Classification report\nprint(classification_report(y_test, rfc.predict(X_test), target_names = class_names))\n# AUC-ROC\nAUC_ROC(rfc, X_train, X_test, y_train, y_test)\n\n# Naive Bayes\nfrom sklearn.naive_bayes import GaussianNB\n## Training model\nnbc = GaussianNB(priors = np.array([0.5, 0.5]))\nnbc.fit(X_train, y_train)\n# Training report\nprint(classification_report(y_train, nbc.predict(X_train), target_names = class_names))\n\n# test data\ncm_Heatmap(y_test, nbc.predict(X_test), class_names)\n# Classification report\nprint(classification_report(y_test, nbc.predict(X_test), target_names = class_names))\n# AUC-ROC\nAUC_ROC(nbc, X_train, X_test, y_train, y_test)" } ]
2
aman229/vqa_tensorflow
https://github.com/aman229/vqa_tensorflow
6deb07d7f8cddec0dcc164de172470df03cb1695
82893d49112d3d5ad274417e973b120d06896471
e2ac33ad7742e452e2aa21c14c385991338025d8
refs/heads/master
2020-03-11T12:22:18.026411
2018-03-19T23:27:17
2018-03-19T23:27:17
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7227138876914978, "alphanum_fraction": 0.7492625117301941, "avg_line_length": 66.4000015258789, "blob_id": "f14fefcbd63fabd8cf10ed0f2a6f99fcb2e43db3", "content_id": "dfce97d21bb66c08056df12e59679dbbfc424d84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 339, "license_type": "no_license", "max_line_length": 170, "num_lines": 5, "path": "/README.md", "repo_name": "aman229/vqa_tensorflow", "src_encoding": "UTF-8", "text": "# Show, Ask, Attend, and Answer\n\nMy TensorFlow implementation of [*Show, Ask, Attend, and Answer: A Strong Baseline For Visual Question Answering* - Vahid Kazemi and Ali Elqursh](https://arxiv.org/abs/1704.03162). \n\nI wanted to try implementing a multimodal model in TF and this seemed like a good candidate. Lots of code needs to be added though\n\n\n" }, { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.5637387633323669, "avg_line_length": 36.62711715698242, "blob_id": "ba556bd6d1b393dc99ac2aad8476a30d2da67302", "content_id": "08e8549d81e16c13677f388aa7b1f7cda397717f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8880, "license_type": "no_license", "max_line_length": 115, "num_lines": 236, "path": "/VQA.py", "repo_name": "aman229/vqa_tensorflow", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom tensorflow.python.framework import random_seed\nfrom collections import Counter\nfrom PIL import Image\nimport numpy as np\nimport itertools\nimport zipfile\nimport urllib\nimport json\nimport os\nimport re\n\n\nclass VQADataSet(object):\n \"\"\"\n Base class for the dataset\n \"\"\"\n\n def __init__(self, data_dir='./data/', split=\"val\", top_answers=3000,\n max_ques_len=15, seed=None):\n self.data_dir = data_dir\n self.split = split\n self.img_dir = self.data_dir + \"{}2014/\".format(self.split)\n self.top_answers = top_answers\n self.max_ques_len = max_ques_len\n self._data = self.preprocess_json(self.split)\n self.question_to_index = self.map_to_index(top=None, answer=False)\n self.vocab_size = len(self.question_to_index)\n self.answer_to_index = self.map_to_index(top=self.top_answers)\n self._num_examples = len(self._data)\n self._epochs_completed = 0\n self._index_in_epoch = 0\n self.number_of_questions = len(self._data)\n seed1, seed2 = random_seed.get_seed(seed)\n np.random.seed(seed1 if seed is None else seed2)\n \n @property\n def data(self):\n return self._data\n \n @property\n def answers(self):\n return (x['answers'] for x in self._data)\n \n @property\n def questions(self):\n return (x['question'] for x in self._data)\n \n @property\n def img_indices(self):\n return (x['image_id'] for x in self._data)\n \n def preprocess_json(self, split='train', use_nltk=True):\n questions_filename = self.data_dir + \"OpenEnded_mscoco_{0}2014_questions.json\"\n answers_filename = self.data_dir + \"mscoco_{0}2014_annotations.json\"\n \n if use_nltk:\n import nltk\n tokenize = nltk.word_tokenize\n else:\n tokenize = lambda x: x.split(' ') \n \n questions = self._read_json(questions_filename.format(split))['questions']\n # Answers are present as a list of dicts under the 'annotations' key in the resulting \n # dictionary when the json file is read\n # The following code reads the json file, then extracts the list of answer dicts\n # And then converts the list into a dict indexed by the question_id\n answers_dict = {x['question_id']:x for x in self._read_json(answers_filename.format(split))['annotations']}\n \n for item in questions:\n question = item['question']\n question = tokenize(question.lower()[:-1])\n \n _id = item['question_id']\n answers = answers_dict.get(_id)['answers']\n # converting answers from list of dicts to just a list of answers without\n # confidence or id\n punc = r'[;>\")<!$.%=#*&/+,@\\'?(-]\\s*'\n answers = [re.sub(punc, ' ', x) for x in [x['answer'] for x in answers]]\n \n item['question'] = question\n item['answers'] = answers \n \n return questions\n\n def map_to_index(self, top, answer=True):\n if answer:\n _data = self.answers\n else:\n _data = self.questions\n\n x = itertools.chain.from_iterable(_data)\n counts = Counter(x)\n sorted_common = (x[0] for x in counts.most_common(top))\n vocab = {word:index for index, word in enumerate(sorted_common, start=1)}\n return vocab \n \n def encode_into_vector(self):\n for item in self.data:\n q_vec = np.zeros(self.max_ques_len)\n for i, word in enumerate(item['question'][:self.max_ques_len]):\n mapped_index = self.question_to_index.get(word, 0)\n q_vec[i] = mapped_index\n \n a_vec = np.zeros(self.top_answers)\n counter = Counter(item['answers'])\n most_freq_ans = counter.most_common(1)[0][0]\n answer_index = self.answer_to_index.get(most_freq_ans, 1)\n a_vec[answer_index-1] = 1\n \n item['question'] = q_vec\n item['answers'] = a_vec\n \n def preprocess_image(self, image_id):\n path = '{}COCO_val2014_{:012d}.jpg'.format(self.img_dir, image_id)\n try:\n img = Image.open(path)\n img = self._scale_img_to_dim(img, 448)\n img = self._center_crop(img, 299, 299)\n img = self._normalize_img(img.resize((448, 448), Image.ANTIALIAS))\n return img\n except FileNotFoundError:\n pass\n \n def return_batch_indices(self, batch_size, shuffle=True):\n start = self._index_in_epoch\n self._indices = list(range(self._num_examples))\n # Shuffle for the first epoch\n if self._epochs_completed == 0 and start == 0 and shuffle:\n perm0 = np.arange(self._num_examples)\n np.random.shuffle(perm0)\n self._indices = list(perm0)\n\n # Go to the next epoch\n if start + batch_size > self._num_examples:\n # Finished epoch\n self._epochs_completed += 1\n\n # Get the rest examples in this epoch\n rest_num_examples = self._num_examples - start\n filenames_rest_part = self._indices[start:self._num_examples]\n\n # Shuffle the data for next epoch\n if shuffle:\n perm = np.arange(self._num_examples)\n np.random.shuffle(perm)\n self._indices = [self.filenames[i] for i in perm]\n\n # Start next epoch\n start = 0\n self._index_in_epoch = batch_size - rest_num_examples\n end = self._index_in_epoch\n filenames_new_part = self._indices[start:end]\n return filenames_rest_part + filenames_new_part\n else:\n self._index_in_epoch += batch_size\n end = self._index_in_epoch\n return self._indices[start:end]\n \n def next_batch(self, batch_size):\n batch_indices = self.return_batch_indices(batch_size)\n data = [self.data[i] for i in batch_indices]\n q = np.stack([x['question'] for x in data])\n a = np.stack([x['answers'] for x in data])\n _img = (x['image_id'] for x in data)\n img = np.stack([self.preprocess_image(x) for x in _img])\n return q.astype(np.int64), a.astype(np.float16), img.astype(np.float32)\n \n \n def _normalize_img(self, img):\n img = np.array(img)\n img = img.astype(np.float32) * (1/255.0)\n _mean=[0.485, 0.456, 0.406]\n _std=[0.229, 0.224, 0.225]\n img = (img - _mean)/_std\n return img\n \n def _scale_img_to_dim(self, img, desired_dim):\n w, h = img.size\n if w > h:\n ratio = float(desired_dim)/w\n hsize = int(h*ratio)\n img = img.resize((448, hsize), Image.ANTIALIAS)\n else:\n ratio = float(desired_dim)/h\n wsize = int(w*ratio)\n img = img.resize((wsize, 448), Image.ANTIALIAS)\n return img\n \n def _center_crop(self, im, new_width, new_height):\n width, height = im.size # Get dimensions\n left = (width - new_width)/2\n top = (height - new_height)/2\n right = (width + new_width)/2\n bottom = (height + new_height)/2\n \n return im.crop((left, top, right, bottom)) \n \n def _read_json(self, file):\n with open(file, 'r') as f:\n x = json.load(f)\n return x\n \n\ndef maybe_download_and_extract(data_dir):\n \"\"\"\n Will download and extract the VQA data automatically\n \"\"\"\n if not os.path.exists(data_dir):\n os.makedirs(data_dir)\n\n # Downloading the question and answers\n datasets = [\"Questions\", \"Annotations\"]\n splits = [\"Train\", \"Val\"]\n for data in datasets:\n for split in splits:\n url = \"http://visualqa.org/data/mscoco/vqa/{}_{}_mscoco.zip\".format(data, split)\n filename = url.split('/')[-1]\n filepath = os.path.join(data_dir, filename)\n if not os.path.exists(filepath):\n filepath, _ = urllib.urlretrieve(url, filepath)\n zipfile.ZipFile(filepath, 'r').extractall(data_dir)\n print('Successfully downloaded and extracted ', filename)\n \n \n # Downloading images\n for split in [x.lower() for x in splits]:\n url = \"http://msvocds.blob.core.windows.net/coco2014/{}2014.zip\".format(split)\n filename = url.split('/')[-1]\n filepath = os.path.join(data_dir, filename)\n if not os.path.exists(filepath):\n filepath, _ = urllib.urlretrieve(url, filepath)\n zipfile.ZipFile(filepath, 'r').extractall(data_dir)\n print('Successfully downloaded and extracted ', filename)\n" }, { "alpha_fraction": 0.6138022541999817, "alphanum_fraction": 0.6310550570487976, "avg_line_length": 50.27586364746094, "blob_id": "6d5a624c75fb1e29cf2e041153f75aab6fd34e05", "content_id": "d46c93b8625bac7c15ca0ba0df6fb87596dc57f2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1507, "license_type": "no_license", "max_line_length": 103, "num_lines": 29, "path": "/main.py", "repo_name": "aman229/vqa_tensorflow", "src_encoding": "UTF-8", "text": "from model import Model\nimport argparse\n\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--epoch', dest='epoch', type=int, default=20, help='# of epoch')\nparser.add_argument('--batch_size', dest='batch_size', type=int, default=128, help='# images in batch')\nparser.add_argument('--lr', dest='lr', type=int, default=0.001, help='initial learning rate')\nparser.add_argument('--state', dest='state', type=int, default=1024, help='LSTM hidden state size')\nparser.add_argument('--embed', dest='embed', type=int, default=300, help='Embedding vector size')\nparser.add_argument('--drop', dest='drop', type=int, default=0.5, help='Dropout probability')\nparser.add_argument('--freq', dest='freq', type=int, default=1024, help='How many top answers')\nparser.add_argument('--resnet_features', dest='resnet', \n default='resnet_ckpt/resnet_v2_152.ckpt', \n help='Path to resnet pretrained weights')\nparser.add_argument('--project', dest='project', type=bool, \n default=False, help='Project text features instead of tile')\n\nargs = parser.parse_args()\n\nvqa_model = Model(batch_size = args.bs, \n init_lr=args.bs, \n state_size=args.state,\n embedding_size=args.embed, \n dropout_prob=args.drop, \n most_freq_limit=args.freq,\n resnet_weights_path=args.resnet,\n project=args.project)\n\nvqa_model.train(args.epoch)\n " }, { "alpha_fraction": 0.5229449272155762, "alphanum_fraction": 0.5453485250473022, "avg_line_length": 49.449581146240234, "blob_id": "4c70508c0c815f4ebe5a60a26127ebe516b487aa", "content_id": "64d846b8d356eaa407828128d97ae1eb563220c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12007, "license_type": "no_license", "max_line_length": 126, "num_lines": 238, "path": "/model.py", "repo_name": "aman229/vqa_tensorflow", "src_encoding": "UTF-8", "text": "from resnet_utils import resnet_arg_scope\nfrom resnet import resnet_v2_152\nfrom VQA import VQADataSet\nimport tensorflow as tf\nimport time\nimport os\n\n# TODO add summaries\n# TODO add validation\n\nclass Model(object):\n \"\"\"\n TF implementation of \"Show, Ask, Attend, and Answer: A Strong Baseline For Visual Question Answering'' [0]\n [0]: https://arxiv.org/abs/1704.03162\n \"\"\"\n\n def __init__(self, batch_size, init_lr=0.001, reuse=False, vocabulary_size=None, state_size=1024,\n embedding_size=300, dropout_prob=0.5, most_freq_limit=3000,\n summary_dir='./logs/', resnet_weights_path = 'resnet_ckpt/resnet_v2_152.ckpt', \n project=False):\n\n \"\"\"\n\n :type max_ques_length: object\n :type embedding_size: object\n \"\"\"\n self.state_size = state_size\n self.batch_size = batch_size\n self.init_lr = init_lr\n self.reuse= reuse\n self.embedding_size = embedding_size\n self.data = VQADataSet()\n self.vocabulary_size = self.data.vocab_size if vocabulary_size is None else vocabulary_size\n self.dropout_prob = dropout_prob\n self.most_freq_limit = most_freq_limit\n self.summary_dir = summary_dir\n self.resnet_weights_path = resnet_weights_path\n self.project = project\n self.sess = tf.Session()\n self.build_model()\n self._check_resnet_weights()\n\n def build_model(self):\n print('\\nBuilding Model')\n # Creating placeholders for the question and the answer\n self.questions = tf.placeholder(tf.int64, shape=[None, 15], name=\"question_vector\") \n self.answers = tf.placeholder(tf.float32, shape=[None, self.most_freq_limit], name=\"answer_vector\")\n self.images = tf.placeholder(tf.float32, shape=[None, 448, 448, 3], name=\"images_matrix\")\n \n\n arg_scope = resnet_arg_scope()\n with tf.contrib.slim.arg_scope(arg_scope):\n resnet_features, _ = resnet_v2_152(self.images, reuse=tf.AUTO_REUSE)\n depth_norm = tf.norm(resnet_features, ord='euclidean', keepdims=True, axis=3) + 1e-8\n self.image_features = resnet_features/depth_norm\n \n with tf.variable_scope(\"text_features\") as scope:\n if self.reuse:\n scope.reuse_variables()\n self.word_embeddings = tf.get_variable('word_embeddings', \n [self.vocabulary_size,\n self.embedding_size],\n initializer=tf.contrib.layers.xavier_initializer())\n word_vectors = tf.nn.embedding_lookup(self.word_embeddings, self.questions)\n len_word = self._len_seq(word_vectors)\n \n embedded_sentence = tf.nn.dropout(tf.nn.tanh(word_vectors, name=\"embedded_sentence\"),\n keep_prob=self.dropout_prob)\n lstm = tf.nn.rnn_cell.LSTMCell(self.state_size,\n initializer=tf.contrib.layers.xavier_initializer())\n _, final_state = tf.nn.dynamic_rnn(lstm, embedded_sentence,\n sequence_length=len_word,\n dtype=tf.float32)\n self.text_features = final_state.c\n \n self.attention_features = self.compute_attention(self.image_features,\n self.text_features)\n \n with tf.variable_scope(\"fully_connected\") as scope:\n if self.reuse:\n scope.reuse_variables()\n self.fc1 = tf.nn.dropout(tf.nn.relu(self.fc_layer(self.attention_features, 1024, name=\"fc1\")),\n keep_prob=self.dropout_prob)\n self.fc2 = self.fc_layer(self.fc1, 3000, name=\"fc2\")\n \n self.answer_prob = tf.nn.softmax(self.fc2) \n self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.answers, \n logits=self.fc2))\n \n self.global_step = tf.Variable(0, name='global_step', trainable=False, dtype=tf.int32)\n self.inc = tf.assign_add(self.global_step, 1, name='increment')\n self.lr = tf.train.exponential_decay(learning_rate=self.init_lr, \n global_step=self.global_step,\n decay_steps=10000,\n decay_rate=0.5,\n staircase=True)\n \n self.optimizer = tf.train.AdamOptimizer(self.lr, beta1=0.9, beta2=0.999, name=\"optim\")\n\n\n def train(self, epochs):\n self.saver = tf.train.Saver()\n self.tf_summary_writer = tf.summary.FileWriter(self.summary_dir, self.sess.graph)\n \n # Loading resnet pretrained weights \n resnet_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=\"resnet\")\n load_resnet = tf.train.Saver(var_list=resnet_vars)\n load_resnet.restore(self.sess, self.resnet_weights_path)\n \n # Freezing resnet weights\n train_vars = [x for x in tf.global_variables() if \"resnet\" not in x.name]\n train_step = self.optimizer.minimize(self.loss, var_list=train_vars, \n global_step=self.global_step)\n \n # Initializing all variables\n print('Initializing variables')\n init_op = tf.global_variables_initializer()\n self.sess.run(init_op)\n \n self.data.encode_into_vector()\n \n start_time = time.time()\n print('Starting training') \n for epoch in range(epochs):\n steps = 10#data.number_of_questions // self.batch_size\n for idx in range(steps):\n print(\"Step {:4d} of epoch {:2d}\".format(idx, epoch))\n print('\\nGetting batches')\n q, a, img = self.data.next_batch(self.batch_size)\n vqa_dict = {self.questions: q, self.answers: a, self.images: img}\n _, cost, _a = self.sess.run([train_step, self.loss, self.inc], feed_dict=vqa_dict)\n \n print(\"\\nEpoch: [%2d] [%4d/%4d] time: %4.4f, Loss: %.8f\"\n % (epoch, idx, steps,\n time.time() - start_time, cost))\n\n\n def compute_attention(self, image, text): \n with tf.variable_scope(\"attention\") as scope:\n if self.reuse:\n scope.reuse_variables()\n text_replicated = self._replicate_features(text, (1, 14, 14, 1), \n project=self.project)\n \n # Now both the features from the resnet and lstm are concatenated along the depth axis\n features = tf.nn.dropout(tf.concat([image, text_replicated], axis=3), \n keep_prob=self.dropout_prob)\n conv1 = tf.nn.dropout(self.conv2d_layer(features, filters=512, \n kernel_size=(1,1), \n name=\"attention_conv1\"),\n keep_prob=self.dropout_prob)\n conv2 = self.conv2d_layer(conv1, filters=2, kernel_size=(1,1), name=\"attention_conv2\")\n \n # Flatenning each attention map to perform softmax\n attention_map = tf.reshape(conv2, (self.batch_size, 14*14, 2))\n attention_map = tf.nn.softmax(attention_map, axis=1, name = \"attention_map\")\n image = tf.reshape(image, (self.batch_size, 196, 2048, 1))\n attention = tf.tile(tf.expand_dims(attention_map, 2), (1, 1, 2048, 1))\n image = tf.tile(image,(1,1,1,2))\n weighted = image * attention\n weighted_average = tf.reduce_mean(weighted, 1)\n \n # Flatten both glimpses into a single vector\n weighted_average = tf.reshape(weighted_average, (self.batch_size, 2048*2))\n attention_output = tf.nn.dropout(tf.concat([weighted_average, text], 1), self.dropout_prob)\n return attention_output\n \n def conv2d_layer(self, input_tensor, filters, kernel_size=(3,3), stride=1, name=\"conv\", padding='VALID'):\n with tf.variable_scope(name):\n weights = tf.get_variable('conv_weights', [kernel_size[0], kernel_size[1], input_tensor.get_shape()[-1], filters],\n initializer=tf.contrib.layers.xavier_initializer())\n biases = tf.get_variable('conv_bias', [filters], initializer=tf.constant_initializer(0.0))\n\n conv = tf.nn.conv2d(input_tensor, weights, strides=[1, stride, stride, 1], padding=padding)\n conv = tf.nn.bias_add(conv, biases)\n return conv\n\n def deconv2d_layer(self, input_tensor, filters, output_size, \n kernel_size=(5,5), stride=2, name=\"deconv2d\"):\n with tf.variable_scope(name):\n h, w = output_size\n weights = tf.get_variable('deconv_weights', \n shape=[kernel_size[0], kernel_size[1],\n filters, input_tensor.get_shape()[-1]],\n initializer=tf.contrib.layers.xavier_initializer())\n biases = tf.get_variable('biases', [filters], initializer=tf.constant_initializer(0.0))\n \n output_dims = [self.batch_size, h, w, filters]\n deconv = tf.nn.conv2d_transpose(input_tensor, weights, strides=[1, stride, stride, 1],\n output_shape=output_dims)\n deconv = tf.nn.bias_add(deconv, biases)\n return deconv\n \n def fc_layer(self, input_tensor, neurons, name=\"fc\"):\n with tf.variable_scope(name):\n weights = tf.get_variable('fc_weights', [input_tensor.get_shape()[-1], neurons],\n initializer=tf.contrib.layers.xavier_initializer())\n biases = tf.get_variable('fc_biases', [neurons], initializer=tf.constant_initializer(0.0))\n \n output = tf.matmul(input_tensor, weights) + biases\n return output\n\n def _len_seq(self, sequence):\n used = tf.sign(tf.reduce_max(tf.abs(sequence), 2))\n length = tf.reduce_sum(used, 1)\n length = tf.cast(length, tf.int32)\n return length\n \n def _replicate_features(self, input_features, multiples, project=False):\n x = tf.reshape(input_features, (self.batch_size, 1, 1, self.state_size))\n if not project:\n # Expanding dimensions of LSTM features to 4-D\n replicated = tf.tile(x, multiples)\n else:\n dc1 = self.deconv2d_layer(x, 1024, output_size=(2,2), name=\"dc1\")\n x1 = tf.nn.dropout(dc1, self.dropout_prob)\n \n dc2 = self.deconv2d_layer(x1, 1536, output_size=(4,4), name=\"dc2\")\n x2 = tf.nn.dropout(dc2, self.dropout_prob)\n \n dc3 = self.deconv2d_layer(x2, 2048, output_size=(8,8), name=\"dc3\")\n x3 = tf.nn.dropout(dc3, self.dropout_prob)\n \n dc4 = self.deconv2d_layer(x3, 2048, output_size=(16,16), name=\"dc4\")\n x4 = tf.nn.dropout(dc4, self.dropout_prob)\n \n replicated = tf.nn.dropout(self.conv2d_layer(x4, 2048, kernel_size=(3,3), \n name=\"conv_dc4\"), 0.5) \n return replicated\n \n def _check_resnet_weights(self):\n resnet_dir = './resnet_ckpt'\n if not os.path.exists(resnet_dir):\n os.mkdir(resnet_dir)\n url = \"http://download.tensorflow.org/models/resnet_v2_152_2017_04_14.tar.gz\"\n os.system(\"wget \" + url)\n command = 'tar -xvzf {} -C ./resnet_ckpt/'.format(url.split(\"/\")[-1])\n os.system(command)\n" } ]
4
APHA-CSU/BovTB-nf
https://github.com/APHA-CSU/BovTB-nf
8498d87fce1cf7580618dcbfdb65bbea1a438f8b
c82cb778aee769b9630d95a7af7ef6b72b4b5dfd
b5d132ccfde00a630e95dccf5d289a5804aac98c
refs/heads/master
2023-03-29T03:20:54.853054
2022-06-22T09:22:35
2022-06-22T09:22:35
293,763,641
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4973357021808624, "alphanum_fraction": 0.5044404864311218, "avg_line_length": 30.27777862548828, "blob_id": "7851db4fdd6a0322c4fa4cf1345cc727b028c5ea", "content_id": "3dce78bfa5e5bb09772858fc26943757912b4981", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 563, "license_type": "permissive", "max_line_length": 130, "num_lines": 18, "path": "/btb-seq", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/sh\n#================================================================\n# btb-seq\n#================================================================\n#% SYNOPSIS\n#+ bov-tb reads_dir results_dir\n#%\n#% DESCRIPTION\n#% Run the pipeline on a batch of samples.\n#%\n#% INPUTS\n#% reads filepath to directory of .fastq.gz read pairs\n#% results filepath to where nextflow results will be stored\n\nREADS=$1\nRESULTS=$2\n\nnextflow run ./bTB-WGS_process.nf --outdir $RESULTS --reads $READS/\"*_{S*_R1,S*_R2}*.fastq.gz\" -with-report \"$RESULTS/report.html\"\n" }, { "alpha_fraction": 0.6702127456665039, "alphanum_fraction": 0.758865237236023, "avg_line_length": 34.25, "blob_id": "1d546d84c122d6d17d97bd644d92896620d919c9", "content_id": "2594b927c7b750d9b277b0bb2c539de949b47673", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 282, "license_type": "permissive", "max_line_length": 90, "num_lines": 8, "path": "/docker/install-bcftools.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# use this to install latest commit of bcftools (as opposed to the v1.9 release)\nwget https://github.com/samtools/bcftools/releases/download/1.10.2/bcftools-1.10.2.tar.bz2\ntar xjf bcftools-1.10.2.tar.bz2\nrm -f bcftools-1.10.2.tar.bz2\ncd bcftools-1.10.2\nmake\nsudo make install\ncd ..\n" }, { "alpha_fraction": 0.7355371713638306, "alphanum_fraction": 0.797520637512207, "avg_line_length": 47.400001525878906, "blob_id": "2bae4cf03627469a36c05511cdaa2708d32cc3dd", "content_id": "b4d6f87c998c180972c3e55bfc6c415061add4c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 242, "license_type": "permissive", "max_line_length": 88, "num_lines": 5, "path": "/docker/install-Trimmomatic.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# Trimmomatic\nwget http://www.usadellab.org/cms/uploads/supplementary/Trimmomatic/Trimmomatic-0.38.zip\nunzip Trimmomatic-0.38.zip\nrm -f Trimmomatic-0.38.zip\nsudo ln -s $PWD/Trimmomatic-0.38/trimmomatic-0.38.jar /usr/local/bin/trimmomatic.jar\n" }, { "alpha_fraction": 0.6038647294044495, "alphanum_fraction": 0.6147342920303345, "avg_line_length": 26.633333206176758, "blob_id": "684a8e44fb5f89c47673cee176ef06a9a4bb8113", "content_id": "8aa888d5a6cbfd99dd41b028d34adb4969bfbda9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 828, "license_type": "permissive", "max_line_length": 110, "num_lines": 30, "path": "/tests/unit_tests/deduplicate_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "import unittest\nimport glob\nimport shutil\n\nfrom btb_tests import BtbTests\n\nclass DeduplicateTests(BtbTests):\n def test_deduplicate(self):\n \"\"\"\n This introductory unit test asserts the deduplicate process completes on tinyreads without errors.\n And produces two fastq files\n \"\"\"\n\n # Copy test data\n reads = self.copy_tinyreads()\n outputs = [\n self.temp_dirname + 'read_1.txt', \n self.temp_dirname + 'read_2.txt'\n ]\n\n # Test the script\n self.assertBashScript(0, ['./bin/deduplicate.bash', reads[0], reads[1], outputs[0], outputs[1]])\n self.assertFileExists(outputs[0])\n self.assertFileExists(outputs[1])\n\n # TODO: Assert that duplicates are actually removed\n\n\nif __name__ == '__main__':\n unittest.main()" }, { "alpha_fraction": 0.5814185738563538, "alphanum_fraction": 0.6073926091194153, "avg_line_length": 24.69230842590332, "blob_id": "ec504dd46fd7418b0b473c21f79d2c1ef4b4a56f", "content_id": "d7e5932fa4d1a3d7130acd01f2cd14934cd735c6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1001, "license_type": "permissive", "max_line_length": 142, "num_lines": 39, "path": "/bin/deduplicate.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#================================================================\n# Deduplicate\n#================================================================\n#% SYNOPSIS\n#+ Deduplicate.bash pair_1 pair_2 deduplicated_1 deduplicated_2\n#%\n#% DESCRIPTION\n#% Removes potential duplicate data (sequencing and optical replcaites from the raw data set) from a pair of .fastq.gz files using FastUniq\n#%\n#% INPUTS\n#% pair_1 input path to first fastq.gz read file\n#% pair_2 input path to second fastq.gz read file\n#% deduplicated_1 output path to first deduplicated file\n#% deduplicated_2 output path to second deduplicated file\n\n# Error handling\nset -eo pipefail\n\n# Inputs\npair_1=$1\npair_2=$2\ndeduplicated_1=$3\ndeduplicated_2=$4\n\nnl=$'\\n'\n\n# Unzip\ngunzip -c $pair_1 > R1.fastq \ngunzip -c $pair_2 > R2.fastq\n\n# Input List\necho \"R1.fastq${nl}R2.fastq\" > fqin.lst\n\n# FastUniq\nfastuniq -i fqin.lst -o $deduplicated_1 -p $deduplicated_2\n\n# Cleanup\nrm R1.fastq R2.fastq fqin.lst" }, { "alpha_fraction": 0.4492753744125366, "alphanum_fraction": 0.45410627126693726, "avg_line_length": 28.64285659790039, "blob_id": "114b3b4595cc13f6a618d3739f84d92851f08e90", "content_id": "fe8d7f5d2d177c367ee16c43c08e16a2918d0992", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 414, "license_type": "permissive", "max_line_length": 65, "num_lines": 14, "path": "/tests/utils/nextflowtest.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#================================================================\n# nextflowtest.bash\n#================================================================\n#\n#% DESCRIPTION\n#% Integration tests for nextflow should be called this way. \n\nnextflow run bTB-WGS_process.nf \\\n--outdir \"/results/\" \\\n--reads \"/reads/*_{S*_R1,S*_R2}*.fastq.gz\" \\\n--lowmem '\"--memory-map\"' \\\n-with-report /artifacts/report.html" }, { "alpha_fraction": 0.6881029009819031, "alphanum_fraction": 0.7154340744018555, "avg_line_length": 27.272727966308594, "blob_id": "49f729f0e41cdf2bf0e298dce9a766776e3da71f", "content_id": "b7893bfa70820c46ccc5118fcf2e517bee15279f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 622, "license_type": "permissive", "max_line_length": 182, "num_lines": 22, "path": "/bin/assignClusterCss.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Assigns cluster by matching patterns of cluster specific SNPs\n# Compares SNPs identified in vcf file to lists in reference table\n\n# Error handling\nset -eo pipefail\n\npair_id=$1\ndiscrimPos=$2\nstage1pat=$3\nmin_mean_cov=$4\nmin_cov_snp=$5\nalt_prop_snp=$6\nmin_qual_snp=$7\nmin_qual_nonsnp=$8\npypath=$9\nref=$10\n\nbcftools view -R ${discrimPos} -O v -o ${pair_id}.discrimPos.vcf ${pair_id}.vcf.gz\npython3 $pypath/Stage1-test.py ${pair_id}_stats.csv ${stage1pat} $ref test ${min_mean_cov} ${min_cov_snp} ${alt_prop_snp} ${min_qual_snp} ${min_qual_nonsnp} ${pair_id}.discrimPos.vcf\nmv _stage1.csv ${pair_id}_stage1.csv\n" }, { "alpha_fraction": 0.6916950941085815, "alphanum_fraction": 0.6951080560684204, "avg_line_length": 26.46875, "blob_id": "41b19de69254949af9dd08991bf3b0319b8e3e86", "content_id": "a0068531fedf2108bca62306afe91398e8e4741e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 879, "license_type": "permissive", "max_line_length": 86, "num_lines": 32, "path": "/tests/utils/print_csv_value.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\n\n\"\"\" print_csv_value.py: \n\t\tPrints an item in a CSV \n\"\"\"\n\nimport pandas as pd\nimport argparse\n\ndef print_csv_value(filename, field, row):\n\tdf = pd.read_csv(filename, dtype=str, keep_default_na=False)\n\n\tif field not in df:\n\t\traise Exception('CSV does not contain field: %s (%s)'%(field, filename))\n\n\tif len(df) < row+1:\n\t\traise Exception('Row number larger than number of rows')\n\n\tprint(df[field][row])\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description=\"\"\"\n\t\tAssert the first entry of a specified column in a csv file against a provided value.\n\t\texitcode 1 on failure and 0 otherwise\n\t\"\"\")\n\tparser.add_argument('filename', help='path to csv')\n\tparser.add_argument('row', type=int, help='which row to access')\n\tparser.add_argument('field', help='name of column to check')\n\n\targs = parser.parse_args()\n\n\tprint_csv_value(**vars(args))\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.7054263353347778, "avg_line_length": 17.428571701049805, "blob_id": "3546dc0480c2244ca7ecbaee64d157ff73301c67", "content_id": "5cf9953765ed18b04953bca29cfee98f09d8c098", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 129, "license_type": "permissive", "max_line_length": 42, "num_lines": 7, "path": "/docker/install-bwa.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# bwa\ngit clone https://github.com/lh3/bwa.git\ncd bwa\ngit checkout v0.7.17\nmake\ncd ..\nsudo ln -s $PWD/bwa/bwa /usr/local/bin/bwa\n" }, { "alpha_fraction": 0.5899705290794373, "alphanum_fraction": 0.5935103297233582, "avg_line_length": 35.84782791137695, "blob_id": "e91b4f3a9fde38b180cd3f08804178c2303cab10", "content_id": "7d1710001c3d37d13aa5eee44cb1b0fb886254dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1695, "license_type": "permissive", "max_line_length": 86, "num_lines": 46, "path": "/tests/unit_tests/mask_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "from btb_tests import BtbTests\nimport shutil\nimport unittest\n\nclass MaskTests(BtbTests):\n allsites = './references/All-sites.bed'\n ref_masked_filepath = './tests/data/edge-cases.bed'\n\n def test_mask(self):\n \"\"\"\n Asserts mask.bash completes without errors when \n the supplied sam file contains no regions of zero coverage\n \"\"\"\n # Copy data\n rpt_mask_filepath = self.temp_dirname+'rpt_mask.bed'\n vcf_filepath = self.temp_dirname+'edge-cases.vcf'\n vcf_gz_filepath = self.temp_dirname+'edge-cases.vcf.gz'\n masked_filepath = self.temp_dirname+'masked.bed'\n regions_filepath = self.temp_dirname+'regions.bed'\n sam_filepath = self.temp_dirname+'edge-cases.sam'\n bam_filepath = self.temp_dirname+'edge-cases.bam'\n shutil.copy('./tests/data/edge-cases.vcf', vcf_filepath) \n shutil.copy('./tests/data/tinymask.bed', rpt_mask_filepath) \n shutil.copy('./tests/data/edge-cases.sam', sam_filepath) \n \n self.gzip(vcf_filepath, vcf_gz_filepath)\n self.sam_to_bam(sam_filepath, bam_filepath)\n\n # Test\n self.assertBashScript(0, ['./bin/mask.bash', \n rpt_mask_filepath, \n vcf_gz_filepath, \n masked_filepath, \n regions_filepath, \n bam_filepath,\n self.allsites, \n str(8), \n str(0.8),\n str(0.7)])\n self.assertFileExists(regions_filepath)\n with open(masked_filepath) as test_f, open(self.ref_masked_filepath) as ref_f:\n self.assertListEqual(list(test_f), list(ref_f))\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.5773542523384094, "alphanum_fraction": 0.5885650515556335, "avg_line_length": 26.030303955078125, "blob_id": "059ed6d94ca28a5ef35485994cab0e0125a34d69", "content_id": "e5647f475138d6dd08317eeaed868f57b59b99b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 892, "license_type": "permissive", "max_line_length": 135, "num_lines": 33, "path": "/docker/Dockerfile", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "FROM ubuntu:20.04\n\n################## METADATA ##########################\n\nLABEL base.image=ubuntu:20.04\nLABEL software=\"Bovine-TB Pipeline Image\"\nLABEL about.summary=\"Bioinformatics Pipeline for post-processing of Bovine TB fastq reads\"\nLABEL about.documentation=\"https://github.com/APHA-CSU/BovTB-nf\"\nLABEL about.tags=\"Genomics, WGS\"\n\n\n################## ARGS #############################\n\nARG BOVTB_PATH=\"/BovTB-nf/\"\n\n\n################## DEPENDENCIES ######################\n\n# Copy repository\nWORKDIR $BOVTB_PATH\nCOPY ./ ./\nRUN chmod +x ./bin/*\n\n# Sudo\nRUN apt-get -y update && DEBIAN_FRONTEND=noninteractive apt-get install -y sudo\n\n# Biotools\nRUN cd ./docker && bash ./install-all-dependancies.bash\n\n\n################## ENTRY ######################\n\nCMD nextflow run bTB-WGS_process.nf --outdir \"/results/\" --reads \"/reads/*_{S*_R1,S*_R2}*.fastq.gz\" -with-report \"/results/report.html\"\n" }, { "alpha_fraction": 0.6817248463630676, "alphanum_fraction": 0.6878849864006042, "avg_line_length": 24.578947067260742, "blob_id": "ea9c6401a7f992777c69ba719149ecdf1c469cf8", "content_id": "a532cf01b32b4211f0ae7206ed770cc64da50f0c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 974, "license_type": "permissive", "max_line_length": 107, "num_lines": 38, "path": "/tests/unit_tests/unit_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\n\n\"\"\" unit_tests.py: \n This file runs unit tests for the pipeline. \n Each unit test should be quick to run (ie. milliseconds typically, but certainly less than second) \n Tests that have a long run time should simplified, mocked, or be a .circleci job.\n\"\"\"\n\nimport unittest\n\nfrom deduplicate_tests import DeduplicateTests\nfrom trim_tests import TrimTests\nfrom mask_tests import MaskTests\nfrom read_stats_tests import ReadStatsTests\nfrom map2Ref_tests import Map2RefTests\nfrom varCall_tests import VarCallTests\nfrom vcf2consensus_tests import Vcf2ConsensusTests\n\ndef main():\n # Test List\n tests = [\n DeduplicateTests,\n TrimTests,\n MaskTests,\n ReadStatsTests,\n Map2RefTests,\n VarCallTests,\n Vcf2ConsensusTests\n ]\n\n # Load 'em up\n for test in tests:\n unittest.TestLoader().loadTestsFromTestCase(test)\n\n unittest.main()\n\nif __name__ == '__main__':\n main()\n\n\n" }, { "alpha_fraction": 0.4449685513973236, "alphanum_fraction": 0.4504716992378235, "avg_line_length": 19.516128540039062, "blob_id": "9202b417f2ea485f8133b9b0db899e9e8e4596b0", "content_id": "f99ad45462b9f7b115c1859ce928b0ba05f0378b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1272, "license_type": "permissive", "max_line_length": 90, "num_lines": 62, "path": "/tests/run_tests", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#================================================================\n# run_tests\n#================================================================\n#\n#% DESCRIPTION\n#% Runs integration tests\n#% Each test should be defined as a bash script and appended in the JOBS variable below\n\nJOBS=(\n minimal-pipeline.bash\n inclusivity.bash\n quality-test.bash\n)\n\nIMAGE=bov-tb-test\nBASEDIR=$PWD/$(dirname \"$0\")\n\n# Run a single job if defined on command line\nif [ -z ${1+x} ]; then \n JOBS=($1) \nfi\n\n# Build docker image\necho ==========================\necho Build\necho ==========================\n\nsudo docker build -t $IMAGE $BASEDIR/../\nif [ $? -ne 0 ]; then\n echo *** BUILD FAILED JOB ***\n exit 1\nfi\n\n# Integration Tests\nfor i in \"${JOBS[@]}\"\ndo\n echo ==========================\n echo $i\n echo ==========================\n\n # Run job in docker\n sudo docker run -v $BASEDIR/jobs:/jobs/ --rm $IMAGE /bin/bash -e /jobs/$i\n exitcode=$?\n\n # Handle exit code\n if [ $exitcode -ne 0 ]; then\n echo\n echo *** JOB FAILED: $i ***\n echo\n exit 1\n else\n echo\n echo --- JOB PASSED: $i ---\n echo\n fi\ndone\n\necho ==========================\necho ALL TEST PASSED\necho ==========================\n" }, { "alpha_fraction": 0.6856725215911865, "alphanum_fraction": 0.7470760345458984, "avg_line_length": 51.61538314819336, "blob_id": "550a48f0bb9fcb766afefbcd29b9451fa1eff6ba", "content_id": "56698174c2cd0b68785eb4017f03815602b2521c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 684, "license_type": "permissive", "max_line_length": 123, "num_lines": 13, "path": "/docker/install-sra-toolkit.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# Install sra-toolkit.\n# This was really annoying to install. The only way to get fasterq-dump to work was by running vdb-config --i at least once\n# vdb-config --i causes weird terminal issues. Workaround is to pipe it to null and ignore the exit code =p\nwget https://ftp-trace.ncbi.nlm.nih.gov/sra/sdk/2.10.8/sratoolkit.2.10.8-ubuntu64.tar.gz\ntar -vxzf sratoolkit.2.10.8-ubuntu64.tar.gz\nrm sratoolkit.2.10.8-ubuntu64.tar.gz\n\nset +e\necho \"q\" | ./sratoolkit.2.10.8-ubuntu64/bin/vdb-config -i > /dev/null 2>&1\nset -e\n\nsudo ln -s $PWD/sratoolkit.2.10.8-ubuntu64/bin/fasterq-dump /usr/local/bin/fasterq-dump\nsudo ln -s $PWD/sratoolkit.2.10.8-ubuntu64/bin/prefetch /usr/local/bin/prefetch\n" }, { "alpha_fraction": 0.752136766910553, "alphanum_fraction": 0.752136766910553, "avg_line_length": 22.399999618530273, "blob_id": "f53ea5f6eaaf00721bdbbdb5ef13c4e01d4da571", "content_id": "cda2728001ad418f013366f5fa1668ef23939b62", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 117, "license_type": "permissive", "max_line_length": 53, "num_lines": 5, "path": "/install.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "##### Install Dependancies for the Bovine TB Pipeline\n\nchmod +x ./bin/*\ncd docker\nbash install-all-dependancies.bash\n" }, { "alpha_fraction": 0.5974886417388916, "alphanum_fraction": 0.6236484050750732, "avg_line_length": 43.10769271850586, "blob_id": "8d05829082ea160b550486c9db5c8e5fcab319ff", "content_id": "d8e4413961160232315ec2b2cb166d227184f0a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2867, "license_type": "permissive", "max_line_length": 170, "num_lines": 65, "path": "/bin/readStats.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# readStats.bash\n#\n# Created by ellisrichardj on 10/10/2019.\n# \n\n# Error handling\nset -eo pipefail\n\n# Define inputs - sample name\npair_id=$1\n\n# Count reads in each catagory; in fastq files each read consists of four lines\n\n raw_R1=$(( $(zcat ${pair_id}_*_R1_*.fastq.gz | wc -l) / 4 )) # counts number of reads in file\n rm ${pair_id}_*_R1_*.fastq.gz\n rm ${pair_id}_*_R2_*.fastq.gz\n uniq_R1=$(( $(cat ${pair_id}_uniq_R1.fastq | wc -l) / 4 )) # counts number of reads in file\n rm `readlink ${pair_id}_uniq_R2.fastq`\n trim_R1=$(( $(cat ${pair_id}_trim_R1.fastq | wc -l) / 4 )) # counts number of reads in file\n num_map=$(samtools view -c ${pair_id}.mapped.sorted.bam) # samtools counts the number of mapped reads\n samtools depth -a ${pair_id}.mapped.sorted.bam > depth.txt # samtools outputs depth at each position\n avg_depth=$(awk '{sum+=$3} END { printf \"%.3f\", sum/NR}' depth.txt)\n zero_cov=$(awk 'BEGIN {count=0} $3<1 {++count} END {print count}' depth.txt)\n sites=$(awk '{++count} END {print count}' depth.txt)\n rm depth.txt\n \n\n\n# Caluclate values and percentages\n\n num_raw=$(($raw_R1*2))\n num_uniq=$(($uniq_R1*2))\n num_trim=$(($trim_R1*2))\n pc_aft_dedup=$(echo \"scale=2; ($num_uniq*100/$num_raw)\" |bc)\n pc_aft_trim=$(echo \"scale=2; ($num_trim*100/$num_uniq)\" |bc)\n pc_mapped=$(echo \"scale=2; ($num_map*100/$num_trim)\" |bc)\n genome_cov=$(echo \"scale=2; (100-($zero_cov*100/$sites))\" |bc)\n\n\n# Define thresholds for flag assignment\n\n mindepth=10 # require an average of at least 10 reads per site \n minpc=60 # require at least 60% of data maps to genome\n minreads=600000 # require at least 600,000 raw reads per sample\n minafttrim=60 # require at least 60% reads to pass quality filtering steps\n\n\n# This section assigns 'flags' based on the number of reads and the proportion mapping to reference genome\n \n if [[ ${pc_aft_trim%%.*} -lt $minafttrim ]]; then flag=\"LowQualData\"\n elif [[ ${avg_depth%%.*} -ge $mindepth ]] && [[ ${pc_mapped%%.*} -gt $minpc ]]; then flag=\"Pass\"\n elif [[ ${avg_depth%%.*} -lt $mindepth ]] && [[ ${pc_mapped%%.*} -lt $minpc ]] && [[ $num_trim -gt $minreads ]]; then flag=\"Contaminated\"\n elif [[ ${avg_depth%%.*} -lt $mindepth ]] && [[ $num_trim -lt $minreads ]]; then flag=\"InsufficientData\"\n# elif [ ${pc_mapped%%.*} -lt $minpc ] && [ $num_trim -gt $minreads ]; then flag=\"q_OtherMycobact\"\n else flag=\"CheckRequired\"\n fi\n\n\n# Write values to csv file\n\n echo \"Sample,NumRawReads,NumDedupReads,%afterDedup,NumTrimReads,%afterTrim,NumMappedReads,%Mapped,MeanDepth,GenomeCov,Outcome\" > ${pair_id}_stats.csv\n echo \"${pair_id},\"$num_raw\",\"$num_uniq\",\"$pc_aft_dedup\",\"$num_trim\",\"$pc_aft_trim\",\"$num_map\",\"$pc_mapped\",\"$avg_depth\",\"$genome_cov\",\"$flag\"\" >> ${pair_id}_stats.csv\n echo \"$flag\" > outcome.txt\n" }, { "alpha_fraction": 0.5869786143302917, "alphanum_fraction": 0.6063072085380554, "avg_line_length": 28.787878036499023, "blob_id": "a65452c7e3b7fdc63677a65f58bf9a0afe9a4d07", "content_id": "fc0daea368cd5a6f627c2fc30588d2ec1a414e72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 983, "license_type": "permissive", "max_line_length": 118, "num_lines": 33, "path": "/tests/unit_tests/varCall_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "import shutil\nimport unittest\nfrom btb_tests import BtbTests\n\nclass VarCallTests(BtbTests):\n ref_path = './references/Mycbovis-2122-97_LT708304.fas'\n\n def test_varCall(self):\n \"\"\"\n Asserts varCall.bash completes on tinymatch.sam without errors and produces a vcf file\n \"\"\"\n sam_path = self.temp_dirname + '/tinymatch.sam'\n bam_path = self.temp_dirname + '/tinymatch.bam'\n output = self.temp_dirname + 'variants.vcf.gz'\n map_qual = str(0)\n base_qual = str(10)\n ploidy = str('GRCh37')\n\n # Copy test data\n shutil.copy2('./tests/data/tinymatch.sam', sam_path)\n\n # Convert to BAM\n self.sam_to_bam(sam_path, bam_path)\n\n # Pass case\n self.assertBashScript(0, ['./bin/varCall.bash', self.ref_path, bam_path, output, map_qual, base_qual, ploidy])\n self.assertFileExists(output)\n\n # Unzip\n self.unzip(output)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6555653214454651, "alphanum_fraction": 0.6555653214454651, "avg_line_length": 27.524999618530273, "blob_id": "b10cff5bb9ced46b0d5ce28658f0838b08aeb217", "content_id": "d737595dd9e8ad2c86594416eacbf778e6e2f190", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1141, "license_type": "permissive", "max_line_length": 98, "num_lines": 40, "path": "/tests/utils/set_uniform_fastq_quality.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\n\n\"\"\" set_uniform_fastq_quality.py: \n Overwrite a fastq with uniform base quality\n\"\"\"\n\nimport argparse\n\nfrom Bio import SeqIO\n\ndef set_uniform_fastq_quality(quality, filepath):\n \"\"\"\n Overwrite a fastq file to a new file with uniform base quality\n \"\"\"\n # Parse\n original_fastq = SeqIO.parse(filepath, \"fastq\")\n\n # Set quality\n new_fastq = []\n for i, line in enumerate(original_fastq):\n num_reads = len(line._per_letter_annotations[\"phred_quality\"])\n line._per_letter_annotations[\"phred_quality\"] = [quality]*num_reads\n \n new_fastq.append(line)\n\n # Write\n SeqIO.write(new_fastq, filepath, \"fastq\")\n\n\nif __name__ == '__main__':\n # Parse\n parser = argparse.ArgumentParser(description=\"Overwrite a fastq to with a uniform quality\")\n parser.add_argument('quality', type=int, help=\"Phred quality score that all bases are set to\")\n parser.add_argument('filepath', nargs=\"+\", help=\"Filepath(s) to fastq file\")\n\n args = parser.parse_args()\n\n # Run\n for filepath in args.filepath:\n set_uniform_fastq_quality(args.quality, filepath)\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.7541666626930237, "avg_line_length": 33.28571319580078, "blob_id": "3e46ad0ff944de4568a718c709ff428aff1bccda", "content_id": "44f3d4f3918f071a9872ccf252b8e904b82b2a18", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 480, "license_type": "permissive", "max_line_length": 77, "num_lines": 14, "path": "/docker/install-Kraken2.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# kraken2 and associated database\nwget http://github.com/DerrickWood/kraken2/archive/v2.0.8-beta.tar.gz\ntar xzf v2.0.8-beta.tar.gz\nrm -f v2.0.8-beta.tar.gz\ncd kraken2-2.0.8-beta\n./install_kraken2.sh ../Kraken2\ncd ..\nsudo ln -s $PWD/Kraken2/kraken2 /usr/local/bin/kraken2\n\nsudo mkdir -p /opt/Kraken2/db\n\nwget https://genome-idx.s3.amazonaws.com/kraken/minikraken2_v1_8GB_201904.tgz\nsudo tar xvf minikraken2_v1_8GB_201904.tgz -C /opt/Kraken2/db/\nrm -f minikraken2_v1_8GB_201904.tgz\n" }, { "alpha_fraction": 0.6069930195808411, "alphanum_fraction": 0.6174825429916382, "avg_line_length": 34.75, "blob_id": "47e1b54e647496c14919add83a764f5016d40778", "content_id": "93500d5b68dea1fad1eec809d598f975688ec5d9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1430, "license_type": "permissive", "max_line_length": 88, "num_lines": 40, "path": "/tests/unit_tests/read_stats_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "import subprocess\nimport shutil\nimport glob\n\nfrom btb_tests import BtbTests\n\nclass ReadStatsTests(BtbTests):\n def assertReadStats(self, reads_path, name):\n \"\"\"\n Asserts read stats returns a 0 exit code for the supplied test reads\n TODO: Neaten test code when readStats.bash has input args for all input data\n \"\"\"\n fastq_1 = reads_path+'_S1_R1_X.fastq.gz'\n fastq_2 = reads_path+'_S1_R2_X.fastq.gz'\n pair_id = self.temp_dirname + name\n\n # Copy over \n shutil.copy(fastq_1, self.temp_dirname)\n shutil.copy(fastq_2, self.temp_dirname)\n\n # Unzip\n fastq_files = glob.glob(self.temp_dirname + '*.gz')\n subprocess.run(['gunzip', '-k'] + fastq_files, cwd=self.temp_dirname)\n\n fastq_file = fastq_files[0][:-3]\n\n subprocess.run(['ln', '-s', fastq_file, pair_id+'_uniq_R1.fastq'])\n subprocess.run(['ln', '-s', fastq_file, pair_id+'_uniq_R2.fastq'])\n shutil.copy(fastq_file, pair_id+'_trim_R1.fastq')\n\n self.sam_to_bam('./tests/data/tinymatch.sam', pair_id+'.mapped.sorted.bam')\n\n # Test\n self.assertBashScript(0, ['./bin/readStats.bash', pair_id]) \n\n def test_read_stats_tinyreads(self):\n self.assertReadStats('./tests/data/tinyreads/tinyreads', 'tinyreads')\n\n def test_read_stats_tinysra(self):\n self.assertReadStats('./tests/data/tinysra/tinysra', 'tinysra')\n" }, { "alpha_fraction": 0.5810276865959167, "alphanum_fraction": 0.6229249238967896, "avg_line_length": 20.440677642822266, "blob_id": "53bb272478b8ec8d8af34061eac5069f3a2b9925", "content_id": "11cff71128913200e38949c4b82fd6c592bbf83d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1265, "license_type": "permissive", "max_line_length": 68, "num_lines": 59, "path": "/tests/jobs/quality.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#================================================================\n# quality.bash\n#================================================================\n#\n#% DESCRIPTION\n#% Checks the pipeline response against good or bad quality reads\n#% Input argument should be either 'low' or 'adequate'\n\n# Import\nsource tests/utils/aliases.bash\n\nTESTCASE=$1\n\n# Test Case\nif [ \"$TESTCASE\" == \"low\" ]; then\n echo Low quality test selected\n\n quality=\"19\"\n outcome=\"LowQualData\"\n group=\"NA\"\n\nelif [ \"$TESTCASE\" == \"adequate\" ]; then\n echo Adequate quality test selected\n\n quality=\"20\"\n outcome=\"Pass\"\n group=\"B6-16\"\n\nelse\n echo Unknown testcase: $TESTCASE\n exit 1\n\nfi\n\n# Download\nread1=ERR4586795_1.fastq.gz\nread2=ERR4586795_2.fastq.gz\nroot=ftp://ftp.sra.ebi.ac.uk/vol1/fastq/ERR458/005/ERR4586795/\nwget $root/$read1 -O /reads/QT_S1_R1_001.fastq.gz\nwget $root/$read2 -O /reads/QT_S1_R2_001.fastq.gz\n\n# Unzip\ngunzip -f /reads/*\n\n# Set quality\npython tests/utils/set_uniform_fastq_quality.py $quality /reads/*\n\n# Zip \ngzip -f /reads/*\n\n# Run nextflow\nnextflowtest\n\n# Check results\nWGS_CLUSTER_CSV=$(print_todays_wgs_cluster)\nassert_first_csv_row $WGS_CLUSTER_CSV \"Outcome\" \"$outcome\"\nassert_first_csv_row $WGS_CLUSTER_CSV \"group\" \"$group\"\n" }, { "alpha_fraction": 0.6958568692207336, "alphanum_fraction": 0.6996233463287354, "avg_line_length": 31.18181800842285, "blob_id": "bb2893f985525376a9f7bd1b01c8a904806e0d0e", "content_id": "4248321f3101488096c195a06689b9def7104e9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "permissive", "max_line_length": 109, "num_lines": 33, "path": "/tests/utils/assert_first_csv_row.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\n\n\"\"\" assert_first_csv_row.py: \n\t\tAssert the first entry of a specified column in a csv file against a provided value. \n\"\"\"\n\nimport pandas as pd\nimport argparse\n\ndef assert_first_csv_row(filename, field, value):\n\tdf = pd.read_csv(filename, dtype=str, keep_default_na=False)\n\n\tif field not in df:\n\t\traise Exception('CSV does not contain field: %s (%s)'%(field, filename))\n\n\tif not len(df):\n\t\traise Exception('No rows found in %s'%filename)\n\n\tif not df[field][0] == value:\n\t\traise Exception(\"First entry in %s field mismatch \\nGot: %s \\nExpected: %s\" % (field, df[field][0], value))\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description=\"\"\"\n\t\tAssert the first entry of a specified column in a csv file against a provided value.\n\t\texitcode 1 on failure and 0 otherwise\n\t\"\"\")\n\tparser.add_argument('filename', help='path to csv')\n\tparser.add_argument('field', help='name of column to check')\n\tparser.add_argument('value', help='what the column should read')\n\n\targs = parser.parse_args()\n\n\tassert_first_csv_row(**vars(args))\n" }, { "alpha_fraction": 0.6380510330200195, "alphanum_fraction": 0.6417633295059204, "avg_line_length": 30.691177368164062, "blob_id": "062666ad12560a6a794a0bc7361e7e9e77d647c4", "content_id": "bb64068d59a56f4652b9967fe17d0b90aa3e8082", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2155, "license_type": "permissive", "max_line_length": 108, "num_lines": 68, "path": "/tests/utils/combine_fastq.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/usr/local/bin/python\n\n\"\"\" combine_fastq.py: \n Creates a new fastq file by taking random subsets from two fastq files\n\"\"\"\n\nimport argparse\nimport random\nimport gzip\n\ndef combine_fastq(\n total_num_reads, \n prop_a_reads, \n filepath_a, \n filepath_b, \n filepath_combined,\n seed\n ):\n random.seed(seed)\n\n num_rand_a_reads = int(total_num_reads*prop_a_reads)\n num_rand_b_reads = int(total_num_reads - num_rand_a_reads)\n\n # Setup output file\n with gzip.open(filepath_a, 'r') as file_a, \\\n gzip.open(filepath_b, 'r') as file_b, \\\n gzip.open(filepath_combined, 'w') as file_combined:\n\n subsample(num_rand_a_reads, file_a, file_combined)\n subsample(num_rand_b_reads, file_b, file_combined)\n\ndef subsample(num_rand_reads, file_in, file_out):\n \"\"\"\n Randomly subsample fastq file_in, writing to file_out\n \"\"\"\n # Get the number of records\n file_in.seek(0)\n num_reads=int(len(file_in.readlines())/4)\n file_in.seek(0)\n\n # Subsample\n record_nums = sorted(random.sample(range(num_reads), num_rand_reads))\n rec_num = -1\n for rr in record_nums:\n # Loop until next record\n while rec_num < rr:\n rec_num += 1\n for i in range(4): file_in.readline()\n\n # Write the random record\n for i in range(4):\n file_out.write(file_in.readline())\n rec_num += 1\n\nif __name__ == '__main__':\n # Parse\n parser = argparse.ArgumentParser(description=\"Overwrite a fastq to with a uniform quality\")\n parser.add_argument('total_num_reads', type=float, help=\"Number of reads to take from first fastq file\")\n parser.add_argument('prop_a_reads', type=float, help=\"Number of reads to take from second fastq file\")\n parser.add_argument('filepath_a', help=\"First fastq filepath\")\n parser.add_argument('filepath_b', help=\"Second fastq filepath\")\n parser.add_argument('filepath_combined', help=\"Output combined fastq filepath\")\n parser.add_argument('--seed', default=None, type=int, help=\"seed to initialise random number generator\")\n\n args = parser.parse_args()\n\n # Run\n combine_fastq(**vars(args))\n" }, { "alpha_fraction": 0.5469924807548523, "alphanum_fraction": 0.5469924807548523, "avg_line_length": 22.130434036254883, "blob_id": "f5a25269eec189b59912333bc69b55d227fd851e", "content_id": "44299e5410c9f33fe7e5b06b068ad444c2119bb4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 532, "license_type": "permissive", "max_line_length": 65, "num_lines": 23, "path": "/tests/jobs/tinyreads.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#================================================================\n# tinyreads.bash\n#================================================================\n#\n#% DESCRIPTION\n#% Tests the nextflow pipeline on a tiny dataset. \n#% Asserts the Outcome is Insufficient Data\n\n# Import\nsource tests/utils/aliases.bash\n\n# Copy Data\ncp -r $PWD/tests/data/tinyreads/* /reads/\n\n# Run nextflow\nnextflowtest\n\n# Check results\nWGS_CLUSTER_CSV=$(print_todays_wgs_cluster)\nassert_first_csv_row $WGS_CLUSTER_CSV \\\n Outcome LowQualData\n" }, { "alpha_fraction": 0.5351608991622925, "alphanum_fraction": 0.5446960926055908, "avg_line_length": 25.21875, "blob_id": "2a5eeb3e96f81c3ce254b33f212bc5744b5fc778", "content_id": "fcbc4096e884191a6bf875c5f513ba9160c1b06a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 839, "license_type": "permissive", "max_line_length": 75, "num_lines": 32, "path": "/bin/varCall.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#================================================================\n# varCall\n#================================================================\n#% SYNOPSIS\n#+ varCall.bash ref read_1 read_2 mapped\n#%\n#% DESCRIPTION\n#% Determines where the sample differs from the reference genome\n#%\n#% INPUTS\n#% ref path to input reference fasta file\n#% bam path to first input fastq read file\n#% vcf path to output vcf.gz file\n\n# Error handling\nset -eo pipefail\n\n# Determines where the sample differs from the reference genome\n\nref=$1\nbam=$2\nvcf=$3\nMAP_QUAL=$4\nBASE_QUAL=$5\nPLOIDY=$6\n\nsamtools index $bam\nbcftools mpileup -q $MAP_QUAL -Q $BASE_QUAL -a INFO/AD -Ou -f $ref \"$bam\" |\n bcftools call --ploidy $PLOIDY -mf GQ - -Ou |\n bcftools norm -f $ref - -Oz -o \"$vcf\"\nbcftools index $vcf\n" }, { "alpha_fraction": 0.5922646522521973, "alphanum_fraction": 0.6099720597267151, "avg_line_length": 33.6129035949707, "blob_id": "cde3dedbb28f55f359357a79bf280878917f59af", "content_id": "4bb5d818001e181d61dbfd705501500b1199f5c2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2146, "license_type": "permissive", "max_line_length": 122, "num_lines": 62, "path": "/tests/unit_tests/trim_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "import unittest\nfrom btb_tests import BtbTests\n\nclass TrimTests(BtbTests):\n adapter_path = './references/adapter.fasta'\n\n def test_trim(self):\n \"\"\"\n This introductory unit test asserts trim.bash completes on tinyreads without errors.\n And produces two fastq files\n \"\"\" \n\n # Copy test data\n reads = self.copy_tinyreads(unzip=True)\n\n # Output Filenames\n outputs = [\n self.temp_dirname + 'out1.fastq',\n self.temp_dirname + 'out2.fastq'\n ]\n\n # Pass case\n self.assertBashScript(0, ['./bin/trim.bash', self.adapter_path, reads[0], reads[1], outputs[0], outputs[1]])\n self.assertFileExists(outputs[0])\n self.assertFileExists(outputs[1])\n\n # Failure Case: adapter sequence file not found\n self.assertBashScript(1, ['./bin/trim.bash', './__does__/not/exist/', reads[0], reads[1], outputs[0], outputs[1]])\n\n def test_trimmomatric_trims(self):\n \"\"\"\n Asserts that low quality reads are removed using a high quality and low quality examples\n \"\"\"\n # Test settings\n high_quality_sequence = \"A\"*40\n low_quality_sequence = \"T\"*40\n\n read_1 = self.temp_dirname+\"read_1.fastq\"\n read_2 = self.temp_dirname+\"read_2.fastq\"\n\n output_1 = self.temp_dirname+\"output_1.fastq\"\n output_2 = self.temp_dirname+\"output_2.fastq\"\n\n # Create Test Fastq files\n high_quality = self.seq_record(high_quality_sequence, quality=93)\n low_quality = self.seq_record(low_quality_sequence, quality=0)\n\n self.write_fastq(read_1, [low_quality, high_quality])\n self.write_fastq(read_2, [low_quality, high_quality])\n \n # Run Trimmomatic\n self.assertBashScript(0, ['./bin/trim.bash', self.adapter_path, read_1, read_2, output_1, output_2])\n\n # Assert Output\n trimmed = self.read_fastq(output_1)\n self.assertEqual(trimmed, high_quality_sequence)\n\n trimmed = self.read_fastq(output_2)\n self.assertEqual(trimmed, high_quality_sequence)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6056337952613831, "alphanum_fraction": 0.609577476978302, "avg_line_length": 34.5, "blob_id": "a569e1c8717e69b0e16fcd395007ef339b8a4313", "content_id": "9c3323f55728d0296c2d2c82b7d5c865c12f7dc3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1775, "license_type": "permissive", "max_line_length": 92, "num_lines": 50, "path": "/tests/unit_tests/vcf2consensus_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "from btb_tests import BtbTests\nimport shutil\nimport unittest\n\nclass Vcf2ConsensusTests(BtbTests):\n ref_consensus_filepath = './tests/data/edge-cases.fas'\n\n def test_vcf2consensus(self):\n \"\"\"\n Asserts vcf2Consensus.bash completes without errors on a minimal example\n \"\"\"\n # Copy data\n ref_filepath = self.temp_dirname + 'ref.fas'\n masked_filepath = self.temp_dirname + 'masked.bed'\n vcf_filepath = self.temp_dirname + 'edge-cases.vcf'\n vcf_gz_filepath = self.temp_dirname+'edge-cases.vcf.gz'\n regions_filepath = self.temp_dirname + 'regions.bed'\n bcf_filepath = self.temp_dirname + 'edge-cases.bcf'\n\n shutil.copy('./tests/data/tinyref.fas', ref_filepath) \n shutil.copy('./tests/data/edge-cases.bed', masked_filepath) \n shutil.copy('./tests/data/edge-cases.vcf', vcf_filepath) \n shutil.copy('./tests/data/edge-cases_regions.bed', regions_filepath) \n\n self.gzip(vcf_filepath, vcf_gz_filepath)\n self.index(vcf_gz_filepath)\n\n # Outputs\n consensus_filepath = self.temp_dirname + 'consensus.fas'\n snps_filepath = self.temp_dirname + 'snps.tab'\n\n # Test\n self.assertBashScript(0, ['./bin/vcf2Consensus.bash', \n ref_filepath, \n masked_filepath,\n regions_filepath,\n vcf_gz_filepath,\n consensus_filepath,\n snps_filepath,\n bcf_filepath,\n str(0.8),\n str('consensus')\n ])\n self.assertFileExists(snps_filepath)\n with open(consensus_filepath) as test_f, open(self.ref_consensus_filepath) as ref_f:\n self.assertMultiLineEqual(test_f.read(), ref_f.read())\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.6152046918869019, "alphanum_fraction": 0.6298245787620544, "avg_line_length": 32.52941131591797, "blob_id": "9e42ea33321d7c8814a6ec501fb63f414f942a2c", "content_id": "5459f05b56ddf91fb928fb882bd5e316b6d66ee8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1710, "license_type": "permissive", "max_line_length": 181, "num_lines": 51, "path": "/bin/mask.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#================================================================\n# Mask\n#================================================================\n#% SYNOPSIS\n#+ mask.bash rpt_mask bam masked\n#%\n#% DESCRIPTION\n#% Masking known repeats regions and sites with zero coverage\n#% Ensure that consensus only includes regions of the genome where there is high confidence\n#%\n#% INPUTS\n#% rpt_mask path to repeat mask\n#% vcf input path to vcf file\n#% masked output path to masked bed file\n#% regions output path to regions file (sites to keep)\n#% allsites input path to allsites bed file\n\n# Error handling\nset -eo pipefail\n\n# Inputs\nrpt_mask=$1\nvcf=$2\nmasked=$3\nregions=$4\nbam=$5\nallsites=$6\nMIN_READ_DEPTH=$7\nMIN_ALLELE_FREQUENCY_ALT=$8\nMIN_ALLELE_FREQUENCY_REF=$9\n\n# Construct a mask: \n# mask regions which don't have {sufficient evidence for alt AND sufficient evidence for the REF}\nbcftools filter -i \"(ALT!='.' && INFO/AD[1] < ${MIN_READ_DEPTH} && INFO/AD[0]/(INFO/AD[0]+INFO/AD[1]) <= ${MIN_ALLELE_FREQUENCY_REF}) ||\n (ALT!='.' && INFO/AD[1]/(INFO/AD[0]+INFO/AD[1]) < ${MIN_ALLELE_FREQUENCY_ALT} && INFO/AD[0]/(INFO/AD[0]+INFO/AD[1]) <= ${MIN_ALLELE_FREQUENCY_REF})\" $vcf -ov -o quality-mask.vcf\nbedtools merge -i quality-mask.vcf > quality-mask.bed\n\n# mash regions where there is zero coverage\nbedtools genomecov -bga -ibam $bam | grep -w \"0\\$\" | cut -f -3 > zerocov.bed\n\n# Merge with exisiting known repeat regions\ncat quality-mask.bed zerocov.bed $rpt_mask | \nsort -k1,1 -k2,2n |\nbedtools merge > $masked\n\n# Make bedfile of sites to keep\nbedtools subtract -a $allsites -b $masked > $regions\n\n# Cleanup\nrm quality-mask.vcf quality-mask.bed zerocov.bed\n" }, { "alpha_fraction": 0.573737382888794, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 22.571428298950195, "blob_id": "4b23fa85a8885ec37b63c29e35dba61d89130c8f", "content_id": "435db722550d005162bc00acbed83e983205a6a4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1485, "license_type": "permissive", "max_line_length": 75, "num_lines": 63, "path": "/tests/jobs/lod.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#================================================================\n# lod.bash\n#================================================================\n#\n#% DESCRIPTION\n#% Checks the pipeline response against specimens computationally mixed \n#% with real-world M. Bovis and Avium samples\n\n# Import\nsource tests/utils/aliases.bash\n\n# Params\ntotal_num_reads=6.5e5\noutcomes=(\"Pass\" \"Pass\" \"CheckRequired\" \"Contaminated\")\nprops=(\"1.0\" \"0.65\" \"0.60\" \"0.0\")\n\n# Args\nTESTCASE=$1\noutcome=${outcomes[$TESTCASE]}\nprop=${props[$TESTCASE]}\n\n# Download files\nmkdir -p fastq\n\nbovine_root=ftp://ftp.sra.ebi.ac.uk/vol1/fastq/ERR458/005/ERR4586795/\nbovine_read1=ERR4586795_1.fastq.gz\nbovine_read2=ERR4586795_2.fastq.gz\n\navium_root=ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR105/096/SRR10541896/\navium_read1=SRR10541896_1.fastq.gz\navium_read2=SRR10541896_2.fastq.gz\n\nwget -P fastq \\\n $bovine_root/$bovine_read1 \\\n $bovine_root/$bovine_read2 \\\n $avium_root/$avium_read1 \\\n $avium_root/$avium_read2\n\n# Combine\necho combining..\nname=lod-bovine-${prop}\ncombine_fastq --seed 1 \\\n $total_num_reads \\\n $prop \\\n fastq/$bovine_read1 \\\n fastq/$avium_read1 \\\n /reads/${name}_SX_R1_X.fastq.gz\n\ncombine_fastq --seed 1 \\\n $total_num_reads \\\n $prop \\\n fastq/$bovine_read2 \\\n fastq/$avium_read2 \\\n /reads/${name}_SX_R2_X.fastq.gz\n\n# Run nextflow\nnextflowtest\n\n# Check results\nWGS_CLUSTER_CSV=$(print_todays_wgs_cluster)\nassert_first_csv_row $WGS_CLUSTER_CSV \"Outcome\" \"$outcome\"\n" }, { "alpha_fraction": 0.6125654578208923, "alphanum_fraction": 0.6282722353935242, "avg_line_length": 26.285715103149414, "blob_id": "2ce60176a03fd27e126468b71df70d0fee1fea00", "content_id": "a9b5ceeaa5826ae7714f457ae3c58efc6410c5c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 955, "license_type": "permissive", "max_line_length": 85, "num_lines": 35, "path": "/tests/jobs/inclusivity.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#================================================================\n# inclusivity.bash\n#================================================================\n#\n#% DESCRIPTION\n#% Tests the nextflow pipeline on a minimal dataset\n\n# Import\nsource tests/utils/aliases.bash\n\n# Args\nTESTCASE=$1\n\ngroup=$(print_csv_value './tests/data/inclusivity_cases.csv' $TESTCASE group)\naccession=$(print_csv_value './tests/data/inclusivity_cases.csv' $TESTCASE accession)\n\n# Fetch SRA Data\nprefetch $accession -O ./\nfasterq-dump ./$accession\nrm ./$accession/*.sra\nrm -r ./$accession\n\ngzip ${accession}_1.fastq ${accession}_2.fastq\nmv ${accession}_1.fastq.gz /reads/${accession}_S1_R1_001.fastq.gz\nmv ${accession}_2.fastq.gz /reads/${accession}_S1_R2_001.fastq.gz\n\n# Run nextflow\nnextflowtest\n\n# Check results\nWGS_CLUSTER_CSV=$(print_todays_wgs_cluster)\nassert_first_csv_row $WGS_CLUSTER_CSV \"Outcome\" \"Pass\"\nassert_first_csv_row $WGS_CLUSTER_CSV \"group\" \"$group\"\n" }, { "alpha_fraction": 0.723433256149292, "alphanum_fraction": 0.7826975584030151, "avg_line_length": 96.73332977294922, "blob_id": "27594950da5db175dcbb1ff08002924bc1ec753f", "content_id": "21346d79d2fd7e8fcbf2b2dd9965ad126ec3f3d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1468, "license_type": "permissive", "max_line_length": 419, "num_lines": 15, "path": "/ReleaseProcess.md", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "\n# Release Process\n\nTo release a new version of the software, the `master` branch needs only to be merged into the `prod` branch. To perform this merge, a pull-request from the `master` branch into the `prod` branch needs to be made. Approval of pull-requests to `prod` is made by the CODEOWNER (Richard Ellis). The CODEOWNER is responsible for ensuring the code conforms to the reliability tests. A positive test result is required for approval.\n\nTo release a new version of the software:\n1. A developer makes a pull-request from the `master` to the `prod` branch. The CODEOWNER is automatically notified by e-mail.\n1. The CODEOWNER ensures the automated tests pass on the `master` branch and reviews the code changes.\n1. The CODEOWNER ensures that results for test datasets are as expected (as defined in APHA SOP MB.048)\n1. The CODEOWNER approves the pull-request if they are satisfied, or requests changes.\n1. The dev merges the `master` branch into `prod`\n1. Following approval, the developer tags the current head of `master` as the next version (see image below). Versions are numbered incrementally with integers, for example `v1`, `v2`, etc. This can be performed by navigating to the github `master` branch and selecting `Create a release`\n\n![image](https://user-images.githubusercontent.com/6979169/163342248-d41c9625-1c79-4463-9425-99522829cd31.png)\n\n![image](https://user-images.githubusercontent.com/6979169/163342279-40bf4673-6af9-4b35-adab-5ea15df601bc.png)\n\n" }, { "alpha_fraction": 0.5431177616119385, "alphanum_fraction": 0.5762852430343628, "avg_line_length": 24.680850982666016, "blob_id": "5bf9862125546674ceffcd7dcf74b4cb6b45045d", "content_id": "bc1a9b5f9d015821817569223809149ce3a575a9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1206, "license_type": "permissive", "max_line_length": 97, "num_lines": 47, "path": "/bin/trim.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#================================================================\n# Trim\n#================================================================\n#% SYNOPSIS\n#+ trim.bash read_1 read_2 trimmed_1 trimmed_2\n#%\n#% DESCRIPTION\n#% Trim adapter and low quality bases from fastq data\n#% Removes the adapters which are added during the lab processing and and any low quality data\n#%\n#% INPUTS\n#% adapters path to adapter sequence\n#% read_1 input path to first fastq read file\n#% read_2 input path to second fastq read file\n#% trimmed_1 output path to first trimmed fastq file\n#% trimmed_2 output path to second trimmed fafstq file\n\n# Error handling\nset -eo pipefail\n\nadapters=$1\nread_1=$2\nread_2=$3\ntrimmed_1=$4\ntrimmed_2=$5\n\n# Error if adapters file does not exist, as trimmomatic won't!\nif [[ ! -f $adapters ]]; then\n echo $adapter does not exist\n exit 1\nfi\n\njava -jar /usr/local/bin/trimmomatic.jar PE \\\n -threads 2 \\\n -phred33 \\\n $read_1 \\\n $read_2 \\\n $trimmed_1 \\\n fail1.fastq \\\n $trimmed_2 \\\n fail2.fastq \\\n ILLUMINACLIP:$adapters:2:30:10 \\\n SLIDINGWINDOW:10:20 \\\n MINLEN:36\n\nrm fail1.fastq fail2.fastq" }, { "alpha_fraction": 0.5684267282485962, "alphanum_fraction": 0.5905172228813171, "avg_line_length": 29.42622947692871, "blob_id": "0550afbe2c95f55190ae86b20064889bda8f30a8", "content_id": "d7d78526ec9755ec44176597854d8c189bc84210", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1856, "license_type": "permissive", "max_line_length": 111, "num_lines": 61, "path": "/bin/vcf2Consensus.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#================================================================\n# vcf2Consensus\n#================================================================\n#% SYNOPSIS\n#+ mask.bash rpt_mask bam masked\n#%\n#% DESCRIPTION\n#% Consensus calling and output snp table for snippy compatability \n#%\n#% INPUTS\n#% ref input path to reference genome (.fas)\n#% mask input path to mask (.bed)\n#% regions input path to regions file containing all regions for masking/filtering(.bed)\n#% vcf input path to variant (.vcf.gz)\n#% consensus output path to consensus file (.fas)\n#% snps output path to snps tab file (.tab)\n#% bcf output path to filtered bcf file (.bcf)\n\n# Error handling\nset -eo pipefail\n\n#=======\n# Inputs\nref=$1\nmask=$2\nregions=$3\nvcf=$4\nconsensus=$5\nsnps=$6\nbcf=$7\nMIN_ALLELE_FREQUENCY=$8\npair_id=$9\npublishDir=${10}\n\n\n# handle the case when the regions file is empty otherwise bcftools filter will fail\nif [ ! -s $regions ]; then\n\t# The file is empty.\n\techo \"LT708304-Mycobacteriumbovis-AF2122-97\t-1\t-1\" > $regions\t\nfi\n\n# Select SNPs\n# applies filter/mask and chooses SNP sites\nbcftools filter -i \"ALT!='.' && INFO/AD[1]/(INFO/AD[0]+INFO/AD[1]) >= ${MIN_ALLELE_FREQUENCY}\" $vcf -Ob -o $bcf\nbcftools index $bcf\n\n# Call Consensus\nbcftools consensus -f ${ref} -e 'TYPE=\"indel\"' -m $mask $bcf |\nsed \"/^>/ s/.*/>${pair_id}/\" > $consensus\n\n# Count Ns in consensus file\nncount=$(grep -o 'N' $consensus | wc -l)\necho -e \"Sample,Ncount,ResultLoc\" > ${pair_id}_ncount.csv\necho -e \"${pair_id},$ncount,$publishDir\" >> ${pair_id}_ncount.csv\n\n# Write SNPs table\necho -e 'CHROM\\tPOS\\tTYPE\\tREF\\tALT\\tEVIDENCE' > $snps\n\nbcftools query -R $regions -e 'TYPE=\"REF\"' -f '%CHROM,%POS,%TYPE,%REF,%ALT,%DP4\\n' $bcf |\nawk -F, '{print $1\"\\t\"$2\"\\t\"$3\"\\t\"$4\"\\t\"$5\"\\t\"$5\":\"$8+$9\" \"$4\":\"$6+$7}' >> $snps\n" }, { "alpha_fraction": 0.6819469332695007, "alphanum_fraction": 0.6842647194862366, "avg_line_length": 51.47297286987305, "blob_id": "baa7f5aad3127c95fcf51f14b63d02a7c3164f40", "content_id": "edc7b86ad0bdba0d27a46c1d8a3228e6ceb99a7f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3883, "license_type": "permissive", "max_line_length": 166, "num_lines": 74, "path": "/bin/combineCsv.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n# Merge the csv output files and determine whether samples are M.bovis positive or not, based on predetemined \n# thresholds for number and proportion of M.bovis reads.\n\nimport pandas as pd\nimport argparse\nimport getpass\nimport git\nimport os\nfrom datetime import datetime, date\n\ndef combine(assigned_csv, bovis_csv, ncount_csv, seq_run, commitId, read_threshold, abundance_threshold):\n\n date_out = date.today().strftime('%d%b%y')\n user = getpass.getuser()\n scriptpath = os.path.dirname(os.path.abspath(__file__))\n repo = git.Repo(scriptpath, search_parent_directories=True)\n \n #Read Assigned Clade csv and replace blank cells with 'NA'\n assigned_df = pd.read_csv(assigned_csv)\n assigned_df['Sample']=assigned_df['Sample'].astype(object)\n assignedround_df = assigned_df.round(2)\n\n #Read ncount csv\n ncount_df = pd.read_csv(ncount_csv)\n ncount_df['Sample']=ncount_df['Sample'].astype(object)\n\n # Read BovPos csv and change ID to either 'Negative' or 'Mycobacterium bovis',\n # depending on number and relative abundance of M.bovis reads.\n # Thresholds set by comparison with output from spoligotyping.\n # Fill empty value cells with zero \n # TODO: Potential that not all scenarios are covered by the options below, so need to add default ID outcome\n bovis_df = pd.read_csv(bovis_csv)\n bovis_df['Sample']=bovis_df['Sample'].astype(object)\n qbovis_df = bovis_df.round(2)\n qbovis_df.loc[(qbovis_df['TotalReads'] >= read_threshold) & (qbovis_df['Abundance'] >= abundance_threshold), 'ID'] = 'Mycobacterium bovis'\n qbovis_df.loc[(qbovis_df['TotalReads'] < read_threshold) & (qbovis_df['Abundance'] < abundance_threshold), 'ID'] = 'Negative'\n qbovis_df.loc[(qbovis_df['TotalReads'] < read_threshold) & (qbovis_df['Abundance'] > abundance_threshold), 'ID'] = 'Inconclusive'\n qbovis_df.loc[(qbovis_df['TotalReads'] > read_threshold) & (qbovis_df['Abundance'] < abundance_threshold), 'ID'] = 'Inconclusive'\n qbovis_df['TotalReads'].fillna('0', inplace = True)\n qbovis_df['Abundance'].fillna('0', inplace = True)\n qbovis_df['ID'].fillna('Negative', inplace = True)\n\n #Merge dataframes fill with appropriate Mycobacterium ID (Other, microti, bovis), then any remaining blank cells with 'NA'\n finalout_df = pd.merge(pd.merge(assignedround_df, ncount_df, on = 'Sample', how = 'left'), qbovis_df, on = 'Sample', how = 'outer')\n finalout_df.loc[(finalout_df['group'] == 'nonbTB' ) | (finalout_df['group'] == 'MicPin' ) | (finalout_df['group'] == 'Pinnipedii' ), 'ID' ] = 'Other Mycobacteria'\n finalout_df.loc[(finalout_df['group'] == 'Microti' ), 'ID' ] = 'Mycobacterium microti'\n finalout_df['ID'].fillna('Mycobacterium bovis', inplace = True)\n finalout_df.fillna('NA', inplace = True)\n finalout_df.set_index('Sample', inplace = True)\n finalout_df.sort_index(inplace = True)\n\n #Write to csv\n finalout_df.to_csv(\"{}_FinalOut_{}.csv\".format(seq_run, date_out))\n\n #Append log info\n with open(\"{}_FinalOut_{}.csv\".format(seq_run, date_out), \"a\") as outFile:\n outFile.write(\"# Operator: \" +user +\"\\n\" +\"# BovTB-nf commit: \" +commitId)\n outFile.close\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('assigned_csv', help='path to AssignedWGSClade.csv')\n parser.add_argument('bovis_csv', help='path to Bovis.csv')\n parser.add_argument('ncount_csv', help='path to ncount.csv')\n parser.add_argument('seq_run', help='Unique sequencer run number')\n parser.add_argument('commitId', help='Nextflow capture of git commit')\n parser.add_argument('--read_threshold', type=int, default=500, help='threshold for number of M.bovis reads')\n parser.add_argument('--abundance_threshold', type=int, default=1, help='threshold for M.bovis abundance')\n\n args = parser.parse_args()\n\n combine(**vars(args))\n" }, { "alpha_fraction": 0.6761133670806885, "alphanum_fraction": 0.7570850253105164, "avg_line_length": 29.875, "blob_id": "ba7e0ec0fe802320a2e5c9ccb00169587ecd5685", "content_id": "b85e87322bb36fd4a44b53f0a7eafec6ee44ae73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 247, "license_type": "permissive", "max_line_length": 88, "num_lines": 8, "path": "/docker/install-bedtools.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# bedtools\nwget https://github.com/arq5x/bedtools2/releases/download/v2.29.0/bedtools-2.29.0.tar.gz\ntar xzf bedtools-2.29.0.tar.gz\nrm -f bedtools-2.29.0.tar.gz\ncd bedtools2\nmake\ncd ..\nsudo ln -s $PWD/bedtools2/bin/bedtools /usr/local/bin/bedtools\n" }, { "alpha_fraction": 0.5019505620002747, "alphanum_fraction": 0.5305591821670532, "avg_line_length": 25.55172348022461, "blob_id": "78934ff4ba5183e8a9dd11b2c0b7ef00ab638b24", "content_id": "c6ec6e1e851b5cbaafdc47ae987b01a343778232", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 769, "license_type": "permissive", "max_line_length": 94, "num_lines": 29, "path": "/bin/map2Ref.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#================================================================\n# map2Ref\n#================================================================\n#% SYNOPSIS\n#+ map2Ref.bash ref read_1 read_2 mapped\n#%\n#% DESCRIPTION\n#% Map to reference sequence. Aligns the individiual sequence reads to the reference genome\n#%\n#% INPUTS\n#% ref path to input reference fasta file\n#% read_1 path to first input fastq read file\n#% read_2 path to second input fastq read file\n#% mapped path to output mapped bam file\n\n# Error handling\nset -eo pipefail\n\n# Args\nref=$1\nread_1=$2\nread_2=$3\nmapped=$4\n\n# Map to reference\nbwa mem -M -E 2 -t2 $ref $read_1 $read_2 |\nsamtools view -@2 -ShuF 2308 - |\nsamtools sort -@2 - -o $mapped" }, { "alpha_fraction": 0.5863007307052612, "alphanum_fraction": 0.5881152153015137, "avg_line_length": 33.4453125, "blob_id": "22fb8946cc6b99ac8efe2a82363ad3167483a18f", "content_id": "d1295da2a5e6d3dc460b309d017a228e246621d2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4409, "license_type": "permissive", "max_line_length": 142, "num_lines": 128, "path": "/tests/unit_tests/btb_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "from sys import stdout\nimport unittest\nimport subprocess\nimport tempfile\nimport os\nimport glob\nimport shutil\nimport subprocess\n\nimport Bio\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\n\nclass BtbTests(unittest.TestCase):\n \"\"\"\n Base class for btb-seq unit tests\n Contains tools that make writing unit tests for nextflow processes easier\n \"\"\"\n def setUp(self):\n \"\"\"\n Create new temporary directory\n \"\"\"\n self.temp_dir = tempfile.TemporaryDirectory()\n self.temp_dirname = self.temp_dir.__enter__() + '/'\n\n print('Temp Dir: ' + self.temp_dirname)\n\n def tearDown(self):\n \"\"\"\n Cleanup temporary directory.\n \"\"\"\n self.temp_dir.__exit__(None, None, None)\n\n def assertBashScript(self, expected_exit_code, cmd):\n \"\"\"\n Runs a bash script with exit on error (set -e) and throws an exception if the exit code doesn't match the expected \n \n Inputs: \n error_code <int>\n cmd <list> The command as a list of strings. eg ['hello-world.bash', '-name', 'Aaron']\n \"\"\"\n\n actual_exit_code = subprocess.run(['bash', '-e'] + cmd).returncode\n self.assertEqual(expected_exit_code, actual_exit_code)\n\n def assertFileExists(self, filepath):\n \"\"\"\n Raises an exception if the file does not exist\n \"\"\"\n if not os.path.exists(filepath):\n raise Exception(f\"File does not exist: {filepath}\")\n\n def sam_to_bam(self, sam_filepath, bam_filepath):\n # Convert to SAM to BAM\n with open(bam_filepath, 'w') as f:\n subprocess.call(['samtools', 'view', '-S', '-b', sam_filepath], stdout=f)\n \n def bam_to_sam(self, bam_filepath, sam_filepath):\n # Convert to BAM to SAM\n proc = subprocess.run(['samtools', 'view', '-h', '-o', sam_filepath, bam_filepath])\n self.assertEquals(0, proc.returncode)\n\n def index(self, variant_call_filepath, indexed_filepath=None):\n # Index .vcf/.vcf.gz/.bcf files\n if indexed_filepath is None:\n indexed_filepath = variant_call_filepath + '.csi'\n proc = subprocess.run(['bcftools', 'index', variant_call_filepath, '-o', indexed_filepath])\n self.assertEquals(0, proc.returncode)\n\n def copy_tinyreads(self, unzip=False):\n \"\"\"\n Copies tinyreads to the temporary directory that tests run in\n \"\"\"\n for read in glob.glob(r'./tests/data/tinyreads/*.fastq.gz'):\n shutil.copy2(read, self.temp_dirname)\n\n reads = glob.glob(self.temp_dirname + '*.fastq.gz')\n\n # Unzip\n if unzip:\n for read in reads:\n self.unzip(read)\n\n reads = [read[:-3] for read in reads]\n\n # Return path to files\n return reads\n\n def unzip(self, path):\n \"\"\" Unzip a .gz file inplace \"\"\"\n proc = subprocess.run(['gunzip', path])\n self.assertFalse(proc.returncode)\n\n def gzip(self, path, outpath=None):\n \"\"\" gzip VCF/BCF file writting output to outpath \"\"\"\n if not outpath:\n outpath = path + '.gz'\n with open(outpath, 'wb') as gzf:\n proc = subprocess.run(['bcftools', 'convert', '-O', 'z', path], \n stdout=gzf)\n self.assertFalse(proc.returncode)\n\n def write_fastq(self, filepath, seq_records):\n \"\"\"\n Write a fastq file to the filepath\n\n filepath: (str) filepath of output fastq file\n sequences: (list/str) a list of strings that represent each sequence. Can also provide just a string if there is only one sequence\n quality: (int) uniform phred33 quality score for each base\n \"\"\"\n with open(filepath, \"w\") as file:\n Bio.SeqIO.write(seq_records, file, \"fastq\")\n\n def read_fastq(self, filepath):\n \"\"\"\n Reads a fastq file and returns the sequence as a string\n Throws an exception if there is more than one record\n \"\"\"\n return str(SeqIO.read(filepath, \"fastq\").seq)\n\n def seq_record(self, seq_str, quality=93):\n \"\"\"\n Makes a new Seq Record with uniform quality from a string of ATCG's \n \"\"\"\n seq = SeqRecord(Seq(seq_str))\n seq.letter_annotations[\"phred_quality\"] = [quality]*len(seq)\n return seq\n" }, { "alpha_fraction": 0.7152974605560303, "alphanum_fraction": 0.7388455867767334, "avg_line_length": 53.29807662963867, "blob_id": "b93773da3bd83a9a37505ae2eb655ffe90720e81", "content_id": "0c06991c5524f99a30d70160073f9fd9b364c7e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5648, "license_type": "permissive", "max_line_length": 835, "num_lines": 104, "path": "/Readme.md", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# **btb-seq**\n\n<img src=\"https://user-images.githubusercontent.com/6979169/130202823-9a2484d0-c13f-4d86-9685-4bfe04bbf8c2.png\" width=\"90\">\n\n[![APHA-CSU](https://circleci.com/gh/APHA-CSU/btb-seq.svg?style=svg)](https://app.circleci.com/pipelines/github/APHA-CSU)\n\n`btb-seq` is the pipeline for APHA's processing of raw *Mycobacterium bovis* Whole Genome Sequencing (WGS) data. The pipeline uses [nextflow](https://www.nextflow.io/docs/latest/getstarted.html) to process batches (1 or more samples) of paired-end `fastq.gz` read files generated on an Illumina sequencer. \n\n## Running the pipeline - quick start\n\nTo get started quickly, just install [Nextflow](https://www.nextflow.io/) and [Docker](https://www.docker.com/) and run the pipeline using the following:\n\n```\nnextflow run APHA-CSU/btb-seq -with-docker aphacsubot/btb-seq --reads='path/to/input/directory' --outdir='path/to/output/directory'\n```\n\nThis will pull the code from this github repository and run the analysis using the pre-prepared docker image containing all required dependencies [here](https://hub.docker.com/r/aphacsubot/btb-seq).\n\nTo run the pipeline on a batch of samples, a directory containing raw `.fastq.gz` files is required (and defined using `--reads`). Each read-pair sample is represented by a pair of files named `*_R1*.fastq.gz` and `*_R2*.fastq.gz`. For example, to batch two samples named `bovis-a` and `bovis-b`, a directory containing `bovis-a_R1.fastq.gz`, `bovis-a_R2.fastq.gz`, `bovis-b_R1.fastq.gz` and `bovis-b_R2.fastq.gz`, is required. This can be also be an AWS s3 uri (denoted using `s3://..`) if required\n\nPipeline output is stored in a results directory (which can also be an s3 uri) that contains:\n- A summary csv file (`FinalOut.csv`) that contains the `Outcome` (see below), WGS Group (Clade) and other high-level metrics for each sample. \n- Consensus `fasta` files\n- Mapped `.bam` files\n- Variant call `.vcf` files\n- Kraken2/Bracken classification of non-*M. bovis* contaminants\n\n## Local Installation\n\nClone this github repository\n```\ngit clone https://github.com/APHA-CSU/btb-seq\n```\n\nTo install the software dependencies required in ubuntu, run\n```\nbash install.bash\n```\n\nThis script installs the following dependencies and adds symlinks to the `$PATH`: \n-\t`nextflow`\n-\t`FastUniq`\n-\t`Trimmomatic`\n-\t`bwa`\n-\t`samtools` and `bcftools`\n-\t`bedtools`\n-\t`Kraken2` (and database)\n-\t`Bracken`\n\n## Pipeline details\n\nThe pipeline processes data in several stages, as shown below. During the pre-processing stage duplicate reads, low quality bases and adapter sequences are removed from the fastq sample files. Following this, pre-processed reads are mapped to a reference genome (*M. bovis* AF2122), variant calling is performed, regions of poor mapping (both pre-defined and on a per-sample basis) are masked and the consensus genome sequence for the sample is generated. Samples are also assigned to a \"Clade\", representing *M. bovis* lineages known to be circulating in GB, based on sequence variation at ~3000 position in the genome. Data quality assessment assigns an \"Outcome\" to each sample by analysing data gathered during the pre-processing and alignment stages. The following \"Outcomes\" are used to signify subsequent lab processing steps:\n\n- **Pass**: The sample contains a known *M. bovis* WGS Cluster.\n- **Contaminated**: The sample contains contaminants\n- **Insufficient Data**: The sample contains insufficient data to allow accurate identification of *M. bovis* \n- **Check Required**: Further scrutiny of the output is needed as quality thresholds fall below certain criteria but is likely to contain *M. bovis*. \n\n![btb-seq](https://user-images.githubusercontent.com/9665142/173056645-d13ccafa-4738-4281-9a4f-13ff477e765f.png)\n\n\n## Validation\n\nThis pipeline has been accredited by the UK Accreditation Service (UKAS) to ISO17025 standard. It has also been internally validated, tested and approved against a dataset in excess of 10,000 samples that have been sequenced at APHA.\n\n\n## Automated Tests (Continuous integration)\n\nThe automated tests provided here ensure the software runs as expected. When changes are made to the code, these tests verify the pipeline is behaving as intended. The tests are automatically run by `.circleci` on each commit to the github repository. \n\n### How to run tests\n\nTo run a test\n```\nbash tests/jobs/NAME_OF_TEST.bash\n```\n\n### Unit Tests\n\nA number of small tests that asserts the functionality of individual components\n\n### Inclusivity Tests\n\nAsserts the `Outcome` and `WGS_CLUSTER` (clade) against samples uploaded by APHA to [ENA](https://www.ebi.ac.uk/ena/browser/view/PRJEB40340). \n\n### Limit of Detection (LoD)\n\nThe limit of detection test ensures mixtures of *M. avium* and *M. bovis* at varying proportions give the correct Outcome. This is performed by taking random reads from reference samples of *M. bovis* and *M. avium*.\n\n| *M. bovis* (%) | *M. avium* (%) | Outcome |\n| ------------- | ------------- | ------------- | \n| 100% | 0% | Pass | \n| 65% | 35% | Pass | \n| 60% | 40% | CheckRequired | \n| 0% | 100% | Contaminated | \n\n### Quality Test\n\nThe quality test ensures that low quality reads (<20) are not considered for variant calling and genotyping. This is performed by setting uniform quality values to a real-world *M. bovis* sample and asserting output. Low quality bases are removed from the sequence using `Trimmomatic`, which uses a sliding window that deletes reads when the average base quality drops below 20. A table of expected results is shown below.\n\n| Base Quality | Outcome | \n| ------------- | ------------- | \n| 19 | LowQualData | \n| 20 | Pass | \n" }, { "alpha_fraction": 0.59765625, "alphanum_fraction": 0.6223958134651184, "avg_line_length": 28.538461685180664, "blob_id": "655147dc623e4e2c5bbd085fe492012da95eda66", "content_id": "41dfcc5eda294897828c72578e0f9796f68524a6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 768, "license_type": "permissive", "max_line_length": 100, "num_lines": 26, "path": "/tests/unit_tests/map2Ref_tests.py", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "import unittest\nfrom btb_tests import BtbTests\n\nclass Map2RefTests(BtbTests):\n ref_path = './references/Mycbovis-2122-97_LT708304.fas'\n\n def test_map2ref(self):\n \"\"\"\n Asserts map2ref.bash completes on tinyreads without errors and produces a named bam file\n \"\"\" \n\n # Copy test data\n reads = self.copy_tinyreads(unzip=True)\n\n # Output Filenames\n output = self.temp_dirname + 'mapped.bam'\n\n # Pass case\n self.assertBashScript(0, ['./bin/map2Ref.bash', self.ref_path, reads[0], reads[1], output])\n self.assertFileExists(output)\n\n # Covert to SAM for visual checking\n self.bam_to_sam(output, self.temp_dirname+'mapped.sam')\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "alpha_fraction": 0.723849356174469, "alphanum_fraction": 0.7489539980888367, "avg_line_length": 33.14285659790039, "blob_id": "c9f3de75c4ec1c8a8a5129561097512d27b9517b", "content_id": "ccb6ce58ae49ea0489333a6b02b809f5f9627b75", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 239, "license_type": "permissive", "max_line_length": 72, "num_lines": 7, "path": "/docker/install-FastUniq.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# FastUniq\nwget https://sourceforge.net/projects/fastuniq/files/FastUniq-1.1.tar.gz\ntar xzf FastUniq-1.1.tar.gz && rm -f FastUniq-1.1.tar.gz\ncd FastUniq/source\nmake\ncd ../..\nsudo ln -s $PWD/FastUniq/source/fastuniq /usr/local/bin/fastuniq\n" }, { "alpha_fraction": 0.6782178282737732, "alphanum_fraction": 0.7673267126083374, "avg_line_length": 24.25, "blob_id": "495bf90451b06c048330785868f58d93a72afdde", "content_id": "80069b2dd033c33b5d98c3eeb9c91807880bc6b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 202, "license_type": "permissive", "max_line_length": 86, "num_lines": 8, "path": "/docker/install-samtools.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# samtools\nwget https://github.com/samtools/samtools/releases/download/1.10/samtools-1.10.tar.bz2\ntar xjf samtools-1.10.tar.bz2\nrm -f samtools-1.10.tar.bz2\ncd samtools-1.10\nmake\nsudo make install\ncd ..\n" }, { "alpha_fraction": 0.5814814567565918, "alphanum_fraction": 0.5935184955596924, "avg_line_length": 19.37735939025879, "blob_id": "98f6db10ba8bdcaf06de2e06bf35adc92a44a573", "content_id": "02b1e0703c7320656a5a4148f07c5ada57b3f837", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1080, "license_type": "permissive", "max_line_length": 82, "num_lines": 53, "path": "/docker/install-all-dependancies.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "set -e\n\n################## ARGS ##############################\n\nBIOTOOLS_PATH=~/biotools/\n\n\n################## DEPENDENCIES ######################\n\nsudo apt-get -y update && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y \\\n openjdk-11-jdk \\\n wget \\\n make \\\n git \\\n curl \\\n liblzma-dev \\\n libz-dev \\\n libncurses5-dev \\\n libncursesw5-dev \\\n libghc-bzlib-prof \\\n gcc \\\n unzip \\\n zlib1g-dev \\\n libncurses5-dev \\\n libbz2-dev \\\n liblzma-dev \\\n libcurl4-openssl-dev \\\n python3 \\\n python3-pip \\\n nano \\\n bc\n\n# python \npip3 install biopython numpy pandas gitpython\nsudo ln -s /usr/bin/python3 /usr/bin/python\n\n################## BIOTOOLS ######################\n\n\nmkdir -p $BIOTOOLS_PATH\ncp ./install*.*sh $BIOTOOLS_PATH\ncd $BIOTOOLS_PATH\n\nbash -e install-FastUniq.sh\nbash -e install-Trimmomatic.sh\nbash -e install-bwa.sh\nbash -e install-samtools.sh\nbash -e install-bcftools.sh\nbash -e install-bedtools.sh\nbash -e install-Kraken2.sh\nbash -e install-bracken.sh\nbash -e install-nextflow.sh\nbash -e install-sra-toolkit.sh\n" }, { "alpha_fraction": 0.5930435061454773, "alphanum_fraction": 0.5930435061454773, "avg_line_length": 29.3157901763916, "blob_id": "d92ca1efd5bf596ac0c1f435f7f6771294777ee9", "content_id": "d5f282b213e7bfb15da1910104f19bb9fbf69d00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 575, "license_type": "permissive", "max_line_length": 75, "num_lines": 19, "path": "/tests/utils/aliases.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#================================================================\n# aliases.bash\n#================================================================\n#\n#% DESCRIPTION\n#% A number of aliases useful for testing\nshopt -s expand_aliases\n\nalias nextflowtest=\"bash tests/utils/nextflowtest.bash\"\n\nalias print_todays_wgs_cluster=\"sh tests/utils/print_todays_wgs_cluster.sh\"\n\nalias assert_first_csv_row=\"python tests/utils/assert_first_csv_row.py\"\n\nalias combine_fastq=\"python tests/utils/combine_fastq.py\"\n\nalias print_csv_value=\"python tests/utils/print_csv_value.py\"" }, { "alpha_fraction": 0.7027027010917664, "alphanum_fraction": 0.7387387156486511, "avg_line_length": 36, "blob_id": "31da57eed16f162297675f9782c28075257084bd", "content_id": "368d994b87369e4980e41469f1b218c7099cbcc5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 111, "license_type": "permissive", "max_line_length": 48, "num_lines": 3, "path": "/docker/install-nextflow.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# Install nextflow.\ncat ./install-nextflow-20.7.1.bash | bash\nsudo ln -s $PWD/nextflow /usr/local/bin/nextflow\n" }, { "alpha_fraction": 0.4550408720970154, "alphanum_fraction": 0.4550408720970154, "avg_line_length": 32.45454406738281, "blob_id": "8892558ad1ef0c58fdfa04b9f9ceefb92e67988f", "content_id": "2b2334d3d5186a4d8206fb0d2e803a9e0bd49ba4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 367, "license_type": "permissive", "max_line_length": 89, "num_lines": 11, "path": "/tests/utils/print_todays_wgs_cluster.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/sh\n#\n#================================================================\n# print_todays_wgs_cluster.sh\n#================================================================\n#\n#% DESCRIPTION\n#% Prints the filepath of the WGS Cluster CSV if it were generated by nextflow today. \n\nTODAY=`date +%d%b%y`\necho /results/Results_reads_${TODAY}/reads_FinalOut_${TODAY}.csv" }, { "alpha_fraction": 0.6930894255638123, "alphanum_fraction": 0.7357723712921143, "avg_line_length": 36.61538314819336, "blob_id": "cf41d0ac8a6f854e569da93fbd5155e6e63e1b9e", "content_id": "e17d5f87433b297dcdaa0afc579ad634d8c8d797", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 492, "license_type": "permissive", "max_line_length": 104, "num_lines": 13, "path": "/docker/install-bracken.sh", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "# bracken\n\n# TODO: Need to look at alternate solutions running bracken. This works, and is the suggested approach, \n# but there must be a better solution than adding a symlink to the bracken src/ directory\n\nwget https://github.com/jenniferlu717/Bracken/archive/v2.6.0.tar.gz\ntar xzf v2.6.0.tar.gz\nrm -f v2.6.0.tar.gz\ncd Bracken-2.6.0\nsh ./install_bracken.sh ../bracken\ncd ..\nsudo ln -s $PWD/Bracken-2.6.0/bracken /usr/local/bin/bracken\nsudo ln -s $PWD/Bracken-2.6.0/src /usr/local/bin/src\n \n" }, { "alpha_fraction": 0.6608884334564209, "alphanum_fraction": 0.6885157227516174, "avg_line_length": 41.930233001708984, "blob_id": "9d66ac53ac94cb5f330fe04b1dc6362b2508219f", "content_id": "dd7dc89048a69ac1b538896ecb44fa3573ec7e67", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1846, "license_type": "permissive", "max_line_length": 147, "num_lines": 43, "path": "/bin/idNonBovis.bash", "repo_name": "APHA-CSU/BovTB-nf", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\n# Error handling\nset -eo pipefail\n\n# Identify any non-M.bovis samples using kraken\n# Samples with flag != 'Pass' are processed to detemine which microbe(s) are present \n# Bracken parses the output which is then sorted to generate a top 20 list of species\n# Presence / absence of M.bovis is also determined by parsing Bracken output\n\npair_id=$1\nkraken2db=$2\nlowmem=$3\n\noutcome=$(cat outcome.txt)\nif [ $outcome != \"Pass\" ]; then\nkraken2 --threads 2 --quick $lowmem --db $kraken2db --output - --report ${pair_id}_\"$outcome\"_kraken2.tab --paired trimmed_1.fastq trimmed_2.fastq \n\n# HACK: (AF) Ignore Bracken errors. Better to handle output from Kraken and have unit tests, \n# but easier let the pipeline pass while we are setting up validation tests.. \nset +e\n\nbracken -d $kraken2db -r 150 -l S -t 10 -i ${pair_id}_\"$outcome\"_kraken2.tab -o ${pair_id}_\"$outcome\"_bracken.out\nsed 1d ${pair_id}_\"$outcome\"_bracken.out | sort -t $'\\t' -k7,7 -nr - | head -20 > ${pair_id}_\"$outcome\"_brackensort.tab\nbracken -d $kraken2db -r150 -l S1 -i ${pair_id}_\"${outcome}\"_kraken2.tab -o ${pair_id}_\"$outcome\"-S1_bracken.out\n( sed -u 1q; sort -t $'\\t' -k7,7 -nr ) < ${pair_id}_\"$outcome\"-S1_bracken.out > ${pair_id}_\"$outcome\"-S1_brackensort.tab\n# Need bovis to be the top Mycobacterium variant for better confidence in confiming M bovis ID - reduce false positives\nMycoPos=$(grep -m 1 'Mycobacterium' ${pair_id}_\"$outcome\"-S1_brackensort.tab)\nBovPos=$(echo $MycoPos | grep 'variant bovis' |\n awk '{printf $1\" \"$2\" \"$3\" \"$4\",\"$9\",\" \"%.3f\", ($10*100)}' || true)\n\necho \"Sample,ID,TotalReads,Abundance\" > ${pair_id}_bovis.csv\necho \"${pair_id},\"$BovPos\"\" >> ${pair_id}_bovis.csv\n\n# HACK: see above\nset -e\n\nelse\necho \"ID not required\"\necho \"Sample,ID,TotalReads,Abundance\" > ${pair_id}_bovis.csv\nfi\nrm `readlink trimmed_1.fastq`\nrm `readlink trimmed_2.fastq`\n" } ]
47
Stephen-Pierre/btc_price
https://github.com/Stephen-Pierre/btc_price
b9f8bf3fb0822c70f1fc4ae1535555f242212ae3
1c94f3f956b2d2cf0680e3f337fcf16bdaa08193
6ed37f6f67fb1742876901b2463520ea55eeca26
refs/heads/main
2023-04-28T20:00:00.524800
2021-05-24T02:09:16
2021-05-24T02:09:16
370,201,130
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5922844409942627, "alphanum_fraction": 0.6187594532966614, "avg_line_length": 29.4761905670166, "blob_id": "5da1583c1af426cae8b224e397ce27dd720b2090", "content_id": "a0855068f9885474a48aca30462d7560231eec5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1322, "license_type": "no_license", "max_line_length": 107, "num_lines": 42, "path": "/src/crawl_okex.py", "repo_name": "Stephen-Pierre/btc_price", "src_encoding": "UTF-8", "text": "import requests\r\nimport json\r\nimport time\r\nfrom selenium import webdriver\r\nfrom selenium.webdriver.common.by import By\r\nfrom selenium.webdriver.support.ui import WebDriverWait\r\nfrom selenium.webdriver.support import expected_conditions as EC\r\n\r\n\r\ndef get_now_price():\r\n headers = {\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '\r\n 'Chrome/73.0.3679.0 Safari/537.36',\r\n 'Connection': 'close'\r\n }\r\n url = 'http://www.okex.com/api/index/v5/BTC-USD/constituents'\r\n response = requests.get(url=url, headers=headers)\r\n content = json.loads(response.text)\r\n # print(content)\r\n price = content['data']['last']\r\n print(price)\r\n\r\n\r\ndef get_now_price_by_selenium():\r\n url = 'https://www.okex.com/markets/prices'\r\n attr = 'last-num'\r\n browser = webdriver.Chrome()\r\n browser.get(url)\r\n WebDriverWait(browser, 60).until(\r\n EC.presence_of_element_located((By.CLASS_NAME, attr))\r\n )\r\n while True:\r\n price = browser.find_element_by_xpath(\"//div[@class='token-list']//tr//td//div[@class='last-num']\")\r\n print(price.text)\r\n time.sleep(0.2)\r\n\r\n\r\nif __name__ == '__main__':\r\n while True:\r\n get_now_price()\r\n time.sleep(0.01)\r\n # get_now_price_by_selenium()\r\n" }, { "alpha_fraction": 0.6655573844909668, "alphanum_fraction": 0.6722129583358765, "avg_line_length": 24.130434036254883, "blob_id": "1dd383b1b8437ffc15d38033fb676d2d5b1cfeb0", "content_id": "102cab33346daf44cf5d053dbd440dfec95d8055", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 601, "license_type": "no_license", "max_line_length": 66, "num_lines": 23, "path": "/main.py", "repo_name": "Stephen-Pierre/btc_price", "src_encoding": "UTF-8", "text": "import threading\r\nfrom src import okex_websocket\r\nfrom btc_platform import workplatform\r\n# from multiprocessing import Process\r\n\r\n\r\ndef main():\r\n # workplatform.main()\r\n threads = []\r\n thread_1 = threading.Thread(target=okex_websocket.subscribe())\r\n\r\n thread_2 = threading.Thread(target=workplatform.main())\r\n threads.append(thread_2)\r\n threads.append(thread_1)\r\n for thread in threads:\r\n thread.start()\r\n\r\n\r\n# Press the green button in the gutter to run the script.\r\nif __name__ == '__main__':\r\n main()\r\n\r\n# See PyCharm help at https://www.jetbrains.com/help/pycharm/\r\n" }, { "alpha_fraction": 0.4828537702560425, "alphanum_fraction": 0.48797792196273804, "avg_line_length": 22.751218795776367, "blob_id": "573e8ea997ef9056c071c7def039a5611a9b398b", "content_id": "c156fc2183a5908074ce50c5f273de6af105fcbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5074, "license_type": "no_license", "max_line_length": 83, "num_lines": 205, "path": "/src/okex_websocket.py", "repo_name": "Stephen-Pierre/btc_price", "src_encoding": "UTF-8", "text": "import time\r\nimport queue\r\nimport websocket\r\nimport json\r\n\r\n\r\ndef subscribe_okex_btc_usdt():\r\n msg = {\r\n \"op\": \"subscribe\",\r\n \"args\": [\r\n {\r\n \"channel\": \"tickers\",\r\n \"instId\": \"BTC-USDT\"\r\n },\r\n ]\r\n }\r\n\r\n ws = websocket.create_connection('wss://ws.okex.com:8443/ws/v5/public')\r\n ws.send(json.dumps(msg))\r\n while True:\r\n yield ws.recv()\r\n\r\n\r\ndef subscribe_okex_eth_usdt():\r\n msg = {\r\n \"op\": \"subscribe\",\r\n \"args\": [\r\n {\r\n \"channel\": \"tickers\",\r\n \"instId\": \"ETH-USDT\"\r\n }\r\n ]\r\n }\r\n\r\n ws = websocket.create_connection('wss://ws.okex.com:8443/ws/v5/public')\r\n ws.send(json.dumps(msg))\r\n while True:\r\n yield ws.recv()\r\n\r\n\r\ndef subscribe_okex_okb_usdt():\r\n msg = {\r\n \"op\": \"subscribe\",\r\n \"args\": [\r\n {\r\n \"channel\": \"tickers\",\r\n \"instId\": \"OKB-USDT\"\r\n }\r\n ]\r\n }\r\n\r\n ws = websocket.create_connection('wss://ws.okex.com:8443/ws/v5/public')\r\n ws.send(json.dumps(msg))\r\n while True:\r\n yield ws.recv()\r\n\r\nprice_dict = {\r\n 'BTC-USDT': 'loading',\r\n 'ETH-USDT': 'loading',\r\n 'DOGE-USDT': 'loading',\r\n 'ADA-USDT': 'loading',\r\n 'XRP-USDT': 'loading',\r\n 'USDT-USDK': 'loading',\r\n 'DOT-USDT': 'loading',\r\n 'ICP-USDT': 'loading',\r\n 'BCH-USDT': 'loading',\r\n 'LTC-USDT': 'loading',\r\n 'LINK-USDT': 'loading',\r\n 'XLM-USDT': 'loading',\r\n 'ETC-USDT': 'loading',\r\n 'THETA-USDT': 'loading',\r\n 'MATIC-USDT': 'loading',\r\n 'TRX-USDT': 'loading',\r\n 'UNI-USDT': 'loading',\r\n 'EOS-USDT': 'loading',\r\n 'FIL-USDT': 'loading',\r\n 'SHIB-USDT': 'loading',\r\n 'USDC-USDT': 'loading',\r\n 'XMR-USDT': 'loading',\r\n 'OKB-USDT': 'loading',\r\n 'NEO-USDT': 'loading',\r\n 'AAVE-USDT': 'loading',\r\n 'BSV-USDT': 'loading',\r\n 'ALGO-USDT': 'loading',\r\n 'KSM-USDT': 'loading',\r\n 'LEO-USDT': 'loading',\r\n 'CEL-USDT': 'loading',\r\n 'ATOM-USDT': 'loading',\r\n 'IOTA-USDT': 'loading',\r\n 'CRO-USDT': 'loading',\r\n 'XTZ-USDT': 'loading',\r\n 'BTT-USDT': 'loading',\r\n 'LUNA-USDT': 'loading',\r\n 'WBTC-USDT': 'loading',\r\n 'MKR-USDT': 'loading',\r\n 'KLAY-USDT': 'loading',\r\n 'XEM-USDT': 'loading',\r\n 'DASH-USDT': 'loading',\r\n 'WAVES-USDT': 'loading',\r\n 'COMP-USDT': 'loading',\r\n 'SNX-USDT': 'loading',\r\n 'ZEC-USDT': 'loading',\r\n 'DCR-USDT': 'loading',\r\n 'HBAR-USDT': 'loading',\r\n 'CHZ-USDT': 'loading',\r\n 'EGLD-USDT': 'loading',\r\n 'DAI-USDT': 'loading',\r\n 'SUSHI-USDT': 'loading',\r\n 'ZIL-USDT': 'loading',\r\n 'SOL-USDT': 'loading',\r\n 'YFI-USDT': 'loading',\r\n 'ENJ-USDT': 'loading',\r\n 'BTG-USDT': 'loading',\r\n 'QTUM-USDT': 'loading',\r\n 'BAT-USDT': 'loading',\r\n 'MANA-USDT': 'loading',\r\n 'DGB-USDT': 'loading',\r\n 'ZEN-USDT': 'loading',\r\n 'STX-USDT': 'loading',\r\n 'GRT-USDT': 'loading',\r\n 'ONT-USDT': 'loading',\r\n 'NANO-USDT': 'loading',\r\n 'OKT-USDT': 'loading',\r\n 'SC-USDT': 'loading',\r\n 'UMA-USDT': 'loading',\r\n 'OMG-USDT': 'loading',\r\n 'ZRX-USDT': 'loading',\r\n 'ICX-USDT': 'loading',\r\n 'NEAR-USDT': 'loading',\r\n 'KISHU-USDT': 'loading',\r\n 'CTC-USDT': 'loading',\r\n 'RVN-USDT': 'loading',\r\n 'BCD-USDT': 'loading',\r\n 'ANC-USDT': 'loading',\r\n 'CELO-USDT': 'loading',\r\n 'LSK-USDT': 'loading',\r\n 'IOST-USDT': 'loading',\r\n 'FTM-USDT': 'loading',\r\n 'PAX-USDT': 'loading',\r\n 'AVAX-USDT': 'loading',\r\n 'LRC-USDT': 'loading',\r\n 'XCH-USDT': 'loading',\r\n 'SUN-USDT': 'loading',\r\n 'LPT-USDT': 'loading',\r\n 'REN-USDT': 'loading',\r\n 'KNC-USDT': 'loading',\r\n 'BCHA-USDT': 'loading',\r\n 'TUSD-USDT': 'loading',\r\n 'SNT-USDT': 'loading',\r\n 'FLOW-USDT': 'loading',\r\n 'RSR-USDT': 'loading',\r\n 'GLM-USDT': 'loading',\r\n 'BNT-USDT': 'loading',\r\n 'AKITA-USDT': 'loading',\r\n 'CFX-USDT': 'loading',\r\n 'MCO-USDT': 'loading',\r\n 'ARDR-USDT': 'loading',\r\n}\r\n\r\ndef subscribe_all():\r\n msg = {\r\n \"op\": \"subscribe\",\r\n \"args\": [{\"channel\": \"tickers\", \"instId\": x} for x in price_dict.keys()]\r\n }\r\n print(msg)\r\n\r\n ws = websocket.create_connection('wss://ws.okex.com:8443/ws/v5/public')\r\n ws.send(json.dumps(msg))\r\n while True:\r\n yield ws.recv()\r\n\r\n\r\n\r\n\r\n\r\ndef main():\r\n res = subscribe_all()\r\n while True:\r\n # for i in range(6):\r\n response = json.loads(next(res))\r\n try:\r\n price_dict[response['data'][0]['instId']] = response['data'][0]['last']\r\n yield price_dict\r\n except KeyError:\r\n pass\r\n # time.sleep(2)\r\n\r\n\r\nq = queue.Queue()\r\n\r\n\r\ndef generate_queue():\r\n res = subscribe_all()\r\n while True:\r\n response = json.loads(next(res))\r\n try:\r\n price_dict[response['data'][0]['instId']] = response['data'][0]['last']\r\n q.put(price_dict)\r\n print(q.get())\r\n except KeyError:\r\n pass\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n" }, { "alpha_fraction": 0.5543328523635864, "alphanum_fraction": 0.5928473472595215, "avg_line_length": 19.382352828979492, "blob_id": "9351d6be6a58f0ca534ebfaba30e1fcc3ed76ca4", "content_id": "08029d2199d84964374aea6537c16d848df8d691", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 61, "num_lines": 34, "path": "/btc_platform/workplatform.py", "repo_name": "Stephen-Pierre/btc_price", "src_encoding": "UTF-8", "text": "import tkinter as tk\r\nfrom src import okex_websocket\r\n\r\nws = okex_websocket.subscribe()\r\n\r\n\r\ndef update_value():\r\n global ws\r\n label_2['text'] = next(ws)\r\n top.after(1000, update_value())\r\n\r\n\r\ntop = tk.Tk()\r\ntop.title('BTC-index')\r\ntop.geometry('1200x600')\r\nlabel_1 = tk.Label(top, text='BTC-USTD:', font=(\"宋体\", 14))\r\nlabel_1.grid(row=0, column=0)\r\nprint('here')\r\nlabel_2 = tk.Label(top, text=next(ws), font=(\"宋体\", 14))\r\nlabel_2.grid(row=0, column=1)\r\n\r\ntop.after(1000, update_value())\r\n\r\ntop.mainloop()\r\n\r\n\r\n# if __name__ == '__main__':\r\n\r\n # t = threading.Thread(target=okex_websocket.subscribe())\r\n # t.daemon = True\r\n # t.start()\r\n # m = threading.Thread(target=main())\r\n # m.start()\r\n # main()\r\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 16.18181800842285, "blob_id": "97609c5ae4aeb090332bad5b707203eb83805f28", "content_id": "78d61c9e77c6a9ee6c2b5d0602407ba767fc0be4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 45, "num_lines": 11, "path": "/src/get_value.py", "repo_name": "Stephen-Pierre/btc_price", "src_encoding": "UTF-8", "text": "from okex_websocket import q, generate_queue\r\nimport threading\r\n\r\nt = threading.Thread(target=generate_queue())\r\nt.setDaemon()\r\nt.start()\r\n\r\n\r\nwhile not q.empty():\r\n val = q.get()\r\n print(val)" }, { "alpha_fraction": 0.5929798483848572, "alphanum_fraction": 0.6228528618812561, "avg_line_length": 36.25714111328125, "blob_id": "8784b91588fd163d61622a9e2f0a046da4ea2698", "content_id": "ccc36c8886d1555563546b5d1ce03e73cd2f57f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1379, "license_type": "no_license", "max_line_length": 130, "num_lines": 35, "path": "/src/test.py", "repo_name": "Stephen-Pierre/btc_price", "src_encoding": "UTF-8", "text": "import tkinter as tk\r\nfrom okex_websocket import price_dict, main\r\n\r\nm = main()\r\n\r\n\r\ndef refreshText():\r\n for i in range(len(price_dict.keys())):\r\n globals()[list(price_dict.keys())[i] + 'price']['text'] = next(m)[list(price_dict.keys())[i]]\r\n windows.after(100, refreshText)\r\n\r\n\r\nwindows = tk.Tk()\r\nwindows.geometry('500x500') ## 规定窗口大小500*500像素\r\n\r\nfor i in range(len(price_dict.keys())):\r\n # print(price_dict.keys())\r\n globals()[list(price_dict.keys())[i]] = tk.Label(windows, text=list(price_dict.keys())[i]+':', font=(\"宋体\", 10))\r\n globals()[list(price_dict.keys())[i]].grid(row=i, column=0)\r\n globals()[list(price_dict.keys())[i] + 'price'] = tk.Label(windows, text=next(m)[list(price_dict.keys())[i]], font=(\"宋体\", 10))\r\n globals()[list(price_dict.keys())[i] + 'price'].grid(row=i, column=1)\r\n\r\n# label_btc = tk.Label(windows, text=\"BTC-USTD:\", font=(\"宋体\", 10))\r\n# label_btc.grid(row=0, column=1)\r\n# label_btc_price = tk.Label(windows, text=next(m)['BTC-USDT'], font=(\"宋体\", 10))\r\n# label_btc_price.grid(row=1, column=1)\r\n\r\n# label_eth = tk.Label(windows, text=\"ETH-USTD:\", font=(\"宋体\", 10))\r\n# label_eth.grid(row=2, column=1)\r\n# label_eth_price = tk.Label(windows, text=next(m)['ETH-USDT'], font=(\"宋体\", 10))\r\n# label_eth_price.grid(row=3, column=1)\r\n\r\n\r\nwindows.after(100, refreshText)\r\nwindows.mainloop()\r\n" }, { "alpha_fraction": 0.6014943718910217, "alphanum_fraction": 0.6052303910255432, "avg_line_length": 21.676469802856445, "blob_id": "25da3dd00232fe88cd963b5d42b803b6f8a9144f", "content_id": "b21b5666f9282cd88798b3fcbe7f9772d62656a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 803, "license_type": "no_license", "max_line_length": 61, "num_lines": 34, "path": "/common/global_price.py", "repo_name": "Stephen-Pierre/btc_price", "src_encoding": "UTF-8", "text": "from src import okex_websocket\r\nimport json\r\n\r\n\r\nbtc_usdt = okex_websocket.subscribe_okex_btc_usdt()\r\neth_usdt = okex_websocket.subscribe_okex_eth_usdt()\r\nokb_usdt = okex_websocket.subscribe_okex_okb_usdt()\r\n\r\n\r\ndef process_okex_btc_value():\r\n global btc_usdt\r\n try:\r\n price = json.loads(next(btc_usdt))['data'][0]['last']\r\n return price\r\n except KeyError:\r\n return 'loading'\r\n\r\n\r\ndef process_okex_eth_value():\r\n global eth_usdt\r\n try:\r\n price = json.loads(next(eth_usdt))['data'][0]['last']\r\n return price\r\n except KeyError:\r\n return 'loading'\r\n\r\n\r\ndef process_okex_okb_value():\r\n global eth_usdt\r\n try:\r\n price = json.loads(next(okb_usdt))['data'][0]['last']\r\n return price\r\n except KeyError:\r\n return 'loading'" } ]
7
lorenzthimann/weeklyreview2
https://github.com/lorenzthimann/weeklyreview2
91bb7acbed6267bd469a5aee7d3c2234417b1902
191f65543c3e6a6ca47e088d5c2a5df34e52899e
e0afb9ec42e2a7c5c6a12fa5516396dd80c9a596
refs/heads/master
2022-12-14T13:28:33.749525
2020-08-29T08:51:52
2020-08-29T08:51:52
291,234,512
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5505743622779846, "alphanum_fraction": 0.5757915377616882, "avg_line_length": 32.61165237426758, "blob_id": "8b8e703a98d220631ecbc16e9ce76d4600d8b949", "content_id": "cec5d9ab08ee087ac3503d79e6cef89ead6840e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3569, "license_type": "no_license", "max_line_length": 278, "num_lines": 103, "path": "/weekly_review.py", "repo_name": "lorenzthimann/weeklyreview2", "src_encoding": "UTF-8", "text": "\r\ni = 9 # delete tha\r\nimport openpyxl\r\n# WEEK NB IS SET TO += 15 !!\r\nfrom openpyxl import Workbook\r\nfrom openpyxl.styles import Color, PatternFill, Font, Border\r\nfrom openpyxl.styles import colors\r\nfrom openpyxl.cell import Cell\r\nfrom datetime import date\r\n\r\nalphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\r\n\r\nwb = openpyxl.load_workbook('weekly_review.xlsx')\r\n\r\n\r\n# grab the active worksheet\r\nws = wb.active\r\n# creating the week in the lines\r\n\r\ni_for_content = 32\r\ni_for_cell = 2\r\nwhile i_for_content < 53:\r\n i_for_cell = str(i_for_cell)\r\n cell = \"A\" + i_for_cell\r\n i_for_cell = int(i_for_cell)\r\n ws[cell] = i_for_content\r\n i_for_cell += 1\r\n i_for_content += 1\r\n\r\n\r\n\r\n\r\n# put the habits on the 1st line\r\nhabits = [\"Carnegie\", \"Drink\", \"Use transportation\", \"Intresting TgB\", \"Beautiful notebooks\", \"fr./g.\", \"c*n*\", \"passionate + part.\", \"Music and places\", \"grat\", \"home: f., (G), in advance, autotests, efficace...\"]\r\nindex_for_habits = 0\r\nindex_for_alphabet = 0\r\nwhile index_for_habits < len(habits):\r\n cell = str(alphabet[index_for_alphabet + 1].upper()) + \"1\"\r\n ws[cell] = habits[index_for_habits]\r\n index_for_alphabet += 1\r\n index_for_habits += 1\r\n\r\nws[\"B1\"] = habits[0]\r\nws[\"C1\"] = habits[1]\r\nws[\"D1\"] = habits[2]\r\nws[\"E1\"] = habits[3]\r\nws[\"F1\"] = habits[4]\r\nws[\"G1\"] = habits[5]\r\nws[\"H1\"] = habits[6]\r\nws[\"I1\"] = habits[7]\r\nws[\"J1\"] = habits[8]\r\nws[\"K1\"] = habits[9]\r\n\r\nws[\"N1\"] = \"home: f., (G), in advance, autotests, wllm...\"\r\n\r\n\r\n\r\n\r\nweek_number = weekNumber = date.today().isocalendar()[1] \r\ncarnegie = input(f\"{habits[0]} : \")\r\ndrink = input(f\"{habits[1]} : \")\r\nuse_transportation = input(f\"{habits[2]} : \")\r\ntgb = input(f\"{habits[3]} : \")\r\nnotebooks = input(f\"{habits[4]} : \")\r\nfr_g = input(f\"{habits[5]} : \")\r\nc_n = input(f\"{habits[6]} : \")\r\npassionate = input(f\"{habits[7]} : \")\r\nmusic = input(f\"{habits[8]} : \")\r\ngrat = input(f\"{habits[9]} : \")\r\nhome = input(f\"{habits[10]} : \")# habits = [\"Carnegie\", \"Drink\", \"Use transportation\", \"S: podcasts, videos, P...\", \"Intresting TgB\", \"Beautiful notebooks\", \"fr./g.\", \"c*n*\", \"passionate + part.\", \"Music and places\", \"grat\", \"home: f., (G), in advance, autotests, efficace...\"]\r\n\r\ntodays_line = int(week_number) #- 33 # to change as well\r\nevaluations = [carnegie, drink, use_transportation, tgb, notebooks, fr_g, c_n, passionate, music, grat, home]\r\n\r\nindex = 0\r\nredFill = PatternFill(start_color='FFFF0000',\r\n end_color='FFFF0000',\r\n fill_type='solid')\r\norangeFill = PatternFill(start_color='F79D00',\r\n end_color='F79D00',\r\n fill_type='solid')\r\nblueFill = PatternFill(start_color='0A9EFF',\r\n end_color='0A9EFF',\r\n fill_type='solid')\r\ngreenFill = PatternFill(start_color='98F50E', \r\n end_color='98F50E',\r\n fill_type='solid')\r\n\r\nwhile index < len(evaluations):\r\n evaluation = evaluations[index]\r\n cell_to_handle = alphabet[index + 1].upper() + str(todays_line - 30 )\r\n print(cell_to_handle)\r\n if evaluation == \"1\":\r\n ws[cell_to_handle].fill = redFill\r\n elif evaluation == \"2\":\r\n ws[cell_to_handle].fill = orangeFill\r\n elif evaluation == \"3\":\r\n ws[cell_to_handle].fill = blueFill\r\n elif evaluation == \"4\":\r\n ws[cell_to_handle].fill = greenFill\r\n print(\"cell to handle\", cell_to_handle)\r\n index += 1\r\nwb.save(\"weekly_review.xlsx\")\r\n# create new ws for txts habits\r\n\r\n" } ]
1
LanQ/stockcal
https://github.com/LanQ/stockcal
9a2eaaa7f292052ca7c2c05b424ad602e2277efe
158e5422f3b794fd3598d78448192fa50bdb7f76
9d0a00d5e6898c43d820d12a03298830a1823fee
refs/heads/master
2022-12-10T19:14:30.009250
2018-06-23T04:23:43
2018-06-23T04:23:43
136,994,601
0
0
null
2018-06-12T00:10:50
2018-06-23T04:24:03
2022-07-06T19:48:45
Python
[ { "alpha_fraction": 0.45402297377586365, "alphanum_fraction": 0.6896551847457886, "avg_line_length": 14.17391300201416, "blob_id": "568f10f9ab16b8e11846f677034b3fb6b6b078a6", "content_id": "a968cd05b5c26313cae9c90b274083abbdaa1092", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 348, "license_type": "no_license", "max_line_length": 22, "num_lines": 23, "path": "/requirements.txt", "repo_name": "LanQ/stockcal", "src_encoding": "UTF-8", "text": "beautifulsoup4==4.6.0\nbs4==0.0.1\ncertifi==2018.4.16\nchardet==3.0.4\nclick==6.7\nFlask==1.0.2\nFlask-WTF==0.14.2\ngunicorn==19.8.1\nidna==2.6\nitsdangerous==0.24\nJinja2==2.10\nlxml==4.2.1\nMarkupSafe==1.0\nnumpy==1.14.3\npandas==0.23.0\npython-dateutil==2.7.3\npytz==2018.4\nrequests==2.18.4\nsix==1.11.0\ntushare==1.2.2\nurllib3==1.22\nWerkzeug==0.14.1\nWTForms==2.2" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5656565427780151, "avg_line_length": 32, "blob_id": "5f5a2567baacc4cd7f65186a7548aabe1e884603", "content_id": "c30e13a955661cf1866f5ff1b490e96375feb39c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 396, "license_type": "no_license", "max_line_length": 86, "num_lines": 12, "path": "/templates/stock_data.html", "repo_name": "LanQ/stockcal", "src_encoding": "UTF-8", "text": "<h1>Hello {% if code %}{{code}} {% else %} Code! {% endif %} </h1>\n\n<form method=\"POST\" action=\"/\">\n {{ form.csrf_token }}\n {{ form.code.label }} {{ form.code(size=20) }}\n {{ form.start_date.label }}{{ form.start_date }}\n {{ form.submit()}}\n</form>\n\n{% if result %} {{result | safe}} {% endif %}\n\n<a target=\"_blank\" href=\"https://dashboard.heroku.com/apps\">heroku apps management</a>\n" }, { "alpha_fraction": 0.6142376065254211, "alphanum_fraction": 0.6277056336402893, "avg_line_length": 27.875, "blob_id": "a41f9a8ae32613049f94710141bf9f50caf4d86e", "content_id": "babce96a11897a831984096a0d9e8210e0f3590b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2095, "license_type": "no_license", "max_line_length": 120, "num_lines": 72, "path": "/stock.py", "repo_name": "LanQ/stockcal", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom flask import Flask\nfrom flask import render_template\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField\nfrom wtforms.validators import DataRequired\n\nimport tushare as ts\nimport pandas as pd\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'hard to guess string'\n\nclass MyForm(FlaskForm):\n code = StringField(u'代码', default='600109', validators=[DataRequired()])\n start_date = StringField(u'起始日期', default='2016-01-01', validators=[DataRequired()]) \n submit = SubmitField(u'提交')\n\[email protected]('/', methods=['GET', 'POST'])\ndef index():\n\tcode = None\n\tform = MyForm()\n\tcode_list = []\n\trecord = pd.DataFrame()\n\trecords = pd.DataFrame()\n\tresult = None\n\n\tif form.validate_on_submit():\n\t\tcode_list = form.code.data.split(',')\n\t\tform.code.data = ''\n\t\t\n\t\tfor code in code_list:\n\t\t\ttry:\n\t\t\t\trecord = ts.get_k_data(code, ktype='W', start='2016-01-01')\n\t\t\t\t\t\t\t\t\n\t\t\t\trecord_decr = record.describe()\n\t\t\t\trecord_decr_filter = record_decr.loc[['mean', 'min', 'max', 'low']]\n\t\t\t\t\n\t\t\t\trecord_custom = pd.Series([code,\\\n\t\t\t\tfloat(record[-1:]['close'].values),\\\n\t\t\t\trecord_decr_filter.loc['mean', 'high'],\\\n\t\t\t\trecord_decr_filter.loc['mean', 'low'],\\\n\t\t\t\trecord_decr_filter.loc['max', 'high'],\\\n\t\t\t\trecord_decr_filter.loc['min', 'high'],\\\n\t\t\t\trecord_decr_filter.loc['min', 'low'],\\\n\t\t\t\t],\\\n\t\t\t\tindex=\\\n\t\t\t\t['code',\\\n\t\t\t\t'close',\\\n\t\t\t\t'high_mean',\\\n\t\t\t\t'low_mean',\\\n\t\t\t\t'high_max',\\\n\t\t\t\t'high_min',\\\n\t\t\t\t'low_min'])\n\t\t\t\t\n\t\t\t\trecord_custom['close_low_mean_pct'] = (record_custom['close']-record_custom['low_mean']) / record_custom['low_mean']\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t#if no NAN value in dataframe\n\t\t\t\tif (record_custom.isnull().values.any() == False):\n\t\t\t\t\trecords = records.append(record_custom, ignore_index=True)\n\t\t\t\telse:\n\t\t\t\t\tprint '%s has NaN value, skip it.' % (code)\t\t\t\n\n\t\t\texcept Exception as e:\n\t\t\t\tprint code, e\n\t\t##app.logger.info(record_decr_filter)\n\t\tresult = records.to_html()\n\treturn render_template('stock_data.html', code=code_list, form=form, result=result)\n\nif __name__ == '__main__':\n\tapp.run(host='0.0.0.0', debug=True)\n" } ]
3
davidengebretson/md2html
https://github.com/davidengebretson/md2html
f2607a1bf73a55895b297bb0d281541d9569d009
238a235fe7669aa53e8430c6511d060eadf550f6
803e2f9b6b3c2d0835c401f975a771fa5ba51658
refs/heads/master
2020-04-11T09:34:31.830581
2018-06-27T16:14:04
2018-06-28T02:51:50
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6574923396110535, "alphanum_fraction": 0.6727828979492188, "avg_line_length": 26.25, "blob_id": "e576036dcfd015056caef003397acdf502556a7b", "content_id": "2720d925bc685b27ea76b42ee9971c12cd30000f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 327, "license_type": "no_license", "max_line_length": 66, "num_lines": 12, "path": "/setup.py", "repo_name": "davidengebretson/md2html", "src_encoding": "UTF-8", "text": "import ez_setup\nez_setup.use_setuptools()\nfrom setuptools import setup\nfrom md2html import __VERSION__\n\nsetup(name='md2html',\n\t author='Gary Campbell',\n\t author_email='[email protected]',\n\t version=__VERSION__,\n\t install_requires = ['markdown'],\n\t py_modules=['md2html'],\n\t entry_points = {'console_scripts': ['md2html = md2html:main']})\n" }, { "alpha_fraction": 0.7666666507720947, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 19, "blob_id": "f8c79d489fc07cf3d54eb2b85055abe28c49f960", "content_id": "29d54cd32d775f935c89d0204ee1ecd8bf8ac2d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 180, "license_type": "no_license", "max_line_length": 67, "num_lines": 9, "path": "/test.md", "repo_name": "davidengebretson/md2html", "src_encoding": "UTF-8", "text": "This is a test file to test placing the TOC after the matched line.\n\n# Introduction\nThis is some introductory material.\n\n# Table of Contents\n\n# More Stuff\nThis is some more stuff.\n" }, { "alpha_fraction": 0.6019607782363892, "alphanum_fraction": 0.6235294342041016, "avg_line_length": 33, "blob_id": "5c8130b930d2846a91a01f58711bc24ff488a68f", "content_id": "3f25eabc555654a51933e121475b7e3afb6219cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "no_license", "max_line_length": 177, "num_lines": 15, "path": "/setupexe.py", "repo_name": "davidengebretson/md2html", "src_encoding": "UTF-8", "text": "from distutils.core import setup\nimport py2exe\nfrom md2html import __VERSION__\nsetup(name='md2html',\n\t version=__VERSION__,\n\t author='Gary Campbell',\n\t author_email='[email protected]',\n\t description='Convert Markdown to HTML',\n\t requires=['markdown(>=2.6.6)'],\n\t console=['md2html.py'],\n options={\"py2exe\":{\n\t\t \"excludes\": [\n\t\t\t 'pyreadline', 'difflib', 'doctest', 'optparse', 'pickle', 'calendar', 'email', 'ftplib', 'httplib', 'rfc822', 'socket', 'select', 'ssl', '_ssl'] # Exclude standard library\n\t\t\t }}\n)\n" }, { "alpha_fraction": 0.7239317893981934, "alphanum_fraction": 0.7341155409812927, "avg_line_length": 52.421688079833984, "blob_id": "54a521f62d1daf118929fe438750cb7fcf79417c", "content_id": "a04aab50acaa957e5016c7ca9ba006cc41057d6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4517, "license_type": "no_license", "max_line_length": 576, "num_lines": 83, "path": "/readme.md", "repo_name": "davidengebretson/md2html", "src_encoding": "UTF-8", "text": "Last updated 6/27/18 (for v1.0.6).\r\n\r\n# Introduction\r\n`md2html` is a tool I use in building the JAWS script for Audacity project to convert `readme.md` to HTML. Although the Python markdown package, on which this tool is built, provides a command line interface, this tool is tailored to the needs of this particular project. It provides the ability to add a table of contents without placing a `[TOC]` marker in the file, and the ability to place options in a configuration file. It does not support all of the available features of the Python Markdown package, only the ones I use in the project for which it was made.\r\n\r\n# Installation:\r\nTo use the binary distribution for Windows, place `md2html.exe` in a folder on your path. By default, `md2html.exe` installs the real executable to a temporary location, executes it, and removes the temporary installation. If you prefer, you can install the executable in a folder of your choosing by running:\r\n\r\n```\r\nmd2html.exe /install\r\n```\r\n\r\nIt will then prompt you to select a folder in which to install the files. If you install this way, to uninstall just remove the folder. It will not appear in Program Features. If you installed in folder myprog, run the installed program by:\r\n\r\n```\r\nmyprog\\md2html.exe <args>\r\n```\r\n\r\n\r\nIf you have Python, you can install it by downloading md2html.py and setup.py and running `python setup.py install`. (Uninstall it with `pip uninstall md2html`.) \r\n\r\n# Usage:\r\n\r\n`md2html [-q] [-t title] [-c] [-l toc_location] infile outfile`\r\n\r\nThe input file is read with utf-8 encoding. A utf-8 BOM in the input file will be skipped. The output file is written as utf-8 and never contains a BOM. The options are:\r\n\r\n- `-t`: text placed in the `<title>` element of the HTML page.\r\n- `-c`: produce a table of contents.\r\n- `-l`: specify the location of the table of contents. It is a Python regular expression that matches the text in the source (Markdown) file where the TOC should appear. The table of contents is placed just before the first match of this re. If the string starts with \"+\", the \"+\" is removed and the TOC is placed after the newline following the start of the matched text. The default is `\"^# \"`, which causes the TOC to be placed just before the first level 1 heading. If the string is only \"+\", the default is used and the TOC follows the matched line. (Implies `-c`.)\r\n- `-T`, `--toctitle`: a title that appears (in a span) just before the TOC. Implies `-c`\r\n- `-q`: Suppress informational messages\r\n\r\n\r\n# Configuration File\r\n`md2html` looks for a file called `md2html.cfg` in the same folder as the source file. It is an INI-style file containing a section for each source file in the folder. It is read as utf-8 (with or without a BOM). It can currently contain the following options:\r\n\r\n- `title=page title`: the title of the HTML page.\r\n- `toctitle=TOC title`: text that is placed in a `<span>` element just before the TOC.\r\n- `toclocation=toc location`: same as the `-l` command line option.\r\n\r\nThis mechanism allows for handling of titles in other languages without requiring inclusion of them in the build system. The config file is processed using the Python [`ConfigParser`](https://docs.python.org/2/library/configparser.html) module. Command line options override configuration file options.\r\n\r\n## Example\r\n\r\n```\r\n[readme.md]\r\ntitle=md2html README\r\ntoctitle=Contents:\r\n\r\n[What's new.md]\r\ntitle=What's New\r\ntoctitle=\"Contents\"\r\n```\r\n\r\nYou can also use a `DEFAULT` section:\r\n\r\n```\r\n[readme.md]\r\ntitle=md2html README\r\n\r\n[What's new.md]\r\ntitle=What's New\r\n\r\n[DEFAULT]\r\ntoctitle=\"Contents\"\r\n```\r\n\r\n# Issues\r\n\r\n- The config file option values read from the command line are not utf-8 encoded. Since they are inserted into HTML, it should be possible to use &# substitutions.\r\n\r\n\r\n# Conclusion\r\n`md2html` is built using Python 2.7.13 on Windows 10 using the [Python Markdown](http://pythonhosted.org/Markdown) package v2.6.11. It uses the `toc` and `fenced_code` extensions. I have only tested it on Windows 10, but it should be platform-independent, however, there may be EOL and encoding issues. The [AutoIt](http://www.autoitscript.com) tool is required to build the stand-alone executable. (Version 3.3.14.2 was used to build the current version.) \r\n\r\nTo build the binary executable distribution file, run:\r\n\r\n```\r\nbuild.cmd\r\n```\r\n\r\nThe finished executable `md2html.exe` will be in your working directory. You ccan then remove the `build` and `dist` folders created by setupexe.py.\r\n" }, { "alpha_fraction": 0.6367916464805603, "alphanum_fraction": 0.6428945064544678, "avg_line_length": 25.187213897705078, "blob_id": "5d46303fd3f33a23259549b1978b854a23640218", "content_id": "fc123cf187ab237975a4569ff32ee70ee70b4cf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5735, "license_type": "no_license", "max_line_length": 304, "num_lines": 219, "path": "/md2html.py", "repo_name": "davidengebretson/md2html", "src_encoding": "UTF-8", "text": "# 5/23/16 md2html-- convert Markdown to HTML-- for the Audacity JAWS Script project.\n__VERSION__ = \"1.0.7\"\nimport sys\nimport os\nimport os.path\nimport argparse\nimport re\nimport io\nimport ConfigParser\nimport markdown\nimport markdown.extensions\n# for py2exe\nimport markdown.extensions.fenced_code\nfrom markdown.extensions.fenced_code import FencedCodeExtension\nimport markdown.extensions.toc\nfrom markdown.extensions.toc import TocExtension\n\n\n# Usage: page_template.format(page_title, body_text)\npage_template = u'''\\\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n<title>{}</title>\n</head>\n<body>\n{}\n</body>\n</html>\n'''\n\ndef msg(s):\n\t#{\n\tprint >>sys.stderr, s\n #} # msg\n \ndesc = \"\"\"\\\nConvert Markdown to HTML\"\"\"\n\ndef main(opts):\n\t#{\n\t\"\"\"@param opts: list of command line args-- sys.argv[1:].\n\t@type opts: list of string\"\"\"\n\tparser = argparse.ArgumentParser(description=desc, argument_default=\"\", fromfile_prefix_chars=\"@\")\n\tparser.add_argument(\"-V\", \"--version\", action=\"version\", version=\"%(prog)s v{}\".format(__VERSION__), help=\"print program version and exit\")\n\tparser.add_argument(\"-q\", \"--quiet\", dest=\"verbose\", action=\"store_false\", default=True, help=\"suppress messages\")\n\tparser.add_argument(\"input\", help=\"input file name, - reads from stdin (default stdin)\")\n\tparser.add_argument(\"output\", help=\"output file\")\n\tparser.add_argument(\"-t\", \"--title\", dest=\"title\", help=\"page title\")\n\tparser.add_argument(\"-c\", \"--toc\", dest=\"toc\", action=\"store_true\", help=\"insert a table of contents\")\n\tparser.add_argument(\"-l\", \"--toclocation\", dest=\"toclocation\", help=\"a Python regular expression that matches the text before which the TOC is to be placed. If the first character is '+', it is removed and the TOC is placed after the first newline following the start of the matched text. Implies -c\")\n\tparser.add_argument(\"-T\", \"--toctitle\", dest=\"toctitle\", help=\"title text shown (in a span) before the TOC, default ''. Implies -c\")\n\t\n\targs = parser.parse_args(opts)\n\tcfg = ConfigParser.SafeConfigParser()\n\tif args.verbose:\n\t\t#{\n\t\tmsg(\"md2html v{}: converting {} to {}\".format(__VERSION__, args.input, args.output))\n\t\t#} # if verbose\n\ttoc_title = \"\"\n\tpage_title = \"\"\n\ttoclocation = \"\"\n\tif args.input and args.input != \"-\":\n\t#{\n\t\tcfgfile = os.path.dirname(args.input)\n\t#} # if input\n\telse:\n\t#{\n\t\tcfgfile = os.getcwd()\n\t#} # no input file\n\tcfgfile = os.path.join(cfgfile, \"md2html.cfg\")\n\t#msg(\"Reading config file {}\".format(cfgfile) # debug)\n\tif os.path.exists(cfgfile):\n\t\t#{\n\t\twith io.open(cfgfile, mode='rt', encoding='utf-8-sig') as cfp:\n\t\t#{\n\t\t\ttry:\n\t\t\t\t#{\n\t\t\t\tcfg.readfp(cfp)\n\t\t\t\t#}\n\t\t\texcept ConfigParser.Error as e:\n\t\t\t\t#{\n\t\t\t\tmsg(\"md2html: Error reading config file: {}\".format(str(e)))\n\t\t\t\tsys.exit(1)\n\t\t\t\t#} # except\n\t\t\t#} # with\n\t\t#} # if cfgfile exists\n\tcfgsection = \"\"\n\tif args.input and args.input != \"-\":\n\t#{\n\t\tcfgsection = os.path.basename(args.input)\n\t#}\n\tif cfgsection:\n\t#{\n\t\tif cfg.has_section(cfgsection):\n\t\t#{\n\t\t\t#msg(\"cfg has section {}\".format(cfgsection))\n\t\t\ttry:\n\t\t\t#{\n\t\t\t\ttoc_title = cfg.get(cfgsection, \"toctitle\")\n\t\t\t\t\n\t\t\t#} # try\n\t\t\texcept ConfigParser.NoOptionError:\n\t\t\t#{\n\t\t\t\tpass\n\t\t\t#} # except\n\t\t\ttry:\n\t\t\t#{\n\t\t\t\ttoclocation = cfg.get(cfgsection, \"toclocation\")\n\t\t\t\t\n\t\t\t#} # try\n\t\t\texcept ConfigParser.NoOptionError:\n\t\t\t#{\n\t\t\t\tpass\n\t\t\t#} # except\n\t\t\ttry:\n\t\t\t#{\n\t\t\t\tpage_title = cfg.get(cfgsection, \"title\")\n\t\t\t#} # try\n\t\t\texcept ConfigParser.NoOptionError:\n\t\t\t#{\n\t\t\t\tpass\n\t\t\t#} # except\n\t\t#} # if has_section\n\t#} # if cfgsection\n\tif args.toctitle: toc_title = args.toctitle\n\tif args.title: page_title = args.title\n\ttoc = args.toc\n\tif args.toclocation: toclocation = args.toclocation\n\tif toclocation or toc_title: toc = True\n\t\n\t# input file\n\tif args.input and args.input != \"-\":\n\t#{\n\t\tf = io.open(args.input, mode=\"rt\", encoding=\"utf-8-sig\")\n\t#}\n\telse:\n\t#{\n\t\tf = io.open(sys.stdin.fileno(), mode=\"rt\", encoding=\"utf-8\")\n\t#}\n\t# output file\n\tfout = io.open(args.output, mode=\"wt\", encoding=\"utf-8\")\n\t# I don't know why, but if I write this encoded I get an extra CR. I would think writing in binary mode would produce UNIX-style line endings, but on my Windows machine it doesn't.\n\t#fout = io.open(sys.stdout.fileno(), mode=\"wb\")\n\ttry:\n\t#{\n\t\ts = f.read()\n\t#} # try\n\texcept UnicodeDecodeError as e:\n\t#{\n\t\tmsg(\"md2html: UnicodeDecodeError in {}: {}\".format(f.name, str(e)))\n\t\tsys.exit(1)\n\t#} # except\n\tfinally:\n\t#{\n\t\tf.close()\n\t#} # finally\n\t\n\tif toc:\n\t#{\n\t\taftertoc = False\n\t\tif toclocation.startswith(\"+\"):\n\t\t#{\n\t\t\taftertoc = True\n\t\t\ttoclocation = toclocation[1:]\n\t\t#} # if\n\t\tif not toclocation: toclocation = \"^# \"\n\t\tm = re.search(toclocation, s, re.M)\n\t\tif not m:\n\t\t\t#{\n\t\t\tmsg(\"md2html: TOC location not found, disabling toc option. Do your headings start in column 1?\")\n\t\t\ttoc = False\n\t\t\t#}\n\t\telse:\n\t\t\t#{\n\t\t\t# toclocation found.\n\t\t\ttocstart = m.start()\n\t\t\tif aftertoc:\n\t\t\t\t#{\n\t\t\t\ti = s.find(\"\\n\", tocstart)\n\t\t\t\tif i > -1: tocstart = i + 1\n\t\t\t\t#} # if tocstart\n\t\t\ts2 = s[:tocstart] + \"[TOC]\\n\" + s[tocstart:]\n\t\t\t#} # else toclocation found\n\t#} # if toc\n\t# toc may have been cleared if toclocation not found.\n\tif not toc:\n\t#{\n\t\ts2 = s\n\t#} # if not toc\n\t#print s2 # debug\n\t#print \"-- after s2\" # debug\n\t\n\t# convert\n\textensions = [FencedCodeExtension()]\n\tif toc:\n\t#{\n\t\textensions.append(TocExtension(title=toc_title))\n\t#}\n\thtml = markdown.markdown(s2, extensions=extensions)\n\ttry:\n\t#{\n\t\tfout.write(page_template.format(page_title, html))\n\t#} # try\n\texcept UnicodeEncodeError as e:\n\t#{\n\t\tmsg(\"md2html: UnicodeEncodeError writing output for {}: {} (mode for output file is {})\".format(f.name, str(e), fout.mode))\n\t\tsys.exit(1)\n\t#} except\n\tfinally:\n\t#{\n\t\tfout.close()\n\t#} # finally\n\t#} # main\n\nif __name__ == \"__main__\":\n\t#{\n\tmain(sys.argv[1:])\n#} # if __main__\n" } ]
5
aybry/trussDFEM
https://github.com/aybry/trussDFEM
a4c5a2c026c5aca406dcc348894ed4c6019abe40
a52fba492650edebb22ce63ac6c5964a11069e1f
e3f787c78edf59bfc51138341dbbf7c97b1fc25b
refs/heads/master
2022-12-21T20:19:55.227509
2020-09-30T11:52:23
2020-09-30T11:52:23
299,899,873
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3397088348865509, "alphanum_fraction": 0.5047102570533752, "avg_line_length": 50.31343460083008, "blob_id": "02b57b3646d8b3181f0bd03250eae91050ee7e0e", "content_id": "ef51a9f44e0a3f37f109f89e99af3fea034ef3a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3503, "license_type": "no_license", "max_line_length": 135, "num_lines": 67, "path": "/testModels.py", "repo_name": "aybry/trussDFEM", "src_encoding": "UTF-8", "text": "import numpy as np\r\nfrom plotsAndTables import nodeTableFunc, elemTableFunc\r\n\r\n# NODES\r\n# node nr | x-coord | y-coord\r\n\r\n# ELEMENTS\r\n# element nr | start node | end node\r\n\r\n# BEARINGS\r\n# bearing type | node | orientation\r\n\r\n# LOADS\r\n# load nr | node | orientation | magnitude\r\n\r\ndef truss1():\r\n nodes = np.array([[1,0.,0.], [2,12.,0.], [3,2*12.,0.], [4,3*12.,0.], [5,4*12.,0.],\r\n [6,12.,-9.], [7,2*12.,-9.], [8,3*12.,-9.]])\r\n nodeTable = nodeTableFunc(nodes)\r\n elements = np.array([[1,1,2], [2,2,3], [3,3,4], [4,4,5], [5,1,6], [6,6,7], [7,7,8], [8,8,5],\r\n [9,2,6], [10,3,7], [11,4,8], [12,6,3], [13,3,8]])\r\n elemTable = elemTableFunc(elements)\r\n bearings = np.array([[1,1,1], [2,5,1]])\r\n loads = np.array([[1,2,3,100000], [2,3,3,200000], [3,4,3,300000]])\r\n E = 2e11; A = 0.01; poiss = 0.3 \r\n return [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss]\r\n\r\ndef truss2():\r\n nodes = np.array([[1,0,0], [2,12,6], [3,0,4], [4,4,4.666667], [5,9,5.5], [6,7,3.5]]) \r\n nodeTable = nodeTableFunc(nodes)\r\n elements = np.array([[1,1,6], [2,6,2], [3,2,5], [4,5,6], [5,6,4], [6,4,3], [7,5,4], [8,4,1]]) \r\n elemTable = elemTableFunc(elements)\r\n bearings = np.array([[1,1,4], [1,3,4]])\r\n loads = np.array([[1,2,3,50000]])\r\n E = 2e11; A = 0.01; poiss = 0.3 \r\n return [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss]\r\n\r\ndef truss3():\r\n nodes = np.array([[1,0,0], [2,2,0], [3,4,0], [4,6,0], [5,1,0], [6,5,0], [7,3,2],\r\n [8,2.5,1], [9,3.5,1], [10,1.5,1], [11,4.5,1], [12,0.75,0.5],\r\n [13,2.25,1.5], [14,3.75,1.5], [15,5.25,0.5]]); nodeTable = nodeTableFunc(nodes)\r\n elements = np.array([[1,1,5], [2,5,2], [3,2,8], [4,8,7], [5,7,9], [6,9,3], [7,3,6], [8,6,4],\r\n [9,1,12], [10,10,13], [11,7,14], [12,11,15], [13,5,10], [14,10,2], [15,10,8],\r\n [16,9,11], [17,11,3], [18,11,6], [19,12,10], [20,13,7], [21,14,11], [22,15,4],\r\n [23,5,12], [24,8,13], [25,9,14], [26,6,15]]); elemTable = elemTableFunc(elements)\r\n bearings = np.array([[1,1,1], [1,4,1]])\r\n loads = np.array([[1,7,3,500000], [2,10,3,500000], [3,11,3,500000]])\r\n E = 2e11; A = 0.1; poiss = 0.3\r\n return [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss]\r\n\r\ndef truss4(): # 6 nodes, fixed/roller bearings\r\n nodes = np.array([[1,0.,0.], [2,4.,0.], [3,2.,1.], [4,0.,2.], [5,4.,2.], [6,2.,3.]]); nodeTable = nodeTableFunc(nodes)\r\n elements = np.array([[1,1,3], [2,1,4], [3,3,2], [4,2,5], [5,5,6],\r\n [6,6,3], [7,6,4], [8,4,3], [9,5,3]]); elemTable = elemTableFunc(elements)\r\n bearings = np.array([[1,1,1], [2,2,1]])\r\n loads = np.array([[1,3,3,100000]])\r\n E = 210e9; A = 0.001; poiss = 0.3\r\n return [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss]\r\n\r\ndef truss5():\r\n nodes = np.array([[1,0.,0.], [2,16.*12,0.], [3,16.*12,12.*12], [4,32.*12,0.], [5,32.*12,12.*12]]); nodeTable = nodeTableFunc(nodes)\r\n elements = np.array([[1,1,3], [2,1,2], [3,2,3], [4,3,5], [5,3,4], [6,2,5], [7,2,4], [8,4,5]]); elemTable = elemTableFunc(elements)\r\n bearings = np.array([[1,1,1], [1,4,1]])\r\n loads = np.array([[1,2,3,100], [2,5,4,50]])\r\n E = 3e4; A = 10; poiss = 0.3 # imperial\r\n # compare: http://people.duke.edu/~hpgavin/cee421/truss-method.pdf\r\n return [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss]" }, { "alpha_fraction": 0.45980334281921387, "alphanum_fraction": 0.47310584783554077, "avg_line_length": 34.0625, "blob_id": "732411a928d0197953db3158dbabd5b96d9da007", "content_id": "68b03e95c7fea60bf984a528f16cf9205880bf50", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1729, "license_type": "no_license", "max_line_length": 108, "num_lines": 48, "path": "/convert.py", "repo_name": "aybry/trussDFEM", "src_encoding": "UTF-8", "text": "import testModels, json\r\n\r\ni = 1\r\nwhile i <= 5:\r\n next_func = 'truss' + str(i)\r\n [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss] = getattr(testModels, next_func)()\r\n nodes_json = '{\"nodes\": {'\r\n elements_json = '{\"elements\": {'\r\n bearings_json = '{\"bearings\": {'\r\n loads_json = '{\"loads\": {'\r\n i_running = 1\r\n for node in nodes:\r\n current_node = ('\"' + str(int(node[0])) + '\": [' + str(node[1]) + ',' + str(node[2]) + ']')\r\n if i_running < len(nodes):\r\n current_node += ', '\r\n nodes_json += current_node\r\n i_running += 1\r\n i_running = 1\r\n for elem in elements:\r\n current_elem = ('\"' + str(int(elem[0])) + '\": [' + str(elem[1]) + ',' + str(elem[2]) + ']')\r\n if i_running < len(elements):\r\n current_elem += ', '\r\n elements_json += current_elem\r\n i_running += 1\r\n i_running = 1\r\n for bear in bearings:\r\n current_bear = ('\"' + str(int(bear[0])) + '\": [' + str(bear[1]) + ',' + str(bear[2]) + ']')\r\n if i_running < len(bearings):\r\n current_bear += ', '\r\n bearings_json += current_bear\r\n i_running += 1\r\n i_running = 1\r\n for load in loads:\r\n current_load = ('\"' + str(int(load[0])) + '\": [' + str(load[1]) + ',' + str(load[2]) + ']')\r\n if i_running < len(loads):\r\n current_load += ', '\r\n loads_json += current_load\r\n i_running += 1\r\n nodes_json += '}}'\r\n elements_json += '}}'\r\n print(nodes_json, '\\n', \r\n elements_json, '\\n',\r\n bearings_json, '\\n',\r\n loads_json)\r\n with open('test_models.json', 'w') as f:\r\n f.write(json.dumps())\r\n print(getattr(next_func, ))\r\n i += 1" }, { "alpha_fraction": 0.4973986744880676, "alphanum_fraction": 0.5419237613677979, "avg_line_length": 46.0639533996582, "blob_id": "f9b1d6e900db4a5158ee8323e20752eec3944340", "content_id": "578f0c56f818c6b509ca29dc10f8567cfdc8c059", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8265, "license_type": "no_license", "max_line_length": 122, "num_lines": 172, "path": "/plotsAndTables.py", "repo_name": "aybry/trussDFEM", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom terminaltables import SingleTable as SingTab\r\n\r\n\r\ndef updatePlot(nodes, nodesNew, elements, bearings, loads, fromSolver):\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111)\r\n alphaNew = 1\r\n if fromSolver == 1:\r\n alphaOrig = 0.2 # if coming from solver, set original truss to alpha = 0.3\r\n ax.plot(nodesNew[:,1], nodesNew[:,2], 'ok', markersize = 5) # plot nodes\r\n elif fromSolver == 0:\r\n alphaOrig = 1\r\n ax.plot(nodes[:,1], nodes[:,2], 'ok', markersize = 5, alpha = alphaOrig) # plot nodes\r\n\r\n if nodes[0,0] == 0:\r\n print ('\\n At least add some nodes...')\r\n return\r\n maxes = np.zeros((2*np.shape(bearings)[0]))\r\n for i in range(0, np.shape(bearings)[0]):\r\n maxes[2*i-1] = nodes[int(bearings[i,1]-1),1]\r\n maxes[2*i] = nodes[int(bearings[i,1]-1),2]\r\n factor = max(maxes)/4 # multiplication factor for resizing\r\n if elements[0,0] != 0:\r\n for i in range(0, np.shape(elements)[0]): # plot elements (lines between connected nodes)\r\n pair = np.array([elements[i,1], elements[i,2]]).astype(int)\r\n ax.plot(nodes[pair-1, 1], nodes[pair-1, 2], 'k', alpha = alphaOrig)\r\n if fromSolver == 1:\r\n for i in range(0, np.shape(elements)[0]): # plot elements (lines between connected nodes)\r\n pair = np.array([elements[i,1], elements[i,2]]).astype(int)\r\n ax.plot(nodesNew[pair-1, 1], nodesNew[pair-1, 2], 'k', alpha = alphaNew)\r\n if bearings[0,0] != 0:\r\n for i in range(0, np.shape(bearings)[0]): \r\n try:\r\n sinVal = np.sin((np.pi)*(bearings[i,2]-1)/2)\r\n cosVal = np.cos((np.pi)*(bearings[i,2]-1)/2)\r\n except IndexError: # if no bearings have been defined\r\n break\r\n plotBearing(bearings[i,0], nodes[int(bearings[i,1]-1),1], \r\n nodes[int(bearings[i,1]-1),2], bearings[i,2], \r\n ax, sinVal, cosVal, alphaOrig, factor)\r\n if fromSolver == 1:\r\n for i in range(0, np.shape(bearings)[0]): \r\n try:\r\n sinVal = np.sin((np.pi)*(bearings[i,2]-1)/2)\r\n cosVal = np.cos((np.pi)*(bearings[i,2]-1)/2)\r\n except IndexError: # if no bearings have been defined\r\n break\r\n plotBearing(bearings[i,0], nodesNew[int(bearings[i,1]-1),1], \r\n nodesNew[int(bearings[i,1]-1),2], bearings[i,2], \r\n ax, sinVal, cosVal, alphaNew, factor)\r\n if loads[0,0] != 0:\r\n for i in range(0, np.shape(loads)[0]):\r\n try:\r\n sinVal = np.sin((np.pi)*(loads[i,2]-1)/2)\r\n cosVal = np.cos((np.pi)*(loads[i,2]-1)/2)\r\n except IndexError: # if no loads have been defined\r\n break\r\n plotLoad(nodesNew[int(loads[i,1]-1),1], nodesNew[int(loads[i,1]-1),2], sinVal, cosVal, ax, factor)\r\n if np.shape(nodes)[0] >= 2:\r\n plotAnnotations(nodesNew, elements, loads, ax, fromSolver)\r\n xleft, xright = (min(nodesNew[:,1])-factor*0.5, max(nodesNew[:,1])+factor*0.5)\r\n ybottom, ytop = (min(nodesNew[:,2])-factor*0.5, max(nodesNew[:,2])+factor*0.5)\r\n ax.set_xlim(xleft, xright)\r\n ax.set_ylim(ybottom, ytop)\r\n ax.set_aspect('equal')\r\n plt.show()\r\n if fromSolver == 0:\r\n print ('\\nClose plot to continue!')\r\n elif fromSolver == 1:\r\n print ('\\nGoodbye!')\r\n\r\n return\r\n\r\ndef plotAnnotations(nodes, elements, loads, ax, fromSolver):\r\n nodeLabels = [nodes[i,0].astype(int) for i in range(np.shape(nodes)[0])]\r\n loadLabels = [repr(loads[i,3]) + ' N' for i in range(np.shape(loads)[0])]\r\n # for label, x, y in zip(nodeLabels, nodes[:,1], nodes[:,2]):\r\n # ax.annotate(\r\n # label,\r\n # xy=(x, y), xytext=(-3, 15), \r\n # textcoords = 'offset points', ha = 'right', va = 'bottom',\r\n # arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3, rad=0.3'))\r\n # if fromSolver == 0:\r\n elemLabels = [elements[i,0].astype(int) for i in range(np.shape(elements)[0])]\r\n for i in range(0, np.shape(elements)[0]):\r\n x1 = nodes[int(elements[i,1]-1),1]\r\n y1 = nodes[int(elements[i,1]-1),2]\r\n x2 = nodes[int(elements[i,2]-1),1]\r\n y2 = nodes[int(elements[i,2]-1),2]\r\n ax.annotate(\r\n elemLabels[i],\r\n xy=(0.5*(x2+x1), 0.5*(y2+y1)), xytext=(-3, 15), color = 'b',\r\n textcoords = 'offset points', ha = 'right', #va = 'bottom',\r\n arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3, rad=0.3'))\r\n if loads[0,0] != 0:\r\n for label, x, y in zip(loadLabels, \r\n nodes[(loads[:,1]-1).astype(int),1], \r\n nodes[(loads[:,1]-1).astype(int),2]):\r\n ax.annotate(\r\n label,\r\n xy=(x, y), xytext=(5, -5), color = 'r',\r\n textcoords = 'offset points', ha = 'left', va = 'top')\r\n\r\ndef plotBearing(bearType, bearX, bearY, orientation, ax, sinVal, cosVal, alpha, factor):\r\n sinVal *= factor\r\n cosVal *= factor\r\n xTriangle = [-0.12,0,0.12] # coordinates for main triangle shape\r\n yTriangle = [-0.18,0,-0.18]\r\n xBase1 = [-0.16,0.16]\r\n yBase1 = [-0.18, -0.18]\r\n xBase2 = [-0.16,0.16]\r\n yBase2 = [-0.2, -0.2]\r\n\r\n ax.plot(bearX + np.multiply(cosVal, xTriangle) - np.multiply(sinVal, yTriangle), \r\n bearY + np.multiply(sinVal, xTriangle) + np.multiply(cosVal, yTriangle), alpha = alpha, color = 'k')\r\n ax.plot(bearX + np.multiply(cosVal, xBase1) - np.multiply(sinVal, yBase1), \r\n bearY + np.multiply(sinVal, xBase1) + np.multiply(cosVal, yBase1), alpha = alpha, color = 'k')\r\n ax.set_aspect('equal')\r\n\r\n if bearType == 1:\r\n for i in np.arange(0,1,0.1):\r\n ax.plot(bearX + np.multiply(cosVal, [0.16-(i)*0.32, 0.16-(i+0.1)*0.32]) - np.multiply(sinVal, [-0.18, -0.2]), \r\n bearY + np.multiply(sinVal, [0.16-(i)*0.32, 0.16-(i+0.1)*0.32]) + np.multiply(cosVal, [-0.18, -0.2]), \r\n alpha = alpha, color = 'k')\r\n elif bearType == 2:\r\n ax.plot(bearX + np.multiply(cosVal, xBase2) - np.multiply(sinVal, yBase2), \r\n bearY + np.multiply(sinVal, xBase2) + np.multiply(cosVal, yBase2), \r\n alpha = alpha, color = 'k')\r\n for i in np.arange(0,1,0.1):\r\n ax.plot(bearX + np.multiply(cosVal, [0.16-(i)*0.32, 0.16-(i+0.1)*0.32]) - np.multiply(sinVal, [-0.2, -0.22]), \r\n bearY + np.multiply(sinVal, [0.16-(i)*0.32, 0.16-(i+0.1)*0.32]) + np.multiply(cosVal, [-0.2, -0.22]), \r\n alpha = alpha, color = 'k')\r\n return\r\n\r\ndef plotLoad(xLoad, yLoad, sinVal, cosVal, ax, factor):\r\n sinVal *= 0.5*factor\r\n cosVal *= 0.5*factor\r\n xStem = [0,0]\r\n yStem = [0,0.4]\r\n xHead = [-0.05, 0, 0.05]\r\n yHead = [0.32, 0.4, 0.32] # pulls (0,0) upwards for direction = 1\r\n ax.plot(xLoad, yLoad, 'or')\r\n ax.plot(xLoad + np.multiply(cosVal, xStem) - np.multiply(sinVal, yStem), \r\n yLoad + np.multiply(sinVal, xStem) + np.multiply(cosVal, yStem), 'r')\r\n ax.plot(xLoad + np.multiply(cosVal, xHead) - np.multiply(sinVal, yHead), \r\n yLoad + np.multiply(sinVal, xHead) + np.multiply(cosVal, yHead), 'r')\r\n return\r\n\r\ndef nodeTableFunc(nodes):\r\n rows = [['Node Nr', '(x, y)']]\r\n for i in range(0, len(nodes)):\r\n rows.append([int(nodes[i,0]), ('(' + str(nodes[i,1]) + ', ' + str(nodes[i,2]) + ')')])\r\n SingTab.table_data = rows\r\n return SingTab.table_data\r\n\r\ndef elemTableFunc(elements):\r\n rows = [['Element Nr', 'From', 'To']]\r\n for i in range(0, len(elements)):\r\n rows.append([int(elements[i,0]), int(elements[i,1]), int(elements[i,2])])\r\n SingTab.table_data = rows\r\n return SingTab.table_data\r\n\r\ndef stressTableFunc(elements, strain, stress):\r\n stressAdj = stress/10**6\r\n strainAdj = strain*10**6\r\n rows = [['Element Nr', 'Strain', 'S11 Stress']]\r\n for i in range(0, len(elements)):\r\n rows.append([int(elements[i,0]), str(round(strainAdj[i,0], 3)) + 'E-06', str(round(stressAdj[i,0], 3)) + 'E+06'])\r\n SingTab.table_data = rows\r\n return SingTab.table_data" }, { "alpha_fraction": 0.5280960202217102, "alphanum_fraction": 0.5635570287704468, "avg_line_length": 39.03731155395508, "blob_id": "3121187340f74e33ee5836c17a1cca60c5988334", "content_id": "cd2707cc44d8bde8c8ead05a3a99094df58573fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5499, "license_type": "no_license", "max_line_length": 117, "num_lines": 134, "path": "/solver.py", "repo_name": "aybry/trussDFEM", "src_encoding": "UTF-8", "text": "import numpy as np\r\nfrom numpy.linalg import solve as npsolve\r\nfrom terminaltables import SingleTable as SingTab\r\nfrom plotsAndTables import *\r\n\r\ndef solver(nodes, elements, bearings, loads, nodeTable, elemTable, A, E):\r\n\r\n np.set_printoptions(precision = 4) # how many decimal places\r\n\r\n print ('\\n -------------\\\r\n \\n -- Results --\\\r\n \\n -------------')\r\n\r\n # print AscTab(nodeTable).table\r\n # print AscTab(elemTable).table\r\n Eprint = E/(10**9)\r\n print ('\\nYoung\\'s modulus: E = ' + str(Eprint) + 'e9')\r\n print ('Cross-sectional area: A =', A)\r\n\r\n elemNum = np.shape(elements)[0]\r\n nodeNum = np.shape(nodes)[0]\r\n Kl = np.zeros((4, 4, elemNum)) # initialise local (element) stiffness matrix\r\n lengths = np.zeros((elemNum,1)) # initialise vector of element lengths for stress()\r\n\r\n F = np.zeros(2*nodeNum) # initialise load vector\r\n U = np.zeros(2*nodeNum) # initialise displacement vector\r\n K = np.zeros((2*nodeNum, 2*nodeNum)) # intitalise global stiffness matrix\r\n\r\n for i in range(0, elemNum):\r\n x1 = nodes[(elements[i,1]-1).astype(int),1]\r\n y1 = nodes[(elements[i,1]-1).astype(int),2]\r\n x2 = nodes[(elements[i,2]-1).astype(int),1]\r\n y2 = nodes[(elements[i,2]-1).astype(int),2]\r\n elemLength = np.sqrt((x2 - x1)**2 + (y2 - y1)**2)\r\n lengths[i,0] = elemLength\r\n c = (x2 - x1) / elemLength\r\n s = (y2 - y1) / elemLength\r\n # element stiffness matrix\r\n Kl[:,:,i] = [[c**2, c*s, -c**2, -c*s],\r\n [c*s, s**2, -c*s, -s**2],\r\n [-c**2, -c*s, c**2, c*s],\r\n [-c*s, -s**2, c*s, s**2]]\r\n Kl[:,:,i] = np.multiply(1/elemLength, Kl[:,:,i])\r\n\r\n node1 = elements[i,1]\r\n node2 = elements[i,2]\r\n\r\n first = (2*node1 - 2).astype(int) # separating nodes into X, Y local\r\n second = (2*node1 - 1).astype(int)\r\n third = (2*node2 - 2).astype(int)\r\n fourth = (2*node2 - 1).astype(int)\r\n\r\n # global stiffness matrix: add DOF from elements\r\n K[first:second+1, first:second+1] += Kl[0:2,0:2,i]\r\n K[first:second+1, third:fourth+1] += Kl[0:2,2:4,i]\r\n K[third:fourth+1, first:second+1] += Kl[2:4,0:2,i]\r\n K[third:fourth+1, third:fourth+1] += Kl[2:4,2:4,i]\r\n\r\n for i in range(0, np.shape(bearings)[0]):\r\n # adjust stiffness matrix for bearings\r\n # this way leaves room to solve for reaction forces at a later date!\r\n node = bearings[i,1]\r\n first = (2*node - 2).astype(int) # separating nodes into X, Y local\r\n second = (2*node - 1).astype(int)\r\n if bearings[i,0] == 1:\r\n K[first, first] += 1e32\r\n K[second, second] += 1e32\r\n elif bearings[i,0] == 2:\r\n K[first, first] += (bearings[i,2] + 1) % 2 * 1e30 # if odd, add 1e30\r\n K[second, second] += (bearings[i,2]) % 2 * 1e30 # if even, add 1e30\r\n\r\n for i in range(0, np.shape(loads)[0]):\r\n # establish load vector\r\n node = loads[i,1]\r\n first = (2*node - 2).astype(int) # separating nodes into X, Y local\r\n second = (2*node - 1).astype(int)\r\n sinVal = np.sin((np.pi)*(loads[i,2]-1)/2)\r\n cosVal = np.cos((np.pi)*(loads[i,2]-1)/2)\r\n F[first] = - sinVal * loads[i,3]\r\n F[second] = cosVal * loads[i,3]\r\n\r\n K = np.multiply(E*A, K) # finalise stiffness matrix with E*A\r\n\r\n U = npsolve(K, F) # solve for displacements \r\n\r\n for i in range(0, np.shape(U)[0]):\r\n if np.abs(U[i]) < 1e-12:\r\n U[i] = 0 # change ~0 to =0 for clarity\r\n if np.abs(F[i]) < 1e-12:\r\n F[i] = 0\r\n\r\n multiplier = 100\r\n nodesNew = np.zeros(np.shape(nodes)) + nodes\r\n nodesNewPlot = np.zeros(np.shape(nodes)) + nodes\r\n \r\n for i in range(0, np.shape(U)[0]):\r\n nodesNew[i//2, i%2+1] += U[i] # new coordinates of nodes after deformation\r\n nodesNewPlot[i//2, i%2+1] += U[i] * multiplier # exaggerated deformations for plotting\r\n\r\n # print '\\nForce vector F = \\n', F\r\n # print '\\nGlobal stiffness matrix U = \\n', K\r\n # print '\\nDisplacement vector U =\\n', U\r\n print ('\\nGraph displacement scale factor: ', multiplier)\r\n\r\n stress(nodesNew, lengths, elements, bearings, loads, E)\r\n updatePlot(nodes, nodesNewPlot, elements, bearings, loads, 1) # 1: coming from solver (plots original + deformed)\r\n\r\n return\r\n\r\ndef stress(nodesNew, lengths, elements, bearings, loads, E):\r\n # initialise vector of element lengths\r\n lengthsNew = np.zeros((np.shape(elements)[0],1)) \r\n # initialise vector of strain and stress in elements\r\n strain = np.zeros(np.shape(elements)[0])\r\n stress = np.zeros(np.shape(elements)[0])\r\n\r\n for i in range(0, np.shape(elements)[0]):\r\n xN1 = nodesNew[(elements[i,1]-1).astype(int), 1]\r\n yN1 = nodesNew[(elements[i,1]-1).astype(int), 2]\r\n xN2 = nodesNew[(elements[i,2]-1).astype(int), 1]\r\n yN2 = nodesNew[(elements[i,2]-1).astype(int), 2]\r\n lengthsNew[i] = np.sqrt((xN2 - xN1)**2 + (yN2 - yN1)**2)\r\n\r\n # strain = change in length by original length\r\n strain = (lengthsNew - lengths) / lengths\r\n\r\n # stress = strain multiplied by Young's modulus \r\n stress = np.multiply(E, strain)\r\n \r\n stressTable = SingTab(stressTableFunc(elements, strain, stress), title = \"Strain and Stress\")\r\n stressTable.justify_columns[1] = stressTable.justify_columns[2] = 'right'\r\n print (\"\\n\")\r\n print(stressTable.table) \r\n return\r\n" }, { "alpha_fraction": 0.535415530204773, "alphanum_fraction": 0.5587005019187927, "avg_line_length": 37.85555648803711, "blob_id": "a697a9996afb6e3611171b716a961b2a6c858af2", "content_id": "55fe8fa3a66c9be0b55199a2badaaed00b5c4e55", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7172, "license_type": "no_license", "max_line_length": 123, "num_lines": 180, "path": "/trussDFEM.py", "repo_name": "aybry/trussDFEM", "src_encoding": "UTF-8", "text": "# Program for calculating the deformation of a simple truss via FEM\r\n\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport os\r\nfrom terminaltables import SingleTable as SingTab\r\nfrom testModels import *\r\nfrom plotsAndTables import *\r\nfrom solver import *\r\n\r\ndef main():\r\n\r\n clearScreen = os.system('cls')\r\n clearScreen\r\n\r\n print('\\n -------------------------------- \\\r\n \\n -- Truss Deformation with FEM -- \\\r\n \\n -------------------------------- \\\r\n \\n Author: Samuel Bryson')\r\n \r\n solve = 0; n = 0; choice = 0; nodeCount = 0\r\n elemCount = 0; bearCount = 0; loadCount = 0\r\n nodes = np.zeros((1,3)); elements = np.zeros((1,3)) \r\n bearings = np.zeros((1,3)); loads = np.zeros((1,4))\r\n E = 210e9; A = 0.01; poiss = 0.3 # default values (vary depending on truss model)\r\n\r\n while solve != 1: # main loop\r\n clearScreen\r\n try:\r\n # clearScreen\r\n choice = float(input('\\nOptions: \\n 1 - Add node \\n 2 - Add element \\\r\n \\n 3 - Add bearing \\n 4 - Add load \\n 5 - Update plot \\n 6 - Edit model\\\r\n \\n 7 - Solve model \\n 8 - Truss 1 \\n 9 - Truss 2 \\n 10 - Truss 3 \\\r\n \\n 11 - Truss 4 \\n 12 - Truss 5 \\n\\n Selection: '))\r\n except ValueError:\r\n print ('\\nPlease enter a number between 1 to 8!')\r\n if choice == 1:\r\n [nodes, nodeTable, nodeCount] = addNode(nodes, nodeCount)\r\n elif choice == 2:\r\n [elements, elemTable, elemCount] = addElement(elements, nodes, nodeTable, elemCount)\r\n elements = elements.astype(int) # consists only of element nr, node 1, node 1\r\n elif choice == 3: \r\n [bearings, bearCount] = addBearing(bearings, nodes, bearCount, nodeTable)\r\n elif choice == 4: \r\n [loads, loadCount] = addLoad(loads, nodes, loadCount, nodeTable)\r\n elif choice == 5:\r\n updatePlot(nodes, nodes, elements, bearings, loads, 0) # 0: not coming from solver (only plots basic structure)\r\n elif choice == 6:\r\n [E, A] = editTruss(nodes, nodeCount, nodeTable, elements, elemCount, elemTable)\r\n elif choice == 7:\r\n solve = 1\r\n elif choice == 8:\r\n [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss] = truss1()\r\n print ('\\n Using values for truss 1.')\r\n elif choice == 9:\r\n [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss] = truss2()\r\n print ('\\n Using values for truss 2.')\r\n elif choice == 10:\r\n [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss] = truss3()\r\n print ('\\n Using values for truss 3.')\r\n elif choice == 11:\r\n [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss] = truss4()\r\n print ('\\n Using values for truss 4.')\r\n elif choice == 12:\r\n [nodes, elements, bearings, loads, nodeTable, elemTable, A, E, poiss] = truss5()\r\n print ('\\n Using values for truss 5.')\r\n choice = 0 # otherwise simply pressing \"enter\" without number input assumes previous option\r\n print(\"\\n\")\r\n print (SingTab(nodeTable, title = \"Nodes\").table)\r\n print (SingTab(elemTable, title = \"Elements\").table)\r\n\r\n solver(nodes, elements, bearings, loads, nodeTable, elemTable, A, E)\r\n\r\ndef addNode(nodes, nodeCount):\r\n newNode = np.zeros((1,3)); # node nr | x-coord | y-coord\r\n newNode[0,0] = nodeCount + 1\r\n print ('\\nEnter x: ')\r\n newNode[0,1] = getNumber()\r\n print ('\\nEnter y: ')\r\n newNode[0,2] = getNumber()\r\n if nodeCount == 0:\r\n nodes = newNode\r\n else:\r\n nodes = np.vstack((nodes, newNode))\r\n nodeTable = nodeTableFunc(nodes)\r\n nodeCount += 1\r\n print (SingTab(nodeTable, title = \"Nodes\").table)\r\n return [nodes, nodeTable, nodeCount]\r\n\r\ndef addElement(elements, nodes, nodeTable, elemCount):\r\n newElem = np.zeros((1,3)) # element nr | start node | end node\r\n print (SingTab(nodeTable, title = \"Nodes\").table)\r\n newElem[0,0] = elemCount + 1\r\n print ('\\n Which nodes would you like to connect?\\n\\n Enter first node: ')\r\n newElem[0,1] = getNumber()\r\n print ('\\n Enter second node: ')\r\n newElem[0,2] = getNumber()\r\n if elemCount == 0:\r\n elements = newElem\r\n else: \r\n elements = np.vstack((elements, newElem))\r\n elemTable = elemTableFunc(elements)\r\n elemCount += 1\r\n print (SingTab(elemTable, title = \"Elements\").table)\r\n return [elements, elemTable, elemCount]\r\n\r\ndef addBearing(bearings, nodes, bearCount, nodeTable):\r\n newBear = np.zeros((1,4)) # bearing nr | node | orientation\r\n print (' Fixed bearing (1) or roller (2)?')\r\n newBear[0,0] = getNumber()\r\n print (SingTab(nodeTable, title = \"Nodes\").table)\r\n print (' \\nPlace bearing at which node?')\r\n newBear[0,1] = getNumber()\r\n if newBear[0,0] == 1:\r\n print (' Is bearing at bottom (1) or top (2) of truss?')\r\n bearSet = getNumber()\r\n if bearSet == 1:\r\n newBear[0,2] = 1 # pointing upwards\r\n elif bearSet == 2:\r\n newBear[0,2] = 3 # downwards\r\n elif newBear[0,0] == 2:\r\n print (' Block vertical (1) or horizontal (2) movement?')\r\n bearSet = getNumber()\r\n if bearSet == 1:\r\n print (' Is bearing at bottom (1) or top (2) of truss?')\r\n bearSet = getNumber()\r\n if bearSet == 1:\r\n newBear[0,2] = 1 # upwards\r\n elif bearSet == 2:\r\n newBear[0,2] = 3 # downwards \r\n elif bearSet == 2:\r\n print (' Is bearing at left (1) or right (2) of truss?')\r\n bearSet = getNumber()\r\n if bearSet == 1:\r\n newBear[0,2] = 4 # pointing right\r\n elif bearSet == 2:\r\n newBear[0,2] = 2 # pointing left\r\n if bearCount == 0:\r\n bearings = newBear\r\n else: \r\n bearings = np.vstack((bearings, newBear))\r\n bearCount += 1\r\n return [bearings, bearCount]\r\n\r\ndef addLoad(loads, nodes, loadCount, nodeTable):\r\n newLoad = np.zeros((1,4)) # load nr | node | orientation | magnitude\r\n print ('\\n List of nodes: \\n', SingTab(nodeTable).table)\r\n newLoad[0,0] = loadCount + 1\r\n print ('\\n To which node is the load attached? Enter node number: ')\r\n newLoad[0,1] = getNumber()\r\n print ('\\n Enter load direction (up (1), left (2), down (3), right (4)):' )\r\n newLoad[0,2] = getNumber()\r\n print ('\\n Enter magnitude: ')\r\n newLoad[0,3] = getNumber()\r\n if loadCount == 0:\r\n loads = newLoad\r\n else: \r\n loads = np.vstack((loads, newLoad))\r\n loadCount += 1\r\n return [loads, loadCount]\r\n\r\ndef getNumber():\r\n errorstr = 'Please enter a number!'\r\n while True:\r\n try:\r\n num = float(input(' '))\r\n break\r\n except ValueError:\r\n print (errorstr)\r\n return num\r\n\r\ndef editTruss(nodes, nodeCount, elements, elemCount):\r\n print ('Enter Young\\'s modulus E')\r\n E = getNumber()\r\n print ('Enter beam cross-sectional area A:')\r\n A = getNumber()\r\n return E, A\r\n\r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.7442273497581482, "alphanum_fraction": 0.758436918258667, "avg_line_length": 61.55555725097656, "blob_id": "f1d9d5b2116aed3fdcc4ac5bb83fa077ffebdcd7", "content_id": "8eace1ab89898f0b0fdffa3d60afeeb5ff1ba721", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 563, "license_type": "no_license", "max_line_length": 155, "num_lines": 9, "path": "/README.md", "repo_name": "aybry/trussDFEM", "src_encoding": "UTF-8", "text": "# trussDFEM\ntrussDFEM (\"trusty FEM\") lets you compute and plot truss deformation using FEM methods.\n\nBuild a truss using bearings, nodes, elements and loads, and compute and plot the truss deformation. Not half as fun as it sounds but it looks pretty cool.\n\nHere's the results and plot for truss 1 (option #8 in the menu). Select 8, then 7 in the menu to compute:\n\n![alt-text](https://github.com/aybry/trussDFEM/blob/master/img/truss_1_results.png \"Truss 1 results\")\n![alt-text](https://github.com/aybry/trussDFEM/blob/master/img/truss_1_plot.png \"Truss 1 plot\")\n" } ]
6
ZiqiLiii/si507_final_project
https://github.com/ZiqiLiii/si507_final_project
64dc08f35456b10fd7c7aa32bb65194b9e967817
0b3fe3c0baceedd9573eab40dd2f540ba10309c1
a2a56a3bcc1cfefed913826ea296a4eda9089341
refs/heads/master
2022-05-17T07:20:58.708248
2020-04-28T05:28:48
2020-04-28T05:28:48
257,166,077
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5660973787307739, "alphanum_fraction": 0.5697343349456787, "avg_line_length": 27.36322784423828, "blob_id": "bb60bf826d6054186297ee9adae6565abbf62c90", "content_id": "8987deeecdb3590d3e0c1f23170bac2b3b239430", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6324, "license_type": "no_license", "max_line_length": 125, "num_lines": 223, "path": "/final_proj.py", "repo_name": "ZiqiLiii/si507_final_project", "src_encoding": "UTF-8", "text": "#################################\n##### Name: Ziqi Li\n##### Uniqname: liziqi\n#################################\n\nfrom bs4 import BeautifulSoup\nimport requests\nimport json\nimport secrets\nimport spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport pandas as pd\nimport csv\nimport sqlite3\n\ncid = secrets.CLIENT_ID\nsecret = secrets.CLIENT_SECRET\n\nclient_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)\nsp = spotipy.Spotify(client_credentials_manager = client_credentials_manager)\n\n\n###############################################\n######### Setting for using Cache #############\n###############################################\n\nCACHE_FILE_NAME = 'cache.json'\nCACHE_DICT = {}\n\ndef load_cache(): \n try:\n cache_file = open(CACHE_FILE_NAME, 'r')\n cache_file_contents = cache_file.read()\n cache = json.loads(cache_file_contents)\n cache_file.close()\n except:\n cache = {}\n return cache\n\ndef save_cache(cache): \n cache_file = open(CACHE_FILE_NAME, 'w')\n contents_to_write = json.dumps(cache)\n cache_file.write(contents_to_write)\n cache_file.close()\n\ndef make_url_request_using_cache(url, cache):\n if (url in cache.keys()): \n print(\"Using cache\")\n return cache[url] \n else:\n print(\"Fetching\")\n response = requests.get(url) \n cache[url] = response.text \n save_cache(cache) \n return cache[url] \n\nCACHE_DICT = load_cache()\n\n\n\n\n#####################################################\n#### Scraping a new single page - From Billboard ####\n#####################################################\n\n#Create a list for storage the information about the songs, artists and ranks from Billboard#\nsong_name_list=[]\nsong_artist_list=[]\nsong_rank_list=[]\nhits_list=[]\nurl=\"https://www.billboard.com/charts/hot-100\"\nhtml_text = make_url_request_using_cache(url, CACHE_DICT)\nsoup = BeautifulSoup(html_text, 'html.parser')\nall_list_name = soup.find_all('span',class_=\"chart-element__information__song text--truncate color--primary\")\nall_list_artist = soup.find_all('span',class_=\"chart-element__information__artist text--truncate color--secondary\")\nall_list_rank = soup.find_all('span',class_=\"chart-element__rank__number\")\n\nfor i in all_list_name:\n name = i.text\n song_name_list.append(name)\nfor i in all_list_artist:\n artist = i.text\n song_artist_list.append(artist)\nfor i in all_list_rank:\n rank = i.text\n song_rank_list.append(rank)\nfor x in range(0,100):\n item={}\n item['track_name']= song_name_list[x]\n item['artist_name'] = song_artist_list[x]\n item['rank'] = x + 1\n hits_list.append(item)\n# print(hits_list)\n\n\n\n\n################################################\n#### Access the Web API - From Spotify API ####\n################################################\n\ndef get_tracks_csv():\n # create empty lists where the results are going to be stored\n artist_name = []\n track_name = []\n popularity = []\n track_id = []\n\n # create csv file to store top 10 songs for each artist by using Spotify API\n for i in range(0,10):\n for name in song_artist_list:\n track_results = sp.search(name)\n # print(result['tracks']['items'][0]['artists'])\n for i, t in enumerate(track_results['tracks']['items']):\n artist_name.append(t['artists'][0]['name'])\n track_name.append(t['name'])\n track_id.append(t['id'])\n popularity.append(t['popularity'])\n # print(track_name)\n\n df_tracks = pd.DataFrame({'artist_name':artist_name,'track_name':track_name,'track_id':track_id,'popularity':popularity})\n df_tracks.to_csv('artists.csv') \n\n#get_tracks_csv() \n#since creating the csv file cost a lot of time everytime so for the next steps I just utilize the former createdcsv file.\n\n\n\n\n\n#####################################################\n############# Database ##############################\n#####################################################\n\n#write the pandas dataframe to a sqlite table\ndef create_tracks():\n conn= sqlite3.connect(\"songs.sqlite\")\n cur = conn.cursor()\n df = pd.read_csv('artists.csv',index_col=0)\n df.drop_duplicates(subset=['track_id'],keep = False,inplace=True)\n drop_tracks_sql = 'DROP TABLE IF EXISTS \"Track\"'\n cur.execute(drop_tracks_sql)\n df.to_sql('Track', conn, if_exists='append', index=False)\n conn.close()\n\ncreate_tracks()\n\n\n#create hits table \ndef create_hits():\n conn = sqlite3.connect(\"songs.sqlite\")\n cur = conn.cursor()\n drop_hits_sql = 'DROP TABLE IF EXISTS \"Hits\"'\n \n create_hits_sql = '''\n CREATE TABLE IF NOT EXISTS \"Hits\" (\n \"Track_Name\" TEXT NOT NULL, \n \"Artist_Name\" TEXT NOT NULL,\n \"Rank\" INTEGER PRIMARY KEY NOT NULL\n )\n '''\n cur.execute(drop_hits_sql)\n cur.execute(create_hits_sql)\n conn.commit()\n conn.close()\n\ncreate_hits() \n\n\ndef load_hits():\n conn = sqlite3.connect(\"songs.sqlite\")\n cur = conn.cursor()\n\n insert_hits_sql = '''\n INSERT INTO Hits\n VALUES (?, ?, ?)\n '''\n \n for item in hits_list:\n cur.execute(insert_hits_sql,\n [\n item['track_name'],\n item['artist_name'],\n item['rank']\n ]\n )\n conn.commit()\n conn.close()\n\nload_hits() \n\n\n# since there is no way right now to set a primary key in the pandas df.to_sql() method\n# I need to create a duplicate table and set primary key followed by copying data over, then drop old table to clean up.\ndef edit_tracks():\n conn = sqlite3.connect(\"songs.sqlite\")\n cur = conn.cursor()\n cur.executescript('''\n\n BEGIN TRANSACTION;\n ALTER TABLE Track RENAME TO old_table;\n\n /*create a new table with the same column names and types while\n defining a primary key for the desired column*/\n\n DROP TABLE IF EXISTS \"Tracks\";\n\n CREATE TABLE Tracks (\n artist_name TEXT,\n track_name TEXT,\n track_id TEXT PRIMARY KEY NOT NULL,\n popularity INTEGER\n );\n\n INSERT INTO Tracks SELECT * FROM old_table;\n\n DROP TABLE old_table;\n COMMIT TRANSACTION;\n ''')\n\n conn.close()\n\nedit_tracks()" }, { "alpha_fraction": 0.786507248878479, "alphanum_fraction": 0.8001707792282104, "avg_line_length": 67.88235473632812, "blob_id": "ba1bf8961abbbd1acb4c8ebff1c9c17a21664a3c", "content_id": "005d5db18a1913b27a803531e0ac695e1f7df533", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1171, "license_type": "no_license", "max_line_length": 313, "num_lines": 17, "path": "/README.md", "repo_name": "ZiqiLiii/si507_final_project", "src_encoding": "UTF-8", "text": "# si507_final_project\n\nIt is a project about a simple hot song browser application is realized. \n\nFirst, the user can view the billboard information of the top 100 billboards, and can choose three different sorting methods: ranking, track name, and artist name. In addition, the number of records displayed is used as a filter for users to choose from. \n\nSecondly, the second part is to let the user input a ranking number, so as to get other ranked songs of the artists of the ranked songs and popular songs in Spotify. In addition, users can choose to view the plot to more intuitively view the specific popularity index on Spotify about the artist's popular tracks.\n\nThe final_proj.py file has three parts: scraping form BillBoard, accessing data from Spotify API through spotipy, creating database and load data into tables.\n\nThe cache.json file and the artists.csv file are the files for storaging the data needed for this project.\n\nThe templates folder include three html files for interacting.\n\nThe app.py file utilizes flask to display the data.\n\nAnd Here is the demo video link: https://drive.google.com/file/d/1h6h6B5rUvc6X7Mi6e-9ExnfMtP4EYCY6/view?usp=sharing\n" }, { "alpha_fraction": 0.5962585210800171, "alphanum_fraction": 0.6034013628959656, "avg_line_length": 27, "blob_id": "b016cabebaa3b13f6a04934006cbae53fa61ecfb", "content_id": "2570b68dd87a67f87c9831cd367b2227638fa0c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2940, "license_type": "no_license", "max_line_length": 139, "num_lines": 105, "path": "/app.py", "repo_name": "ZiqiLiii/si507_final_project", "src_encoding": "UTF-8", "text": "\nfrom flask import Flask, render_template, request\nimport sqlite3\nimport plotly.graph_objects as go\n\napp = Flask(__name__)\n\ndef get_songs_results(sort_by,sort_range):\n conn = sqlite3.connect('songs.sqlite')\n cur = conn.cursor()\n\n if sort_by == 'ranking':\n sort_column = 'Rank'\n elif sort_by == 'track name':\n sort_column = 'Track_Name'\n else:\n sort_column = 'Artist_Name'\n \n if sort_range == 'All':\n sort_range_nm = 100\n elif sort_range == '50':\n sort_range_nm = 50\n elif sort_range == '30':\n sort_range_nm = 30\n elif sort_range == '10':\n sort_range_nm = 10\n \n\n q = f'''\n SELECT Track_Name, Artist_Name, Rank\n FROM Hits\n ORDER BY {sort_column}\n LIMIT {sort_range_nm}\n '''\n results = cur.execute(q).fetchall()\n conn.close()\n return results\n\ndef get_more_results(rank_number):\n conn = sqlite3.connect('songs.sqlite')\n cur = conn.cursor()\n \n q = f'''\n SELECT Track_Name, Artist_Name, Rank\n FROM Hits\n WHERE Artist_Name == (SELECT Artist_Name FROM Hits\n WHERE RANK == {rank_number})\n '''\n moreresults = cur.execute(q).fetchall()\n conn.close()\n return moreresults\n\ndef get_spotify_results(rank_number):\n conn = sqlite3.connect('songs.sqlite')\n cur = conn.cursor()\n \n q = f'''\n SELECT Tracks.artist_name, Tracks.track_name, Tracks.popularity\n FROM Tracks \n WHERE Tracks.artist_name == (SELECT Artist_Name FROM Hits\n WHERE RANK == {rank_number})\n '''\n spotifyresults = cur.execute(q).fetchall()\n conn.close()\n return spotifyresults\n\n\[email protected]('/')\ndef index():\n return render_template('index.html')\n\n\[email protected]('/results', methods=['POST'])\ndef results():\n sort_by = request.form['sort']\n sort_range = request.form['region']\n results = get_songs_results(sort_by, sort_range)\n return render_template('results.html', \n sort=sort_by, results=results,region= sort_range)\n\[email protected]('/moreresults', methods=['POST'])\n\ndef moreresults():\n rank_number = request.form[\"number\"]\n moreresults = get_more_results(rank_number)\n spotifyresults = get_spotify_results(rank_number)\n plot_results = request.form.get('plot', False)\n if (plot_results):\n x_vals = [r[1] for r in spotifyresults]\n y_vals = [r[2] for r in spotifyresults]\n bars_data = go.Bar(\n x=x_vals,\n y=y_vals\n )\n fig = go.Figure(data=bars_data)\n div = fig.to_html(full_html=False)\n return render_template('moreresults.html',number=rank_number, moreresults=moreresults,spotifyresults=spotifyresults, plot_div=div)\n else:\n return render_template('moreresults.html', \n number=rank_number, moreresults=moreresults,spotifyresults=spotifyresults)\n\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)" } ]
3
microsoft/SCXcore
https://github.com/microsoft/SCXcore
f9ee3a0157c5f8a1123d517ffdcfdeb0871d88e7
19cffe0bd0ea797f3cecabc387732bfa97115893
3e8a6afc16381ecb255f84f9c86fd0d7df154551
refs/heads/master
2023-08-18T08:41:04.872752
2023-08-03T09:13:06
2023-08-03T09:13:06
46,682,294
17
22
MS-PL
2015-11-22T21:58:55
2023-03-31T21:48:35
2023-08-03T09:13:07
C++
[ { "alpha_fraction": 0.6124035716056824, "alphanum_fraction": 0.6160156726837158, "avg_line_length": 31.99798011779785, "blob_id": "67cef65dd0a07cac1f3a7d97ec9fc953ef8e7e89", "content_id": "628a295829c04bd38444e7c1b4cdef8f082f6a59", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16334, "license_type": "permissive", "max_line_length": 133, "num_lines": 495, "path": "/source/code/providers/SCX_UnixProcess_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_UnixProcess_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-22-2013 17:48:44\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_UnixProcess_Class_Provider.h\"\n#include \"SCX_UnixProcess.h\"\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxthreadlock.h>\n#include <scxcorelib/scxnameresolver.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <scxsystemlib/processinstance.h>\n#include \"support/scxcimutils.h\"\n#include \"support/processprovider.h\"\n#include <sstream>\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/scxpatternfinder.h>\n#include <string>\n\n# define QLENGTH 1000\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nnamespace SCXCore\n{\n ProcessProvider g_ProcessProvider;\n int ProcessProvider::ms_loadCount = 0;\n}\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(Context& context,\n SCX_UnixProcess_Class& inst, bool keysOnly,\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> processinst)\n{\n SCXLogHandle& log = SCXCore::g_ProcessProvider.GetLogHandle();\n\n // Add the key properties first.\n scxulong pid = 0;\n if (processinst->GetPID(pid))\n {\n inst.Handle_value(StrToUTF8(StrFrom(pid)).c_str());\n }\n\n SCX_LOGHYSTERICAL(log, StrAppend(L\"UnixProcess Provider sending instance for handle: \", StrFrom(pid)));\n \n // Add keys of scoping operating system\n try {\n SCXCoreLib::NameResolver mi;\n inst.CSName_value(StrToMultibyte(mi.GetHostDomainname()).c_str());\n } catch (SCXException& e){\n SCX_LOGWARNING(log, StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n try {\n SCXSystemLib::SCXOSTypeInfo osinfo;\n inst.OSName_value(StrToMultibyte(osinfo.GetOSName(true)).c_str());\n } catch (SCXException& e){\n SCX_LOGWARNING(log, StrAppend(\n StrAppend(L\"Can't read OS name because \", e.What()),\n e.Where()));\n }\n\n inst.CSCreationClassName_value(\"SCX_ComputerSystem\");\n inst.OSCreationClassName_value(\"SCX_OperatingSystem\");\n inst.CreationClassName_value(\"SCX_UnixProcess\");\n\n\n if (!keysOnly)\n {\n std::string name(\"\");\n std::vector<std::string> params;\n std::wstring str(L\"\");\n unsigned int uint = 0;\n unsigned short ushort = 0;\n scxulong ulong = 0, ulong1 = 0;\n SCXCoreLib::SCXCalendarTime ctime;\n int ppid = 0;\n\n inst.Description_value(\"A snapshot of a current process\");\n inst.Caption_value(\"Unix process information\");\n\n if (processinst->GetOtherExecutionDescription(str))\n {\n inst.OtherExecutionDescription_value(StrToUTF8(str).c_str());\n }\n\n if (processinst->GetKernelModeTime(ulong))\n {\n inst.KernelModeTime_value(ulong);\n }\n\n if (processinst->GetUserModeTime(ulong))\n {\n inst.UserModeTime_value(ulong);\n }\n\n if (processinst->GetWorkingSetSize(ulong))\n {\n inst.WorkingSetSize_value(ulong);\n }\n\n if (processinst->GetProcessSessionID(ulong))\n {\n inst.ProcessSessionID_value(ulong);\n }\n\n if (processinst->GetProcessTTY(name))\n {\n inst.ProcessTTY_value(name.c_str());\n }\n\n if (processinst->GetModulePath(name))\n {\n inst.ModulePath_value(name.c_str());\n }\n\n if (processinst->GetParameters(params))\n {\n std::vector<mi::String> strArrary;\n for (std::vector<std::string>::const_iterator iter = params.begin();\n iter != params.end(); ++iter)\n {\n strArrary.push_back((*iter).c_str());\n }\n mi::StringA props(&strArrary[0], static_cast<MI_Uint32>(params.size()));\n inst.Parameters_value(props);\n } \n\n if (processinst->GetProcessWaitingForEvent(name))\n {\n inst.ProcessWaitingForEvent_value(name.c_str());\n }\n\n if (processinst->GetName(name))\n {\n inst.Name_value(name.c_str());\n }\n\n if (processinst->GetNormalizedWin32Priority(uint))\n {\n inst.Priority_value(uint);\n }\n\n if (processinst->GetExecutionState(ushort))\n {\n inst.ExecutionState_value(ushort);\n }\n\n if (processinst->GetCreationDate(ctime))\n {\n MI_Datetime creationDate; \n CIMUtils::ConvertToCIMDatetime(creationDate, ctime);\n inst.CreationDate_value(creationDate);\n }\n\n if (processinst->GetTerminationDate(ctime))\n {\n MI_Datetime terminationDate; \n CIMUtils::ConvertToCIMDatetime(terminationDate, ctime);\n inst.TerminationDate_value(terminationDate);\n }\n\n if (processinst->GetParentProcessID(ppid))\n {\n inst.ParentProcessID_value(StrToUTF8(StrFrom(ppid)).c_str());\n }\n\n if (processinst->GetRealUserID(ulong))\n {\n inst.RealUserID_value(ulong);\n }\n\n if (processinst->GetProcessGroupID(ulong))\n {\n inst.ProcessGroupID_value( ulong);\n }\n\n if (processinst->GetProcessNiceValue(uint))\n {\n inst.ProcessNiceValue_value(uint);\n }\n\n if (processinst->GetPercentUserTime(ulong) && processinst->GetPercentPrivilegedTime(ulong1))\n {\n inst.PercentBusyTime_value((unsigned char) (ulong + ulong1));\n }\n\n if (processinst->GetUsedMemory(ulong))\n {\n inst.UsedMemory_value(ulong);\n }\n }\n context.Post(inst);\n\n SCX_LOGHYSTERICAL(log, StrAppend(L\"UnixProcess Provider sent instance for handle: \", StrFrom(pid)));\n}\n\nSCX_UnixProcess_Class_Provider::SCX_UnixProcess_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_UnixProcess_Class_Provider::~SCX_UnixProcess_Class_Provider()\n{\n}\n\nvoid SCX_UnixProcess_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n SCXCore::g_ProcessProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_ProcessProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_UnixProcess_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcess_Class_Provider::Load\", SCXCore::g_ProcessProvider.GetLogHandle() );\n}\n\nvoid SCX_UnixProcess_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n SCXCore::g_ProcessProvider.Unload();\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcess_Class_Provider::Unload\", SCXCore::g_ProcessProvider.GetLogHandle() );\n}\n\nvoid SCX_UnixProcess_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_ProcessProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"UnixProcess Provider EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n\n SCXHandle<SCXSystemLib::ProcessEnumeration> processEnum = SCXCore::g_ProcessProvider.GetProcessEnumerator();\n\n\tstring processID=\"\";\n\n if(filter) {\n char* exprStr[QLENGTH]={NULL};\n char* qtypeStr[QLENGTH]={NULL};\n\n const MI_Char** expr=(const MI_Char**)&exprStr;\n const MI_Char** qtype=(const MI_Char**)&qtypeStr;\n\n MI_Filter_GetExpression(filter, qtype, expr);\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"Unix Process Provider Filter Set with Expression: \",*expr));\n\n\t std::wstring filterQuery(SCXCoreLib::StrFromUTF8(*expr));\n\n SCXCoreLib::SCXPatternFinder::SCXPatternCookie s_patternID = 0, id=0;\n SCXCoreLib::SCXPatternFinder::SCXPatternMatch param;\n std::wstring s_pattern(L\"select * from SCX_UnixProcess where Handle=%name\");\n\n SCXCoreLib::SCXPatternFinder patterenfinder;\n patterenfinder.RegisterPattern(s_patternID, s_pattern);\n\n bool status=patterenfinder.Match(filterQuery, id, param);\n\n if (status && id == s_patternID && param.end() != param.find(L\"name\"))\n {\n processID=StrToUTF8(param.find(L\"name\")->second);\n SCX_LOGTRACE(log, StrAppend(L\"Unix Process Provider Enum Requested for Process ID: \", param.find(L\"name\")->second));\n }\n }\n\n if ( processID != \"\" ) {\n stringstream ss(processID);\n int pid;\n ss >> pid;\n processEnum->UpdateSpecific(pid);\n }\n else\n processEnum->Update();\n\n SCX_LOGTRACE(log, StrAppend(L\"Number of Processes = \", processEnum->Size()));\n\n for(size_t i = 0; i < processEnum->Size(); i++)\n {\n if ( processID != \"\"){\n scxulong pid = 0;\n processEnum->GetInstance(i)->GetPID(pid);\n stringstream ss; ss<<pid;\n string spid;ss>>spid;\n if ( spid != processID) continue;\n }\n\n SCX_UnixProcess_Class proc;\n EnumerateOneInstance(context, proc, keysOnly, processEnum->GetInstance(i));\n if ( processID != \"\") break;\n }\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcess_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"UnixProcess Provider EnumerateInstances end\");\n}\n\nvoid SCX_UnixProcess_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcess_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n\n // We have 6-part key:\n // [Key] CSCreationClassName=SCX_ComputerSystem\n // [Key] CSName=jeffcof64-rhel6-01.scx.com\n // [Key] OSCreationClassName=SCX_OperatingSystem\n // [Key] OSName=Red Hat Distribution\n // [Key] CreationClassName=SCX_UnixProcess\n // [Key] Handle=54321\n\n if (!instanceName.CSCreationClassName_exists() || !instanceName.CSName_exists() ||\n !instanceName.OSCreationClassName_exists() || !instanceName.OSName_exists() ||\n !instanceName.CreationClassName_exists() || !instanceName.Handle_exists())\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::string csName;\n try {\n NameResolver mi;\n csName = StrToMultibyte(mi.GetHostDomainname()).c_str();\n } catch (SCXException& e) {\n SCX_LOGWARNING(SCXCore::g_ProcessProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n std::string osName;\n try {\n SCXSystemLib::SCXOSTypeInfo osinfo;\n osName = StrToMultibyte(osinfo.GetOSName(true)).c_str();\n } catch (SCXException& e){\n SCX_LOGWARNING(SCXCore::g_ProcessProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read OS name because \", e.What()),\n e.Where()));\n }\n\n // Now compare (case insensitive for the class names, case sensitive for the others)\n if ( 0 != strcasecmp(\"SCX_ComputerSystem\", instanceName.CSCreationClassName_value().Str())\n || 0 != strcmp(csName.c_str(), instanceName.CSName_value().Str())\n || 0 != strcasecmp(\"SCX_OperatingSystem\", instanceName.OSCreationClassName_value().Str())\n || 0 != strcmp(osName.c_str(), instanceName.OSName_value().Str())\n || 0 != strcasecmp(\"SCX_UnixProcess\", instanceName.CreationClassName_value().Str()))\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n if (!strlen(instanceName.Handle_value().Str()) )\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n SCX_LOGTRACE(SCXCore::g_ProcessProvider.GetLogHandle(), L\"Process Provider GetInstances\");\n SCXHandle<SCXSystemLib::ProcessEnumeration> processEnum = SCXCore::g_ProcessProvider.GetProcessEnumerator();\n processEnum->Update();\n\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> processInst = processEnum->GetInstance(\n StrFromMultibyte(instanceName.Handle_value().Str()));\n\n if (processInst == NULL)\n {\n // Didn't find a match.\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n // Found a Match. Enumerate the properties for the instance.\n SCX_UnixProcess_Class proc;\n EnumerateOneInstance(context, proc, false, processInst);\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcess_Class_Provider::GetInstances\", SCXCore::g_ProcessProvider.GetLogHandle() );\n\n\n}\n\nvoid SCX_UnixProcess_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcess_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_UnixProcess_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcess_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_UnixProcess_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcess_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_UnixProcess_Class_Provider::Invoke_RequestStateChange(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcess_Class& instanceName,\n const SCX_UnixProcess_RequestStateChange_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_UnixProcess_Class_Provider::Invoke_TopResourceConsumers(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcess_Class& instanceName,\n const SCX_UnixProcess_TopResourceConsumers_Class& in)\n{\n SCXCoreLib::SCXLogHandle log = SCXCore::g_ProcessProvider.GetLogHandle();\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n SCX_LOGTRACE( log, L\"SCX_UnixProcess_Class_Provider::Invoke_TopResourceConsumers\" );\n\n // Validate that we have mandatory arguments\n if ( !in.count_exists() || !in.resource_exists() )\n {\n SCX_LOGTRACE( log, L\"Missing arguments to Invoke_TopResourceConsumers method\" );\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n std::wstring return_str;\n std::wstring resourceStr = StrFromUTF8(in.resource_value().Str());\n SCXCore::g_ProcessProvider.GetTopResourceConsumers(resourceStr, (unsigned short)in.count_value(), return_str);\n\n SCX_UnixProcess_TopResourceConsumers_Class inst;\n inst.MIReturn_value(StrToMultibyte(return_str).c_str());\n\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcess_Class_Provider::Invoke_TopResourceConsumers\", log );\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.6113153100013733, "alphanum_fraction": 0.6199226379394531, "avg_line_length": 37.15497970581055, "blob_id": "80f2d896edbc85b3ea897202d186728125a53878", "content_id": "7bd1d68ea348a9a882df06116869a389e4be7ff9", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10340, "license_type": "permissive", "max_line_length": 148, "num_lines": 271, "path": "/test/code/providers/runas_provider/scxrunasconfigurator_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the runas configurator\n\n \\date 2008-08-27 16:04:59\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxrunasconfigurator.h>\n#include <testutils/scxunit.h>\n\nusing namespace SCXCoreLib;\nusing namespace SCXCore;\n\n/*----------------------------------------------------------------------------*/\n/**\n Class for parsing strings with generic configuration\n\n*/\nclass ConfigurationStringParser : public ConfigurationParser\n{\npublic:\n ConfigurationStringParser(const std::wstring& configuration) :\n m_Configuration(configuration)\n {};\n\n void Parse()\n {\n std::wistringstream stream(m_Configuration);\n ParseStream(stream);\n };\nprivate:\n std::wstring m_Configuration;\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n Class for writing generic configuration to a string.\n\n*/\nclass ConfigurationStringWriter : public ConfigurationWriter\n{\npublic:\n ConfigurationStringWriter() :\n m_Configuration(L\"\")\n {};\n\n void Write()\n {\n std::wostringstream stream(m_Configuration);\n WriteToStream(stream);\n m_Configuration = stream.str();\n };\n \n std::wstring GetString() const\n {\n return m_Configuration;\n }\nprivate:\n std::wstring m_Configuration;\n};\n\nclass SCXRunAsConfiguratorTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXRunAsConfiguratorTest );\n CPPUNIT_TEST( testEmptyConfiguration );\n CPPUNIT_TEST( testCommentsAreIgnored );\n CPPUNIT_TEST( testInvalidRowsAreIgnored );\n CPPUNIT_TEST( testAllowRoot );\n CPPUNIT_TEST( testGetChRootPath );\n CPPUNIT_TEST( testGetCWD );\n CPPUNIT_TEST( testUnexistingEnvVar );\n CPPUNIT_TEST( testSimpleEnvVarReplacement );\n CPPUNIT_TEST( testRecursiveEnvVarReplacement );\n CPPUNIT_TEST( testEnvVarRecurseLimit );\n CPPUNIT_TEST( testWriteEmptyConfiguration );\n CPPUNIT_TEST( testWriteAndRead );\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n void setUp(void)\n {\n }\n\n void tearDown(void)\n {\n }\n\n void testEmptyConfiguration()\n {\n RunAsConfigurator p = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n CPPUNIT_ASSERT(p.GetAllowRoot() == true);\n CPPUNIT_ASSERT(p.GetChRootPath() == SCXFilePath(L\"\"));\n CPPUNIT_ASSERT(p.GetCWD() == SCXFilePath(L\"/var/opt/microsoft/scx/tmp/\"));\n }\n\n void testCommentsAreIgnored()\n {\n RunAsConfigurator p = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"# AllowRoot = false\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0) ).Parse();\n \n CPPUNIT_ASSERT(p.GetAllowRoot() == true);\n }\n\n void testInvalidRowsAreIgnored()\n {\n std::wstring configData(L\"# The next few lines are invalid\\n\"\n L\"AllowRoot = false = invalid row\\n\"\n L\"AllowRoot\\n\"\n L\"AllowRoot = invalidvalue\\n\"\n L\"${CWD}\\n\"\n L\"# Next is the valid line\\n\"\n L\"AllowRoot = true\\n\");\n RunAsConfigurator configParser(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(configData) ), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0));\n configParser.Parse();\n \n CPPUNIT_ASSERT(configParser.GetAllowRoot() == true);\n }\n\n void testAllowRoot()\n {\n // inline construction was too complicated for old HP compiler - declare a variable\n RunAsConfigurator p1 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"AllowRoot = false\")),\n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n \n CPPUNIT_ASSERT(p1.GetAllowRoot() == false);\n\n RunAsConfigurator p2 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"AllowRoot = no\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n \n CPPUNIT_ASSERT(p2.GetAllowRoot() == false);\n\n RunAsConfigurator p3 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"AllowRoot = 0\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n \n CPPUNIT_ASSERT(p3.GetAllowRoot() == false);\n }\n\n void testGetChRootPath()\n {\n RunAsConfigurator p = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"ChRootPath = /What/ever/\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n \n CPPUNIT_ASSERT( p.GetChRootPath() == SCXFilePath(L\"/What/ever/\"));\n }\n\n void testGetCWD()\n {\n RunAsConfigurator p = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"CWD = /foo/bar/\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n \n CPPUNIT_ASSERT( p.GetCWD() == SCXFilePath(L\"/foo/bar/\"));\n }\n\n void testUnexistingEnvVar()\n {\n // Test unexisting env var results in empty string.\n RunAsConfigurator p1 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"ChRootPath = $THIS_DOES_NOT_EXIST\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n CPPUNIT_ASSERT(p1.GetChRootPath() == L\"\");\n \n // Test again with different notation\n RunAsConfigurator p2 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"ChRootPath = ${THIS_DOES_NOT_EXIST}\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n CPPUNIT_ASSERT(p2.GetChRootPath() == L\"\");\n }\n\n void testSimpleEnvVarReplacement()\n {\n putenv(const_cast<char *>(\"TEST_ENV_VARS_1=testEnvVars_1\"));\n RunAsConfigurator p1 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"ChRootPath = $TEST_ENV_VARS_1/\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n CPPUNIT_ASSERT(p1.GetChRootPath() == L\"testEnvVars_1/\");\n \n // Test again with different notation\n RunAsConfigurator p2 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"ChRootPath = ${TEST_ENV_VARS_1}/\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n CPPUNIT_ASSERT(p2.GetChRootPath() == L\"testEnvVars_1/\");\n }\n\n void testRecursiveEnvVarReplacement()\n {\n putenv(const_cast<char *>(\"TEST_ENV_VARS_2=/$TEST_ENV_VARS_3/$TEST_ENV_VARS_4/\"));\n putenv(const_cast<char *>(\"TEST_ENV_VARS_3=testEnvVars_3\"));\n putenv(const_cast<char *>(\"TEST_ENV_VARS_4=testEnvVars_4\"));\n RunAsConfigurator p1 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"ChRootPath = $TEST_ENV_VARS_2\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n CPPUNIT_ASSERT(p1.GetChRootPath() == L\"/testEnvVars_3/testEnvVars_4/\");\n // Test again with different notation\n putenv(const_cast<char *>(\"TEST_ENV_VARS_2=/${TEST_ENV_VARS_3}/${TEST_ENV_VARS_4}/\"));\n putenv(const_cast<char *>(\"TEST_ENV_VARS_3=testEnvVars_3\"));\n putenv(const_cast<char *>(\"TEST_ENV_VARS_4=testEnvVars_4\"));\n RunAsConfigurator p2 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"ChRootPath = ${TEST_ENV_VARS_2}\")), \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n CPPUNIT_ASSERT(p2.GetChRootPath() == L\"/testEnvVars_3/testEnvVars_4/\");\n }\n\n void testEnvVarRecurseLimit()\n {\n // Test that we don't recurse too far.\n putenv(const_cast<char *>(\"TEST_ENV_VARS_5=/$TEST_ENV_VARS_6/\"));\n putenv(const_cast<char *>(\"TEST_ENV_VARS_6=/$TEST_ENV_VARS_5/\"));\n\n RunAsConfigurator p(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"ChRootPath = $TEST_ENV_VARS_5\")),\n SCXCoreLib::SCXHandle<ConfigurationWriter>(0));\n\n try {\n p.Parse();\n CPPUNIT_FAIL(\"\\\"SCXRunAsConfigurationException\\\" exception expected\");\n } catch(SCXRunAsConfigurationException& e) {\n CPPUNIT_ASSERT(e.What().find(L\"recursion\") != std::wstring::npos);\n }\n }\n\n void testWriteEmptyConfiguration()\n {\n SCXHandle<ConfigurationStringWriter> writer( new ConfigurationStringWriter() );\n RunAsConfigurator p = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"\")), \n writer).Write();\n CPPUNIT_ASSERT(L\"\" == writer->GetString());\n }\n\n void testWriteAndRead()\n {\n SCXHandle<ConfigurationStringWriter> writer( new ConfigurationStringWriter() );\n RunAsConfigurator c1 = RunAsConfigurator(\n SCXCoreLib::SCXHandle<ConfigurationParser>(new ConfigurationStringParser(L\"\")), \n writer);\n c1.SetAllowRoot(false);\n c1.SetChRootPath(L\"/what/ever/\");\n c1.SetCWD(L\"/foo/bar/\");\n c1.Write();\n\n SCXHandle<ConfigurationParser> parser( new ConfigurationStringParser(writer->GetString()));\n RunAsConfigurator c2 = RunAsConfigurator(\n parser, \n SCXCoreLib::SCXHandle<ConfigurationWriter>(0)).Parse();\n\n CPPUNIT_ASSERT(c2.GetAllowRoot() == false);\n CPPUNIT_ASSERT(c2.GetChRootPath() == SCXFilePath(L\"/what/ever/\"));\n CPPUNIT_ASSERT(c2.GetCWD() == SCXFilePath(L\"/foo/bar/\"));\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXRunAsConfiguratorTest );\n" }, { "alpha_fraction": 0.6766355037689209, "alphanum_fraction": 0.6853582262992859, "avg_line_length": 31.755102157592773, "blob_id": "cd564c730100a4bbf58233a32609241a33b0c0c9", "content_id": "216019daeab33622b335b023465ba8dfe107a77e", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1605, "license_type": "permissive", "max_line_length": 100, "num_lines": 49, "path": "/source/code/shared/tools/scx_prune_repository/dependencywalker.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n#\n##\n# Contains the DependencyWalker class\n#\n# Date: 2008-10-28 16:19:13\n#\n\nfrom moffile import MofFile\n\n##\n# This class knows how to translate cim class\n# dependencies to generate a list of filenames\n# that must be included for a functional\n# repository.\n#\nclass DependencyWalker:\n ##\n # Constructor\n # Recursively builds up the list of files in the mof repository\n # that must be included in the final repository in order for\n # all the dependencies off all mof files in moffiles to be sattisfied.\n #\n def __init__(self, mofrepository, moffiles):\n self.mofRepository = mofrepository\n self.files = []\n for moffile in moffiles:\n self.RecursiveGetRequiredFiles(moffile)\n \n ##\n # Recursively builds up the list of files in the mof repository\n # that must be included in the final repository in order for\n # all the dependencies of moffile to be sattisfied.\n #\n def RecursiveGetRequiredFiles(self, moffile):\n cimclasses = moffile.GetDependentClasses()\n for cimclass in cimclasses:\n definingFile = self.mofRepository.GetFileDefiningClass(cimclass)\n if definingFile and definingFile not in self.files:\n self.RecursiveGetRequiredFiles(definingFile)\n self.files.append(definingFile)\n\n ##\n # Return the list of mof files generated by the constructor as\n # a list of MofFile objects.\n #\n def GetRequiredFiles(self):\n return self.files\n" }, { "alpha_fraction": 0.6211221218109131, "alphanum_fraction": 0.6225742697715759, "avg_line_length": 35.06904602050781, "blob_id": "86c24212cde95fefcbd09a4d5eeda03d6549be75", "content_id": "39ad748acbae873df1500ee29f81edc2dd26f711", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15150, "license_type": "permissive", "max_line_length": 112, "num_lines": 420, "path": "/test/code/shared/tools/scx_admin/runasadminprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. \n \n*/\n/**\n \\file \n\n \\brief Tests for cim (i.e. openpegasus) configurator functionality which is part of the scx_admin tool\n\n \\date 2008-08-28 16:41:48\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <testutils/scxunit.h> /* This will include CPPUNIT helper macros too */\n#include <scxcorelib/scxfile.h>\n\n#include \"runasadminprovider.h\"\n\n/*----------------------------------------------------------------------------*/\n/**\n Class for parsing strings with generic configuration\n\n*/\nclass ConfigurationStringParser : public SCXCore::ConfigurationParser\n{\npublic:\n ConfigurationStringParser(const std::wstring& configuration) :\n m_Configuration(configuration)\n {};\n\n void Parse()\n {\n std::wistringstream stream(m_Configuration);\n ParseStream(stream);\n };\nprivate:\n std::wstring m_Configuration;\n};\n\nclass ConfigurationDummyWriter : public SCXCore::ConfigurationWriter {\npublic:\n // this function is called from \"SCX_RunAsConfigurator::Set\"\n // since the latest has to update configuration file.\n // in unit-test we ignore it, so original file is not updated by the test\n void Write() {}\n \n};\n \nclass RunAsAdminProviderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( RunAsAdminProviderTest );\n CPPUNIT_TEST( TestEmptyConfiguration );\n CPPUNIT_TEST( TestWriteAndRead );\n CPPUNIT_TEST( TestUnsupportedValues );\n CPPUNIT_TEST( TestReset );\n CPPUNIT_TEST( TestResetAllowRootWithNoSSHConfFile );\n CPPUNIT_TEST( TestResetAllowRootWithNoSSHConf );\n CPPUNIT_TEST( TestResetAllowRootWithSSHConfTrue );\n CPPUNIT_TEST( TestResetAllowRootWithSSHConfFalse );\n CPPUNIT_TEST( ResetCWDIsCaseInsensitive );\n CPPUNIT_TEST( ResetChRootPathIsCaseInsensitive );\n CPPUNIT_TEST( ResetAllowRootIsCaseInsensitive );\n CPPUNIT_TEST( CWDIsCaseInsensitive );\n CPPUNIT_TEST( CWDValueIsCaseSensitive );\n CPPUNIT_TEST( ChRootPathIsCaseInsensitive );\n CPPUNIT_TEST( ChRootPathValueIsCaseSensitive );\n CPPUNIT_TEST( AllowRootIsCaseInsensitive );\n CPPUNIT_TEST( AllowRootValueIsCaseInsensitive );\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n SCX_RunAsAdminProvider GivenAdminProviderWithEmptyConfiguration()\n {\n return SCX_RunAsAdminProvider(\n SCXCoreLib::SCXHandle<SCXCore::ConfigurationParser>(new ConfigurationStringParser(L\"\")), \n SCXCoreLib::SCXHandle<SCXCore::ConfigurationWriter>(new ConfigurationDummyWriter),\n SCXCoreLib::SCXFilePath(m_sshConf)\n );\n }\n\n SCXCoreLib::SCXFilePath m_sshConf;\n\n /**\n This method will print the configuration to a stream and then use \n a RunAsConfigurator to parse the output so that it can be verified.\n */\n SCXCore::RunAsConfigurator GivenAReparsedConfiguration(const SCX_RunAsAdminProvider& conf)\n {\n // print configuration to stream.\n std::wostringstream buf;\n conf.Print(buf);\n\n // Create a string configuration parser.\n SCXHandle<ConfigurationStringParser> parser( new ConfigurationStringParser(buf.str()));\n \n // Inject the string configuration parser into a RunAsConfigurator and use it to\n // parse the configuration.\n return SCXCore::RunAsConfigurator(parser, \n SCXCoreLib::SCXHandle<SCXCore::ConfigurationWriter>(0))\n .Parse();\n }\n\npublic:\n RunAsAdminProviderTest() : m_sshConf(L\"./sshd.conf\")\n {}\n\n void setUp(void)\n {\n CPPUNIT_ASSERT( ! SCXCoreLib::SCXFile::Exists(m_sshConf) );\n }\n\n void tearDown(void)\n {\n SCXCoreLib::SCXFile::Delete(m_sshConf);\n }\n\n void TestEmptyConfiguration()\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n std::wostringstream buf;\n CPPUNIT_ASSERT(conf.Print(buf));\n CPPUNIT_ASSERT(L\"CWD = /var/opt/microsoft/scx/tmp/\\nChRootPath = \\nAllowRoot = true\\n\" == buf.str());\n }\n\n void TestWriteAndRead()\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n\n CPPUNIT_ASSERT(conf.Set(L\"AllowRoot\", L\"false\"));\n CPPUNIT_ASSERT(conf.Set(L\"ChRootPath\", L\"/what/ever/\"));\n CPPUNIT_ASSERT(conf.Set(L\"CWD\", L\"/foo/bar/\"));\n std::wostringstream buf;\n CPPUNIT_ASSERT(conf.Print(buf));\n \n SCXHandle<ConfigurationStringParser> parser( new ConfigurationStringParser(buf.str()));\n SCXCore::RunAsConfigurator c2 = SCXCore::RunAsConfigurator(\n parser, \n SCXCoreLib::SCXHandle<SCXCore::ConfigurationWriter>(0)).Parse();\n\n CPPUNIT_ASSERT(c2.GetAllowRoot() == false);\n CPPUNIT_ASSERT(c2.GetChRootPath() == SCXFilePath(L\"/what/ever/\"));\n CPPUNIT_ASSERT(c2.GetCWD() == SCXFilePath(L\"/foo/bar/\"));\n }\n\n void TestUnsupportedValues()\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n\n CPPUNIT_ASSERT_THROW_MESSAGE( \"exception is expected for unsupported property\",\n conf.Set(L\"AllowRoot\", L\"blaha\"),\n SCXAdminException );\n \n CPPUNIT_ASSERT_THROW_MESSAGE( \"exception is expected for unsupported property\",\n conf.Set(L\"NotSupported\", L\"/what/ever/\"),\n SCXAdminException );\n }\n void TestReset()\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n\n CPPUNIT_ASSERT(conf.Set(L\"ChRootPath\", L\"/what/ever/\"));\n CPPUNIT_ASSERT(conf.Set(L\"CWD\", L\"/foo/bar/\"));\n CPPUNIT_ASSERT(conf.Set(L\"AllowRoot\", L\"false\"));\n\n CPPUNIT_ASSERT(conf.Reset(L\"ChRootPath\"));\n CPPUNIT_ASSERT(conf.Reset(L\"CWD\"));\n CPPUNIT_ASSERT(conf.Reset(L\"AllowRoot\"));\n\n CPPUNIT_ASSERT_THROW_MESSAGE( \"exception is expected for unsupported property\",\n conf.Reset(L\"NotSupported\"),\n SCXAdminException );\n \n std::wostringstream buf;\n CPPUNIT_ASSERT(conf.Print(buf));\n CPPUNIT_ASSERT(L\"CWD = /var/opt/microsoft/scx/tmp/\\nChRootPath = \\nAllowRoot = true\\n\" == buf.str());\n }\n\n void TestResetAllowRootWithNoSSHConfFile()\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n\n CPPUNIT_ASSERT(conf.Set(L\"AllowRoot\", L\"false\"));\n CPPUNIT_ASSERT(conf.Reset(L\"AllowRoot\"));\n std::wostringstream buf;\n CPPUNIT_ASSERT(conf.Print(buf));\n CPPUNIT_ASSERT(L\"CWD = /var/opt/microsoft/scx/tmp/\\nChRootPath = \\nAllowRoot = true\\n\" == buf.str());\n }\n\n void TestResetAllowRootWithNoSSHConf()\n {\n // This tests an ssh configuration whith no PermitRootLogin setting.\n std::vector<std::wstring> lines;\n lines.push_back(L\"something 42\");\n lines.push_back(L\"# PermitRootLogin no\");\n lines.push_back(L\"something else\");\n lines.push_back(L\"\");\n SCXFile::WriteAllLines(m_sshConf, lines, std::ios_base::out);\n \n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n\n CPPUNIT_ASSERT(conf.Set(L\"AllowRoot\", L\"false\"));\n CPPUNIT_ASSERT(conf.Reset(L\"AllowRoot\"));\n std::wostringstream buf;\n CPPUNIT_ASSERT(conf.Print(buf));\n CPPUNIT_ASSERT(L\"CWD = /var/opt/microsoft/scx/tmp/\\nChRootPath = \\nAllowRoot = true\\n\" == buf.str());\n }\n\n void TestResetAllowRootWithSSHConfTrue()\n {\n std::vector<std::wstring> lines;\n lines.push_back(L\"PermitRootLogin yes\");\n lines.push_back(L\"\");\n SCXFile::WriteAllLines(m_sshConf, lines, std::ios_base::out);\n \n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n\n CPPUNIT_ASSERT(conf.Set(L\"AllowRoot\", L\"false\"));\n CPPUNIT_ASSERT(conf.Reset(L\"AllowRoot\"));\n std::wostringstream buf;\n CPPUNIT_ASSERT(conf.Print(buf));\n CPPUNIT_ASSERT(L\"CWD = /var/opt/microsoft/scx/tmp/\\nChRootPath = \\nAllowRoot = true\\n\" == buf.str());\n }\n\n void TestResetAllowRootWithSSHConfFalse()\n {\n std::vector<std::wstring> lines;\n lines.push_back(L\"PermitRootLogin no\");\n lines.push_back(L\"\");\n SCXFile::WriteAllLines(m_sshConf, lines, std::ios_base::out);\n \n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n\n CPPUNIT_ASSERT(conf.Set(L\"AllowRoot\", L\"false\"));\n CPPUNIT_ASSERT(conf.Reset(L\"AllowRoot\"));\n std::wostringstream buf;\n CPPUNIT_ASSERT(conf.Print(buf));\n CPPUNIT_ASSERT(L\"CWD = /var/opt/microsoft/scx/tmp/\\nChRootPath = \\nAllowRoot = false\\n\" == buf.str());\n }\n\n /**\n The CWD parameter to the reset command should be\n case insensitive.\n */ \n void ResetCWDIsCaseInsensitive()\n {\n std::vector<std::wstring> parameters;\n parameters.push_back(L\"CWD\");\n parameters.push_back(L\"cwd\");\n parameters.push_back(L\"CwD\");\n\n for (std::vector<std::wstring>::const_iterator iter = parameters.begin();\n iter != parameters.end();\n ++iter)\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(L\"CWD\", L\"/foo/bar/\");\n conf.Reset(*iter);\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetCWD() != SCXFilePath(L\"/foo/bar/\"));\n }\n }\n\n /**\n The ChRootPath parameter to the reset command should be\n case insensitive.\n */ \n void ResetChRootPathIsCaseInsensitive()\n {\n std::vector<std::wstring> parameters;\n parameters.push_back(L\"ChRootPath\");\n parameters.push_back(L\"chrootpath\");\n parameters.push_back(L\"CHROOTPATH\");\n\n for (std::vector<std::wstring>::const_iterator iter = parameters.begin();\n iter != parameters.end();\n ++iter)\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(L\"ChRootPath\", L\"/foo/bar/\");\n conf.Reset(*iter);\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetChRootPath() != SCXFilePath(L\"/foo/bar/\"));\n }\n }\n\n /**\n The AllowRoot parameter to the reset command should be\n case insensitive.\n */ \n void ResetAllowRootIsCaseInsensitive()\n {\n std::vector<std::wstring> parameters;\n parameters.push_back(L\"AllowRoot\");\n parameters.push_back(L\"allowroot\");\n parameters.push_back(L\"ALLOWROOT\");\n\n for (std::vector<std::wstring>::const_iterator iter = parameters.begin();\n iter != parameters.end();\n ++iter)\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(L\"AllowRoot\", L\"false\");\n conf.Reset(*iter);\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetAllowRoot() == true);\n }\n }\n\n /**\n The CWD parameter (the name) to the set command should be\n case insensitive.\n */ \n void CWDIsCaseInsensitive()\n {\n std::vector<std::wstring> parameters;\n parameters.push_back(L\"CWD\");\n parameters.push_back(L\"cwd\");\n parameters.push_back(L\"CwD\");\n\n for (std::vector<std::wstring>::const_iterator iter = parameters.begin();\n iter != parameters.end();\n ++iter)\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(*iter, L\"/foo/bar/\");\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetCWD() == SCXFilePath(L\"/foo/bar/\"));\n }\n }\n\n /**\n The value of the CWD setting should becase sensitive.\n */ \n void CWDValueIsCaseSensitive()\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(L\"CWD\", L\"/FoO/bAr/\");\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetCWD() == SCXFilePath(L\"/FoO/bAr/\"));\n }\n\n /**\n The ChRootPath parameter (the name) to the set command should be\n case insensitive.\n */\n void ChRootPathIsCaseInsensitive()\n {\n std::vector<std::wstring> parameters;\n parameters.push_back(L\"ChRootPath\");\n parameters.push_back(L\"chrootpath\");\n parameters.push_back(L\"CHROOTPATH\");\n\n for (std::vector<std::wstring>::const_iterator iter = parameters.begin();\n iter != parameters.end();\n ++iter)\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(*iter, L\"/foo/bar/\");\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetChRootPath() == SCXFilePath(L\"/foo/bar/\"));\n }\n }\n\n /**\n The value of the ChRootPath setting should becase sensitive.\n */ \n void ChRootPathValueIsCaseSensitive()\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(L\"ChRootPath\", L\"/FoO/bAr/\");\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetChRootPath() == SCXFilePath(L\"/FoO/bAr/\"));\n }\n\n /**\n The AllowRoot parameter (the name) to the set command should be\n case insensitive.\n */ \n void AllowRootIsCaseInsensitive()\n {\n std::vector<std::wstring> parameters;\n parameters.push_back(L\"AllowRoot\");\n parameters.push_back(L\"allowroot\");\n parameters.push_back(L\"ALLOWROOT\");\n\n for (std::vector<std::wstring>::const_iterator iter = parameters.begin();\n iter != parameters.end();\n ++iter)\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(*iter, L\"false\");\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetAllowRoot() == false);\n }\n }\n\n /**\n The value of the AllowRoot setting should becase insensitive.\n */ \n void AllowRootValueIsCaseInsensitive()\n {\n std::vector<std::wstring> parameters;\n parameters.push_back(L\"false\");\n parameters.push_back(L\"FALSE\");\n parameters.push_back(L\"FaLsE\");\n\n for (std::vector<std::wstring>::const_iterator iter = parameters.begin();\n iter != parameters.end();\n ++iter)\n {\n SCX_RunAsAdminProvider conf = GivenAdminProviderWithEmptyConfiguration();\n conf.Set(L\"AllowRoot\", *iter);\n SCXCore::RunAsConfigurator c = GivenAReparsedConfiguration(conf);\n CPPUNIT_ASSERT(c.GetAllowRoot() == false);\n }\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( RunAsAdminProviderTest ); \n" }, { "alpha_fraction": 0.5118573904037476, "alphanum_fraction": 0.5178965926170349, "avg_line_length": 29.1733341217041, "blob_id": "669d2f8a9d2cb1ae44a414d1ff25077ccd8b8a3a", "content_id": "21c572f3b107418c2e564bf54992849b4129dc0d", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6789, "license_type": "permissive", "max_line_length": 137, "num_lines": 225, "path": "/source/code/providers/support/processprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file processprovider.cpp\n\n \\brief implementation of the Process Provider class.\n \n \\date 12-03-27 14:15\n*/\n/*----------------------------------------------------------------------------*/\n\n#include \"processprovider.h\"\n#include <scxsystemlib/processenumeration.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/stringaid.h>\n\n#include <sstream>\n#include <algorithm>\n#include <vector>\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\n\nnamespace SCXCore\n{\n\n /*----------------------------------------------------------------------------*/\n /**\n Struct used for sorting on a specific value\n */\n struct ProcessInstanceSort \n {\n ProcessInstanceSort() : procinst(0), value(0){}\n\n //! Pointer to instance containing all values\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> procinst;\n //! Copy of value to sort on\n scxulong value;\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Compare two ProcessInstanceSort structs\n\n \\param[in] p1 First struct to comapare\n \\param[in] p2 Second struct to compare\n\n \\returns true if value in p1 is greater then in p2\n */\n static bool CompareProcSort(ProcessInstanceSort p1, ProcessInstanceSort p2)\n {\n return p1.value > p2.value;\n }\n\n void ProcessProvider::Load()\n {\n SCXASSERT( ms_loadCount >= 0 );\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.process_provider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"ProcessProvider::Load()\");\n\n // UnixProcess provider\n SCXASSERT( NULL == m_processes );\n m_processes = new ProcessEnumeration();\n m_processes->Init();\n }\n }\n\n void ProcessProvider::Unload()\n {\n SCX_LOGTRACE(m_log, L\"ProcessProvider::Unload()\");\n\n SCXASSERT( ms_loadCount >= 1 );\n if ( 0 == --ms_loadCount )\n {\n if (m_processes != NULL)\n {\n m_processes->CleanUp();\n m_processes = NULL;\n }\n }\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Get the value for the spcified resource from a specified instance\n\n \\param[in] resource Name of resource to get\n \\param[in] processinst Instance to get resource from\n\n \\returns Value for specifed resource\n\n \\throws SCXInternalErrorException If given resource not handled\n */\n scxulong ProcessProvider::GetResource(const std::wstring &resource, SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> processinst)\n {\n\n scxulong res = 0;\n bool gotResource = false;\n\n if (StrCompare(resource, L\"CPUTime\", true) == 0)\n {\n unsigned int cputime;\n gotResource = processinst->GetCPUTime(cputime);\n res = static_cast<scxulong>(cputime);\n }\n else if (StrCompare(resource, L\"BlockReadsPerSecond\", true) == 0)\n {\n gotResource = processinst->GetBlockReadsPerSecond(res);\n }\n else if (StrCompare(resource, L\"BlockWritesPerSecond\", true) == 0)\n {\n gotResource = processinst->GetBlockWritesPerSecond(res);\n }\n else if (StrCompare(resource, L\"BlockTransfersPerSecond\", true) == 0)\n {\n gotResource = processinst->GetBlockTransfersPerSecond(res);\n }\n else if (StrCompare(resource, L\"PercentUserTime\", true) == 0)\n {\n gotResource = processinst->GetPercentUserTime(res);\n }\n else if (StrCompare(resource, L\"PercentPrivilegedTime\", true) == 0)\n {\n gotResource = processinst->GetPercentPrivilegedTime(res);\n }\n else if (StrCompare(resource, L\"UsedMemory\", true) == 0)\n {\n gotResource = processinst->GetUsedMemory(res);\n }\n else if (StrCompare(resource, L\"PercentUsedMemory\", true) == 0)\n {\n gotResource = processinst->GetPercentUsedMemory(res);\n }\n else if (StrCompare(resource, L\"PagesReadPerSec\", true) == 0)\n {\n gotResource = processinst->GetPagesReadPerSec(res);\n }\n else\n {\n throw UnknownResourceException(resource, SCXSRCLOCATION);\n }\n\n if ( ! gotResource)\n {\n throw SCXInternalErrorException(StrAppend(L\"GetResource: Failed to get resouce: \", resource), SCXSRCLOCATION);\n }\n\n return res;\n }\n\n void ProcessProvider::GetTopResourceConsumers(const std::wstring &resource, unsigned int count, std::wstring &result)\n {\n SCX_LOGTRACE(m_log, L\"SCXProcessProvider GetTopResourceConsumers\");\n\n std::wstringstream ss;\n std::vector<ProcessInstanceSort> procsort;\n\n SCXCoreLib::SCXThreadLock lock(m_processes->GetLockHandle());\n\n m_processes->UpdateNoLock();\n\n // Build separate vector for sorting\n for(size_t i=0; i<m_processes->Size(); i++)\n {\n ProcessInstanceSort p;\n\n p.procinst = m_processes->GetInstance(i);\n p.value = GetResource(resource, p.procinst);\n procsort.push_back(p);\n }\n\n std::sort(procsort.begin(), procsort.end(), CompareProcSort);\n\n ss << std::endl << L\"PID Name \" << resource << std::endl;\n ss << L\"-------------------------------------------------------------\" << std::endl;\n\n for(size_t i=0; i<procsort.size() && i<count; i++)\n {\n const ProcessInstanceSort* processinst = &procsort[i];\n\n scxulong pid;\n\n ss.width(5);\n if (processinst->procinst->GetPID(pid))\n {\n ss << pid;\n }\n else\n {\n ss << L\"-----\";\n }\n ss << L\" \";\n\n std::string name;\n ss.setf(std::ios_base::left);\n ss.width(20);\n if (processinst->procinst->GetName(name))\n {\n ss << StrFromMultibyte(name);\n }\n else\n {\n ss << L\"<unknown>\";\n }\n ss.unsetf(std::ios_base::left);\n ss << L\" \";\n\n ss.width(10);\n ss << processinst->value;\n\n ss << std::endl;\n }\n\n result = ss.str();\n }\n\n}\n" }, { "alpha_fraction": 0.5036175847053528, "alphanum_fraction": 0.5067183375358582, "avg_line_length": 39.3125, "blob_id": "602527f74b6827d854f740b0fa2a8a5d4788c481", "content_id": "3b0d291a30efdffb2f58a8c663b801cad37f66ad", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3870, "license_type": "permissive", "max_line_length": 161, "num_lines": 96, "path": "/source/code/providers/support/appserver/manipulateappserverinstances.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file manipulateappserverinstances.h\n\n \\brief Manipulates vectors of application server instances\n\n \\date 11-05-26 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef MANIPULATEAPPSERVERINSTANCES_H\n#define MANIPULATEAPPSERVERINSTANCES_H\n\n#include <vector>\n\n#include <scxcorelib/scxcmn.h>\n\n#include \"appserverinstance.h\"\n#include \"removenonexistentappserverinstances.h\"\n\nnamespace SCXSystemLib\n{\n /*---------------------------------------------------------------------*/\n /**\n Class that with static methods for manipulate vectors of application\n server instances\n */\n class ManipulateAppServerInstances\n {\n\n public:\n \n /*\n * Default no-arg constructor\n */\n ManipulateAppServerInstances();\n\n /*\n * Destructor\n */\n virtual ~ManipulateAppServerInstances();\n\n static void UpdateInstancesWithRunningProcesses(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& previouslyKnownInstances,\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& runningProcesses,\n SCXCoreLib::SCXHandle<SCXSystemLib::IRemoveNonexistentAppServerInstances> remover = \n SCXCoreLib::SCXHandle<SCXSystemLib::IRemoveNonexistentAppServerInstances>( new SCXSystemLib::RemoveNonexistentAppServerInstances()));\n \n \n /*---------------------------------------------------------------*/\n /**\n Given a list of running processes, merge this with the results \n of the cache and return this in the third parameter. The \n resulting output should be returned to the provider caller as \n well as persisted to disk.\n */\n static void MergeProcessesAndCache(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& processes,\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& cache,\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& result);\n\n /*---------------------------------------------------------------*/\n /*\n * Delegate method used comparing AppServerInstances based-on\n * their path on disk. Other properties like running state and\n * port are not used because only the path on disk is important\n * for removing duplicates between the process list and the cache.\n */\n static bool PathCompare (\n SCXCoreLib::SCXHandle<AppServerInstance> i,\n SCXCoreLib::SCXHandle<AppServerInstance> j);\n\n /*---------------------------------------------------------------*/\n /*\n * Delegate method used for ordering the AppServerInstances\n * by the path \n */\n static bool PathOrdering (\n SCXCoreLib::SCXHandle<AppServerInstance> i,\n SCXCoreLib::SCXHandle<AppServerInstance> j);\n \n /*---------------------------------------------------------------*/\n /*\n * Delegate method used for ordering the AppServerInstances\n * by the path \n */\n static SCXCoreLib::SCXHandle<AppServerInstance> SetIsRunningToFalse(\n SCXCoreLib::SCXHandle<AppServerInstance> i);\n \n };\n\n}\n\n#endif /* MANIPULATEAPPSERVERINSTANCES_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5296708941459656, "alphanum_fraction": 0.535631000995636, "avg_line_length": 31.982906341552734, "blob_id": "ed9ea35ad10d044681f86c1308d8002d3d3ef2f4", "content_id": "138ea46cbc20f8a27d8f693b61c681c6f835bb2f", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3859, "license_type": "permissive", "max_line_length": 141, "num_lines": 117, "path": "/source/code/providers/support/productdependencies.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file productdependencies.cpp\n\n \\brief Implements the product-specific dependencies for SCXCore\n\n \\date 2013-02-26 13:38:00\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxprocess.h>\n#include <scxcorelib/scxnameresolver.h>\n#include <scxcorelib/scxproductdependencies.h>\n#include <scxsystemlib/scxproductdependencies.h>\n\n#if !defined(WIN32)\n#include \"buildversion.h\"\n#endif\n\nnamespace SCXCoreLib\n{\n namespace SCXProductDependencies\n {\n static bool s_fSuppressHeader = false;\n\n void SetLogFileHeaderSuppression(bool fSet)\n {\n s_fSuppressHeader = fSet;\n }\n\n void WriteLogFileHeader( SCXHandle<std::wfstream> &stream, int logFileRunningNumber, SCXCalendarTime& procStartTimestamp )\n {\n if (s_fSuppressHeader)\n {\n return;\n }\n\n std::wstringstream continuationLogMsg;\n if ( logFileRunningNumber > 1 )\n {\n continuationLogMsg << L\"* Log file number: \" << StrFrom(logFileRunningNumber) << std::endl;\n }\n\n (*stream) << L\"*\" << std::endl\n << L\"* Microsoft System Center Cross Platform Extensions (SCX)\" << std::endl\n#if !defined(WIN32)\n << L\"* Build number: \" << SCX_BUILDVERSION_MAJOR << L\".\" << SCX_BUILDVERSION_MINOR << L\".\" <<\n SCX_BUILDVERSION_PATCH << L\"-\" << SCX_BUILDVERSION_BUILDNR << L\" \" << SCX_BUILDVERSION_STATUS << std::endl\n#endif\n << L\"* Process id: \" << StrFrom(SCXProcess::GetCurrentProcessID()) << std::endl\n << L\"* Process started: \" << procStartTimestamp.ToExtendedISO8601() << std::endl\n << L\"* System Hostname: \" << GetHostDomainname() << std::endl\n << continuationLogMsg.str() \n << L\"*\" << std::endl\n << L\"* Log format: <date> <severity> [<code module>:<line number>:<process id>:<thread id>] <message>\" << std::endl\n << L\"*\" << std::endl;\n }\n\n void WrtieItemToLog( SCXHandle<std::wfstream> &stream, const SCXLogItem& item, const std::wstring& message )\n {\n (void) item;\n\n (*stream) << message << std::endl;\n }\n }\n}\n\nnamespace SCXSystemLib\n{\n namespace SCXProductDependencies\n {\n std::wstring GetLinuxOS_ScriptPath()\n {\n return std::wstring(L\"/opt/microsoft/scx/bin/tools/GetLinuxOS.sh\");\n }\n\n std::wstring GetLinuxOS_ReleasePath()\n {\n return std::wstring(L\"/etc/opt/microsoft/scx/conf/scx-release\");\n }\n\n void Disk_IgnoredFileSystems( std::set<std::wstring> &igfs )\n {\n // To suppress compiler warnings about parameter not being used\n (void)igfs;\n return;\n }\n\n void Disk_IgnoredFileSystems_StartsWith( std::set<std::wstring> &igfs )\n {\n // To suppress compiler warnings about parameter not being used\n (void)igfs;\n return;\n }\n\n void Disk_IgnoredFileSystems_Contains( std::set<std::wstring> &igfs )\n {\n (void)igfs;\n return;\n }\n\n void Disk_IgnoredFileSystems_NoLinkToPhysical( std::set<std::wstring> &igfs )\n {\n (void)igfs;\n return;\n }\n \n std::wstring OSTypeInfo_GetConfigPath()\n {\n return std::wstring(L\"/etc/opt/microsoft/scx/conf/scxconfig.conf\");\n }\n }\n}\n" }, { "alpha_fraction": 0.7448874115943909, "alphanum_fraction": 0.7461817264556885, "avg_line_length": 80.3263168334961, "blob_id": "ac39261c92f1fd7a97226d45ef85d24258a268c5", "content_id": "bd7d73e2fff19167742ebcd6c39c953b6b3920f2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 7726, "license_type": "permissive", "max_line_length": 186, "num_lines": 95, "path": "/build/Makefile.providerstests", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n# \n# Definition of all provider unit tests\n#\n#--------------------------------------------------------------------------------\n\n#--------------------------------------------------------------------------------\n# Provider tests.\n\n# For now, providertestutils.cpp lives in PAL, but is built in OM. This creates\n# some build issues. To resolve, create a link to the real file.\n\nTESTPROVIDER_SUPPORT_DIR=$(SCX_UNITTEST_ROOT)/providers\n\n$(SCX_UNITTEST_ROOT)/providers/providertestutils.cpp: $(SCXPAL_TEST_ROOT)/testutils/providertestutils.cpp\n# We need to recreate the symlink if the link is older than what it points to. Touch will not work, and ln -fs does not work on Sun5.9\n\trm -f $(SCX_UNITTEST_ROOT)/providers/providertestutils.cpp\n\tln -s $(SCXPAL_TEST_ROOT)/testutils/providertestutils.cpp $(TESTPROVIDER_SUPPORT_DIR)/providertestutils.cpp\n\nPOSIX_UNITTESTS_PROVIDERS_SRCFILES = \\\n\t$(SCX_UNITTEST_ROOT)/providers/providertestutils.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/testutilities.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/meta_provider/metaprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/appserverenumeration_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/appserverinstance_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/appserverprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/jbossappserverinstance_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/tomcatappserverinstance_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/weblogicappserverenumeration_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/weblogicappserverinstance_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/websphereappserverinstance_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/manipulateappserverinstances_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/appserver_provider/persistappserverinstances_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/cpu_provider/cpuprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/disk_provider/diskkey_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/disk_provider/diskprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/logfile_provider/logfileprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/logfile_provider/logfilereader_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/memory_provider/memoryprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/network_provider/networkprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/os_provider/osprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/process_provider/processprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/process_provider/unixprocesskey_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/runas_provider/runasprovider_test.cpp \\\n\t$(SCX_UNITTEST_ROOT)/providers/runas_provider/scxrunasconfigurator_test.cpp\n\n\n# The OMI source files won't compile with our very strict flags - ease up for them\n# (and, for HP, allow a mechanism to modify the flags)\n$(call src_to_obj,$(POSIX_UNITTESTS_PROVIDERS_SRCFILES)): CXX_WARN_STRICT_FLAGS=$(CXX_WARN_STRICT_FLAGS_PROVIDERS)\n$(call src_to_obj,$(POSIX_UNITTESTS_PROVIDERS_SRCFILES)): C_WARN_STRICT_FLAGS=$(CXX_WARN_STRICT_FLAGS_PROVIDERS)\n\n$(call src_to_obj,$(POSIX_UNITTESTS_PROVIDERS_SRCFILES)): INCLUDES += -I$(SCXOMI_DIR) -I$(SCXOMI_DIR)/common -I$(SCX_SRC_ROOT)/providers/support\n$(patsubst %.$(PF_OBJ_FILE_SUFFIX), %.d, $(call src_to_obj,$(POSIX_UNITTESTS_PROVIDERS_SRCFILES))): INCLUDES += -I$(SCXOMI_DIR) -I$(SCXOMI_DIR)/common -I$(SCX_SRC_ROOT)/providers/support\n\n# Extra include dirs for certain include files\n\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/appserverenumeration_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/appserverenumeration_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/appserverinstance_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/appserverinstance_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/jbossappserverinstance_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/jbossappserverinstance_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/tomcatappserverinstance_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/tomcatappserverinstance_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/weblogicappserverenumeration_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/weblogicappserverenumeration_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/weblogicappserverinstance_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/weblogicappserverinstance_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/websphereappserverinstance_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/websphereappserverinstance_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/manipulateappserverinstances_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/manipulateappserverinstances_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/persistappserverinstances_test.d: INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/appserver_provider/persistappserverinstances_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(APPSERVER_SUPPORT_DIR)\n\n$(INTERMEDIATE_DIR)/test/code/providers/logfile_provider/logfileprovider_test.d: INCLUDES += -I$(PROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/logfile_provider/logfileprovider_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(PROVIDER_SUPPORT_DIR)\n\n$(INTERMEDIATE_DIR)/test/code/providers/os_provider/osprovider_test.d: INCLUDES += -I$(TESTPROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/os_provider/osprovider_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(TESTPROVIDER_SUPPORT_DIR)\n\n$(INTERMEDIATE_DIR)/test/code/providers/process_provider/processprovider_test.d: INCLUDES += -I$(TESTPROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/process_provider/processprovider_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(TESTPROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/process_provider/unixprocesskey_test.d: INCLUDES += -I$(TESTPROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/process_provider/unixprocesskey_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(TESTPROVIDER_SUPPORT_DIR)\n\n$(INTERMEDIATE_DIR)/test/code/providers/runas_provider/scxrunasconfigurator_test.d: INCLUDES += -I$(PROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/providers/runas_provider/scxrunasconfigurator_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(PROVIDER_SUPPORT_DIR)\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.512937605381012, "alphanum_fraction": 0.5220699906349182, "avg_line_length": 25.816326141357422, "blob_id": "375bd79e553c9ad99f40b7f8fe01175e6778e1b1", "content_id": "f451b812f54dc8badae3bd5590465e5b69052fca", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1314, "license_type": "permissive", "max_line_length": 102, "num_lines": 49, "path": "/source/code/providers/support/appserver/weblogicappserverinstance.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file weblogicappservcerinstance.h\n\n \\brief Representation of a WebLogic Application Server instance\n\n \\date 11-08-18 12:00:00\n*/\n/*--------------------------------------------------------------------*/\n#ifndef WEBLOGICAPPSERVERINSTANCE_H\n#define WEBLOGICAPPSERVERINSTANCE_H\n\n#include <string>\n\n#include \"appserverinstance.h\"\n\nnamespace SCXSystemLib {\n /*----------------------------------------------------------------*/\n /**\n Class that represents an instances.\n\n Concrete implementation of an instance of a WebLogic \n Application Server\n\n */\n class WebLogicAppServerInstance : public AppServerInstance {\n friend class AppServerEnumeration;\n\n public:\n\n WebLogicAppServerInstance(const std::wstring& id);\n\n virtual ~WebLogicAppServerInstance();\n\n virtual void Update();\n\n protected:\n\n virtual std::wstring ExtractMajorVersion(\n const std::wstring& version);\n\n };\n\n}\n\n#endif /* WEBLOGICAPPSERVERINSTANCE_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6932666301727295, "alphanum_fraction": 0.6944538950920105, "avg_line_length": 37.28571319580078, "blob_id": "aa284dff173370bc708cd27a32f22086abc4f865", "content_id": "d9b30345fd9e0abca1ce147be18108988e30ebb2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11792, "license_type": "permissive", "max_line_length": 113, "num_lines": 308, "path": "/test/code/providers/disk_provider/diskkey_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests the keys of the SCX_DiskDrive and SCX_FileSystem classes\n\n \\date 2008-09-23 12:51:03\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <scxcorelib/scxexception.h>\n#include <testutils/scxunit.h>\n#include <testutils/disktestutils.h>\n#include <testutils/providertestutils.h>\n#include \"support/diskprovider.h\"\n\n#include \"SCX_DiskDrive.h\"\n#include \"SCX_DiskDrive_Class_Provider.h\"\n#include \"SCX_DiskDriveStatisticalInformation_Class_Provider.h\"\n#include \"SCX_FileSystem_Class_Provider.h\"\n#include \"SCX_FileSystemStatisticalInformation_Class_Provider.h\"\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nclass SCXDiskKeyTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXDiskKeyTest );\n\n CPPUNIT_TEST( TestDiskDriveEnumerateKeysOnly );\n CPPUNIT_TEST( TestFileSystemEnumerateKeysOnly );\n CPPUNIT_TEST( TestDiskDriveStatisticalInformationEnumerateKeysOnly );\n CPPUNIT_TEST( TestFileSystemStatisticalInformationEnumerateKeysOnly );\n\n CPPUNIT_TEST( TestDiskDriveCheckKeyValues );\n CPPUNIT_TEST( TestFileSystemCheckKeyValues );\n\n CPPUNIT_TEST( TestVerifyKeyCompletePartialFileSystemStatisticalInformation );\n CPPUNIT_TEST( TestVerifyKeyCompletePartialDiskDriveStatisticalInformation );\n CPPUNIT_TEST( TestVerifyKeyCompletePartialDiskDrive );\n CPPUNIT_TEST( TestVerifyKeyCompletePartialFileSystem );\n\n CPPUNIT_TEST( TestDiskDriveGetInstance );\n CPPUNIT_TEST( TestFileSystemGetInstance );\n CPPUNIT_TEST( TestDiskDriveStatisticalInformationGetInstance );\n CPPUNIT_TEST( TestFileSystemStatisticalInformationGetInstance );\n\n\n SCXUNIT_TEST_ATTRIBUTE(TestDiskDriveEnumerateKeysOnly, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestFileSystemEnumerateKeysOnly, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDiskDriveStatisticalInformationEnumerateKeysOnly, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestFileSystemStatisticalInformationEnumerateKeysOnly, SLOW);\n\n SCXUNIT_TEST_ATTRIBUTE(TestDiskDriveCheckKeyValues, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestFileSystemCheckKeyValues, SLOW);\n\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartialFileSystemStatisticalInformation, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartialDiskDriveStatisticalInformation, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartialDiskDrive, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartialFileSystem, SLOW);\n\n SCXUNIT_TEST_ATTRIBUTE(TestDiskDriveGetInstance, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestFileSystemGetInstance, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDiskDriveStatisticalInformationGetInstance, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestFileSystemStatisticalInformationGetInstance, SLOW);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector<std::wstring> m_keyNamesFSS;\n std::vector<std::wstring> m_keyNamesDDS;\n std::vector<std::wstring> m_keyNamesDD;\n std::vector<std::wstring> m_keyNamesFS;\n\npublic:\n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_DiskDrive_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_FileSystem_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n\n m_keyNamesFSS.push_back(L\"Name\");\n\n m_keyNamesDDS.push_back(L\"Name\");\n\n m_keyNamesDD.push_back(L\"SystemCreationClassName\");\n m_keyNamesDD.push_back(L\"SystemName\");\n m_keyNamesDD.push_back(L\"CreationClassName\");\n m_keyNamesDD.push_back(L\"DeviceID\");\n\n m_keyNamesFS.push_back(L\"Name\");\n m_keyNamesFS.push_back(L\"CSCreationClassName\");\n m_keyNamesFS.push_back(L\"CSName\");\n m_keyNamesFS.push_back(L\"CreationClassName\");\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_DiskDrive_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_FileSystem_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void TestDiskDriveEnumerateKeysOnly()\n {\n if ( ! MeetsPrerequisites(L\"SCXDiskKeyTest::TestDiskDriveEnumerateKeysOnly\"))\n {\n return;\n }\n if ( ! HasPhysicalDisks(L\"SCXDiskKeyTest::TestDiskDriveEnumerateKeysOnly\") )\n {\n return;\n }\n\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_DiskDrive_Class_Provider>(\n m_keyNamesDD, context, CALL_LOCATION(errMsg));\n }\n\n void TestFileSystemEnumerateKeysOnly()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_FileSystem_Class_Provider>(\n m_keyNamesFS, context, CALL_LOCATION(errMsg));\n }\n\n void TestDiskDriveStatisticalInformationEnumerateKeysOnly()\n {\n if ( ! HasPhysicalDisks(L\"SCXDiskKeyTest::TestDiskDriveStatisticalInformationEnumerateKeysOnly\") )\n {\n return;\n }\n\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(\n m_keyNamesDDS, context, CALL_LOCATION(errMsg));\n }\n\n void TestFileSystemStatisticalInformationEnumerateKeysOnly()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(\n m_keyNamesFSS, context, CALL_LOCATION(errMsg));\n }\n\n void TestDiskDriveCheckKeyValues()\n {\n if ( ! MeetsPrerequisites(L\"SCXDiskKeyTest::TestDiskDriveCheckKeyValues\"))\n {\n return;\n }\n if ( ! HasPhysicalDisks(L\"SCXDiskKeyTest::TestDiskDriveCheckKeyValues\") )\n {\n return;\n }\n\n std::wstring errMsg;\n TestableContext context;\n\n std::vector<std::wstring> keysSame;// Unused.\n\n std::vector<std::wstring> keyNames;\n std::vector<std::wstring> keyValues;\n keyNames.push_back(L\"SystemCreationClassName\");\n keyValues.push_back(L\"SCX_ComputerSystem\");\n keyNames.push_back(L\"SystemName\");\n keyValues.push_back(GetFQHostName(CALL_LOCATION(errMsg)));\n keyNames.push_back(L\"CreationClassName\");\n keyValues.push_back(L\"SCX_DiskDrive\");\n StandardTestCheckKeyValues<mi::SCX_DiskDrive_Class_Provider>(keyNames, keyValues, keysSame, context,\n CALL_LOCATION(errMsg));\n }\n\n void TestFileSystemCheckKeyValues()\n {\n std::wstring errMsg;\n TestableContext context;\n\n std::vector<std::wstring> keysSame;// Unused.\n\n std::vector<std::wstring> keyNames;\n std::vector<std::wstring> keyValues;\n keyNames.push_back(L\"CSCreationClassName\");\n keyValues.push_back(L\"SCX_ComputerSystem\");\n keyNames.push_back(L\"CSName\");\n keyValues.push_back(GetFQHostName(CALL_LOCATION(errMsg)));\n keyNames.push_back(L\"CreationClassName\");\n keyValues.push_back(L\"SCX_FileSystem\");\n StandardTestCheckKeyValues<mi::SCX_FileSystem_Class_Provider>(keyNames, keyValues, keysSame, context,\n CALL_LOCATION(errMsg));\n }\n\n void TestDiskDriveGetInstance()\n {\n if ( ! MeetsPrerequisites(L\"SCXDiskKeyTest::TestDiskDriveGetInstance\"))\n {\n return;\n }\n if ( ! HasPhysicalDisks(L\"SCXDiskKeyTest::TestDiskDriveGetInstance\") )\n {\n return;\n }\n\n std::wstring errMsg;\n TestableContext context;\n StandardTestGetInstance<mi::SCX_DiskDrive_Class_Provider, mi::SCX_DiskDrive_Class>(\n context, m_keyNamesDD.size(), CALL_LOCATION(errMsg));\n }\n\n void TestFileSystemGetInstance()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestGetInstance<mi::SCX_FileSystem_Class_Provider, mi::SCX_FileSystem_Class>(\n context, m_keyNamesFS.size(), CALL_LOCATION(errMsg));\n }\n\n void TestDiskDriveStatisticalInformationGetInstance()\n {\n if ( ! HasPhysicalDisks(L\"SCXDiskKeyTest::TestDiskDriveStatisticalInformationGetInstance\") )\n {\n return;\n }\n\n std::wstring errMsg;\n TestableContext context;\n StandardTestGetInstance<mi::SCX_DiskDriveStatisticalInformation_Class_Provider,\n mi::SCX_DiskDriveStatisticalInformation_Class>(\n context, m_keyNamesDDS.size(), CALL_LOCATION(errMsg));\n }\n\n void TestFileSystemStatisticalInformationGetInstance()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestGetInstance<mi::SCX_FileSystemStatisticalInformation_Class_Provider,\n mi::SCX_FileSystemStatisticalInformation_Class>(\n context, m_keyNamesFSS.size(), CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartialFileSystemStatisticalInformation()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_FileSystemStatisticalInformation_Class_Provider,\n mi::SCX_FileSystemStatisticalInformation_Class>(m_keyNamesFSS, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartialDiskDriveStatisticalInformation()\n {\n if ( ! HasPhysicalDisks(L\"SCXDiskKeyTest::TestVerifyKeyCompletePartialDiskDriveStatisticalInformation\") )\n {\n return;\n }\n\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_DiskDriveStatisticalInformation_Class_Provider,\n mi::SCX_DiskDriveStatisticalInformation_Class>(m_keyNamesDDS, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartialDiskDrive()\n {\n if ( ! MeetsPrerequisites(L\"SCXDiskKeyTest::TestVerifyKeyCompletePartialDiskDrive\"))\n {\n return;\n }\n if ( ! HasPhysicalDisks(L\"SCXDiskKeyTest::TestVerifyKeyCompletePartialDiskDrive\") )\n {\n return;\n }\n \n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_DiskDrive_Class_Provider,\n mi::SCX_DiskDrive_Class>(m_keyNamesDD, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartialFileSystem()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_FileSystem_Class_Provider,\n mi::SCX_FileSystem_Class>(m_keyNamesFS, CALL_LOCATION(errMsg));\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXDiskKeyTest );\n" }, { "alpha_fraction": 0.5407568216323853, "alphanum_fraction": 0.5482164621353149, "avg_line_length": 31.48017692565918, "blob_id": "62d6af92ce3d5c2537da495cbe40d9038832cee5", "content_id": "2aceaf94420be3a34960f65ac67977da7d48d8e0", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7373, "license_type": "permissive", "max_line_length": 164, "num_lines": 227, "path": "/source/code/providers/support/metaprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n * \n * */\n /**\n \\file metaprovider.h\n\n \\brief Meta provider (SCX_Agent)\n\n \\date 04-01-03\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlocale.h>\n#include <scxcorelib/scxstream.h>\n\n#include \"metaprovider.h\"\n#include \"scxcimutils.h\"\n#include \"startuplog.h\"\n\n#include \"buildversion.h\"\n\n#include <fstream>\n\n#if defined(sun)\n#include <sys/systeminfo.h>\n#include <scxcorelib/scxlocale.h>\n#endif\n\n\nusing namespace SCXCoreLib;\n//using namespace SCXSystemLib;\nusing namespace std;\n\nnamespace SCXCore\n{\n /** Installation information file name */\n#if defined (macos)\n static const string installInfoFileName = \"/private/etc/opt/microsoft/scx/conf/installinfo.txt\";\n#else\n static const string installInfoFileName = \"/etc/opt/microsoft/scx/conf/installinfo.txt\";\n#endif\n\n //\n // Meta provider class implementation\n //\n\n void MetaProvider::Load()\n {\n // Not strictly necessary to worry about multithreaded use, but here for consistency\n // (Note: This is thread-safe due to upper-level lock in all relevant OMI calls)\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXCoreLib::SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.metaprovider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"MetaProvider::Load()\");\n\n /* The seems like a suitable place to report the active locale */\n SCX_LOGINFO(m_log, SCXCoreLib::StrAppend(L\"Active locale setting is \",\n SCXCoreLib::SCXLocaleContext::GetActiveLocale()));\n\n ReadInstallInfoFile();\n GetReleaseDate();\n }\n }\n\n void MetaProvider::Unload()\n {\n // (Note: This is thread-safe due to upper-level lock in all relevant OMI calls)\n SCX_LOGTRACE(m_log, L\"MetaProvider::Unload()\");\n --ms_loadCount;\n }\n\n bool MetaProvider::GetInstallInfoData(string& installVersion, MI_Datetime& installTime)\n {\n if ( m_readInstallInfoFile )\n {\n installVersion = StrToMultibyte(m_installVersion);\n CIMUtils::ConvertToCIMDatetime( installTime, m_installTime );\n\n return true;\n }\n\n return false;\n }\n\n bool MetaProvider::GetBuildTime( string& buildTime )\n {\n if (m_buildTimeOK)\n {\n buildTime = StrToMultibyte( m_buildTime.ToExtendedISO8601() );\n return true;\n }\n\n return false;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Read installation information from file\n\n This method reads some proprietary information the SCX installer saves \n in well-known location. Called from constructor since this reads in \n information that should not change.\n\n */\n void MetaProvider::ReadInstallInfoFile()\n {\n std::wifstream infofile( installInfoFileName.c_str() );\n\n m_readInstallInfoFile = false;\n\n if (SCXStream::IsGood(infofile))\n {\n vector<wstring> lines;\n SCXStream::NLFs nlfs;\n\n // Read all lines from install info file\n // First line should be install date on ISO8601 format\n // Second line should be install version string\n // Example:\n // 2008-03-17T17:28:32.0Z\n // 1.0.1-70\n //\n SCXStream::ReadAllLines(infofile, lines, nlfs);\n if (lines.size() == 2)\n {\n SCX_LOGTRACE(m_log, StrAppend(L\"Read time from installinfo file: \", lines[0]));\n SCX_LOGTRACE(m_log, StrAppend(L\"Read install version from installinfo file: \", lines[1]));\n\n m_installVersion = lines[1];\n try\n {\n m_installTime = SCXCalendarTime::FromISO8601(lines[0]);\n m_readInstallInfoFile = true;\n }\n catch (SCXCoreLib::SCXException &e)\n {\n SCX_LOGERROR(m_log, StrAppend(StrAppend(StrAppend(L\"Failed to convert install time string to SCXCalenderTime: \", lines[0]), L\" - \"), e.What()));\n }\n }\n else\n {\n SCX_LOGERROR(m_log, StrAppend(L\"Wrong number of rows in install info file. Expected 2, got: \", lines.size()));\n }\n }\n else\n {\n std::wstring errStr = L\"Failed to open installinfo file \" + StrFromMultibyte(installInfoFileName);\n SCX_LOGERROR(m_log, errStr);\n }\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Convert build date string to SCXCalendarTime\n\n At compile time the build timestamp is provided by preprocessor in \n SCX_BUILDVERSION_DATE. This method converts time format to SCXCalendarTime.\n\n */\n void MetaProvider::GetReleaseDate()\n {\n m_buildTimeOK = false;\n\n wstring buildDate(SCX_BUILDVERSION_DATE);\n\n if (buildDate.length() == 8)\n {\n wstring buildYear = buildDate.substr(0, 4);\n wstring buildMonth = buildDate.substr(4, 2);\n wstring buildDay = buildDate.substr(6, 2);\n\n try\n {\n m_buildTime = SCXCalendarTime(StrToUInt(buildYear),StrToUInt(buildMonth),StrToUInt(buildDay));\n m_buildTimeOK = true;\n SCX_LOGTRACE(m_log, StrAppend(L\"Build time: \", buildDate));\n }\n catch (SCXCoreLib::SCXException& e)\n {\n SCX_LOGERROR(m_log, StrAppend(L\"Failed to convert build time string to SCXCalenderTime: \", buildDate));\n }\n }\n else\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"Build time string is not correct length: \", buildDate));\n }\n }\n\n // Only construct MetaProvider class once - installation date/version never changes!\n int SCXCore::MetaProvider::ms_loadCount = 0;\n SCXCore::MetaProvider g_MetaProvider;\n\n /*----------------------------------------------------------------------------*/\n /**\n Log the startup message once regardless of how many times called\n \n This function will be called from all provider ctors except RunAs to \n provide one initial log, regardless of how many times called.\n \n */\n void LogStartup(void) \n {\n static bool bLoggedInitMessage = false;\n if (!bLoggedInitMessage) \n {\n SCXCoreLib::SCXLogHandle log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers\");\n SCX_LOGINFO(log, L\"SCX Provider Module loaded\");\n \n#if defined(sun)\n // Log any errors encountered during SCXLocaleContext initialization.\n for (size_t i = 0; i < SCXLocaleContext::GetErrors().size(); i++)\n {\n SCX_LOGWARNING(log, SCXLocaleContext::GetErrors()[i]);\n }\n \n#endif /* defined(sun) */\n \n bLoggedInitMessage = true;\n }\n }\n}\n\n /*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5436118245124817, "alphanum_fraction": 0.5457213521003723, "avg_line_length": 31.643712997436523, "blob_id": "783120afb04ceb6d545d03fc528357ce5e1122cd", "content_id": "880e612bc7c42a661ffefbd90fb6ffef6dc25e5b", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10903, "license_type": "permissive", "max_line_length": 122, "num_lines": 334, "path": "/source/code/providers/support/logfileprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n \n*/\n/**\n \\file logfileprovider.cpp\n \n \\brief Main implementation file for Log File Provider\n \n \\date 2008-0-08 09:35:36\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxmarshal.h>\n#include <scxcorelib/scxprocess.h>\n#include <scxsystemlib/scxsysteminfo.h>\n\n#include <errno.h>\n#include <stdlib.h>\n\n#include \"logfileprovider.h\"\n#include \"logfileutils.h\"\n#include \"startuplog.h\"\n\nusing namespace SCXCoreLib;\nusing namespace std;\n\nnamespace SCXCore {\n // Static assignments\n int LogFileProvider::ms_loadCount = 0;\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Default constructor\n */\n LogFileProvider::LogFileProvider() :\n m_pLogFileReader(NULL)\n {\n // Assuming we have one global object - initialized at load time\n }\n\n LogFileProvider::LogFileProvider(SCXCoreLib::SCXHandle<LogFileReader> pLogFileReader)\n : m_pLogFileReader(pLogFileReader)\n {\n // Assuming we have one global object - initialized at load time\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Destructor\n */\n LogFileProvider::~LogFileProvider()\n {\n // Do not log here since when this destructor is called the objects neccesary for logging might no longer be alive\n }\n\n void LogFileProvider::Load()\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.logfileprovider\");\n\n SCXASSERT( ms_loadCount >= 0 );\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.logfileprovider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"LogFileProvider::Load()\");\n\n if (NULL == m_pLogFileReader)\n {\n m_pLogFileReader = new LogFileReader();\n }\n }\n }\n\n void LogFileProvider::Unload()\n {\n SCX_LOGTRACE(m_log, L\"LogFileProvider::Unload()\");\n\n SCXASSERT( ms_loadCount >= 1 );\n if ( 0 == --ms_loadCount )\n {\n m_pLogFileReader = NULL;\n }\n }\n\n SCXLogHandle& LogFileProvider::GetLogHandle()\n {\n return m_log;\n }\n\n /**\n Dump object as string (for logging).\n \n \\returns The object represented as a string suitable for logging.\n */\n const std::wstring LogFileProvider::DumpString() const\n {\n return L\"LogFileProvider\";\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Invoke the logfileread CLI (command line) program, with elevation if needed\n\n \\param[in] filename Filename to scan for matches\n \\param[in] qid QID used for state file handling\n \\param[in] regexps List of regular expressions to look for\n \\param[in] performElevation Perform elevation when running the command\n \\param[out] matchedLines Resulting matched lines, if any, from log file\n\n \\returns Boolean flag to indicate if partial matches were returned\n */\n bool LogFileProvider::InvokeLogFileReader(\n const std::wstring& filename,\n const std::wstring& qid,\n const std::vector<SCXRegexWithIndex>& regexps,\n bool fPerformElevation,\n std::vector<std::wstring>& matchedLines)\n {\n SCX_LOGTRACE(m_log, L\"SCXLogFileProvider InvokeLogFileReader\");\n\n // Process of log file was called by something like:\n //\n // bPartial = m_pLFR->ReadLogFile(filename, qid, regexps, matchedLines);\n //\n // Marshal our data to send along to the subprocess\n // (Note that matchedLines is returned, along with partial flag)\n\n std::stringstream processInput;\n std::stringstream processOutput;\n std::stringstream processError;\n\n SCX_LOGTRACE(m_log, L\"SCXLogFileProvider InvokeLogFileReader - Marshaling\");\n\n Marshal send(processInput);\n send.Write(filename);\n send.Write(qid);\n send.Write(regexps);\n send.Flush();\n\n // Test to see if we're running under testrunner. This makes it easy\n // to know where to launch our test program, allowing unit tests to\n // test all the way through to the CLI.\n\n wstring programName;\n char *testrunFlag = getenv(\"SCX_TESTRUN_ACTIVE\");\n if (NULL != testrunFlag)\n {\n programName = L\"testfiles/scxlogfilereader-test -t -p\";\n }\n else\n {\n programName = L\"/opt/microsoft/scx/bin/scxlogfilereader -p\";\n }\n\n // Elevate the command if that's called for\n SCXSystemLib::SystemInfo si;\n\n if (fPerformElevation)\n {\n programName = si.GetElevatedCommand(programName);\n }\n\n // Call the log file reader (CLI) program\n\n SCX_LOGTRACE(m_log,\n StrAppend(L\"SCXLogFileProvider InvokeLogFileReader - Running \",\n programName));\n\n try\n {\n int returnCode = SCXProcess::Run(\n programName,\n processInput, processOutput, processError);\n\n SCX_LOGTRACE(m_log,\n StrAppend(L\"SCXLogFileProvider InvokeLogFileReader - Result \", returnCode));\n\n switch (returnCode)\n {\n case 0:\n // Normal exit code\n break;\n case ENOENT:\n // Log file didn't exist - scxlogfilereader logged message about it\n // Nothing to unmarshal at this point ...\n return false;\n default:\n wstringstream errorMsg;\n errorMsg << L\"Unexpected return code running '\"\n << programName\n << L\"': \"\n << returnCode;\n\n throw SCXInternalErrorException(errorMsg.str(), SCXSRCLOCATION);\n }\n }\n catch (SCXCoreLib::SCXException& e)\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"LogFileProvider InvokeLogFileReader - Exception: \", e.What()));\n throw;\n }\n\n // Unmarshall matchedLines and partialRead flag\n //\n // Note that we can't marshal/unmarshal a bool, so we treat as int\n\n int wasPartialRead;\n\n SCX_LOGTRACE(m_log, L\"SCXLogFileProvider InvokeLogFileReader - UnMarshaling\");\n\n UnMarshal receive(processOutput);\n receive.Read(wasPartialRead);\n receive.Read(matchedLines);\n\n SCX_LOGTRACE(m_log, StrAppend(L\"SCXLogFileProvider InvokeLogFileReader - Returning: \", (0 != wasPartialRead)));\n\n return (0 != wasPartialRead);\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Invoke the logfilereader CLI (command line) program, with elevation if needed,\n to reset a specific state file.\n\n \\param[in] filename Filename to scan for matches\n \\param[in] qid QID used for state file handling\n \\param[in] resetOnRead Rather than reset now, reset on next logfile read\n \\param[in] performElevation Perform elevation when running the command\n\n \\returns Result status (if operation was successful or not)\n */\n int LogFileProvider::InvokeResetStateFile(\n const std::wstring& filename,\n const std::wstring& qid,\n int resetOnRead,\n bool fPerformElevation)\n {\n SCX_LOGTRACE(m_log, L\"SCXLogFileProvider InvokeResetStateFile\");\n\n // Marshal our data to send along to the subprocess\n\n std::stringstream processInput;\n std::stringstream processOutput;\n std::stringstream processError;\n\n SCX_LOGTRACE(m_log, L\"SCXLogFileProvider InvokeResetStateFile - Marshaling\");\n\n Marshal send(processInput);\n send.Write(filename);\n send.Write(qid);\n send.Write(resetOnRead);\n send.Flush();\n\n // Test to see if we're running under testrunner. This makes it easy\n // to know where to launch our test program, allowing unit tests to\n // test all the way through to the CLI.\n\n wstring programName;\n char *testrunFlag = getenv(\"SCX_TESTRUN_ACTIVE\");\n if (NULL != testrunFlag)\n {\n programName = L\"testfiles/scxlogfilereader-test -t -r\";\n }\n else\n {\n programName = L\"/opt/microsoft/scx/bin/scxlogfilereader -r\";\n }\n\n // Elevate the command if that's called for\n SCXSystemLib::SystemInfo si;\n\n if (fPerformElevation)\n {\n programName = si.GetElevatedCommand(programName);\n }\n\n // Call the log file reader (CLI) program\n\n SCX_LOGTRACE(m_log,\n StrAppend(L\"SCXLogFileProvider InvokeResetStateFile - Running \",\n programName));\n\n int returnCode = -1;\n try\n {\n returnCode = SCXProcess::Run(\n programName,\n processInput, processOutput, processError);\n\n SCX_LOGTRACE(m_log,\n StrAppend(L\"SCXLogFileProvider InvokeResetStateFile - Result \", returnCode));\n\n switch (returnCode)\n {\n case 0:\n // Normal exit code\n break;\n case ENOENT:\n // Log file didn't exist - scxlogfilereader logged message about it\n // Nothing to unmarshal at this point ...\n break;\n default:\n wstringstream errorMsg;\n errorMsg << L\"Unexpected return code running '\"\n << programName\n << L\"': \"\n << returnCode;\n\n throw SCXInternalErrorException(errorMsg.str(), SCXSRCLOCATION);\n }\n }\n catch (SCXCoreLib::SCXException& e)\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"LogFileProvider InvokeResetStateFile - Exception: \", e.What()));\n throw;\n }\n\n // No unmarshalling to do ...\n\n SCX_LOGTRACE(m_log, StrAppend(L\"SCXLogFileProvider InvokeResetStateFile - Returning: \", returnCode));\n\n return returnCode;\n }\n\n LogFileProvider g_LogFileProvider;\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6533864736557007, "alphanum_fraction": 0.6549800634384155, "avg_line_length": 35.509090423583984, "blob_id": "fcec2040c6fb0809eee702ca0f275e4c68dac438", "content_id": "de121583298e14f6a60b91618ef07bf8c7a10d39", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10040, "license_type": "permissive", "max_line_length": 148, "num_lines": 275, "path": "/source/code/providers/SCX_Application_Server_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_Application_Server_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-22-2013 17:48:44\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include <string>\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n#include \"support/appserver/appserverenumeration.h\"\n#include \"support/appserver/appserverprovider.h\"\n#include \"support/scxcimutils.h\"\n#include \"support/startuplog.h\"\n#include \"SCX_Application_Server_Class_Provider.h\"\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_Application_Server_Class& inst,\n bool keysOnly,\n SCXCoreLib::SCXHandle<SCXSystemLib::AppServerInstance> asinst)\n{\n if (asinst == NULL)\n {\n throw SCXInvalidArgumentException(L\"asinst\", L\"Not a AppServerInstance\", SCXSRCLOCATION);\n }\n\n // Fill in the key\n inst.Name_value( StrToMultibyte(asinst->GetId()).c_str() );\n\n if ( !keysOnly )\n {\n inst.Caption_value( \"SCX Application Server\" );\n inst.Description_value( \"Represents a JEE Application Server\" );\n inst.HttpPort_value( StrToMultibyte(asinst->GetHttpPort()).c_str() );\n inst.HttpsPort_value( StrToMultibyte(asinst->GetHttpsPort()).c_str() );\n inst.Version_value( StrToMultibyte(asinst->GetVersion()).c_str() );\n inst.MajorVersion_value( StrToMultibyte(asinst->GetMajorVersion()).c_str() );\n inst.Port_value( StrToMultibyte(asinst->GetPort()).c_str() );\n inst.Protocol_value( StrToMultibyte(asinst->GetProtocol()).c_str() );\n inst.DiskPath_value( StrToMultibyte(asinst->GetDiskPath()).c_str() );\n inst.Type_value( StrToMultibyte(asinst->GetType()).c_str() );\n inst.IsDeepMonitored_value( asinst->GetIsDeepMonitored() );\n inst.IsRunning_value( asinst->GetIsRunning() );\n inst.Profile_value( StrToMultibyte(asinst->GetProfile()).c_str() );\n inst.Cell_value( StrToMultibyte(asinst->GetCell()).c_str() );\n inst.Node_value( StrToMultibyte(asinst->GetNode()).c_str() );\n inst.Server_value( StrToMultibyte(asinst->GetServer()).c_str() );\n }\n}\n\nSCX_Application_Server_Class_Provider::SCX_Application_Server_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_Application_Server_Class_Provider::~SCX_Application_Server_Class_Provider()\n{\n}\n\nvoid SCX_Application_Server_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::AppServerProvider::Lock\"));\n SCXCore::g_AppServerProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_AppServerProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_Application_Server_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Application_Server_Class_Provider::Load\", SCXCore::g_AppServerProvider.GetLogHandle() );\n}\n\nvoid SCX_Application_Server_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::AppServerProvider::Lock\"));\n SCXCore::g_AppServerProvider.Unload();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Application_Server_Class_Provider::Unload\", SCXCore::g_AppServerProvider.GetLogHandle() );\n}\n\nvoid SCX_Application_Server_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_AppServerProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"App Server EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::AppServerProvider::Lock\"));\n SCXCoreLib::SCXHandle<SCXSystemLib::AppServerEnumeration> appServers = SCXCore::g_AppServerProvider.GetAppServers();\n\n // Update instances (doing full update if enumerating values - not just keys)\n appServers->Update( !keysOnly );\n\n SCX_LOGTRACE(log, StrAppend(L\"Number of Application Servers = \", appServers->Size()));\n\n for (size_t i = 0; i < appServers->Size(); i++)\n {\n // For each appserver instance, add it to the collection of instances\n SCX_Application_Server_Class inst;\n EnumerateOneInstance( context, inst, keysOnly, appServers->GetInstance(i) );\n context.Post(inst);\n }\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Application_Server_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"App Server EnumerateInstances end\");\n}\n\nvoid SCX_Application_Server_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_Application_Server_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCXLogHandle& log = SCXCore::g_AppServerProvider.GetLogHandle();\n\n SCX_PEX_BEGIN\n {\n if ( !instanceName.Name_exists() )\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n // Global lock for AppServerProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::AppServerProvider::Lock\"));\n SCX_LOGTRACE(log, L\"SCX_Application_Server_Class_Provider::GetInstance\");\n\n SCXCoreLib::SCXHandle<SCXSystemLib::AppServerEnumeration> appServers = SCXCore::g_AppServerProvider.GetAppServers();\n\n // Refresh the collection (both keys and current data)\n appServers->Update();\n\n // See if we have the requested instance\n SCXCoreLib::SCXHandle<SCXSystemLib::AppServerInstance> appInst = appServers->GetInstance(StrFromMultibyte(instanceName.Name_value().Str()));\n\n if ( appInst == NULL )\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCX_Application_Server_Class inst;\n EnumerateOneInstance( context, inst, false, appInst );\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Application_Server_Class_Provider::GetInstances\", log );\n}\n\nvoid SCX_Application_Server_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_Application_Server_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_Application_Server_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_Application_Server_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_Application_Server_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_Application_Server_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_Application_Server_Class_Provider::Invoke_SetDeepMonitoring(\n Context& context,\n const String& nameSpace,\n const SCX_Application_Server_Class& instanceName,\n const SCX_Application_Server_SetDeepMonitoring_Class& in)\n{\n SCXLogHandle& log = SCXCore::g_AppServerProvider.GetLogHandle();\n\n SCX_PEX_BEGIN\n {\n // Global lock for AppServerProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::AppServerProvider::Lock\"));\n SCX_LOGTRACE(log, L\"SCX_Application_Server_Class_Provider::Invoke_SetDeepMonitoring\");\n\n // Get the arguments:\n // id : string\n // deep : boolean\n // protocol : string\n //\n // Validate that we have mandatory arguments\n SCX_Application_Server_SetDeepMonitoring_Class inst;\n if ( !in.id_exists() || !in.deep_exists() )\n {\n inst.MIReturn_value( false );\n context.Post(inst);\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::wstring id = SCXCoreLib::StrFromMultibyte( in.id_value().Str() );\n bool deep = in.deep_value();\n\n // Treat the protocol parameter as optional and fall back to HTTP if not specified\n std::wstring protocol = L\"HTTP\";\n if ( in.protocol_exists() && strlen(in.protocol_value().Str()) > 0 )\n protocol = SCXCoreLib::StrFromMultibyte( in.protocol_value().Str() );\n\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCX_Application_Server_Class_Provider::Invoke_SetDeepMonitoring - id = \", id));\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCX_Application_Server_Class_Provider::Invoke_SetDeepMonitoring - deep = \", deep));\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCX_Application_Server_Class_Provider::Invoke_SetDeepMonitoring - protocol = \", protocol));\n\n SCXCoreLib::SCXHandle<SCXSystemLib::AppServerEnumeration> appServers = SCXCore::g_AppServerProvider.GetAppServers();\n appServers->Update(false);\n\n bool fDeepResult = false;\n SCXHandle<AppServerInstance> appInst = appServers->GetInstance(id);\n if (appInst != NULL)\n {\n appInst->SetIsDeepMonitored(deep, protocol);\n fDeepResult = true;\n }\n else\n {\n inst.MIReturn_value( fDeepResult );\n context.Post(inst);\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n \n inst.MIReturn_value( fDeepResult );\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Application_Server_Class_Provider::Invoke_SetDeepMonitoring\", log );\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.7015939354896545, "alphanum_fraction": 0.7545197010040283, "avg_line_length": 28.51223373413086, "blob_id": "50a582965cbf817e11f05226608cd070be33d282", "content_id": "2cb496036ab4e0ff5872bed615aee6429fb2f72c", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 37393, "license_type": "permissive", "max_line_length": 131, "num_lines": 1267, "path": "/docs/SCX Provider Description.md", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "***Providers for Linux and UNIX (XPlatProviders)***\n\n**Table of Contents**\n\n1 Introduction \n1.1 License \n1.2 Platforms \n1.3 About the Providers \n1.4 Installing and Using the Providers \n2 Provider Classes \n2.1 SCX\\_Agent \n2.1.1 Name \n2.1.2 Caption \n2.1.3 Description \n2.1.4 VersionString \n2.1.5 MajorVersion \n2.1.6 MinorVersion \n2.1.7 RevisionNumber \n2.1.8 BuildNumber \n2.1.9 BuildDate \n2.1.10 Architecture \n2.1.11 OSName \n2.1.12 OSType \n2.1.13 OSVersion \n2.1.14 KitVersionString \n2.1.15 Hostname \n2.1.16 OSAlias \n2.1.17 UnameArchitecture \n2.1.18 MinActiveLogSeverityThreshold \n2.1.19 MachineType \n2.1.20 PhysicalProcessors \n2.1.21 LogicalProcessors \n2.2 SCX\\_DiskDrive \n2.2.1 Caption \n2.2.2 Description \n2.2.3 Name \n2.2.4 IsOnline \n2.2.5 InterfaceType \n2.2.6 Manufacturer \n2.2.7 Model \n2.2.8 TotalCylinders \n2.2.9 TotalHeads \n2.2.10 TotalSectors \n2.2.11 TotalTracks \n2.2.12 TracksPerCylinder \n2.2.13 RemoveByName() \n2.3 SCX\\_FileSystem \n2.3.1 Caption \n2.3.2 Description \n2.3.3 IsOnline \n2.3.4 TotalInodes \n2.3.5 FreeInodes \n2.3.6 RemoveByName \n2.4 SCX\\_LogFile \n2.4.1 GetMatchedRows \n2.5 SCX\\_UnixProcess \n2.5.1 Caption \n2.5.2 Description \n2.5.3 TopResourceConsumers() \n2.6 SCX\\_IPProtocolEndpoint \n2.6.1 Caption \n2.6.2 Description \n2.6.3 IPv4BroadcastAddress \n2.7 SCX\\_OperatingSystem \n2.7.1 Caption \n2.7.2 Description \n2.7.3 OperatingSystemCapability \n2.7.4 SystemUpTime \n2.7.5 ExecuteCommand() \n2.7.6 ExecuteShellCommand() \n2.7.7 ExecuteScript() \n2.8 SCX\\_StatisticalInformation \n2.8.1 IsAggregate \n2.9 SCX\\_ProcessorStatisticalInformation \n2.9.1 Caption \n2.9.2 Description \n2.9.3 Name \n2.9.4 PercentIdleTime \n2.9.5 PercentUserTime \n2.9.6 PercentNiceTime \n2.9.7 PercentPrivilegedTime \n2.9.8 PercentDPCTime \n2.9.9 PercentProcessorTime \n2.9.10 PercentIOWaitTime \n2.10 SCX\\_MemoryStatisticalInformation \n2.10.1 Caption \n2.10.2 Description \n2.10.3 Name \n2.10.4 AvailableMemory \n2.10.5 PercentAvailableMemory \n2.10.6 UsedMemory \n2.10.7 PercentUsedMemory \n2.10.8 PagesPerSec \n2.10.9 PagesReadPerSec \n2.10.10 PagesWrittenPerSec \n2.10.11 AvailableSwap \n2.10.12 PercentAvailableSwap \n2.10.13 UsedSwap \n2.10.14 PercentUsedSwap \n2.11 SCX\\_EthernetPortStatistics \n2.11.1 Caption \n2.11.2 Description \n2.11.3 BytesTotal \n2.11.4 TotalRxErrors \n2.11.5 TotalTxErrors \n2.11.6 TotalCollisions \n2.12 SCX\\_DiskDriveStatisticalInformation \n2.12.1 Caption \n2.12.2 Description \n2.12.3 Name \n2.12.4 IsOnline \n2.12.5 PercentBusyTime \n2.12.6 PercentIdleTime \n2.12.7 BytesPerSecond \n2.12.8 ReadBytesPerSecond \n2.12.9 WriteBytesPerSecond \n2.12.10 TransfersPerSecond \n2.12.11 ReadsPerSecond \n2.12.12 WritePerSecond \n2.12.13 AverageReadTime \n2.12.14 AverageWriteTime \n2.12.15 AverageTransferTime \n2.12.16 AverageDiskQueueLength \n2.13 SCX\\_FileSystemStatisticalInformation \n2.13.1 Caption \n2.13.2 Description \n2.13.3 Name \n2.13.4 IsOnline \n2.13.5 FreeMegabytes \n2.13.6 UsedMegabytes \n2.13.7 PercentFreeSpace \n2.13.8 PercentUsedSpace \n2.13.9 PercentFreeInodes \n2.13.10 PercentUsedInodes \n2.13.11 PercentBusyTime \n2.13.12 PercentIdleTime \n2.13.13 BytesPerSecond \n2.13.14 ReadBytesPerSecond \n2.13.15 WriteBytesPerSecond \n2.13.16 TransfersPerSecond \n2.13.17 ReadsPerSecond \n2.13.18 WritesPerSecond \n2.13.19 AverageTransferTime \n2.13.20 AverageDiskQueueLength \n2.14 SCX\\_UnixProcessStatisticalInformation \n2.14.1 Caption \n2.14.2 Description \n2.14.3 BlockReadsPerSecond \n2.14.4 BlockWritesPerSecond \n2.14.5 BlockTransfersPerSecond \n2.14.6 PercentUserTime \n2.14.7 PercentPrivilegedTime \n2.14.8 UsedMemory \n2.14.9 PercentUsedMemory \n2.14.10 PagesReadPerSec \n2.15 SCX\\_LANEndpoint \n2.15.1 Caption  \n2.15.2 Description \n2.15.3 Name \n2.15.4 MACAddress \n2.15.5 FormattedMACAddress \n \n \n3 Configuration Files \n3.1 scxlog.conf \n3.2 scxrunas.conf\n\n**1 Introduction**\n\nWelcome to the Providers for Linux and UNIX, a set of providers for\nLinux and UNIX operating systems as used in System Center 2012 R2\nOperations Manager. This document describes the classes, properties, and\nmethods implemented by these providers. \n \n1.1 License \nThe Providers for Linux and UNIX are published under the Microsoft\nPublic License, which is described here\nhttp://opensource.org/licenses/ms-pl.html. \n \n1.2 Platforms \nThe Providers for Linux and UNIX have been tested on the following\noperating systems:\n\n- Red Hat Enterprise Linux 4, 5, 6, and 7 (x86/x64)\n\n- SUSE Linux Enterprise Server 9 (x86), 10 SP1 (x86/x64), 11 (x86/64)\n\n- CentOS Linux 5, 6, and 7 (x86/64)\n\n- Debian GNU/Linux 5, 6, 7, 8, and 9 (x86/x64)\n\n- Oracle Linux 5 and 6 (x86/x64)\n\n- Ubuntu Linux Server 10.04, 12.04, 14.04, and 16.04 (x86/x64)\n\n- IBM AIX 5.3, 6.1, and 7.1 (POWER)\n\n- HP-UX 11i v2 and v3 (PA-RISC and IA64)\n\n- Oracle Solaris 9 (SPARC), Solaris 10 (SPARC and x86), and Solaris 11\n (SPARC and x86)\n\nOther platforms will be supported over time. See README.md in top level\ndirectory for details.\n\n1.3 About the Providers \nThe Providers for Linux and UNIX are intended for use with Open\nManagement Infrastructure\n([OMI](https://www.github.com/Microsoft/omi)). \n \n1.4 Installing and Using the Providers \nBuilding the provider uses the\n[Build-SCXcore](https://github.com/Microsoft/Build-SCXcore)\nsuper-project on GitHub. Refer to that project for information on how to\nbuild the providers from source.\n\nPre-built providers are available in repository\n[SCXcore-kits](https://github.com/Microsoft/SCXcore-kits), also on\nGitHub.\n\n**2 Provider Classes**\n\nThis chapter discusses the CIM classes and methods implemented by\nXPlatProviders. See scx.mof, located in the MOF installation directory\n(--mofdir) for more details. \n \n2.1 SCX\\_Agent \nThere is a single instance of this class. It provides information about\nthe XPlatProviders package and the system it is installed on. The\nfollowing instance was obtained from a Suse 10.1 system. \n \nName = \"scx\" \nCaption = \"SCX Agent meta-information\" \nDescription = \"Developer\\_Build - 20090426\" \nVersionString = \"1.0.4-249\" \nMajorVersion = 1 \nMinorVersion = 0 \nRevisionNumber = 4 \nBuildNumber = 249 \nBuildDate = \"2009-04-26T00:00:00Z\" \nArchitecture = \"x86\"; \nOSName = \"SUSE Linux Enterprise Server\" \nOSType = \"Linux\" \nOSVersion = \"10.1\" \nHostname = \"scxcore-suse01.scx.com\" \nOSAlias = \"SLES\" \nUnameArchitecture = \"i686\" \nMinActiveLogSeverityThreshold = \"INFO\" \nMachineType = \"Virtual\" \nPhysicalProcessors = 2 \nLogicalProcessors = 4 \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.1.1 Name \nThis key property uniquely identifies the single instance of this class.\nThe value is always \"scx\", which stands for \"System-Center\nX-Platform\". \n \n2.1.2 Caption \nA human readable name for this instance. \n \n2.1.3 Description \nThe build date of XPlatProviders. \n \n2.1.4 VersionString \nThe version of XPlatProviders (major, minor, revision, and build\nnumber). \n \n2.1.5 MajorVersion \nThe major version number of the XPlatProviders package. \n \n2.1.6 MinorVersion \nThe minor version number of the XPlatProviders package. \n \n2.1.7 RevisionNumber \nThe revision number of the XPlatProviders package. \n \n2.1.8 BuildNumber \nThe build number of the XPlatProviders package. \n \n2.1.9 BuildDate \nThe build date of the XPlatProviders package. \n \n2.1.10 Architecture \nThe system architecture (e.g., x86 or IA64) \n \n2.1.11 OSName \nThe system's operating system type (e.g., Linux or SunOS) \n \n2.1.12 OSType \nThe system operating system version (e.g. 10 or 5.10) \n \n2.1.13 OSVersion \nThe system operating system version (e.g. 10 or 5.10) \n \n2.1.14 KitVersionString \nA string representing the complete software version of the installed\nkit. \n \n2.1.15 Hostname \nThe hostname of the machine (including domain name if available). \n \n2.1.16 OSAlias \nShort name version of the OSName that provides an abbreviated name of OS\nwithout formating. \n \n2.1.17 UnameArchitecture \nOutput of uname -m or uname -p. \n \n2.1.18 MinActiveLogSeverityThreshold \nLowest log severity threshold currently in use in the agent, which is\none of the following: \"HYSTERICAL\", \"TRACE\", \"INFO\", \"WARNING\", \"ERROR\",\n\"SUPPRESS\". \n \n2.1.19 MachineType \nAn indicator of whether the hardware running the monitored operating\nsystem is physical or virtual. Possible valuesof this field are:\n\"Physical\", \"Virtual\", and \"Unknown\". \n \n2.1.20 PhysicalProcessors \nThe number of physical processors in the hardware, as seen by the\nmonitored operating system. \n \n2.1.21 LogicalProcessors \nThe number of logical processors in the hardware, as seen by the\nmonitored operating system. \n \n2.2 SCX\\_DiskDrive \nEach instance of this class provides information about a disk drive\nattached to the current system. A typical instance looks like this. \n \nEnabledState = 5 \nRequestedState = 12 \nEnabledDefault = 2 \nSystemCreationClassName = \"SCX\\_ComputerSystem\" \nSystemName = \"scxcore-suse01.scx.com\" \nCreationClassName = \"SCX\\_DiskDrive\" \nDeviceID = \"sda\" \nMaxMediaSize = 17179869184 \nCaption = \"Disk drive information\" \nDescription = \"Information pertaining to a physical unit of secondary\nstorage\" \nName = \"sda\" \nIsOnline = TRUE \nInterfaceType = \"SCSI\" \nModel = \"\" \nTotalCylinders = 2088 \nTotalHeads = 255 \nTotalSectors = 63 \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.2.1 Caption \nA human readable caption for this disk. \n \n2.2.2 Description \nA textual description of this disk. \n \n2.2.3 Name \nA unique key property that uniquely identifies this disk. \n \n2.2.4 IsOnline \nTrue if the disk is online. \n \n2.2.5 InterfaceType \nType of interface (e.g., SCSI, IDE). \n \n2.2.6 Manufacturer \nName of the disk manufacturer if available. \n \n2.2.7 Model \nModel of the disk if available. \n \n2.2.8 TotalCylinders \nTotal number of cylinders on this disk. \n \n2.2.9 TotalHeads \nTotal number of heads on this disk. \n \n2.2.10 TotalSectors \nTotal number of sectors on this disk. \n \n2.2.11 TotalTracks \nTotal number of tracks on this disk. \n \n2.2.12 TracksPerCylinder \nThe number of tracks per cyclinder if available. \n \n2.2.13 RemoveByName() \nboolean SCX\\_DiskDrive.RemoveByName( \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring Name) \n \nRemove the disk with the given Name from the list of monitored disks. \n \n2.3 SCX\\_FileSystem \nEach instance of this class provides information about a file system on\nthis computer. Here is an example instance obtained from a Linux system.\nThis instance represents the root file system. \n \nEnabledState = 5; \nRequestedState = 12; \nEnabledDefault = 2; \nCSCreationClassName = \"SCX\\_ComputerSystem\"; \nCSName = \"scxcore-suse01.scx.com\"; \nCreationClassName = \"SCX\\_FileSystem\"; \nName = \"/\"; \nRoot = \"/\"; \nBlockSize = 4096; \nFileSystemSize = 16376020992; \nAvailableSpace = 6574993408; \nReadOnly = FALSE; \nEncryptionMethod = \"Not Encrypted\"; \nCompressionMethod = \"Not Compressed\"; \nCaseSensitive = TRUE; \nCasePreserved = TRUE; \nMaxFileNameLength = 255; \nFileSystemType = \"reiserfs\"; \nPersistenceType = 2; \nCaption = \"File system information\"; \nDescription = \"Information about a logical unit of secondary storage\"; \nIsOnline = TRUE; \nTotalInodes = 2048000; \nFreeInodes = 1984563; \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.3.1 Caption \nA human-readable caption for this insatnce. \n \n2.3.2 Description \nA human-readable description of this instance. \n \n2.3.3 IsOnline \nTrue if this file system is online (mounted). \n \n2.3.4 TotalInodes \nThe total number of inodes allocated in this file system. A value of\nzero indicates that this file system does not have a preset number of\ninodes. \n \n2.3.5 FreeInodes \nThe number of inodes in this file system that are currently free and\nhence available for creating a new file. \n \n2.3.6 RemoveByName \nboolean RemoveByName( \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring Name) \n \nRemoves from the list of monitored file systems. \n \n2.4 SCX\\_LogFile \nEach instance of this class provides information about a \\`log' file, on\nwhich SCX\\_LogFile.GetMatchedRows() has been called. It defines a single\nstatic method, described below. \n \n2.4.1 GetMatchedRows \nuint32 GetMatchedRows( \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring filename, \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring regexps\\[\\], \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring qid, \n[*OUT,\nArrayType(\"Ordered\")*](https://scx.codeplex.com/wikipage?title=OUT%2c%20ArrayType%28%22Ordered%22%29&referringTitle=xplatproviders)\nstring rows\\[\\]); \n \nGets rows from the named file that match any of the supplied regular\nexpressions. On the first invocation, it returns all matching lines in\nthe file. On subsequent calls, only lines that appeared since the\nprevious call are returned. After the first call, a CIM instance of\nSCX\\_LogFile is created. To begin where the previous call left off, you\nmust pass in exactlyt he same values for the filename, regexps, and qid\nparameters. \n \n2.5 SCX\\_UnixProcess \nEach instance of this class provides information about a Unix (or Linux)\nprocess. The following instance provides information about the Unix init\nprocess obtained from a Linux system. \n \nEnabledState = 5 \nRequestedState = 12 \nEnabledDefault = 2 \nCSCreationClassName = \"SCX\\_ComputerSystem\" \nCSName = \"scxcore-suse01.scx.com\" \nOSCreationClassName = \"SCX\\_OperatingSystem\" \nOSName = \"SuSE Distribution\" \nCreationClassName = \"SCX\\_UnixProcess\" \nHandle = \"1\" \nName = \"init\" \nPriority = 76 \nExecutionState = 6 \nCreationDate = \"20090416105118.035100-420\" \nKernelModeTime = 19300 \nUserModeTime = 2000 \nParentProcessID = \"0\" \nRealUserID = 0 \nProcessGroupID = 0 \nProcessSessionID = 0 \nModulePath = \"/sbin/init\" \nParameters = \"init\n[*3*](https://scx.codeplex.com/wikipage?title=3&referringTitle=xplatproviders)\" \nProcessNiceValue = 20 \nProcessWaitingForEvent = \"\\_stext\" \nCaption = \"Unix process information\" \nDescription = \"A snapshot of a current process\" \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.5.1 Caption \nA human-readable caption for this instance. \n \n2.5.2 Description \nA human-readable description of this instance. \n \n2.5.3 TopResourceConsumers() \nstring TopResourceConsumers( \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring resource, \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nuint16 count) \n \nReturns a list of processes that are the top count consumers of the\ngiven resource. The resoure parameter is one of the following. \n \n\"CPUTime\" \n\"BlockReadsPerSecond\" \n\"BlockWritesPerSecond\" \n\"BlockTransfersPerSecond\" \n\"PercentUserTime\" \n\"PercentPrivilegedTime\" \n\"UsedMemory\" \n\"PercentUsedMemory\" \n\"PagesReadPerSec\" \nThe returned string is formatted with one process per line (includes the\npid and process name). \n \nThe following call, finds the top 10 consumers of memory. \n \nTopResourceConsumers(\"UsedMemory\", 10) \n \n2.6 SCX\\_IPProtocolEndpoint \nEach instance of this class provides information about an IP protocol\nendpoint. The following instance provides information about Ethernet\ninterface eth1. \n \nElementName = \"eth1\" \nRequestedState = 12 \nEnabledDefault = 2 \nSystemCreationClassName = \"SCX\\_ComputerSystem\" \nSystemName = \"scxcore-suse01.scx.com\" \nCreationClassName = \"SCX\\_IPProtocolEndpoint\" \nEnabledState = 2 \nName = \"eth1\"; \nIPv4Address = \"10.195.173.73\" \nSubnetMask = \"255.255.254.0\" \nProtocolIFType = 4096 \nCaption = \"IP protocol endpoint information\" \nDescription = \"Properties of an IP protocol connection endpoint\" \nIPv4BroadcastAddress = \"10.195.173.255\" \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.6.1 Caption \nA human-readable caption for this instance. \n \n2.6.2 Description \nA human-readable description of this instance. \n \n2.6.3 IPv4BroadcastAddress \nThe IPV4 broadcast IP for this ProtocolEndpoint. \n \n2.7 SCX\\_OperatingSystem \nThe instance of this class represents the operating system on the\ncurrent system. The following instance was obtained from a Linux Suse\n10.1 system. \n \nCaption = \"SUSE Linux Enterprise Server 10 (i586)\" \nDescription = \"SUSE Linux Enterprise Server 10 (i586)\" \nEnabledState = 5 \nRequestedState = 12 \nEnabledDefault = 2 \nCSCreationClassName = \"SCX\\_ComputerSystem\" \nCSName = \"scxcore-suse01.scx.com\" \nCreationClassName = \"SCX\\_OperatingSystem\" \nName = \"SuSE Distribution\" \nOSType = 36 \nOtherTypeDescription = \"2.6.16.54-0.2.8-smp \\#1 SMP Mon Jun 23 13:41:12\nUTC 2008\" \nVersion = \"2.6.16.54-0.2.8-smp\" \nLastBootUpTime = \"20090416105118.029909-420\" \nLocalDateTime = \"20090610135832.699909-420\" \nCurrentTimeZone = -420 \nNumberOfLicensedUsers = 0 \nNumberOfUsers = 13 \nNumberOfProcesses = 114 \nMaxNumberOfProcesses = 8192 \nTotalSwapSpaceSize = 778240 \nTotalVirtualMemorySize = 1292288 \nFreeVirtualMemory = 1157120 \nFreePhysicalMemory = 386048 \nTotalVisibleMemorySize = 514048 \nSizeStoredInPagingFiles = 778240 \nFreeSpaceInPagingFiles = 771072 \nMaxProcessMemorySize = 0 \nMaxProcessesPerUser = 4096 \nOperatingSystemCapability = \"32 bit\" \nSystemUpTime = 4763234 \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.7.1 Caption \nA human-readable caption for this instance. \n \n2.7.2 Description \nA human-readable description of this instance. \n \n2.7.3 OperatingSystemCapability \nThe capability of this operating system, either '32 bit' or '64 bit'. \n \n2.7.4 SystemUpTime \nThe elapsed time, in seconds, since the OS was booted. A convenience\nproperty, versus having to calculate the time delta from LastBootUpTime\nto LocalDateTime. \n \n2.7.5 ExecuteCommand() \nboolean ExecuteCommand( \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring Command, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nsint32 ReturnCode, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nstring StdOut, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nstring StdErr, \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nuint32 timeout) \n \nExecute a command, with the option of terminating the command after a\ntimeout specified in seconds. Never times out if timeout is zero. \n \n2.7.6 ExecuteShellCommand() \nboolean ExecuteShellCommand( \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring Command, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nsint32 ReturnCode, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nstring StdOut, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nstring StdErr, \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nuint32 timeout) \n \nExecute a command in the default shell, with the option of terminating\nthe command after a timeout specified in seconds. Never times out if\ntimeout is zero. \n \n2.7.7 ExecuteScript() \nboolean ExecuteScript( \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring Script, \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nstring Arguments, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nsint32 ReturnCode, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nstring StdOut, \n[*OUT*](https://scx.codeplex.com/wikipage?title=OUT&referringTitle=xplatproviders)\nstring StdErr, \n[*IN*](https://scx.codeplex.com/wikipage?title=IN&referringTitle=xplatproviders)\nuint32 timeout) \n \nExecute a script, with the option of terminating the script after a\ntimeout specified in seconds. Never times out if timeout is zero. \n \n2.8 SCX\\_StatisticalInformation \nThis is a base class for two other classes defined below. It defines one\nlocal property defined below. See the superclass for a description of\ninherited features. \n \n2.8.1 IsAggregate \nTrue if data is aggregated from several instances. \n \n2.9 SCX\\_ProcessorStatisticalInformation \nInstances of this class capture statistical information about processors\non the current system. An instance is defined for each processor and an\nadditional instance is defined that aggregates statiscial information\nabout all processors. The following instance was obtained from a\ndual-processor Linux system and has statistical information about the\nfirst processor. \n \nIsAggregate = FALSE \nCaption = \"Processor information\" \nDescription = \"CPU usage statistics\" \nName = \"0\" \nPercentIdleTime = 0 \nPercentUserTime = 0 \nPercentNiceTime = 0 \nPercentPrivilegedTime = 0 \nPercentInterruptTime = 0 \nPercentDPCTime = 0 \nPercentProcessorTime = 100 \nPercentIOWaitTime = 0 \n \nA second instance has the following properties. \n \nIsAggregate = FALSE \nCaption = \"Processor information\" \nDescription = \"CPU usage statistics\" \nName = \"1\" \nPercentIdleTime = 0 \nPercentUserTime = 0 \nPercentNiceTime = 0 \nPercentPrivilegedTime = 0 \nPercentInterruptTime = 0 \nPercentDPCTime = 0 \nPercentProcessorTime = 100 \nPercentIOWaitTime = 0 \n \nAnd finally, a third instance aggregates these two instances and is\nshown below (note that IsAggregate is TRUE). \n \nIsAggregate = TRUE \nCaption = \"Processor information\" \nDescription = \"CPU usage statistics\" \nName = \"\\_Total\" \nPercentIdleTime = 0 \nPercentUserTime = 0 \nPercentNiceTime = 0 \nPercentPrivilegedTime = 0 \nPercentInterruptTime = 0 \nPercentDPCTime = 0 \nPercentProcessorTime = 100 \nPercentIOWaitTime = 0 \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.9.1 Caption \nA human-readable caption for this instance. \n \n2.9.2 Description \nA human-readable description of this instance. \n \n2.9.3 Name \nThis key property uniquely identifies this instance. It holds the\nprocessor number. \n \n2.9.4 PercentIdleTime \nPercentage of time during the sample interval that the processor was\nidle. \n \n2.9.5 PercentUserTime \nPercentage of non-idle processor time spent in user mode. \n \n2.9.6 PercentNiceTime \nPercentage of non-idle processor time spent in user mode. \n \n2.9.7 PercentPrivilegedTime \nPercentage of non-idle processor time spent in privileged. \n \n2.9.8 PercentDPCTime \nPercentage of time spent receiving and servicing DPC (Deferred Procedure\nCalls). \n \n2.9.9 PercentProcessorTime \nPercentage of time that the processor spent executing a non-idle\nthread. \n \n2.9.10 PercentIOWaitTime \nPercentage of time that the processor spent waiting for IO operations to\ncomplete. \n \n2.10 SCX\\_MemoryStatisticalInformation \nA single instance of this class provides memory statistics for the\ncurrent system. The following instance was obtained from a Linux\nsystem. \n \nIsAggregate = TRUE \nCaption = \"Memory information\" \nDescription = \"Memory usage and performance statistics\" \nName = \"Memory\" \nAvailableMemory = 378 \nPercentAvailableMemory = 75 \nUsedMemory = 124 \nPercentUsedMemory = 25 \nPagesPerSec = 0 \nPagesReadPerSec = 0 \nPagesWrittenPerSec = 0 \nAvailableSwap = 753 \nPercentAvailableSwap = 99 \nUsedSwap = 7 \nPercentUsedSwap = 1 \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.10.1 Caption \nA human-readable caption for this instance. \n \n2.10.2 Description \nA human-readable description of instance. \n \n2.10.3 Name \nThis key property uniquely identifies the memory instance. \n \n2.10.4 AvailableMemory \nAvailable physical memory in megabytes. \n \n2.10.5 PercentAvailableMemory \nAvailable physical memory in percent. \n \n2.10.6 UsedMemory \nUsed physical memory in megabytes. \n \n2.10.7 PercentUsedMemory \nUsed physical memory in percent. \n \n2.10.8 PagesPerSec \nPages read or written from/to disk per second to resolve hard page\nfaults. \n \n2.10.9 PagesReadPerSec \nPages read from disk per second to resolve hard page faults. \n \n2.10.10 PagesWrittenPerSec \nPages written to disk per second to resolve hard page faults. \n \n2.10.11 AvailableSwap \nAvailable swap space in megabytes. \n \n2.10.12 PercentAvailableSwap \nAvailable swap space in percent. \n \n2.10.13 UsedSwap \nUsed swap space in megabytes. \n \n2.10.14 PercentUsedSwap \nUsed swap space in percent. \n \n2.11 SCX\\_EthernetPortStatistics \nEach instance of this class provides statiscial information about an\nEthernet port. For example, the following instance provides statistics\nfor the Ethernet interface eth1. \n \nInstanceID = \"eth1\" \nSampleInterval = \"00000000000000.000000:000\" \nBytesTransmitted = 1634798148 \nBytesReceived = 2938050399 \nPacketsTransmitted = 40129891 \nPacketsReceived = 72116482 \nCaption = \"Ethernet port information\" \nDescription = \"Statistics on transfer performance for a port\" \nBytesTotal = 4572848547 \nTotalRxErrors = 147 \nTotalTxErrors = 0 \nTotalCollisions = 0 \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.11.1 Caption \nA human-readable caption for this instance. \n \n2.11.2 Description \nA human-readable description of instance. \n \n2.11.3 BytesTotal \nThe total number of bytes sent or received through the port. \n \n2.11.4 TotalRxErrors \nThe aggregated number of receive errors. \n \n2.11.5 TotalTxErrors \nThe aggregated number of transmit errors. \n \n2.11.6 TotalCollisions \nThe aggregated number of collisions. \n \n2.12 SCX\\_DiskDriveStatisticalInformation \nEach instance of this class provides statiscial information about a disk\ndrive. For example, consider the following instance. \n \nIsAggregate = TRUE \nCaption = \"Disk drive information\" \nDescription = \"Performance statistics related to a physical unit of\nsecondary storage\" \nName = \"\\_Total\" \nIsOnline = TRUE \nBytesPerSecond = 0 \nReadBytesPerSecond = 0 \nWriteBytesPerSecond = 0 \nTransfersPerSecond = 0 \nReadsPerSecond = 0 \nWritesPerSecond = 0 \nAverageReadTime = 0.0000000000000000e+00 \nAverageWriteTime = 0.0000000000000000e+00 \nAverageTransferTime = 0.0000000000000000e+00 \nAverageDiskQueueLength = 0.0000000000000000e+00 \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.12.1 Caption \nA human-readable caption for this instance. \n \n2.12.2 Description \nA human-readable description of instance. \n \n2.12.3 Name \nA key property that uniquely identifies this instance. \n \n2.12.4 IsOnline \nTrue if this disk is online. \n \n2.12.5 PercentBusyTime \nPercent of time the disk is busy. \n \n2.12.6 PercentIdleTime \nPercent of time the disk is idle. \n \n2.12.7 BytesPerSecond \nTotal Disk bytes per second. \n \n2.12.8 ReadBytesPerSecond \nBytes read from disk per second. \n \n2.12.9 WriteBytesPerSecond \nBytes written to from disk per second. \n \n2.12.10 TransfersPerSecond \nTotal I/Os per second. \n \n2.12.11 ReadsPerSecond \nRead I/Os per second. \n \n2.12.12 WritePerSecond \nWrite I/Os per second. \n \n2.12.13 AverageReadTime \nAverage time, in seconds, of a read of data from the disk. \n \n2.12.14 AverageWriteTime \nAverage time, in seconds, of a write of data to the disk. \n \n2.12.15 AverageTransferTime \nAverage time, in seconds, of a disk transfer. \n \n2.12.16 AverageDiskQueueLength \nAverage number of queued read/write requests. \n \n2.13 SCX\\_FileSystemStatisticalInformation \nEach instance of this class provides statiscial information about a file\nsystem. The following instance provides statistics for the root files\nsytem. \n \nIsAggregate = FALSE \nCaption = \"File system information\" \nDescription = \"Performance statistics related to a logical unit of\nsecondary storage\" \nName = \"/\" \nIsOnline = TRUE \nFreeMegabytes = 6271 \nUsedMegabytes = 9347 \nPercentFreeSpace = 40 \nPercentUsedSpace = 60 \nPercentFreeInodes = 83 \nPercentUsedInodes = 17 \nPercentBusyTime = NULL \nPercentIdleTime = NULL \nBytesPerSecond = 1583 \nReadBytesPerSecond = 0 \nWriteBytesPerSecond = 1583 \nTransfersPerSecond = 0 \nReadsPerSecond = 0 \nWritesPerSecond = 0 \nAverageTransferTime = NULL \nAverageDiskQueueLength = NULL \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.13.1 Caption \nA human-readable caption for this instance. \n \n2.13.2 Description \nA human-readable description of instance. \n \n2.13.3 Name \nA key property that uniquely identifies this instance. \n \n2.13.4 IsOnline \nTrue if this file system is online (mounted). \n \n2.13.5 FreeMegabytes \nAvailable space in megabytes. \n \n2.13.6 UsedMegabytes \nUsed space in megabytes. \n \n2.13.7 PercentFreeSpace \nAvailable space in percent. \n \n2.13.8 PercentUsedSpace \nUsed space in percent. \n \n2.13.9 PercentFreeInodes \nAvailable inodes in percent. \n \n2.13.10 PercentUsedInodes \nUsed inodes in percent. \n \n2.13.11 PercentBusyTime \nPercent of time filesystem is busy. \n \n2.13.12 PercentIdleTime \nPercent of time filesystem is idle. \n \n2.13.13 BytesPerSecond \nTotal bytes per second. \n \n2.13.14 ReadBytesPerSecond \nBytes read per second. \n \n2.13.15 WriteBytesPerSecond \nBytes written per second. \n \n2.13.16 TransfersPerSecond \nTotal I/Os per second. \n \n2.13.17 ReadsPerSecond \nRead I/Os per second. \n \n2.13.18 WritesPerSecond \nWrite I/Os per second. \n \n2.13.19 AverageTransferTime \nAverage time of transfer in seconds. \n \n2.13.20 AverageDiskQueueLength \nAverage number of queued read/write requests. \n \n2.14 SCX\\_UnixProcessStatisticalInformation \nEach instance of this class provides statiscial information about a Unix\nprocess. The following instance provides statistics for the init\nprocess. \n \nCSCreationClassName = \"SCX\\_ComputerSystem\" \nCSName = \"scxcore-suse01.scx.com\" \nOSCreationClassName = \"SCX\\_OperatingSystem\" \nOSName = \"SuSE Distribution\" \nHandle = \"1\" \nProcessCreationClassName = \"SCX\\_UnixProcessStatisticalInformation\" \nName = \"init\" \nCPUTime = 0 \nVirtualText = 499712 \nVirtualData = 233472 \nVirtualSharedMemory = 40 \nCpuTimeDeadChildren = 3170331 \nSystemTimeDeadChildren = 1418717 \nCaption = \"Unix process information\" \nDescription = \"Performance statistics for an individual Unix process\" \nPercentUserTime = 0 \nPercentPrivilegedTime = 0 \nUsedMemory = 64 \nPercentUsedMemory = 8 \nPagesReadPerSec = 0 \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.14.1 Caption \nA human-readable caption for this instance. \n \n2.14.2 Description \nA human-readable description of instance. \n \n2.14.3 BlockReadsPerSecond \nBlock reads per second. \n \n2.14.4 BlockWritesPerSecond \nBlock writes per second. \n \n2.14.5 BlockTransfersPerSecond \nBlock transfers per second. \n \n2.14.6 PercentUserTime \nPercentage of non-idle processor time spent in user mode. \n \n2.14.7 PercentPrivilegedTime \nPercentage of non-idle processor time spent in privileged mode. \n \n2.14.8 UsedMemory \nUsed physical memory in kilobytes. \n \n2.14.9 PercentUsedMemory \nRatio of Resident Set Size to Virtual Memory for process (essentially\npercentage of process loaded into memory). \n \n2.14.10 PagesReadPerSec \nPages read from disk per second to resolve hard page faults.\n\n2.15 SCX\\_LanEndpoint\n\nEach instance of this class provides information about an Ethernet\nendpoint on this com- puter. Here is an example instance obtained from a\nLinux system. This instance represents the eth0 endpoint.\n\nInstanceID=eth0 \nCaption=LAN endpoint caption information \nDescription=LAN Endpoint description information \nElementName=eth0 \\[Key\\] \nName=eth0 \\[Key\\] \nSystemCreationClassName=SCX\\_ComputerSystem \n\\[Key\\] SystemName=lab-nx-02.contosolab.com \n\\[Key\\] CreationClassName=SCX\\_LANEndpoint \nMACAddress=00155d84495b \nFormattedMACAddress=00-15-5D-84-49-5B \n \nThe following subsections describe the local properties and methods of\nthis class. See the superclass for a description of inherited\nfeatures. \n \n2.15.1 Caption \nA human-readable caption for this instance.\n\n2.15.2 Description \nA human-readable description of instance.\n\n2.15.3 Name \nThe name of the LAN endpoint.\n\n2.15.4 MACAddress \nThe MAC address of the LAN endpoint.\n\n2.15.5 FormattedMACAddress \nThe formatted MAC address of the LAN endpoint.\n\n**3 Configuration Files**\n\nXPlatProviders uses the following two configuration files. \n \n{confdir}/scxlog.conf \n{confdir}/scxrunas.conf \n \nThese are discussed in the sections below. \n \n3.1 scxlog.conf \nThis configuration file controls the provider logging facility. By\ndefault, all provider logging is directed to {logdir}/log/scx.log. The\ndefault logging threshold is \\`WARNING'. The scxlog.conf file can\nredirect logging to multiple files and it may control the logging\nthreshold for those files. For example, consider the following file. \n \nFILE ( \nPATH: /opt/xplatproviders/log/log1 \nMODULE: WARNING \nMODULE: scx.core.providers TRACE \n) \nFILE ( \nPATH: /opt/xplatproviders/log/log2 \nMODULE: WARNING \nMODULE: scx.core.common TRACE \n) \n \nThis log has two sections. Each section sends logging output to a\nspecific file. The first section directs log output to\n/opt/xplatproviders/log/myfile. TRACE severity log messages are logged\nfor the logging module called scx.core.providers. For the \\`root' module\n(everything else), only WARNING severity log messages are logged. Any\nsection may have multiple module lines. \n \nThe logging severities are as follows. \n \nERROR - The system could not perform the task it was supposed to\nperform. Contact support. \nWARNING - Abnormal behavior that could be handled. \nINFORMATION - Information that is useful to someone trying to figure out\nthe general state of the application. Example: Successful\ninitialization. \nTRACE - Information that is useful to someone trying to follow general\nprogram execution flow. \nHYSTERICAL - Information that is useful to someone trying to follow very\ndetailed program execution flow. This level will normally only be used\nfor finding and fixing bugs and in those cases only for small modules. \nSUPPRESS - It must be possible to suppress messages using a severity\nthreshold that is higher than any log message can have. \nThe logging modules are listed here. \n \nscx \nscx.core \nscx.core.common \nscx.core.common.pal \nscx.core.common.pal.os \nscx.core.common.pal.os.filepath \nscx.core.common.pal.os.filestream \nscx.core.common.pal.system \nscx.core.common.pal.system.common \nscx.core.common.pal.system.common.entityenumeration \nscx.core.common.pal.system.common.entityinstance \nscx.core.common.pal.system.cpu.cpuenumeration \nscx.core.common.pal.system.cpu.cpuinstance \nscx.core.common.util \nscx.core.common.util.math \nscx.core.common.util.stringaid \nscx.core.providers \nscx.core.providers.cpu \nscx.core.providersupport \nscx.core.providersupport.cmpibase \n \nThese are arranged in a hierarcy, so specifiying scx.core.providers also\naffects the following modules (of which scx.core.providers is a\nprefix). \n \nscx.core.providers \nscx.core.providers.cpu \nscx.core.providersupport \nscx.core.providersupport.cmpibase \n \n3.2 scxrunas.conf \nThis configuration file controls the execution of the following\nextrinsic methods (described above). \n \nSCX\\_OperatingSystem.ExecuteCommand() \nSCX\\_OperatingSystem.ExecuteShellCommand() \nSCX\\_OperatingSystem.ExecuteScript() \n \nThe SCX\\_OperatingSystem provider runs in its own agent process. The\nprocess owner is the same as the user that initiated the CIM client\nrequest. The three methods above spawn a new process to execute the\ncommand or script. This configuration file controls three options that\naffect this new process. The following scxrunas.conf file has the\ndefault settings (the settings used if the file is empty or missing). \n \nAllowRoot=false \nChRootPath= \nCWD=/opt/xplatproviders/run \n \nThe AllowRoot option indicates whether the process may execute as root.\nBy default it cannot. The ChRootPath, if non-empty, is the path on which\na chroot system call is performed immediately after creating the process\nbut before executing the command or script. By default ChRootPath is\nempty, indicating that no chroot is performed. The CWD option is the\ndirectory that the process executes in. By default it is the same as the\n{rundir} configured during installation.\n" }, { "alpha_fraction": 0.4759916365146637, "alphanum_fraction": 0.48709431290626526, "avg_line_length": 28.965877532958984, "blob_id": "ea4e479886bd9e8a291cc9618bfee9dbd271ccd2", "content_id": "24f875f4396e6e245e1e0561651ec1f7591721f2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 31614, "license_type": "permissive", "max_line_length": 218, "num_lines": 1055, "path": "/test/util/testapp/testapp.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n */\n#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <stdio.h>\n#include <string.h>\n#include <time.h>\n#include <unistd.h>\n\n#ifndef WIN32\n#include <pthread.h>\n#include <syslog.h>\n#include <stdlib.h>\n#include <ulimit.h>\n#else\n#include <windows.h>\n#endif\n\n#include \"memdata.h\"\n#include \"diskdata.h\"\n\n#ifdef WIN32\n#define LOG_ERR 3\n#endif\n\nusing namespace std;\n\nconst unsigned int defaultdiskfillpercent = 60;\nconst unsigned int defaultmemfillpercent = 96;\nconst string bigfilename = \"bigfile.txt\";\n//Network load Parameters\nconst string NWFileSendPath = \"/tmp/scx*\";\nconst string NWFileRcvPath = \"/tmp/junk\";\nstring NWCompName;\nunsigned int Nwmode;\n\nconst string defaultsyslogmessage = \"Test Message\";\nint disk_fill_files=0;\nvoid DoStopSyslog();\nvoid DoStopPegasus();\nvoid DoLoadCPU();\nvoid DoLoadNetwork();\nvoid DoLoadMemory();\nvoid DoFillDisk();\nvoid DoWriteToSyslog();\n\nstruct TestConfig\n{\n bool StopSyslog;\n bool StopPegasus;\n bool LoadCPU;\n bool LoadNetwork;\n bool LoadMemory;\n bool FillDisk;\n bool WriteSyslog;\n unsigned int SyslogLevel;\n unsigned int NWLoadMode;\n string SyslogMessage;\n string CompName;\n unsigned int Seconds;\n unsigned int FillPercent;\n unsigned int Threads;\n};\n\nstruct MenuItem\n{\n string name;\n void (*function)();\n};\n\nconst MenuItem mainmenu[] = { \n { \"Stop syslog\", DoStopSyslog },\n { \"Stop Pegasus\", DoStopPegasus },\n { \"Load CPU\", DoLoadCPU },\n { \"Load Memory\", DoLoadMemory },\n { \"Fill Disk\", DoFillDisk },\n { \"Write to syslog\", DoWriteToSyslog },\n { \"Load Network\", DoLoadNetwork },\n { \"\", NULL }\n };\n\n#ifdef WIN32\nconst string syslogstopcmd = \"echo Execute Stop syslog\";\nconst string pegasusstopcmd = \"echo Execute Stop Pegasus\";\nconst string deletefilecommand = \"del \";\n#else\nconst string syslogstopcmd = \"/etc/init.d/syslog stop\";\nconst string pegasusstopcmd = \"/etc/init.d/scx-cimd stop\";\nconst string deletefilecommand = \"rm -f \";\n#endif\n\nvoid WaitForEnter(string txt=\"continue\")\n{\n char tmp[32];\n\n cout << endl << \"Press ENTER to \" << txt;\n cin.getline(tmp, 31);\n}\n\nvoid WaitForTime(unsigned int seconds)\n{\n cout << \"Sleeping for \" << seconds << \" seconds:\" << endl;\n\n for (unsigned int i=0; i<seconds; i++)\n {\n#ifdef WIN32\n Sleep(1000);\n#else\n sleep(1);\n#endif\n cout << \".\";\n cout.flush();\n }\n cout << endl;\n}\n\nbool MenuChoice(const MenuItem *menu, int &choice)\n{\n int count = 0;\n\n cout << endl;\n\n while (menu[count].name.length() > 0)\n {\n cout << count+1 << \". \" << menu[count].name << endl;\n count++;\n }\n\n do\n {\n char tmp[256] = \"\";\n\n cout << endl << \"Select [1-\" << count << \"] (Just ENTER to quit) \";\n cin.getline(tmp, 255);\n\n if (tmp[0] == '\\0')\n {\n choice = 0;\n return false;\n }\n else\n {\n choice = atoi(tmp);\n }\n } \n while (choice < 1 || choice > count);\n\n return true;\n}\n\nvoid ExecuteWriteToSyslog(unsigned int level, string message)\n{\n#ifndef WIN32\n\n cout << \"Writing to message: '\" << message << \"' with level: \" << level << \" to syslog\" << endl;\n\n openlog(\"MSTest\", 0, LOG_USER);\n syslog(level, \"%s\", message.c_str());\n closelog();\n\n cout << \"Done writing to syslog\" << endl;\n\n#endif\n}\n\nvoid DoWriteToSyslog()\n{\n ExecuteWriteToSyslog(LOG_ERR, defaultsyslogmessage);\n}\n\nvoid DoStopSyslog()\n{\n cout << endl << \"Stopping syslog\" << endl;\n system(syslogstopcmd.c_str());\n}\n\n\nvoid DoStopPegasus()\n{\n cout << endl << \"Stopping Pegasus\" << endl;\n system(pegasusstopcmd.c_str());\n}\n\nextern \"C\" void *LoadCPUFunc(void *arg_p)\n{\n bool *stopload = (bool*)arg_p;\n int i;\n long wrk = 4711;\n\n // Simulate some real work\n srandom(wrk);\n\n do {\n for(i = 0; i < 1000; i++) {\n \n wrk *= random();\n wrk /= 17;\n \n }\n } while (!(*stopload)) ;\n\n return (void*)wrk;\n}\n\n//Fucntion used to create scp for send and receive file in the network\nvoid *LoadNetworkFunc(void *arg_p)\n{\n bool *stopload = (bool*)arg_p;\n string SetUpCmd;\n string ExeCmd;\n string CleanUpCmd;\n if(Nwmode==1)\n {\n ExeCmd =\"scp -B -r root@\";\n ExeCmd +=NWCompName;\n ExeCmd +=\":\";\n ExeCmd +=NWFileSendPath;\n ExeCmd +=\" \";\n ExeCmd +=NWFileRcvPath;\n CleanUpCmd = \"rm -rf \";\n CleanUpCmd +=NWFileRcvPath;\n }\n else if(Nwmode==2)\n {\n SetUpCmd =\"ssh root@\";\n SetUpCmd +=NWCompName;\n SetUpCmd +=\" \";\n SetUpCmd +=\" 'mkdir \";\n SetUpCmd +=NWFileRcvPath;\n SetUpCmd +=\"' \";\n ExeCmd =\"scp -B -r \";\n ExeCmd +=NWFileSendPath;\n ExeCmd +=\" \";\n ExeCmd +=\"root@\";\n ExeCmd +=NWCompName;\n ExeCmd +=\":\";\n ExeCmd +=NWFileRcvPath;\n CleanUpCmd =\"ssh root@\";\n CleanUpCmd +=NWCompName;\n CleanUpCmd +=\" \";\n CleanUpCmd +=\"'rm -rf \";\n CleanUpCmd +=NWFileRcvPath;\n CleanUpCmd +=\" '\";\n }\n\n #ifdef WIN32\n Sleep(1000);\n #else\n sleep(1);\n #endif\n // Setup the client/server\n system(SetUpCmd.c_str());\n // Start transfer of files through scp\n while(!(*stopload)) \n { \n system(ExeCmd.c_str());\n }\n // Cleanup the transferred files\n system(CleanUpCmd.c_str());\n return NULL;\n}\nvoid ExecuteLoadCPU(unsigned int seconds, unsigned int threads)\n{\n cout << endl << \"Loading CPU\" << endl;\n\n#ifndef WIN32\n\n pthread_t* tn = new pthread_t[threads];\n\n bool stopload = false;\n\n for (unsigned int i = 0; i < threads; i++) {\n if (pthread_create(&tn[i], NULL, LoadCPUFunc, &stopload) != 0)\n {\n cout << endl << \"Failed to create load thread\" << endl;\n return;\n }\n }\n\n#endif\n\n if (seconds == 0)\n {\n WaitForEnter(\"stop CPU load\");\n }\n else\n {\n WaitForTime(seconds);\n }\n \n#ifndef WIN32\n \n stopload = true;\n for (unsigned int j = 0; j < threads; j++) {\n pthread_join(tn[j], NULL);\n }\n delete [] tn; \n\n#endif\n\n if (seconds == 0)\n {\n WaitForEnter();\n }\n}\n\nvoid DoLoadCPU()\n{\n // Note: You can't adjust the number of threads during interactive use.\n ExecuteLoadCPU(0, 1);\n}\n\n/* Function to start the network load . Creates thread and interleaves it .\n On user signal stops the thread and cleans up the dump\n*/\nvoid ExecuteLoadNetwork(unsigned int seconds,string CompName,unsigned int mode)\n{\n if(mode == 1)\n cout << endl << \"Loading Incoming Network\" << endl;\n else if(mode == 2)\n cout << endl << \"Loading Outgoing Network\" << endl;\n\n NWCompName=CompName;\n Nwmode=mode;\n bool stopload = false;\n\n#ifndef WIN32\n\n pthread_t t1;\n //Create thread to start network file transfer\n if (pthread_create(&t1, NULL, LoadNetworkFunc, &stopload ) != 0)\n {\n cout << endl << \"Failed to create load thread\" << endl;\n }\n else\n {\n\n#endif\n\n if (seconds == 0)\n {\n char tmp[32];\n cin.getline(tmp, 31);\n WaitForEnter(\"stop Network load\");\n stopload = true;\n }\n else\n {\n WaitForTime(seconds);\n stopload = true;\n }\n\n#ifndef WIN32\n\n stopload = true;\n pthread_join(t1, NULL);\n }\n\n#endif\n \n if (seconds == 0)\n {\n WaitForEnter();\n }\n}\n//Function used to get the parameters from user for network loading\nvoid DoLoadNetwork()\n{\n string CompName;\n cout << endl << \" Another Temprary Machine with enabled RSA/DSA Certificates \"<< endl ;\n cout <<\" is required for performing this operation\"<< endl ;\n cout << endl << \" 1 --> To get help on Installing RSA/DSA Certificate\"<< endl ;\n cout << \" Enter --> To Continue Loading Network\"<< endl ;\n cout << endl << \" Enter Your Choice ::\" ;\n if(getchar()=='1')\n {\n cout << endl << \".................................................................\" <<endl;\n cout << \"Procedure : \"<< endl ;\n cout << \".................................................................\" <<endl;\n cout << \"1. In this instructions, the user name is the same in both machines. \"<< endl ;\n cout << \" Instructions for different user names could differ from these \"<< endl ;\n cout << \" (but see note below!) \"<< endl ;\n cout << \"2. The user keys will be stored in ~/.ssh in both machines. \"<< endl ;\n cout << \"3. At the client, run 'ssh-keygen -t dsa' to generate a key pair. Accept \"<< endl ;\n cout << \" default options by pressing return. Specially, do not enter any \"<< endl ;\n cout << \" passphrase. (Option -d seems to be an alias of -t dsa in some \"<< endl ;\n cout << \" platforms). \"<< endl ;\n cout << \"4. Change the permissions of the generated .pub file to 600 by commanding\"<< endl ;\n cout << \" chmod 600 id_dsa.pub \"<< endl ;\n cout << \"5. Copy the public key to the server with\"<< endl; \n cout << \" scp id_dsa.pub 'user@server:~/.ssh/authorized_keys'. (Caution: if that\"<< endl; \n cout << \" destination file already exists on the server, copy first to a\"<< endl;\n cout << \" different file foo and then append the contents with\"<< endl;\n cout << \" cat foo >> authorized_keys executed on the server). \"<< endl;\n cout << \"6. Done! Verify that now you can connect directly from the client with ssh\"<< endl;\n cout << \" user@server without being prompted for a password. \"<< endl ;\n cout << \"7. If it doesn't work, verify that in the server your home directory, the\"<< endl;\n cout << \" .ssh subdirectory, and the authorized_keys file do not have writing\"<< endl; \n cout << \" permissions to others. If they do, they won't be considered to grant\"<< endl;\n cout << \" access. You can correct this with something like: \"<< endl ;\n cout << \" chmod 755 ~\"<< endl ;\n cout << \" chmod 700 ~/.ssh\"<< endl ;\n cout << \" chmod 600 ~/.ssh/authorized_keys\"<< endl ;\n cout << \"8. If it still doesn't work, try changing the authorized_keys file name to\"<< endl;\n cout << \" authorized_keys2, or ask your system administrator what file name \"<< endl ;\n cout << \" is ssh actually using. \"<< endl ;\n cout << \"9. If it worked, you can now run SCP in batch mode with the -B option, as\"<< endl ;\n cout << \" in scp -B foofile 'user@server:~/foodir/'. \"<< endl ;\n cout << endl << \"................................................................\" <<endl;\n cout << \"Notes :\"<< endl ;\n cout << \"................................................................\" <<endl;\n cout << \"The name of the server must have been registered in the known_hosts. This\"<< endl ; \n cout << \"can be done with a regular (with password) ssh connection, and accepting\"<< endl ;\n cout << \"the host as known. Then, the host name should be the same as the one\"<< endl ; \n cout << \"accepted! If you used user@server first, do not use\"<< endl ; \n cout << \"[email protected] later on! \"<< endl ;\n cout << \"SSH protocol 2 is assumed in this procedure (it uses dsa keys). If your ssh\"<< endl ; \n cout << \"configuration files (at /etc/ssh/) do not establish this as a default, you may\"<< endl ; \n cout << \"have to force it with the -2 option of the ssh and scp. Moreover, if the default\"<< endl ; \n cout << \"public key is not configured to be 'id_dsa.pub' you can specify what key to use\"<< endl ; \n cout << \"for identification with the -i option. \"<< endl ;\n cout << \"The same procedure worked fine when the username was different in both machines.\"<< endl ;\n cout << \"I simply copied userA's public key at the end of userB's authorized_keys file, \"<< endl ; \n cout << \"then I could login from my client as userA with ssh userB@server. \"<< endl ;\n cout << \"................................................................\" <<endl;\n }\n cout << endl << \"Enter Machine IP/HostName::\";\n cin >> CompName; \n unsigned int mode;\n cout << endl << \"Select Network Load Mode\"<< endl ;\n cout << endl << \"1-- Load Incoming network\"<< endl ;\n cout << endl << \"2-- Load Outgoing network\"<< endl ;\n cout << endl << \"Enter Choice :: \";\n cin >>mode; \n ExecuteLoadNetwork(0,CompName,mode);\n}\n\nvoid ExecuteLoadMemory(unsigned int seconds, unsigned int fillpercent)\n{\n MEMData memdata;\n\n cout << endl << \"Loading Memory\" << endl;\n\n if (memdata.UpdateData() == 0)\n {\n cout << \"Total Memory=\" << memdata.MEMTotalMB << endl;\n cout << \"Used Memory =\" << memdata.MEMUsedMB << endl;\n cout << \"Used Percent=\" << memdata.MEMUsedPercent << endl;\n\n if (memdata.MEMUsedPercent < fillpercent)\n {\n#if defined(aix)\n //Converting the unsigned int to long\n size_t alloc_bytes = (unsigned long)((fillpercent*memdata.MEMTotalMB)/100 - memdata.MEMUsedMB)*1024*1024;\n printf(\"Allocating %ld bytes \\n\",alloc_bytes);\n //Setting the Resource Limits\n int limitrc;\n errno=0;\n //Set Soft Data Resource limit\n if (limitrc=ulimit(SET_DATALIM,RLIM_INFINITY)<0)\n {\n if (errno == EPERM)\n {\n cout<<\"Attempting to increase the Data Resource limit without root user authority\"<<endl;\n }\n else if(errno == EINVAL)\n {\n cout<<\"Invalid Command Parameter in ulimit()\"<<endl;\n }\n }\n else\n {\n cout<<\"Successful setting of Data Resource Limit to \"<<RLIM_INFINITY<<endl;\n }\n \n //Set Soft Stack Resource limit\n if (limitrc=ulimit(SET_STACKLIM,RLIM_INFINITY)<0)\n {\n if (errno == EPERM)\n {\n cout<<\"Attempting to increase the Stack Resource limit without root user authority\"<<endl;\n }\n else if(errno == EINVAL)\n {\n cout<<\"Invalid Command Parameter in ulimit()\"<<endl;\n }\n }\n else\n {\n cout<<\"Successful setting of Stack Resource Limit to \"<<RLIM_INFINITY<<endl;\n }\n#else\n size_t alloc_bytes = ((fillpercent*memdata.MEMTotalMB)/100 - memdata.MEMUsedMB)*1024*1024;\n cout << \"Allocating \" << alloc_bytes << \" bytes\" << endl;\n#endif\n if (seconds == 0)\n {\n WaitForEnter();\n }\n void *a = malloc(alloc_bytes);\n if (a == NULL)\n {\n cout << \"Failed to allocate memory\";\n }\n else\n {\n memset(a, 17, alloc_bytes);\n if (memdata.UpdateData() == 0)\n {\n cout << \"Used Percent is now: \" << memdata.MEMUsedPercent << endl;\n }\n else\n {\n cout << endl << \"Failed to get Memory data\" << endl;\n }\n if (seconds == 0)\n {\n WaitForEnter(\"free the memory\");\n }\n else\n {\n WaitForTime(seconds);\n }\n free(a);\n cout << \"Memory freed\" << endl;\n }\n }\n else\n {\n cout << endl << \"Already at least \" << fillpercent << \"% memory allocated\" << endl;\n }\n\n }\n else\n {\n cout << endl << \"Failed to get Memory data\" << endl;\n }\n\n if (seconds == 0)\n {\n WaitForEnter();\n }\n}\n\nvoid ExecuteFillMemory(unsigned int seconds, unsigned int fillpercent)\n{\n MEMData memdata;\n \n cout << endl << \"Loading Memory using -fm option\" << endl;\n \n if (memdata.UpdateData() == 0)\n {\n cout << \"Total Memory=\" << memdata.MEMTotalMB << endl;\n cout << \"Used Memory =\" << memdata.MEMUsedMB << endl;\n cout << \"Used Percent=\" << memdata.MEMUsedPercent << endl;\n \n if (memdata.MEMUsedPercent > fillpercent)\n {\n cout << endl << \"Already at least \" << fillpercent << \"% memory allocated\" << endl;\n cout <<\"exiting Loading Memory -fm option\"<<endl;\n }\n else\n {\n //Temporary variables used for time slicing\n unsigned int timeslice,remsec,loopcnt;\n\n // To Allocate dynamic memory\n void *a;\n\n // time slicing for every 30 seconds\n timeslice=30;\n\n remsec=seconds%timeslice;\n loopcnt = seconds/timeslice;\n \n for(unsigned int i=0;i<=loopcnt;i++)\n {\n if (memdata.MEMUsedPercent < fillpercent)\n {\n cout << \"Memory used % < Target Memory % \" << endl;\n\n#if defined(aix)\n //Converting the unsigned int to long\n size_t alloc_bytes = (unsigned long)((fillpercent*memdata.MEMTotalMB)/100 - memdata.MEMUsedMB)*1024*1024;\n printf(\"Allocating %ld bytes \\n\",alloc_bytes);\n //Setting the Resource Limits\n int limitrc;\n errno=0;\n //Set Soft Data Resource limit\n if (limitrc=ulimit(SET_DATALIM,RLIM_INFINITY)<0)\n {\n if (errno == EPERM)\n {\n cout<<\"Attempting to increase the Data Resource limit without root user authority\"<<endl;\n }\n else if(errno == EINVAL)\n {\n cout<<\"Invalid Command Parameter in ulimit()\"<<endl;\n }\n }\n else\n {\n cout<<\"Successful setting of Data Resource Limit to \"<<RLIM_INFINITY<<endl;\n }\n \n //Set Soft Stack Resource limit\n if (limitrc=ulimit(SET_STACKLIM,RLIM_INFINITY)<0)\n {\n if (errno == EPERM)\n {\n cout<<\"Attempting to increase the Stack Resource limit without root user authority\"<<endl;\n }\n else if(errno == EINVAL)\n {\n cout<<\"Invalid Command Parameter in ulimit()\"<<endl;\n }\n }\n else\n {\n cout<<\"Successful setting of Stack Resource Limit to \"<<RLIM_INFINITY<<endl;\n }\n#else\n size_t alloc_bytes = ((fillpercent*memdata.MEMTotalMB)/100 - memdata.MEMUsedMB)*1024*1024;\n cout << \"Allocating \" << alloc_bytes << \" bytes\" << endl;\n#endif\n a = malloc(alloc_bytes);\n if (a == NULL)\n {\n cout << \"Failed to allocate memory\";\n }\n else\n {\n memset(a, 17, alloc_bytes);\n }\n }\n\n if ( i !=loopcnt)\n {\n WaitForTime(timeslice);\n }\n else\n {\n //Waiting for remaining time in the last timeslice\n WaitForTime(remsec);\n }\n \n // Checking for used memory after the time slice\n if (memdata.UpdateData() == 0)\n {\n cout << \"Used Percent is now: \" << memdata.MEMUsedPercent << endl;\n }\n else\n {\n cout << endl << \"Failed to get Memory data\" << endl;\n }\n \n }\n if (a != NULL)\n { \n free(a);\n cout << \"Memory freed\" << endl;\n }\n }\n }\n else\n {\n cout << endl << \"Failed to get Memory data\" << endl; \n }\n }\n\nvoid DoLoadMemory()\n{\n ExecuteLoadMemory(0, defaultmemfillpercent);\n}\n\nint CreateLargeFile(string filename, unsigned int mb_size)\n{\n FILE *fileptr;\n char mb_buf[1024*1024+1];\n memset(mb_buf, 'a', 1024*1024);\n mb_buf[1024*1024] = '\\0';\n disk_fill_files=0;\n //Open a file and write the buffer data to it\n fileptr = fopen(filename.c_str(), \"w\");\n if (fileptr== NULL)\n {\n cout << \"Failed to open file '\" << filename << \"' for output\" << endl;\n return -1;\n }\n\n // Split the files for sun machines if the file creating size is more than 2 GiB\n #if defined(sun)\n if(mb_size>2000)\n {\n int mb_chunks=mb_size/2000;\n disk_fill_files=mb_chunks;\n mb_size=mb_size%2000;\n for(unsigned int i=0;i<mb_chunks;i++)\n {\n std::string new_file;\n char temp[100];\n sprintf(temp,\"%d\",i);\n new_file +=filename;\n new_file +=temp;\n //Create files of 2 GiB each\n CreateLargeFile(new_file, 2000);\n }\n }\n #endif\n //Write the buffer data to the file.\n for (unsigned int i=0; i< mb_size; i++)\n {\n fprintf(fileptr, mb_buf); \n }\n\n //Close the file \n fclose(fileptr);\n return 1;\n}\n\nvoid DeleteLargeFile(string filename,int disk_fill_file)\n{\n string command = deletefilecommand + \" \" + filename + \"*\";\n system(command.c_str());\n //Delete the files if more than one file is created with same name and different suffix(for sun compiler switch only)\n #if defined(sun)\n if(disk_fill_file>0)\n {\n for(unsigned int i=0;i<disk_fill_file;i++)\n {\n std::string new_file;\n char temp[100];\n sprintf(temp,\"%d\",i);\n new_file +=filename;\n new_file +=temp;\n DeleteLargeFile(new_file, 0);\n }\n }\n #endif\n\n}\n\nvoid ExecuteFillDisk(unsigned int seconds, unsigned int fillpercent)\n{\n DiskData diskdata;\n vector<DiskInfo> disks;\n string filename;\n\n cout << endl << \"Filling Disk\" << endl;\n \n diskdata.GetDiskInfo(disks);\n\n if (disks.size() > 0)\n {\n cout << \"Disk \" << disks[0].physical << \" mounted on \" << disks[0].name << \" is \" << disks[0].size_kb << \"kB large and has \" << disks[0].free_kb << \"kB free, which means \" << disks[0].usage << \"% used\" << endl;\n\n filename = disks[0].name;\n if (filename[filename.length()-1] != '/')\n {\n filename += \"/\";\n }\n filename += bigfilename;\n\n if (disks[0].usage < fillpercent)\n {\n unsigned int alloc_mb = (unsigned int)(disks[0].free_kb/1024 - (((100-fillpercent)*(disks[0].size_kb/1024))/100));\n cout << \"Trying to use up \" << alloc_mb << \"MB extra on disk \" << disks[0].physical << endl;\n#ifndef WIN32\n CreateLargeFile(filename, alloc_mb);\n#endif\n disks.clear();\n diskdata.GetDiskInfo(disks);\n if (disks.size() > 0)\n {\n cout << \"Used Percent is now: \" << disks[0].usage << endl;\n }\n else\n {\n cout << endl << \"Failed to get disk data\" << endl;\n }\n\n if (seconds == 0)\n {\n WaitForEnter(\"delete the file\");\n }\n else\n {\n WaitForTime(seconds);\n }\n#ifndef WIN32\n DeleteLargeFile(filename,disk_fill_files);\n#endif\n cout << \"File deleted\" << endl;\n }\n else\n {\n cout << \"Disk \" << disks[0].physical << \" already at least \" << fillpercent << \"% used\" << endl;\n }\n }\n else\n {\n cout << endl << \"No disks found\" << endl;\n }\n \n if (seconds == 0)\n {\n WaitForEnter();\n }\n}\n\nvoid DoFillDisk()\n{\n ExecuteFillDisk(0, defaultdiskfillpercent);\n}\n\nvoid ShowMenu(const MenuItem *menu)\n{\n int choice = 0;\n\n do\n {\n if (MenuChoice(menu, choice))\n {\n menu[choice-1].function();\n }\n }\n while (choice > 0);\n}\n\nvoid ResetConfig(TestConfig *config)\n{\n config->StopSyslog = false;\n config->StopPegasus = false;\n config->LoadCPU = false;\n config->LoadNetwork = false;\n config->LoadMemory = false;\n config->FillDisk = false;\n config->WriteSyslog = false;\n config->SyslogLevel = 0;\n config->SyslogMessage = \"\";\n config->Seconds = 0;\n config->FillPercent = 0;\n config->Threads = 1;\n}\n\nbool ParseArgs(int argc, char *argv[], TestConfig *config)\n{\n ResetConfig(config);\n\n if (argc < 2)\n {\n return false;\n }\n\n if (strcmp(argv[1], \"-ss\") == 0)\n {\n config->StopSyslog = true;\n return true;\n }\n\n if (strcmp(argv[1], \"-sp\") == 0)\n {\n config->StopPegasus = true;\n return true;\n }\n\n if (strcmp(argv[1], \"-lc\") == 0 && argc > 2)\n {\n config->LoadCPU = true;\n config->Seconds = atoi(argv[2]);\n\n if (argc > 3 && *argv[3] != '-')\n {\n config->Threads = atoi(argv[3]);\n }\n\n return true;\n }\n if (strcmp(argv[1], \"-lni\") == 0 && argc > 2)\n {\n config->LoadNetwork = true;\n config->Seconds = atoi(argv[2]);\n if (argc > 3)\n {\n config->CompName = argv[3];\n }\n else\n {\n config->CompName = \"scxom-suse16\";\n }\n config->NWLoadMode= 1;\n\n return true;\n }\n if (strcmp(argv[1], \"-lno\") == 0 && argc > 2)\n {\n config->LoadNetwork = true;\n config->Seconds = atoi(argv[2]);\n if (argc > 3)\n {\n config->CompName = argv[3];\n }\n else\n {\n config->CompName = \"scxom-suse16\";\n }\n config->NWLoadMode= 2; \n return true;\n }\n if (strcmp(argv[1], \"-sl\") == 0)\n {\n config->WriteSyslog = true;\n if (argc > 2)\n {\n config->SyslogLevel = atoi(argv[2]);\n if (argc > 3)\n {\n config->SyslogMessage = argv[3];\n }\n else\n {\n config->SyslogMessage = defaultsyslogmessage;\n }\n }\n else\n {\n config->SyslogLevel = LOG_ERR;\n config->SyslogMessage = defaultsyslogmessage;\n }\n return true;\n }\n\n if (strcmp(argv[1], \"-fm\") == 0 && argc > 2)\n {\n config->LoadMemory = true;\n config->Seconds = atoi(argv[2]);\n if (argc > 3)\n {\n config->FillPercent = atoi(argv[3]);\n }\n else\n {\n config->FillPercent = defaultmemfillpercent;\n }\n return true;\n }\n\n if (strcmp(argv[1], \"-fd\") == 0 && argc > 2)\n {\n config->FillDisk = true;\n config->Seconds = atoi(argv[2]);\n if (argc > 3)\n {\n config->FillPercent = atoi(argv[3]);\n }\n else\n {\n config->FillPercent = defaultmemfillpercent;\n }\n return true;\n }\n\n return false;\n}\n\nvoid ExecuteTest(TestConfig *config)\n{\n if (config->StopSyslog)\n {\n DoStopSyslog();\n }\n\n if (config->StopPegasus)\n {\n DoStopPegasus();\n }\n\n if (config->LoadCPU)\n {\n ExecuteLoadCPU(config->Seconds, config->Threads);\n }\n if (config->LoadNetwork)\n {\n ExecuteLoadNetwork(config->Seconds,config->CompName,config->NWLoadMode);\n }\n if (config->LoadMemory)\n {\n ExecuteFillMemory(config->Seconds, config->FillPercent);\n }\n\n if (config->FillDisk)\n {\n ExecuteFillDisk(config->Seconds, config->FillPercent);\n }\n\n if (config->WriteSyslog)\n {\n ExecuteWriteToSyslog(config->SyslogLevel, config->SyslogMessage);\n }\n}\n\nvoid PrintUsage(void)\n{\n cout << endl;\n cout << \"testapp [-ss|-sp|-lc <seconds> [<threads>] |-fm <seconds> [<percent>]\" << endl;\n cout << \" |-fd <seconds> [<percent>]|-sl [<level> <message>]\" << endl;\n cout << \" |-lno <seconds> <File transfer machine name/IP>\" << endl;\n cout << \" |-lni <seconds> <File transfer machine name/IP>\" << endl;\n cout << endl;\n cout << \" -ss - Stop syslog\" << endl;\n cout << \" -sp - Stop Pegasus\" << endl;\n cout << \" -lc <seconds> [<threads>] - Load CPU to 100% during the number of seconds given\" << endl;\n cout << \" using the number of threads (default 1)\" << endl;\n cout << \" -fm <seconds> [<percent>] - Fill Memory to given percent (default \" << defaultmemfillpercent << \"%)\" << endl;\n cout << \" during the number of seconds given\" << endl;\n cout << \" -fd <seconds> [<percent>] - Fill Disk to given percent (default \" << defaultdiskfillpercent << \"%)\" << endl;\n cout << \" during the number of seconds given\" << endl;\n cout << \" -sl [<level> <message>] - Write to syslog. If no message is given a\" << endl;\n cout << \" default test message is written\" << endl;\n cout << \" Level is a number between 0 (EMERG) and 7 (DEBUG)\" << endl;\n cout << \" Default level is 3 (ERR)\" << endl;\n cout << \" -lno <seconds> <Client IP> -Load Outgoing Network to 100% during the\" << endl;\n cout << \" number of seconds given\" << endl;\n cout << \" -lni <seconds> <Client IP> -Load incoming Network to 100% during the\" << endl;\n cout << \" number of seconds given\" << endl;\n cout << endl;\n}\n\nint main(int argc, char* argv[])\n{\n if (argc > 1)\n {\n TestConfig config;\n if (ParseArgs(argc, argv, &config))\n {\n ExecuteTest(&config);\n }\n else\n {\n PrintUsage();\n }\n }\n else\n {\n ShowMenu(mainmenu);\n }\n\n cout << endl << \"Bye!\" << endl;\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6099379062652588, "alphanum_fraction": 0.6109139323234558, "avg_line_length": 30.836158752441406, "blob_id": "9866460af3e5fb6daa02a8985845e8cfc0b79053", "content_id": "55954aa4a8c3307d43ae10a1ef9c74886ff0cb26", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11270, "license_type": "permissive", "max_line_length": 139, "num_lines": 354, "path": "/source/code/providers/SCX_RTProcessorStatisticalInformation_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/* @migen@ */\n#include <MI.h>\n#include \"SCX_RTProcessorStatisticalInformation_Class_Provider.h\"\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxconfigfile.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/stringaid.h>\n#include <scxsystemlib/cpuenumeration.h>\n\n#include \"support/startuplog.h\"\n#include \"support/scxcimutils.h\"\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\n// Note that this is copied from the SCX_RTProcessorStatisticalInforamtion class\n// code, but it must be separate since the two classes are constructed\n// differently. Since this is in a private namespace, this works.\n//\n// It would be nice to restructure this code to share more common code, but it\n// isn't possible to do that in the short timeframe before shipping. It's also\n// not clear how to do this from an OMI perspective, unless the implementation\n// is totally divorced from the _Class_Provider.cpp code. We'll leave that for\n// another day.\n\nnamespace\n{\n class CPUProvider\n {\n public:\n virtual ~CPUProvider() { };\n void Load()\n {\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.rtcpuprovider\");\n SCXCore::LogStartup();\n SCX_LOGTRACE(m_log, L\"RTCPUProvider::Load()\");\n\n // See if we have a config file for overriding default RT provider settings\n time_t sampleSecs = 10;\n size_t sampleSize = 2;\n\n do {\n SCXConfigFile conf(SCXCore::SCXConfFile);\n try {\n conf.LoadConfig();\n }\n catch (SCXFilePathNotFoundException &e)\n {\n continue;\n }\n\n std::wstring value;\n if (conf.GetValue(L\"RTCPUProvider_SampleSecs\", value))\n {\n sampleSecs = StrToUInt(value);\n }\n\n if (conf.GetValue(L\"RTCPUProvider_SampleSize\", value))\n {\n sampleSize = StrToUInt(value);\n }\n }\n while (false);\n\n // Log what we're starting the real time provider with\n SCX_LOGTRACE(m_log, StrAppend(StrAppend(\n StrAppend(L\"RTCPUProvider parameters: Sample Seconds = \",sampleSecs),\n L\", SampleSize = \"), sampleSize));\n\n m_cpusEnum = new CPUEnumeration(\n SCXHandle<CPUPALDependencies>(new CPUPALDependencies()),\n sampleSecs, sampleSize);\n m_cpusEnum->Init();\n }\n }\n\n void Unload()\n {\n SCX_LOGTRACE(m_log, L\"CPUProvider::Unload()\");\n if (0 == --ms_loadCount)\n {\n if (m_cpusEnum != NULL)\n {\n m_cpusEnum->CleanUp();\n m_cpusEnum == NULL;\n }\n }\n }\n\n SCXCoreLib::SCXHandle<SCXSystemLib::CPUEnumeration> GetEnumCPUs() const\n {\n return m_cpusEnum;\n }\n\n SCXLogHandle& GetLogHandle() { return m_log; }\n\n private:\n //! PAL implementation retrieving CPU information for local host\n SCXCoreLib::SCXHandle<SCXSystemLib::CPUEnumeration> m_cpusEnum;\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n };\n\n CPUProvider g_CPUProvider;\n int CPUProvider::ms_loadCount = 0;\n}\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_RTProcessorStatisticalInformation_Class& inst,\n bool keysOnly,\n SCXHandle<SCXSystemLib::CPUInstance> cpuinst)\n{\n // Populate the key values\n std::wstring name = cpuinst->GetProcName();\n inst.Name_value(StrToMultibyte(name).c_str());\n\n if (!keysOnly)\n {\n inst.Caption_value(\"Processor information\");\n inst.Description_value(\"CPU usage statistics\");\n\n scxulong data;\n\n inst.IsAggregate_value(cpuinst->IsTotal());\n\n if (cpuinst->GetProcessorTime(data))\n {\n inst.PercentProcessorTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetIdleTime(data))\n {\n inst.PercentIdleTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetUserTime(data))\n {\n inst.PercentUserTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetNiceTime(data))\n {\n inst.PercentNiceTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetPrivilegedTime(data))\n {\n inst.PercentPrivilegedTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetIowaitTime(data))\n {\n inst.PercentIOWaitTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetInterruptTime(data))\n {\n inst.PercentInterruptTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetDpcTime(data))\n {\n inst.PercentDPCTime_value(static_cast<unsigned char> (data));\n }\n }\n context.Post(inst);\n}\n\nSCX_RTProcessorStatisticalInformation_Class_Provider::SCX_RTProcessorStatisticalInformation_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_RTProcessorStatisticalInformation_Class_Provider::~SCX_RTProcessorStatisticalInformation_Class_Provider()\n{\n}\n\nvoid SCX_RTProcessorStatisticalInformation_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for CPUProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"CPUProvider::Lock\"));\n g_CPUProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(g_CPUProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_RTProcessorStatisticalInformation_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_RTProcessorStatisticalInformation_Class_Provider::Load\", g_CPUProvider.GetLogHandle() );\n}\n\nvoid SCX_RTProcessorStatisticalInformation_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for CPUProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"CPUProvider::Lock\"));\n g_CPUProvider.Unload();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_RTProcessorStatisticalInformation_Class_Provider:::Unload\", g_CPUProvider.GetLogHandle() );\n}\n\nvoid SCX_RTProcessorStatisticalInformation_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = g_CPUProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"RTProcessorStat EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for CPUProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"CPUProvider::Lock\"));\n\n // Prepare ProcessorStatisticalInformation Enumeration\n // (Note: Only do full update if we're not enumerating keys)\n SCXHandle<SCXSystemLib::CPUEnumeration> cpuEnum = g_CPUProvider.GetEnumCPUs();\n cpuEnum->Update(!keysOnly);\n\n for(size_t i = 0; i < cpuEnum->Size(); i++)\n {\n SCX_RTProcessorStatisticalInformation_Class inst;\n SCXHandle<SCXSystemLib::CPUInstance> cpuInst = cpuEnum->GetInstance(i);\n EnumerateOneInstance(context, inst, keysOnly, cpuInst);\n }\n\n // Enumerate Total instance\n SCXHandle<SCXSystemLib::CPUInstance> totalInst = cpuEnum->GetTotalInstance();\n if (totalInst != NULL)\n {\n // There will always be one total instance\n SCX_RTProcessorStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, keysOnly, totalInst);\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_RTProcessorStatisticalInformation_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"RTProcessorStat EnumerateInstances end\");\n}\n\nvoid SCX_RTProcessorStatisticalInformation_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_RTProcessorStatisticalInformation_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for CPUProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"CPUProvider::Lock\"));\n\n SCXHandle<SCXSystemLib::CPUEnumeration> cpuEnum = g_CPUProvider.GetEnumCPUs();\n cpuEnum->Update(true);\n\n const std::string name = instanceName.Name_value().Str();\n\n if (name.size() == 0)\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n bool instFound = false;\n SCXHandle<SCXSystemLib::CPUInstance> cpuInst;\n for(size_t i=0; i<cpuEnum->Size(); i++)\n {\n cpuInst = cpuEnum->GetInstance(i);\n // Compare key values of input args and the current instance\n if (cpuInst->GetProcName() == StrFromUTF8(name))\n {\n // Match\n instFound = true;\n break;\n }\n }\n\n if (instFound == false)\n {\n // As last resort, check if we the request is for the _Total instance\n if (cpuEnum->GetTotalInstance() != NULL)\n {\n cpuInst = cpuEnum->GetTotalInstance();\n if (cpuInst->GetProcName() == StrFromUTF8(name))\n {\n instFound = true;\n }\n }\n\n if (instFound == false)\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n }\n\n SCX_RTProcessorStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, false, cpuInst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_RTProcessorStatisticalInformation_Class_Provider::GetInstance\",\n g_CPUProvider.GetLogHandle() );\n}\n\nvoid SCX_RTProcessorStatisticalInformation_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_RTProcessorStatisticalInformation_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_RTProcessorStatisticalInformation_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_RTProcessorStatisticalInformation_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_RTProcessorStatisticalInformation_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_RTProcessorStatisticalInformation_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.624374508857727, "alphanum_fraction": 0.6269423365592957, "avg_line_length": 30.84067153930664, "blob_id": "2d0a18d74c95e0852e533e1aeccad8d8f7f644ef", "content_id": "5c71e6917837f15b3741cf214445aed3d17c7638", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15188, "license_type": "permissive", "max_line_length": 127, "num_lines": 477, "path": "/source/code/providers/SCX_DiskDrive_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_DsikDrive_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-14-2013 11:09:45\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_DiskDrive_Class_Provider.h\"\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxnameresolver.h>\n#include \"support/diskprovider.h\"\n#include \"support/scxcimutils.h\"\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/scxpatternfinder.h>\n\n# define QLENGTH 1000\n\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_DiskDrive_Class& inst,\n bool keysOnly,\n SCXHandle<SCXSystemLib::StaticPhysicalDiskInstance> diskInst)\n{\n SCXCoreLib::NameResolver nr;\n std::wstring hostname = nr.GetHostDomainname();\n\n diskInst->Update();\n \n // Populate the key values\n inst.CreationClassName_value(\"SCX_DiskDrive\");\n inst.SystemCreationClassName_value(\"SCX_ComputerSystem\");\n\n std::wstring deviceId;\n if (diskInst->GetDiskName(deviceId)) \n {\n inst.DeviceID_value(StrToMultibyte(deviceId).c_str());\n }\n inst.SystemName_value(StrToMultibyte(hostname).c_str());\n\n if (!keysOnly) \n {\n //populate caption and descriptions\n inst.Caption_value(\"Disk drive information\");\n inst.Description_value(\"Information pertaining to a physical unit of secondary storage\");\n \n if (deviceId.size() > 0)\n {\n inst.Name_value(StrToMultibyte(deviceId).c_str());\n }\n\n scxulong data;\n std::wstring sdata;\n bool healthy;\n\n if (diskInst->GetHealthState(healthy)) \n {\n inst.IsOnline_value();\n }\n\n DiskInterfaceType ifcType;\n if (diskInst->GetInterfaceType(ifcType)) \n {\n std::string interfaceTypeStringValue ;\n switch (ifcType) \n {\n case eDiskIfcIDE:\n interfaceTypeStringValue = \"IDE\";\n break;\n\n case eDiskIfcSCSI:\n interfaceTypeStringValue = \"SCSI\";\n break;\n\n case eDiskIfcVirtual:\n interfaceTypeStringValue = \"Virtual\";\n break;\n\n case eDiskIfcUnknown:\n case eDiskIfcMax:\n default:\n interfaceTypeStringValue = \"Unknown\";\n break;\n }\n\n inst.InterfaceType_value(interfaceTypeStringValue.c_str());\n }\n\n if (diskInst->GetManufacturer(sdata)) \n {\n inst.Manufacturer_value(StrToMultibyte(sdata).c_str());\n }\n\n if (diskInst->GetModel(sdata)) \n {\n inst.Model_value(StrToMultibyte(sdata).c_str());\n }\n\n if (diskInst->GetSizeInBytes(data)) \n {\n inst.MaxMediaSize_value(data);\n }\n\n if (diskInst->GetTotalCylinders(data)) \n {\n inst.TotalCylinders_value(data);\n }\n\n if (diskInst->GetTotalHeads(data)) \n {\n inst.TotalHeads_value(data);\n }\n\n if (diskInst->GetTotalSectors(data)) \n {\n inst.TotalSectors_value(data);\n }\n }\n context.Post(inst);\n}\n\nSCX_DiskDrive_Class_Provider::SCX_DiskDrive_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_DiskDrive_Class_Provider::~SCX_DiskDrive_Class_Provider()\n{\n}\n\nvoid SCX_DiskDrive_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n SCXCore::g_DiskProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_DiskProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_DiskDrive_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_DiskDrive_Class_Provider::Load\", SCXCore::g_DiskProvider.GetLogHandle() );\n}\n\nvoid SCX_DiskDrive_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n SCXCore::g_DiskProvider.UnLoad();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_DiskDrive_Class_Provider::Unload\", SCXCore::g_DiskProvider.GetLogHandle() );\n}\n\nvoid SCX_DiskDrive_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_DiskProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"DiskDrive EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n \n wstring diskName=L\"\";\n size_t instancePos=(size_t)-1;\n\n if(filter) {\n char* exprStr[QLENGTH]={NULL};\n char* qtypeStr[QLENGTH]={NULL};\n\n const MI_Char** expr=(const MI_Char**)&exprStr;\n const MI_Char** qtype=(const MI_Char**)&qtypeStr;\n\n MI_Filter_GetExpression(filter, qtype, expr);\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"DiskDrive Provider Filter Set with Expression: \",*expr));\n\n std::wstring filterQuery(SCXCoreLib::StrFromUTF8(*expr));\n\n SCXCoreLib::SCXPatternFinder::SCXPatternCookie s_patternID = 0, id=0;\n SCXCoreLib::SCXPatternFinder::SCXPatternMatch param;\n std::wstring s_pattern(L\"select * from SCX_DiskDrive where DeviceID=%name\");\n\n SCXCoreLib::SCXPatternFinder patterenfinder;\n patterenfinder.RegisterPattern(s_patternID, s_pattern);\n\n bool status=patterenfinder.Match(filterQuery, id, param);\n\n\n if ( status && param.end() != param.find(L\"name\") && id == s_patternID )\n {\n diskName=param.find(L\"name\")->second;\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"DiskDrive Provider Enum Requested for disk: \",diskName));\n }\n }\n\n // Prepare Disk Drive Enumeration\n // (Note: Only do full update if we're not enumerating keys)\n SCXHandle<SCXSystemLib::StaticPhysicalDiskEnumeration> diskEnum = SCXCore::g_DiskProvider.getEnumstaticPhysicalDisks();\n diskName != L\"\"?diskEnum->UpdateSpecific(diskName, &instancePos):diskEnum->Update(!keysOnly);\n \n if (instancePos != (size_t)-1) {\n\t SCXHandle<SCXSystemLib::StaticPhysicalDiskInstance> diskInst = diskEnum->GetInstance(instancePos);\n\t SCX_DiskDrive_Class inst;\n\t EnumerateOneInstance(context, inst, keysOnly, diskInst);\n }\n else {\n for(size_t i = 0; i < diskEnum->Size(); i++) \n {\n SCX_DiskDrive_Class inst;\n SCXHandle<SCXSystemLib::StaticPhysicalDiskInstance> diskInst = diskEnum->GetInstance(i);\n EnumerateOneInstance(context, inst, keysOnly, diskInst);\n }\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_DiskDrive_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"DiskDrive EnumerateInstances end\");\n}\n\nvoid SCX_DiskDrive_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n\n // We have 4-part key:\n // [Key] SystemCreationClassName=SCX_ComputerSystem\n // [Key] SystemName=jeffcof64-rhel6-01.scx.com\n // [Key] CreationClassName=SCX_DiskDrive\n // [Key] DeviceID=sda\n\n if (!instanceName.SystemCreationClassName_exists() || !instanceName.SystemName_exists() ||\n !instanceName.CreationClassName_exists() || !instanceName.DeviceID_exists())\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::string csName;\n try {\n NameResolver mi;\n csName = StrToMultibyte(mi.GetHostDomainname()).c_str();\n } catch (SCXException& e) {\n SCX_LOGWARNING(SCXCore::g_DiskProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n // Now compare (case insensitive for the class names, case sensitive for the others)\n if ( 0 != strcasecmp(\"SCX_ComputerSystem\", instanceName.SystemCreationClassName_value().Str())\n || 0 != strcasecmp(\"SCX_DiskDrive\", instanceName.CreationClassName_value().Str())\n || 0 != strcmp(csName.c_str(), instanceName.SystemName_value().Str()))\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n // Prepare Disk Drive Enumeration\n SCXHandle<SCXSystemLib::StaticPhysicalDiskEnumeration> diskEnum = SCXCore::g_DiskProvider.getEnumstaticPhysicalDisks();\n diskEnum->Update(true);\n\n const std::string deviceId = (instanceName.DeviceID_value()).Str();\n if (deviceId.size() == 0)\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n \n SCXHandle<SCXSystemLib::StaticPhysicalDiskInstance> diskInst;\n diskInst = diskEnum->GetInstance(StrFromUTF8(deviceId));\n \n if (diskInst == NULL)\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCX_DiskDrive_Class inst;\n EnumerateOneInstance(context, inst, false, diskInst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_DiskDrive_Class_Provider::GetInstance\",\n SCXCore::g_DiskProvider.GetLogHandle() );\n}\n\nvoid SCX_DiskDrive_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_RequestStateChange(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_RequestStateChange_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_SetPowerState(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_SetPowerState_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_Reset(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_Reset_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_EnableDevice(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_EnableDevice_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_OnlineDevice(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_OnlineDevice_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_QuiesceDevice(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_QuiesceDevice_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_SaveProperties(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_SaveProperties_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_RestoreProperties(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_RestoreProperties_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_LockMedia(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_LockMedia_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_DiskDrive_Class_Provider::Invoke_RemoveByName(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_RemoveByName_Class& in)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n \n SCXHandle<SCXSystemLib::StaticPhysicalDiskEnumeration> diskEnum = SCXCore::g_DiskProvider.getEnumstaticPhysicalDisks();\n diskEnum->Update(true);\n \n SCX_DiskDrive_RemoveByName_Class inst;\n if (!in.Name_exists() || strlen(in.Name_value().Str()) == 0)\n {\n inst.MIReturn_value(0);\n context.Post(inst);\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n std::wstring name = StrFromMultibyte(in.Name_value().Str());\n\n SCXHandle<SCXSystemLib::StaticPhysicalDiskInstance> diskInst;\n if ( (diskInst = diskEnum->GetInstance(name)) == NULL )\n {\n inst.MIReturn_value(0);\n context.Post(inst);\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCX_DiskDrive_Class ddInst;\n EnumerateOneInstance(context, ddInst, false, diskInst);\n\n bool cmdok = SCXCore::g_DiskProvider.getEnumstatisticalPhysicalDisks()->RemoveInstanceById(name) && \n SCXCore::g_DiskProvider.getEnumstaticPhysicalDisks()->RemoveInstanceById(name);\n\n inst.MIReturn_value(cmdok);\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_DiskDrive_Class_Provider::Invoke_RemoveByName\", SCXCore::g_DiskProvider.GetLogHandle() );\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.5902474522590637, "alphanum_fraction": 0.5931586623191833, "avg_line_length": 33.78480911254883, "blob_id": "6052b643193f09ee1ebbbaa80da2ee51d8cace8b", "content_id": "7fca7347cbcb13ad97f9c1b56ac57206b3698ba7", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2748, "license_type": "permissive", "max_line_length": 108, "num_lines": 79, "path": "/source/code/providers/support/filesystemprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n * \n * */\n /**\n \\file filesystemprovider.h\n\n \\brief FileSystem provider\n\n \\date 08-30-13\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef FILESYSTEMPROVIDER_H\n#define FILESYSTEMPROVIDER_H\n\n#include <scxcorelib/scxlog.h>\n#include \"startuplog.h\"\n#include <scxsystemlib/diskdepend.h>\n#include <scxsystemlib/entityenumeration.h>\n#include <scxsystemlib/staticlogicaldiskenumeration.h>\n#include <scxsystemlib/statisticallogicaldiskenumeration.h>\n#include <scxcorelib/scxhandle.h>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXCore\n{\n /*------------------------------------------------------------------------------*/\n /**\n * FileSystemProvider \n * Helper class to handle the dependency and Logging\n */\n class FileSystemProvider\n {\n public:\n FileSystemProvider()\n : m_staticLogicaldeps(0),\n m_statisticalLogicaldeps(0) { };\n virtual ~FileSystemProvider() { };\n virtual void UpdateDependency(SCXHandle<SCXSystemLib::DiskDepend> staticLogicaldeps,\n SCXHandle<SCXSystemLib::DiskDepend> statisticalLogicaldeps) \n { \n m_staticLogicaldeps = staticLogicaldeps;\n m_statisticalLogicaldeps = statisticalLogicaldeps;\n }\n\n SCXLogHandle& GetLogHandle() { return m_log; }\n void Load();\n void UnLoad();\n\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskEnumeration> getEnumstatisticalLogicalDisks() const\n {\n return m_statisticalLogicalDisks;\n }\n\n SCXHandle<SCXSystemLib::StaticLogicalDiskEnumeration> getEnumstaticLogicalDisks() const\n {\n return m_staticLogicalDisks;\n }\n\n private:\n SCXHandle<SCXSystemLib::DiskDepend> m_staticLogicaldeps, m_statisticalLogicaldeps;\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n\n //! PAL implementation retrieving logical disk information for local host\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskEnumeration> m_statisticalLogicalDisks;\n //! PAL implementation retrieving static logical disk information for local host\n SCXHandle<SCXSystemLib::StaticLogicalDiskEnumeration> m_staticLogicalDisks;\n };\n\n extern SCXCore::FileSystemProvider g_FileSystemProvider;\n}\n\n#endif /* FILESYSTEMPROVIDER_H */\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6940639019012451, "alphanum_fraction": 0.6961948275566101, "avg_line_length": 38.10714340209961, "blob_id": "a6af88bc24fa3d0de2b130d6b6f0a3b54ec78d14", "content_id": "28a418174347e04443b9f56f6e0a486b19a43a5c", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6570, "license_type": "permissive", "max_line_length": 112, "num_lines": 168, "path": "/test/code/providers/process_provider/unixprocesskey_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests the keys of the SCX_UnixProcess.\n\n \\date 2008-09-23 10:26:18\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n#include \"SCX_UnixProcess_Class_Provider.h\"\n#include \"SCX_UnixProcessStatisticalInformation_Class_Provider.h\"\n\n#include \"testutilities.h\"\n\nusing namespace SCXCoreLib;\n\nclass SCXUnixProcessKeyTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXUnixProcessKeyTest );\n\n CPPUNIT_TEST( TestUnixProcessEnumerateKeysOnly );\n CPPUNIT_TEST( TestUnixProcessStatisticalInformationEnumerateKeysOnly );\n\n CPPUNIT_TEST( TestUnixProcessCheckKeyValues );\n CPPUNIT_TEST( TestUnixProcessStatisticalInformationCheckKeyValues );\n\n CPPUNIT_TEST( TestVerifyKeyCompletePartialUnixProcess );\n CPPUNIT_TEST( TestVerifyKeyCompletePartialUnixProcessStatisticalInformation );\n\n\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessEnumerateKeysOnly, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessStatisticalInformationEnumerateKeysOnly, SLOW);\n\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessCheckKeyValues, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessStatisticalInformationCheckKeyValues, SLOW);\n\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartialUnixProcess, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartialUnixProcessStatisticalInformation, SLOW);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector<std::wstring> m_keyNamesUP;\n std::vector<std::wstring> m_keyNamesUPS;\n\npublic:\n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_UnixProcess_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_UnixProcessStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n \n m_keyNamesUP.push_back(L\"CSCreationClassName\");\n m_keyNamesUP.push_back(L\"CSName\");\n m_keyNamesUP.push_back(L\"OSCreationClassName\");\n m_keyNamesUP.push_back(L\"OSName\");\n m_keyNamesUP.push_back(L\"CreationClassName\");\n m_keyNamesUP.push_back(L\"Handle\");\n\n m_keyNamesUPS.push_back(L\"Name\");\n m_keyNamesUPS.push_back(L\"CSCreationClassName\");\n m_keyNamesUPS.push_back(L\"CSName\");\n m_keyNamesUPS.push_back(L\"OSCreationClassName\");\n m_keyNamesUPS.push_back(L\"OSName\");\n m_keyNamesUPS.push_back(L\"Handle\");\n m_keyNamesUPS.push_back(L\"ProcessCreationClassName\");\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_UnixProcess_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_UnixProcessStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void TestUnixProcessEnumerateKeysOnly()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_UnixProcess_Class_Provider>(\n m_keyNamesUP, context, CALL_LOCATION(errMsg));\n }\n\n void TestUnixProcessStatisticalInformationEnumerateKeysOnly()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_UnixProcessStatisticalInformation_Class_Provider>(\n m_keyNamesUPS, context, CALL_LOCATION(errMsg));\n }\n\n void TestUnixProcessCheckKeyValues()\n {\n std::wstring errMsg;\n TestableContext context;\n\n std::vector<std::wstring> keysSame;// Unused.\n\n std::vector<std::wstring> keyNames;\n std::vector<std::wstring> keyValues;\n keyNames.push_back(L\"CSCreationClassName\");\n keyValues.push_back(L\"SCX_ComputerSystem\");\n keyNames.push_back(L\"CSName\");\n keyValues.push_back(GetFQHostName(CALL_LOCATION(errMsg)));\n keyNames.push_back(L\"OSCreationClassName\");\n keyValues.push_back(L\"SCX_OperatingSystem\");\n keyNames.push_back(L\"OSName\");\n keyValues.push_back(SCXCore::GetActualDistributionName(CALL_LOCATION(errMsg)));\n keyNames.push_back(L\"CreationClassName\");\n keyValues.push_back(L\"SCX_UnixProcess\");\n StandardTestCheckKeyValues<mi::SCX_UnixProcess_Class_Provider>(\n keyNames, keyValues, keysSame, context, CALL_LOCATION(errMsg));\n }\n\n void TestUnixProcessStatisticalInformationCheckKeyValues()\n {\n std::wstring errMsg;\n TestableContext context;\n\n std::vector<std::wstring> keysSame;// Unused.\n\n std::vector<std::wstring> keyNames;\n std::vector<std::wstring> keyValues;\n keyNames.push_back(L\"CSCreationClassName\");\n keyValues.push_back(L\"SCX_ComputerSystem\");\n keyNames.push_back(L\"CSName\");\n keyValues.push_back(GetFQHostName(CALL_LOCATION(errMsg)));\n keyNames.push_back(L\"OSCreationClassName\");\n keyValues.push_back(L\"SCX_OperatingSystem\");\n keyNames.push_back(L\"OSName\");\n keyValues.push_back(SCXCore::GetActualDistributionName(CALL_LOCATION(errMsg)));\n keyNames.push_back(L\"ProcessCreationClassName\");\n keyValues.push_back(L\"SCX_UnixProcessStatisticalInformation\");\n StandardTestCheckKeyValues<mi::SCX_UnixProcessStatisticalInformation_Class_Provider>(\n keyNames, keyValues, keysSame, context, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartialUnixProcess()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_UnixProcess_Class_Provider,\n mi::SCX_UnixProcess_Class>(m_keyNamesUP, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartialUnixProcessStatisticalInformation()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_UnixProcessStatisticalInformation_Class_Provider,\n mi::SCX_UnixProcessStatisticalInformation_Class>(m_keyNamesUPS, CALL_LOCATION(errMsg));\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXUnixProcessKeyTest );\n" }, { "alpha_fraction": 0.5200361013412476, "alphanum_fraction": 0.5243682265281677, "avg_line_length": 30.477272033691406, "blob_id": "4f26290f3ad18cbbffb85a61104ee239a67abc93", "content_id": "4f1d14945f99ac4ce5b5e71aa6bb8030361f3426", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5540, "license_type": "permissive", "max_line_length": 102, "num_lines": 176, "path": "/source/code/providers/support/scxrunasconfigurator.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file scxrunasconfigurator.h\n\n \\brief Implements a configuration parser for the runas provider.\n\n \\date 2008-08-27 15:51:24\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef SCXRUNASCONFIGURATOR_H\n#define SCXRUNASCONFIGURATOR_H\n\n#include <map>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxhandle.h>\n#include <scxcorelib/scxexception.h>\n\nnamespace SCXCore\n{\n /*----------------------------------------------------------------------------*/\n /**\n Class for parsing generic configuration streams of the form:\n\n # Comment\n key1 = value1\n key2 = value2\n */\n class ConfigurationParser : public std::map<std::wstring, std::wstring>\n {\n public:\n /**\n Parses configuration.\n */\n virtual void Parse() = 0;\n /**\n Virtual destructor.\n */\n virtual ~ConfigurationParser() {};\n protected:\n virtual void ParseStream(std::wistream& configuration);\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Class for parsing files with generic configuration\n\n */\n class ConfigurationFileParser : public ConfigurationParser\n {\n public:\n ConfigurationFileParser(const SCXCoreLib::SCXFilePath& file);\n\n /**\n Parses the configuration file. If the file does not exist this is ignored.\n */\n void Parse();\n private:\n //! Path to file containing configuration.\n SCXCoreLib::SCXFilePath m_file;\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Class for writing generic configuration streams of the form:\n\n # Comment\n key1 = value1\n key2 = value2\n */\n class ConfigurationWriter : public std::map<std::wstring, std::wstring>\n {\n public:\n /**\n Writes configuration.\n */\n virtual void Write() = 0;\n /**\n Virtual destructor.\n */\n virtual ~ConfigurationWriter() {};\n protected:\n virtual void WriteToStream(std::wostream& configuration);\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Class for writing files with generic configuration\n\n */\n class ConfigurationFileWriter : public ConfigurationWriter\n {\n public:\n ConfigurationFileWriter(const SCXCoreLib::SCXFilePath& file);\n\n /**\n Writes the configuration file.\n */\n void Write();\n private:\n //! Path to configuration file.\n SCXCoreLib::SCXFilePath m_file;\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Class for parsing and writing configuration for the RunAs provider.\n */\n class RunAsConfigurator\n {\n public:\n RunAsConfigurator();\n RunAsConfigurator(SCXCoreLib::SCXHandle<ConfigurationParser> parser,\n SCXCoreLib::SCXHandle<ConfigurationWriter> writer);\n const RunAsConfigurator& Parse();\n const RunAsConfigurator& Write();\n void Write(ConfigurationWriter& writer) const;\n\n bool GetAllowRoot() const;\n void SetAllowRoot(bool allowRoot);\n const SCXCoreLib::SCXFilePath& GetChRootPath() const;\n void SetChRootPath(const SCXCoreLib::SCXFilePath& path);\n void ResetChRootPath();\n const SCXCoreLib::SCXFilePath& GetCWD() const;\n void SetCWD(const SCXCoreLib::SCXFilePath& path);\n void ResetCWD();\n\n private:\n static const bool s_AllowRootDefault;\n static const SCXCoreLib::SCXFilePath s_ChRootPathDefault;\n static const SCXCoreLib::SCXFilePath s_CWDDefault;\n\n const std::wstring ResolveEnvVars(const std::wstring& input) const;\n\n //! Handles the actual parsing.\n SCXCoreLib::SCXHandle<ConfigurationParser> m_Parser; \n //! Handles the actual writing of configuration.\n SCXCoreLib::SCXHandle<ConfigurationWriter> m_Writer; \n //! Value of AllowRoot configuration.\n bool m_AllowRoot;\n //! Value of ChRootPath configuration.\n SCXCoreLib::SCXFilePath m_ChRootPath;\n //! Value of CWD configuration.\n SCXCoreLib::SCXFilePath m_CWD;\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Exeception for problems with RunAs configuration.\n */\n class SCXRunAsConfigurationException : public SCXCoreLib::SCXException {\n public: \n /*----------------------------------------------------------------------------*/\n /**\n Ctor\n \\param[in] reason Description of the error\n \\param[in] l Source code location object\n\n */\n SCXRunAsConfigurationException(std::wstring reason, const SCXCoreLib::SCXCodeLocation& l) : \n SCXException(l), m_Reason(reason)\n { };\n\n std::wstring What() const {\n return L\"Error parsing RunAs configuration: \" + m_Reason;\n }\n\n protected:\n //! Description of error\n std::wstring m_Reason;\n }; \n} // SCXCore\n\n#endif /* SCXRUNASCONFIGURATOR_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.754050076007843, "alphanum_fraction": 0.7569955587387085, "avg_line_length": 34.47368240356445, "blob_id": "3acd70538627cedeb6364a78e40680e3c9eba14c", "content_id": "23a15491b0a0aca1685fcfc7b629e27e97cc733b", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 679, "license_type": "permissive", "max_line_length": 84, "num_lines": 19, "path": "/test/code/shared/tools/scx_prune_repository/testrunner.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "import unittest\nimport moffile_test\nimport moffilerepository_test\nimport dependencywalker_test\nimport commandlineparser_test\n\n##\n# Entry point to the test suite.\n#\nif __name__ == '__main__':\n suite = unittest.TestSuite()\n suite.addTest(unittest.TestLoader().loadTestsFromModule(moffile_test))\n suite.addTest(unittest.TestLoader().loadTestsFromModule(moffilerepository_test))\n suite.addTest(unittest.TestLoader().loadTestsFromModule(dependencywalker_test))\n suite.addTest(unittest.TestLoader().loadTestsFromModule(commandlineparser_test))\n \n result = unittest.TextTestRunner(verbosity=2).run(suite)\n if not result.wasSuccessful():\n sys.exit(1)\n \n" }, { "alpha_fraction": 0.6207674741744995, "alphanum_fraction": 0.6238986253738403, "avg_line_length": 31.854066848754883, "blob_id": "fbebeca597f03dfa63e443dbea3cbe929aee7f1e", "content_id": "9542f5d52066c5a2c335d64da0885a40f5e07808", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13733, "license_type": "permissive", "max_line_length": 145, "num_lines": 418, "path": "/source/code/providers/SCX_FileSystem_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_FileSystem_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-14-2013 11:09:45\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_FileSystem_Class_Provider.h\"\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxassert.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxnameresolver.h>\n#include \"support/filesystemprovider.h\"\n#include \"support/scxcimutils.h\"\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/scxpatternfinder.h>\n\n# define QLENGTH 1000\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_FileSystem_Class& inst,\n bool keysOnly,\n SCXHandle<SCXSystemLib::StaticLogicalDiskInstance> diskinst)\n{\n SCXCoreLib::NameResolver nr;\n std::wstring hostname = nr.GetHostDomainname();\n\n diskinst->Update();\n\n std::wstring name;\n if (diskinst->GetDeviceName(name)) \n {\n inst.Name_value(StrToMultibyte(name).c_str());\n }\n\n inst.CreationClassName_value(\"SCX_FileSystem\");\n inst.CSCreationClassName_value(\"SCX_ComputerSystem\");\n inst.CSName_value(StrToMultibyte(hostname).c_str());\n\n if (!keysOnly) \n {\n inst.Caption_value(\"File system information\");\n inst.Description_value(\"Information about a logical unit of secondary storage\");\n\n scxulong data;\n std::wstring sdata;\n bool bdata;\n\n if (diskinst->GetHealthState(bdata)) \n {\n inst.IsOnline_value(bdata);\n }\n\n if (diskinst->GetMountpoint(sdata)) \n {\n inst.Root_value(StrToMultibyte(sdata).c_str());\n }\n\n if (diskinst->GetFileSystemType(sdata)) \n {\n inst.FileSystemType_value(StrToMultibyte(sdata).c_str());\n }\n\n if (diskinst->GetSizeInBytes(data)) \n {\n inst.FileSystemSize_value(data);\n }\n\n if (diskinst->GetCompressionMethod(sdata)) \n {\n inst.CompressionMethod_value(StrToMultibyte(sdata).c_str());\n }\n\n if (diskinst->GetIsReadOnly(bdata)) \n {\n inst.ReadOnly_value(bdata);\n }\n\n if (diskinst->GetEncryptionMethod(sdata)) \n {\n inst.EncryptionMethod_value(StrToMultibyte(sdata).c_str());\n }\n\n int idata;\n if (diskinst->GetPersistenceType(idata)) \n {\n inst.PersistenceType_value(static_cast<unsigned short>(idata));\n }\n\n if (diskinst->GetBlockSize(data)) \n {\n inst.BlockSize_value(data);\n }\n\n if (diskinst->GetAvailableSpaceInBytes(data)) \n {\n inst.AvailableSpace_value(data);\n }\n \n scxulong inodesTotal, inodesFree;\n if (diskinst->GetTotalInodes(inodesTotal) && diskinst->GetAvailableInodes(inodesFree)) \n {\n inst.TotalInodes_value(inodesTotal);\n inst.FreeInodes_value(inodesFree);\n inst.NumberOfFiles_value(inodesTotal - inodesFree);\n }\n\n if (diskinst->GetIsCaseSensitive(bdata)) \n {\n inst.CaseSensitive_value(bdata);\n }\n\n if (diskinst->GetIsCasePreserved(bdata)) \n {\n inst.CasePreserved_value(bdata);\n }\n \n /*\n if (diskinst->GetCodeSet(idata))\n {\n Uint16A tmp;\n tmp[0] = (Uint16)idata;\n inst.CodeSet_value(tmp);\n }\n */\n\n if (diskinst->GetMaxFilenameLen(data)) \n {\n inst.MaxFileNameLength_value(static_cast<unsigned int>(data));\n }\n }\n context.Post(inst);\n}\n\nSCX_FileSystem_Class_Provider::SCX_FileSystem_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_FileSystem_Class_Provider::~SCX_FileSystem_Class_Provider()\n{\n}\n\nvoid SCX_FileSystem_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n SCXCore::g_FileSystemProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_FileSystemProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_FileSystem_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystem_Class_Provider::Load\", SCXCore::g_FileSystemProvider.GetLogHandle() );\n}\n\nvoid SCX_FileSystem_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n SCXCore::g_FileSystemProvider.UnLoad();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystem_Class_Provider::Unload\", SCXCore::g_FileSystemProvider.GetLogHandle() );\n}\n\nvoid SCX_FileSystem_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_FileSystemProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"FileSystem EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n\n wstring mountPoint=L\"\";\n size_t instancePos=(size_t)-1;\n\n if(filter) {\n char* exprStr[QLENGTH]={NULL};\n char* qtypeStr[QLENGTH]={NULL};\n\n const MI_Char** expr=(const MI_Char**)&exprStr;\n const MI_Char** qtype=(const MI_Char**)&qtypeStr;\n\n MI_Filter_GetExpression(filter, qtype, expr);\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"FileSystem Provider Filter Set with Expression: \",*expr));\n\n std::wstring filterQuery(SCXCoreLib::StrFromUTF8(*expr));\n\n SCXCoreLib::SCXPatternFinder::SCXPatternCookie s_patternID = 0, id=0;\n SCXCoreLib::SCXPatternFinder::SCXPatternMatch param;\n std::wstring s_pattern(L\"select * from SCX_FileSystem where Name=%name\");\n\n SCXCoreLib::SCXPatternFinder patterenfinder;\n patterenfinder.RegisterPattern(s_patternID, s_pattern);\n\n bool status=patterenfinder.Match(filterQuery, id, param);\n\n\n if ( status && param.end() != param.find(L\"name\") && id == s_patternID )\n {\n mountPoint=param.find(L\"name\")->second;\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"FileSystem Provider Enum Requested for mount point: \",mountPoint));\n }\n }\n\n // (Note: Only do full update if we're not enumerating keys) \n SCXHandle<SCXSystemLib::StaticLogicalDiskEnumeration> staticLogicalDisksEnum = SCXCore::g_FileSystemProvider.getEnumstaticLogicalDisks();\n mountPoint != L\"\"?staticLogicalDisksEnum->UpdateSpecific(!keysOnly,mountPoint,&instancePos):staticLogicalDisksEnum->Update(!keysOnly);\n\n if (instancePos != (size_t)-1)\n {\n SCX_FileSystem_Class inst;\n SCXHandle<SCXSystemLib::StaticLogicalDiskInstance> diskinst = staticLogicalDisksEnum->GetInstance(instancePos);\n EnumerateOneInstance(context, inst, keysOnly, diskinst);\n }\n else {\n for(size_t i = 0; i < staticLogicalDisksEnum->Size(); i++) \n {\n SCX_FileSystem_Class inst;\n SCXHandle<SCXSystemLib::StaticLogicalDiskInstance> diskinst = staticLogicalDisksEnum->GetInstance(i);\n EnumerateOneInstance(context, inst, keysOnly, diskinst);\n }\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystem_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"FileSystem EnumerateInstances end\");\n}\n\nvoid SCX_FileSystem_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystem_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n\n // We have 4-part key:\n // [Key] Name=/boot\n // [Key] CSCreationClassName=SCX_ComputerSystem\n // [Key] CSName=jeffcof64-rhel6-01.scx.com\n // [Key] CreationClassName=SCX_FileSystem\n\n if (!instanceName.Name_exists() || !instanceName.CSCreationClassName_exists() ||\n !instanceName.CSName_exists() || !instanceName.CreationClassName_exists())\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::string csName;\n try {\n NameResolver mi;\n csName = StrToMultibyte(mi.GetHostDomainname()).c_str();\n } catch (SCXException& e) {\n SCX_LOGWARNING(SCXCore::g_FileSystemProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n // Now compare (case insensitive for the class names, case sensitive for the others)\n if ( 0 != strcasecmp(\"SCX_ComputerSystem\", instanceName.CSCreationClassName_value().Str())\n || 0 != strcasecmp(\"SCX_FileSystem\", instanceName.CreationClassName_value().Str())\n || 0 != strcmp(csName.c_str(), instanceName.CSName_value().Str()))\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCXHandle<SCXSystemLib::StaticLogicalDiskEnumeration> staticLogicalDisksEnum = SCXCore::g_FileSystemProvider.getEnumstaticLogicalDisks();\n staticLogicalDisksEnum->Update(true);\n\n const std::string name = (instanceName.Name_value()).Str();\n if (name.size() == 0)\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n SCXHandle<SCXSystemLib::StaticLogicalDiskInstance> diskinst;\n diskinst = staticLogicalDisksEnum->GetInstance(StrFromUTF8(name));\n\n if (diskinst == NULL)\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCX_FileSystem_Class inst;\n EnumerateOneInstance(context, inst, false, diskinst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystem_Class_Provider::GetInstance\",\n SCXCore::g_FileSystemProvider.GetLogHandle() );\n}\n\nvoid SCX_FileSystem_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystem_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_FileSystem_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystem_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_FileSystem_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystem_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_FileSystem_Class_Provider::Invoke_RequestStateChange(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystem_Class& instanceName,\n const SCX_FileSystem_RequestStateChange_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_FileSystem_Class_Provider::Invoke_RemoveByName(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystem_Class& instanceName,\n const SCX_FileSystem_RemoveByName_Class& in)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n \n SCXHandle<SCXSystemLib::StaticLogicalDiskEnumeration> staticLogicalDisksEnum = SCXCore::g_FileSystemProvider.getEnumstaticLogicalDisks();\n staticLogicalDisksEnum->Update(true);\n\n SCX_FileSystem_RemoveByName_Class inst;\n if (!in.Name_exists() || strlen(in.Name_value().Str()) == 0)\n {\n inst.MIReturn_value(0);\n context.Post(inst);\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n const std::wstring name = StrFromMultibyte(in.Name_value().Str());\n\n SCXHandle<SCXSystemLib::StaticLogicalDiskInstance> diskinst;\n if ( (diskinst = staticLogicalDisksEnum->GetInstance(name)) == NULL)\n {\n inst.MIReturn_value(0);\n context.Post(inst);\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCX_FileSystem_Class fsInst;\n EnumerateOneInstance(context, fsInst, false, diskinst);\n\n bool cmdok = SCXCore::g_FileSystemProvider.getEnumstatisticalLogicalDisks()->RemoveInstanceById(name) && \n SCXCore::g_FileSystemProvider.getEnumstaticLogicalDisks()->RemoveInstanceById(name);\n\n inst.MIReturn_value(cmdok);\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystem_Class_Provider::Invoke_RemoveByName\", SCXCore::g_FileSystemProvider.GetLogHandle() );\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.4011620581150055, "alphanum_fraction": 0.4121510684490204, "avg_line_length": 27.0744686126709, "blob_id": "7044ab3f52fb6a398ffa151e53a4c179766ad468", "content_id": "a4ce457ffed7374874df699d3acc6a5bbe0900c8", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 7917, "license_type": "permissive", "max_line_length": 122, "num_lines": 282, "path": "/installer/conf/uninstall", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nuninstallMode=R\nif [ -n \"$1\" ]; then\n uninstallMode=$1\nfi\n\nif [ \"$2\" = \"force\" ]; then\n dpkgForce=\"--force-all\"\n rpmForce=\"--nodeps\"\nfi\n\nPATH=/usr/bin:/usr/sbin:/bin:/sbin\numask 022\n\nPF_FILE_PATH=/etc/opt/microsoft/scx/pf_file.sh\n\nif [ ! -f $PF_FILE_PATH ]; then\n echo \"Error: package file $PF_FILE_PATH does not exist. Unable to uninstall.\"\n exit 1\nfi\n\n. $PF_FILE_PATH\n\nwhich dpkg 1> /dev/null 2> /dev/null\nDPKG_EXISTS=$?\n\ncleanup_and_exit()\n{\n if [ \"$PLATFORM\" = \"SunOS\" ]; then\n rm -f scx-admin scx-admin-upgrade\n rm -f /tmp/.ai.pkg.zone.lock*\n fi\n if [ -n \"$1\" ]; then\n exit $1\n else\n exit 0\n fi\n}\n\n# $1 - The package name of the package to be uninstalled\n# $2 - Optional parameter. Only used when forcibly removing omi on SunOS\npkg_rm() {\n echo \"----- Removing package: $1 -----\"\n case \"$PF\" in\n Linux)\n case \"$PF_DISTRO\" in\n ULINUX)\n if [ \"$DPKG_EXISTS\" -eq 0 ]; then\n if [ \"$uninstallMode\" = \"P\" ]; then\n dpkg --purge $1 # 1> /dev/null 2> /dev/null\n else\n dpkg --remove $dpkgForce $1 # 1> /dev/null 2> /dev/null\n fi\n else\n rpm --erase $rpmForce $1 # 1> /dev/null 2> /dev/null\n fi\n ;;\n\t\t\n REDHAT|SUSE)\n rpm --erase $rpmForce $1 # 1> /dev/null 2> /dev/null\n ;;\n\n UBUNTU)\n if [ \"$uninstallMode\" = \"P\" ]; then\n dpkg --purge $1 # 1> /dev/null 2> /dev/null\n else\n dpkg --remove $dpkgForce $1 # 1> /dev/null 2> /dev/null\n fi\n ;;\n\n *)\n echo \"Unsupported Linux platform: $PF_DISTRO\"\n ;;\n esac\n ;;\n\n AIX)\n /usr/sbin/installp -u $1.rte # 1> /dev/null 2> /dev/null\n ;;\n \n HPUX)\n /usr/sbin/swremove $1 # 1> /dev/null 2> /dev/null\n ;;\n \n SunOS)\n /usr/sbin/pkgrm -a scx-admin -n MSFT$1 # 1> /dev/null 2> /dev/null\n ;;\n\n *)\n echo \"Unsupported platform: $PF\"\n ;;\n esac\n}\n\nservice_action_delay()\n{\n case \"$PF_MINOR\" in\n 10|11)\n COUNT=0\n while [ $COUNT -lt 15 ]; do\n /usr/bin/svcs -H $1 2> /dev/null | grep -i $2 2> /dev/null 1> /dev/null\n [ $? -eq 0 ] && break\n echo \"Waiting for service: $1 ...\"\n sleep 2\n COUNT=`expr $COUNT + 1`\n done\n ;;\n\n esac\n}\n\n\nstop_omiserver() {\n if [ -f /opt/omi/bin/service_control ]; then\n /opt/omi/bin/service_control stop\n return $?\n fi\n if [ -f /var/opt/omi/run/omiserver.pid ]; then\n case \"$PF\" in\n AIX)\n stopsrc -s omiserverd\n ;;\n \n Linux)\n case \"$PF_DISTRO\" in\n UBUNTU|ULINUX)\n if [ -x /usr/sbin/invoke-rc.d ]; then\n invoke-rc.d omiserverd stop\n elif [ -x /sbin/service ]; then\n service omiserverd stop\n else\n echo \"Unrecognized Service Controller to stop OMI Service.\"\n cleanup_and_exit 1\n fi\n ;;\n SUSE)\n case \"$PF_MAJOR\" in\n 9)\n /etc/init.d/omiserverd stop\n ;;\n *)\n service omiserverd stop\n ;;\n esac\n ;;\n REDHAT)\n service omiserverd stop\n ;;\n esac\n ;;\n \n HPUX)\n $OMI_HOME/bin/omiserver -s\n ;;\n \n SunOS)\n case \"$PF_MINOR\" in\n 9)\n $OMI_HOME/bin/omiserver -s\n ;;\n 10|11)\n svcs -l omiserverd 2> /dev/null 1> /dev/null\n if [ $? -eq 0 ]; then\n svcadm disable -s svc:/application/management/omiserverd\n service_action_delay svc:/application/management/omiserverd disabled\n fi\n ;;\n esac\n ;;\n esac\n fi\n}\n\n\nstart_omiserver() {\n if [ -f /opt/omi/bin/service_control ]; then\n /opt/omi/bin/service_control start\n return $?\n fi\n case \"$PF\" in\n AIX)\n startsrc -s omiserverd -e \"LD_LIBRARY_PATH=$OMI_HOME/lib\"\n ;;\n \n Linux)\n case \"$PF_DISTRO\" in\n UBUNTU|ULINUX)\n if [ -x /usr/sbin/invoke-rc.d ]; then\n invoke-rc.d omiserverd start\n elif [ -x /sbin/service ]; then\n service omiserverd start\n else\n echo \"Unrecognized Service Controller to start SCX Service\"\n cleanup_and_exit 1\n fi\n ;;\n SUSE)\n case \"$PF_MAJOR\" in\n 9)\n /etc/init.d/omiserverd start\n ;;\n *)\n service omiserverd start\n ;;\n esac\n ;;\n REDHAT)\n service omiserverd start\n ;;\n esac\n ;;\n\n HPUX)\n /opt/omi/bin/omiserver -d\n ;;\n \n SunOS)\n case \"$PF_MINOR\" in\n 9)\n /opt/omi/bin/omiserver -d\n ;;\n 10|11)\n svcs -H omiserverd 2> /dev/null | grep -i online 2> /dev/null 1> /dev/null\n if [ $? -eq 0 ]; then\n return\n fi\n \n service_action_delay svc:/application/management/omiserverd disabled\n svcadm enable -s svc:/application/management/omiserverd\n ;;\n esac\n ;;\n esac\n}\n\n# Create installation administrative file for Solaris platform if needed\nif [ \"$PF\" = \"SunOS\" ]; then\n echo \"mail=\" > scx-admin\n echo \"instance=overwrite\" >> scx-admin\n echo \"partial=nocheck\" >> scx-admin\n echo \"idepend=quit\" >> scx-admin\n echo \"rdepend=quit\" >> scx-admin\n echo \"conflict=nocheck\" >> scx-admin\n echo \"action=nocheck\" >> scx-admin\n echo \"basedir=default\" >> scx-admin\nfi\n\necho \"Removing cross-platform agent(s) ...\"\n\n# First remove any bundled agents\n\nBUNDLE_EXIT_STATUS=\"0\"\n\nfor i in /opt/microsoft/*-cimprov; do\n PKG_NAME=`basename $i`\n if [ \"$PKG_NAME\" != \"*-cimprov\" ]; then\n pkg_rm ${PKG_NAME}\n TEMP_STATUS=$?\n [ $TEMP_STATUS -ne 0 ] && BUNDLE_EXIT_STATUS=\"$TEMP_STATUS\"\n fi\ndone\n\n# Now remove actual SCX/OMI agents\n\npkg_rm scx\nSCX_EXIT_STATUS=$?\n\npkg_rm omi\nOMI_EXIT_STATUS=$?\n\nif [ $OMI_EXIT_STATUS -ne 0 ]; then\n # Unable to uninstall omi. This is most likely due to another dependency on omi. In this case, we should restart omi\n stop_omiserver\n start_omiserver\nfi\n\nif [ \"$SCX_EXIT_STATUS\" -ne \"0\" -o \"$BUNDLE_EXIT_STATUS\" -ne \"0\" ]; then\n cleanup_and_exit 1\nelse\n cleanup_and_exit 0\nfi\n" }, { "alpha_fraction": 0.7463557124137878, "alphanum_fraction": 0.7478134036064148, "avg_line_length": 33.29999923706055, "blob_id": "efb8e2983692ae38fc83b39a0f9ab1c4af6ce630", "content_id": "dd7fcf1501e7ab67bda3f59038f48253172bb8fe", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 686, "license_type": "permissive", "max_line_length": 77, "num_lines": 20, "path": "/test/code/providers/logfile_provider/scxlogfilereader-test", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#\n# Test hook for scxlogfilereader program. The purpose of this script is to\n# set the locale (controllable on a per-test basis) for scxlogfilereader\n# prior to running scxlogfilereader.\n#\n# This is done by creating file testfiles/scxlogfilereader-locale. If this\n# file exists, it should contain the locale that is desired to be used.\n#\n# Sparc9 seems to require LC_ALL to be set rather than LANG; just do that for\n# all platforms (harmless elsewhere).\n\nLOCALE_FILE=\"testfiles/scxlogfilereader-locale\"\nif [ -f $LOCALE_FILE ]; then\n LC_ALL=\"`cat $LOCALE_FILE`\"\n export LC_ALL\nfi\nexec scxlogfilereader \"$@\"\n" }, { "alpha_fraction": 0.5437648892402649, "alphanum_fraction": 0.5533090829849243, "avg_line_length": 32.0414924621582, "blob_id": "9196790431a478e0e294a3e47346ad566d36d278", "content_id": "33a8fe02648e4cecc62c0118201cbe614c2500f7", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7963, "license_type": "permissive", "max_line_length": 92, "num_lines": 241, "path": "/docs/int/doxygen/example.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. \n \n*/\n/**\n \\file \n\n \\brief Public interface of blah blah functionality\n \n \\date 07-07-13 11:23:02\n\n Contains blah blah detailed description. [OPTIONAL]\n \n*/\n/*----------------------------------------------------------------------------*/\n#ifndef EXAMPLE_H\n#define EXAMPLE_H\n\n\n/** \n The demo namespace used in the Doxygen example.\n\n This is the full description of the namespace. It need to be defined in one \n single location only. \n */\nnamespace DoxyDemo {\n\n\n //! This is the description of the enumeration, using C++ syntax. The text \n //! can obviously span several lines. In that case the first sentence \n //! used as brief description, and the rest goes to detailed description.\n enum DoxyDemoEnumeration {\n eFirstValue1, //!< Value is first\n eSecondValue1, //!< Value is second\n eDoxyDemoEnumerationEndmark1 //!< Endmark \n }; \n\n /** This is the description of the enumeration, using block comment syntax. */\n enum DoxyDemoEnumerationBlock {\n eFirstValue2, /**< Value is first */\n eSecondValue2, /**< Value is second */\n eDoxyDemoEnumerationEndmark2 /**< Endmark */\n }; \n\n //! This is the description of the enumeration, with documentation before each item. \n enum DoxyDemoEnumerationBefore {\n //! Value is first - could have used block comments as well\n eFirstValue3,\n //! Value is second\n eSecondValue3, \n //! Endmark \n eDoxyDemoEnumerationEndmark3 \n }; \n\n /*----------------------------------------------------------------------------*/\n /**\n This is the brief description of a function.\n \n \\param x Control which X to use \n \\param[in] y The name of the X\n \\returns The calculated xy value\n \n \\date 07-07-13 11:22:22\n \n This function usk dui a hams suttle, unproportionable, ax monogynist, dye \n meloe, idyll mainsail wag lye, gauming, be. Drawl, fanes, arless in \n screeman boy fred, pons, junkmen <em>really</em> asweve agoranome, wise \n spew, med. This is controlled by \\a and \\a y.\n\n Dippy, nock, jimpy anisoin wry cyclized, loll so shunted, sides, cesta, \n a ladyfishes. Haversine gulose misdiet, specific bye, cyst galvanizers\n extravasate, restab, unharmoniousness apse, ganglionless a chuckholes, \n unwit. A headstall hi nonconvergently tie, uh, ropand, euphrasies, \n he, immarginate. Ark portaging, cure tax, myrtol. \n \n \\li Rerises a dud, in textarian.\n \\li Slow um ptyalocele blushes, cub.\n \\li Voguey, ungainness, do. \n \n Mob windjam, shed, sold aril, coy, par, me. Dept, manors stagedom \n sped coyotillos ha bebed, sativae. This function is blah blurgh bliff. \n \n */\n int MyDemoFunction(int x, std::string y) \n {\n return 2;\n };\n \n\n /*----------------------------------------------------------------------------*/\n /**\n Inefficient algorithm\n \n \\param[in] zooBaff Specifies which baff to use\n \\returns The calculated \\a zoo value\n \n \\date 07-07-13 11:22:22\n \n This function usk dui a hams suttle, unproportionable, ax monogynist, dye \n meloe. Dippy, nock, jimpy anisoin wry cyclized.\n\n \\deprecated Use the more efficient MyDemoFunction instead.\n\n \\note This function is very expensive to call.\n\n \\warning This is what a warning looks like.\n\n More text\n\n \\remarks This is a remark paragraph. \n \n \n */\n int SomeOldFunctionDoxygenDemo(int zooBaff) \n {\n return 9;\n };\n \n /*----------------------------------------------------------------------------*/\n /**\n Brief explanation here, appearing in lists etc.\n \n \\date 07-07-13 11:22:54\n\n Taily hoiden ya folk unvivacious bug, ha naveled slog, a dispensable, bar,\n fruitier, hideous dublin, size sue soft. Nab on stereotypography sit,\n chazzanut ok, nowch pant, a a averts it joypopping a nightless. Oh lug\n oleary, dank, hurt. Cafe, tubular, preform sovkhozes, git hared, \n nondoctrinal, byland. Decontamination, overannotate. Reconsigns, if, \n chicanes, other.\n\n \\ex\n \\code\n for (DoxyDemoClass.xyz();;)\n {\n enter verbatim code examples here\n }\n \\endcode\n \n \\internal \n This text will be rendered only for internal documentation, until the \n end of the comment is encountered.\n \n \\li This bullet will only be visible in internal documentation\n \\li This bullet too\n \n And this text as well. \n \n */\n class DoxyDemoClass \n {\n public:\n /*----------------------------------------------------------------------------*/\n /**\n This is the brief description of a function.\n \n \\param theParameter Controls something\n \\returns The calculated xy value\n \n \\date 07-07-13 11:22:22\n\n \\throws SCXInvalidArgument for incorrect input\n \\throws SCXInternalError for incorrect input\n\n \\pre The scrop must be initiated\n \\post Boofle will be restored\n \\invariant Sprof is always positive\n\n This member function usk dui a hams suttle, unproportionable, ax monogynist, dye \n meloe, idyll mainsail wag lye, gauming, be. Drawl, fanes, arless in \n screeman boy fred, pons, junkmen <em>really</em> asweve agoranome, wise \n spew, med. This is controlled by \\a x.\n \n Dippy, nock, jimpy anisoin wry cyclized, loll so shunted, sides, cesta, \n a ladyfishes. Haversine gulose misdiet, specific bye, cyst galvanizers\n extravasate, restab, unharmoniousness apse, ganglionless a chuckholes, \n unwit. A headstall hi nonconvergently tie, uh, ropand, euphrasies, \n he, immarginate. Ark portaging, cure tax, myrtol. \n \n \\li Rerises a dud, in textarian.\n \\li Slow um ptyalocele blushes, cub.\n \\li Voguey, ungainness, do. \n \n Mob windjam, shed, sold aril, coy, par, me. Dept, manors stagedom \n sped coyotillos ha bebed, sativae. This function is blah blurgh bliff. \n\n \\ex\n \\verbatim\n $> drook -baff=49\n \\endverbatim\n \n */\n int AMemberFunction(int theParameter = 3) const\n {\n return 5;\n }\n\n /**\n \\overload\n */\n // NOTE that the overload directive must be in a block comment, for some reason\n // (according to documentation and tests)\n int AMemberFunction(string theParameter) const\n {\n return 6;\n }\n \n private:\n /** One syntax of commenting the variable */\n int m_Something; \n \n int m_Different; //!< If you prefer to have documentation afterwards\n };\n \n}\n\n/**\n \\page ExamplePAL Overview of the Example PAL implementation\n\n The PAL funcitonality is designed to proivide the same information output \n although the data collection is very different. \n\n \\section Solaris\n On Solaris, blah blah\n \\li Swap - read via API\n \\li Page - the same thing, right?\n\n \\section Linux\n\n Linux values are read from /proc/blahblah\n \\li Swap - read from file\n \\li Page - the same thing, right?\n \n This is implemented using MyDemoFunction(), basta.\n\n*/\n\n\n\n#endif /* EXAMPLE_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.48878923058509827, "alphanum_fraction": 0.4927040934562683, "avg_line_length": 32.85301208496094, "blob_id": "d9c1a1a020ece1f467bf842b6742b3ade6f7d2ab", "content_id": "73206268f03c273c7fa06031a9f79d10b05377b2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14049, "license_type": "permissive", "max_line_length": 127, "num_lines": 415, "path": "/source/code/providers/support/scxrunasconfigurator.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file scxrunasconfigurator.cpp\n\n \\brief Implementation of the runas configurator.\n\n \\date 2008-08-27 15:57:34\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/scxstream.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfile.h>\n#include <vector>\n\n#include \"scxrunasconfigurator.h\"\n\nusing namespace SCXCoreLib;\n\nnamespace SCXCore\n{\n /*----------------------------------------------------------------------------*/\n /**\n Parses a stream of the form \n\n # Comment\n key1 = value1\n key2 = value2\n\n \\param[in] configuration Stream with configuration data. Typically as\n read from a configuration file.\n */\n void ConfigurationParser::ParseStream(std::wistream& configuration)\n {\n SCXCoreLib::SCXLogHandle log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.runasprovider.configparser\");\n\n std::vector<std::wstring> lines;\n SCXStream::NLFs nlfs;\n SCXStream::ReadAllLines(configuration, lines, nlfs);\n SCX_LOGTRACE(log, StrAppend(L\"Number of lines in configuration: \", lines.size()));\n\n for (std::vector<std::wstring>::const_iterator it = lines.begin();\n it != lines.end(); it++)\n {\n std::wstring line = StrTrim(*it);\n SCX_LOGTRACE(log, StrAppend(L\"Parsing line: \", line));\n if (line.length() == 0 ||\n line.substr(0,1) == L\"#\") //comment\n {\n continue;\n }\n std::vector<std::wstring> parts;\n StrTokenize(line, parts, L\"=\");\n if (parts.size() == 2)\n {\n iterator iter = lower_bound(parts[0]);\n if ((end() != iter) && !(key_comp()(parts[0], iter->first)))\n {\n iter->second = parts[1];\n }\n else\n {\n insert(iter, std::pair<const std::wstring, std::wstring>(parts[0], parts[1]));\n }\n }\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor for the configuration file parser.\n */\n ConfigurationFileParser::ConfigurationFileParser(const SCXCoreLib::SCXFilePath& file) :\n m_file(file)\n {\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Parses the configuration file. If the file does not exist this is ignored.\n */\n void ConfigurationFileParser::Parse()\n {\n SCXCoreLib::SCXLogHandle log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.runasprovider.configparser\");\n\n try\n {\n ParseStream(*SCXFile::OpenWFstream(m_file, std::ios_base::in));\n }\n catch (SCXException& e)\n {\n SCX_LOGWARNING(log, StrAppend(L\"Failed to read file: \", m_file.Get()));\n SCX_LOGWARNING(log, StrAppend(L\"Reason for failure: \", e.What()));\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Writes configuration of the form \n\n # Comment\n key1 = value1\n key2 = value2\n\n to a stream.\n\n \\param[out] configuration Stream to write configuration data to.\n */\n void ConfigurationWriter::WriteToStream(std::wostream& configuration)\n {\n SCXCoreLib::SCXLogHandle log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.runasprovider.configwriter\");\n\n for (const_iterator iter = begin(); iter != end(); ++iter)\n {\n SCX_LOGTRACE(log, StrAppend(L\"Writing line: \", iter->first + L\" = \" + iter->second));\n configuration << iter->first << L\" = \" << iter->second << std::endl;\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor for the configuration file writer.\n */\n ConfigurationFileWriter::ConfigurationFileWriter(const SCXCoreLib::SCXFilePath& file) :\n m_file(file)\n {\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Writes the configuration file.\n */\n void ConfigurationFileWriter::Write()\n {\n SCXCoreLib::SCXLogHandle log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.runasprovider.configparser\");\n\n WriteToStream(*SCXFile::OpenWFstream(m_file, std::ios_base::out));\n }\n\n /** Default value for allow root. */\n const bool RunAsConfigurator::s_AllowRootDefault(true);\n /** Default value for chrootpath. */\n const SCXCoreLib::SCXFilePath RunAsConfigurator::s_ChRootPathDefault(L\"\");\n /** Default value for CWD. */\n const SCXCoreLib::SCXFilePath RunAsConfigurator::s_CWDDefault(L\"/var/opt/microsoft/scx/tmp/\");\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor for the run as configurator.\n */\n RunAsConfigurator::RunAsConfigurator() :\n m_Parser(new ConfigurationFileParser(L\"/etc/opt/microsoft/scx/conf/scxrunas.conf\")),\n m_Writer(new ConfigurationFileWriter(L\"/etc/opt/microsoft/scx/conf/scxrunas.conf\")),\n m_AllowRoot(s_AllowRootDefault),\n m_ChRootPath(s_ChRootPathDefault),\n m_CWD(s_CWDDefault)\n {\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor for the run as configurator.\n */\n RunAsConfigurator::RunAsConfigurator(SCXCoreLib::SCXHandle<ConfigurationParser> parser,\n SCXCoreLib::SCXHandle<ConfigurationWriter> writer) :\n m_Parser(parser),\n m_Writer(writer),\n m_AllowRoot(s_AllowRootDefault),\n m_ChRootPath(s_ChRootPathDefault),\n m_CWD(s_CWDDefault)\n {\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Parse configuration stream.\n\n \\returns this\n */\n const RunAsConfigurator& RunAsConfigurator::Parse()\n {\n m_Parser->Parse();\n\n SCXCoreLib::SCXLogHandle log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.runasprovider.configurator\");\n\n ConfigurationParser::const_iterator allowRoot = m_Parser->find(L\"AllowRoot\");\n if (allowRoot != m_Parser->end() && (\n allowRoot->second == L\"false\" ||\n allowRoot->second == L\"no\" ||\n allowRoot->second == L\"0\"))\n {\n m_AllowRoot = false;\n }\n\n ConfigurationParser::const_iterator chRootPath = m_Parser->find(L\"ChRootPath\");\n if (chRootPath != m_Parser->end())\n {\n m_ChRootPath = ResolveEnvVars(chRootPath->second);\n if (L\"\" == m_ChRootPath)\n {\n SCX_LOGINFO(log, L\"ChRootPath has been resolved to empty string\");\n }\n }\n\n ConfigurationParser::const_iterator cwd = m_Parser->find(L\"CWD\");\n if (cwd != m_Parser->end())\n {\n m_CWD = ResolveEnvVars(cwd->second);\n if (L\"\" == m_CWD)\n {\n SCX_LOGINFO(log, L\"CWD has been resolved to empty string\");\n }\n }\n\n return *this;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Write configuration stream.\n\n \\returns this\n */\n const RunAsConfigurator& RunAsConfigurator::Write()\n {\n Write(*m_Writer);\n return *this;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Write configuration stream using supplied writer.\n\n \\param writer ConfigurationWriter to use for writing.\n */\n void RunAsConfigurator::Write(ConfigurationWriter& writer) const\n {\n writer.clear();\n \n if (m_AllowRoot != s_AllowRootDefault)\n {\n writer.insert(std::pair<const std::wstring, std::wstring>(L\"AllowRoot\",\n m_AllowRoot ? L\"true\" : L\"false\"));\n }\n if (m_ChRootPath != s_ChRootPathDefault)\n {\n writer.insert(std::pair<const std::wstring, std::wstring>(L\"ChRootPath\", m_ChRootPath.Get()));\n }\n if (m_CWD != s_CWDDefault)\n {\n writer.insert(std::pair<const std::wstring, std::wstring>(L\"CWD\", m_CWD.Get()));\n }\n\n writer.Write();\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Return if configuration says that root access is allowed.\n\n \\returns Value of AllowRoot.\n */\n bool RunAsConfigurator::GetAllowRoot() const\n {\n return m_AllowRoot;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set configuration if root access is allowed.\n\n \\param[in] allowRoot Value of AllowRoot.\n */\n void RunAsConfigurator::SetAllowRoot(bool allowRoot)\n {\n m_AllowRoot = allowRoot;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get the path configured as chroot path. Empty string means no chroot.\n\n \\returns Value of ChRootPath.\n */\n const SCXCoreLib::SCXFilePath& RunAsConfigurator::GetChRootPath() const\n {\n return m_ChRootPath;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set the path configured as chroot path. Empty string means no chroot.\n\n \\param[in] path Value of ChRootPath.\n */\n void RunAsConfigurator::SetChRootPath(const SCXCoreLib::SCXFilePath& path)\n {\n m_ChRootPath = path;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Reset the path configured as chroot path to default.\n\n */\n void RunAsConfigurator::ResetChRootPath()\n {\n m_ChRootPath = s_ChRootPathDefault;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get the path configured as CWD.\n\n \\returns Value of CWD.\n */\n const SCXCoreLib::SCXFilePath& RunAsConfigurator::GetCWD() const\n {\n return m_CWD;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set the path configured as CWD.\n\n \\param[in] path Value of CWD.\n */\n void RunAsConfigurator::SetCWD(const SCXCoreLib::SCXFilePath& path)\n {\n m_CWD = path;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Reset the path configured as CWD to default.\n\n */\n void RunAsConfigurator::ResetCWD()\n {\n m_CWD = s_CWDDefault;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Recursively translate all environment variables with their actual values.\n\n \\param[in] input String to remove environment variables from.\n \\returns String where all environment variables have been translated.\n \\throws SCXRunAsConfigurationException if a loop in environmen variables is suspected.\n */\n const std::wstring RunAsConfigurator::ResolveEnvVars(const std::wstring& input) const\n {\n static const std::wstring allowedVarNameChars(L\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_\");\n \n // We need to know when we run into an infinite loop.\n int numberOfVariableSubstitutionsAllowed = 100;\n std::wstring output(input);\n for (std::wstring::size_type varstart = output.find(L'$');\n varstart != std::wstring::npos;\n varstart = output.find(L'$', varstart))\n {\n std::wstring variableName;\n std::wstring::size_type varend;\n if (L'{' == output[varstart + 1])\n {\n varend = output.find(L'}', varstart + 2);\n if (varend == std::wstring::npos)\n {\n throw SCXRunAsConfigurationException(\n std::wstring(L\"Configuration value \")\n .append(input)\n .append(L\" seems to be malformed. '{' and '}' are not matching.\"), SCXSRCLOCATION);\n }\n variableName = output.substr(varstart + 2, varend - 2 - varstart);\n }\n else\n {\n varend = output.find_first_not_of(allowedVarNameChars, varstart + 1);\n if (varend == std::wstring::npos)\n {\n varend = output.size();\n }\n --varend; // Index of the last character in the variable name.\n\n variableName = output.substr(varstart + 1, varend - varstart);\n }\n\n const char *variableValuePtr = ::getenv(StrToMultibyte(variableName).c_str());\n if (0 == variableValuePtr)\n {\n output.erase(varstart, varend - varstart + 1);\n }\n else\n {\n output.replace(varstart, varend - varstart + 1, StrFromMultibyte(variableValuePtr));\n }\n\n --numberOfVariableSubstitutionsAllowed;\n if (0 == numberOfVariableSubstitutionsAllowed)\n {\n throw SCXRunAsConfigurationException(\n std::wstring(L\"Configuration value \")\n .append(input)\n .append(L\" seems to contain environment variables that form an infinite recursion loop.\"), SCXSRCLOCATION);\n }\n }\n return output;\n }\n\n} // SCXCoreLib\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.29418885707855225, "alphanum_fraction": 0.32324454188346863, "avg_line_length": 21.600000381469727, "blob_id": "3ff04eb1e1bc6992821061cc6a87a1995efaa130", "content_id": "cdd3d513dbd3534e52396183bb009d1971cb456a", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 826, "license_type": "permissive", "max_line_length": 82, "num_lines": 35, "path": "/docs/int/template_files/template_header_file.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\r\n Copyright (c) Microsoft Corporation. All rights reserved. \r\n \r\n*/\r\n/**\r\n \\file \r\n\r\n \\brief < Brief description of purpose of the file > \r\n \r\n \\date 07-07-13 11:23:02\r\n\r\n < Optional detailed description of file purpose >\r\n \r\n*/\r\n/*----------------------------------------------------------------------------*/\r\n#ifndef FILENAME_H\r\n#define FILENAME_H\r\n\r\n\r\n\r\n\r\n/*----------------------------------------------------------------------------*/\r\n/**\r\n < Brief description of CLASS >\r\n \r\n \\date 07-05-06 23:43:30\r\n \r\n < Detailed description of the class > \r\n \r\n*/\r\n\r\n\r\n\r\n#endif /* FILENAME_H */\r\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\r\n" }, { "alpha_fraction": 0.64870285987854, "alphanum_fraction": 0.654363214969635, "avg_line_length": 38.44186019897461, "blob_id": "20b31b14af4d00dbf04dbe9984cc3ad5840b3218", "content_id": "930ae539ede032c4c1e44c71659667b41bae82b7", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8480, "license_type": "permissive", "max_line_length": 124, "num_lines": 215, "path": "/test/code/providers/meta_provider/metaprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the meta provider\n\n \\date 2008-03-18 09:20:15\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n\n#include \"metaprovider.h\"\n#include \"SCX_Agent.h\"\n#include \"SCX_Agent_Class_Provider.h\"\n\nusing namespace SCXCore;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nclass SCXMetaProviderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXMetaProviderTest );\n\n CPPUNIT_TEST( callDumpStringForCoverage );\n CPPUNIT_TEST( VerifyMultipleLoadUnloadMethods );\n CPPUNIT_TEST( VerifyBasicFunctions );\n CPPUNIT_TEST( TestEnumerateKeysOnly );\n CPPUNIT_TEST( VerifyKeyCompletePartial );\n CPPUNIT_TEST( TestLowestLogLevel );\n// CPPUNIT_TEST( PrintAsEnumeration ); /* For debug printouts */\n\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_Agent_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_Agent_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void callDumpStringForCoverage()\n {\n CPPUNIT_ASSERT(g_MetaProvider.DumpString().find(L\"MetaProvider\") != std::wstring::npos);\n }\n\n // Since setUp() / tearDown() already load/unload, this tests that a second call to Load() works\n void VerifyMultipleLoadUnloadMethods()\n {\n mi::Module Module;\n mi::SCX_Agent_Class_Provider agent(&Module);\n TestableContext context;\n\n // Call load, verify result is okay, and verify RefuseUnload() was called\n agent.Load(context);\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, context.GetResult() );\n CPPUNIT_ASSERT_EQUAL( true, context.WasRefuseUnloadCalled() );\n\n agent.Unload(context);\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, context.GetResult() );\n }\n\n void VerifyBasicFunctions()\n {\n mi::Module Module;\n mi::SCX_Agent_Class_Provider agent(&Module);\n TestableContext context;\n\n agent.EnumerateInstances(context, NULL, context.GetPropertySet(), false, NULL);\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, context.GetResult() );\n\n const std::vector<TestableInstance>& instances = context.GetInstances();\n CPPUNIT_ASSERT_EQUAL(static_cast<size_t> (1), instances.size());\n\n TestableInstance inst(instances[0]);\n struct TestableInstance::PropertyInfo info;\n\n // Verify that the key is correct\n CPPUNIT_ASSERT_EQUAL( static_cast<MI_Uint32>(1), inst.GetNumberOfKeys() );\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, inst.FindProperty(\"Name\", info) );\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Field 'Name' is not a key\", true, info.isKey);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Field 'Name' is not of type string\", MI_STRING, info.type);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Field 'Name' has wrong value\", std::string(\"scx\"), info.value.string);\n\n // Test for presence of a few non-null string properties\n const char *stringprops[] = {\n#if !defined(PF_DISTRO_ULINUX)\n \"Description\", \"VersionString\", \"Architecture\", \"OSName\", \"OSType\", \n \"OSVersion\", \"Hostname\", \"OSAlias\", \"UnameArchitecture\", 0\n#else // !defined(PF_DISTRO_LINUX)\n // ULINUX: Not \"OSVersion\" since we may run on an uninstalled machine\n \"Description\", \"VersionString\", \"Architecture\", \"OSName\", \"OSType\", \n \"Hostname\", \"OSAlias\", \"UnameArchitecture\", 0\n#endif // !defined(PF_DISTRO_LINUX)\n }; // NB: Not \"KitVersionString\" since we may run on an uninstalled machine.\n\n for (int i = 0; stringprops[i]; i++) \n {\n std::string msgFragment = std::string(\"Property \") + stringprops[i];\n CPPUNIT_ASSERT_EQUAL_MESSAGE(msgFragment + \" not found\", MI_RESULT_OK, inst.FindProperty(stringprops[i], info));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(msgFragment + \" not of type string\", MI_STRING, info.type);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(msgFragment + \" was not enumerated\", true, info.exists);\n CPPUNIT_ASSERT_MESSAGE(msgFragment + \" is zero in length\", strlen(info.value.string) > 0);\n }\n\n // Test that major version is 1 or above.\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, inst.FindProperty(\"MajorVersion\", info) );\n CPPUNIT_ASSERT_EQUAL(MI_UINT16, info.type);\n CPPUNIT_ASSERT(info.value.uint16 >= 1);\n }\n\n void TestEnumerateKeysOnly()\n {\n mi::Module Module;\n mi::SCX_Agent_Class_Provider agent(&Module);\n TestableContext context;\n\n agent.EnumerateInstances(context, NULL, context.GetPropertySet(), true, NULL);\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, context.GetResult() );\n\n const std::vector<TestableInstance>& instances = context.GetInstances();\n CPPUNIT_ASSERT_EQUAL(static_cast<size_t> (1), instances.size());\n\n TestableInstance inst(instances[0]);\n\n // We know the key is correct from VerifyBasicFunctions()\n // Just validate that we didn't enumerate properties we didn't need\n CPPUNIT_ASSERT_EQUAL( static_cast<MI_Uint32>(1), inst.GetNumberOfKeys() );\n CPPUNIT_ASSERT_EQUAL( static_cast<MI_Uint32>(1), inst.GetNumberOfProperties() );\n }\n\n void VerifyKeyCompletePartial()\n {\n std::wstring errMsg;\n std::vector<std::wstring> keyNames;\n keyNames.push_back(L\"Name\");\n StandardTestVerifyGetInstanceKeys<mi::SCX_Agent_Class_Provider,\n mi::SCX_Agent_Class>(keyNames, CALL_LOCATION(errMsg));\n }\n\n void TestLowestLogLevel()\n {\n mi::Module Module;\n mi::SCX_Agent_Class_Provider agent(&Module);\n TestableContext context;\n\n agent.EnumerateInstances(context, NULL, context.GetPropertySet(), false, NULL);\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, context.GetResult() );\n\n const std::vector<TestableInstance>& instances = context.GetInstances();\n CPPUNIT_ASSERT_EQUAL(static_cast<size_t> (1), instances.size());\n\n TestableInstance inst(instances[0]);\n struct TestableInstance::PropertyInfo info;\n\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, inst.FindProperty(\"MinActiveLogSeverityThreshold\", info));\n\n std::string lowestLogThreshold = info.value.string;\n CPPUNIT_ASSERT_EQUAL(std::string(\"INFO\"), lowestLogThreshold); // Since this is the default.\n\n // Set a lower logging threshold, then fetch again and verify we pick it up\n SCXCoreLib::SCXLogHandle logH = SCXLogHandleFactory::GetLogHandle(L\"scx.test\");\n logH.SetSeverityThreshold(SCXCoreLib::eTrace);\n\n context.Reset();\n agent.EnumerateInstances(context, NULL, context.GetPropertySet(), false, NULL);\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, context.GetResult() );\n const std::vector<TestableInstance>& instances2 = context.GetInstances();\n CPPUNIT_ASSERT_EQUAL(static_cast<size_t> (1), instances2.size());\n\n TestableInstance inst2(instances2[0]);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, inst2.FindProperty(\"MinActiveLogSeverityThreshold\", info));\n\n lowestLogThreshold = info.value.string;\n CPPUNIT_ASSERT_EQUAL(std::string(\"TRACE\"), lowestLogThreshold);\n }\n\n /** Print the same output that an enumeration would. */\n void PrintAsEnumeration()\n {\n mi::Module Module;\n mi::SCX_Agent_Class_Provider agent(&Module);\n TestableContext context;\n\n agent.EnumerateInstances(context, NULL, context.GetPropertySet(), false, NULL);\n CPPUNIT_ASSERT_EQUAL( MI_RESULT_OK, context.GetResult() );\n\n const std::vector<TestableInstance>& instances = context.GetInstances();\n CPPUNIT_ASSERT_EQUAL(static_cast<size_t> (1), instances.size());\n\n TestableInstance inst(instances[0]);\n inst.Print();\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXMetaProviderTest );\n" }, { "alpha_fraction": 0.5613126158714294, "alphanum_fraction": 0.5654577016830444, "avg_line_length": 33.46428680419922, "blob_id": "6c03820cbcd7ebb28895ba2a189eb5e2c7736f53", "content_id": "3835e9a56155797ea5c079e25aee5ea5c6b047c8", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2895, "license_type": "permissive", "max_line_length": 142, "num_lines": 84, "path": "/source/code/providers/support/networkprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file networkprovider.cpp\n\n \\brief Implementation of the Network Provider Dependencies class.\n\n \\date 12-03-21 11:21\n*/\n/*----------------------------------------------------------------------------*/\n#include \"networkprovider.h\"\n\nnamespace SCXCore\n{\n NetworkProvider g_NetworkProvider;\n}\nint SCXCore::NetworkProvider::ms_loadCount = 0;\n\n/*----------------------------------------------------------------------------*/\n/**\n * Initialize the interfaces\n */\nvoid SCXCore::NetworkProviderDependencies::InitIntf() \n{\n SCX_LOGTRACE(SCXCore::g_NetworkProvider.GetLogHandle(), L\"SCXCore::NetworkProviderDeps::InitIntf entry\");\n\n SCX_LOGTRACE(SCXCore::g_NetworkProvider.GetLogHandle(), L\"SCXCore::NetworkProviderDeps::InitIntf Creating class\");\n m_interfaces = new NetworkInterfaceEnumeration();\n SCX_LOGTRACE(SCXCore::g_NetworkProvider.GetLogHandle(), L\"SCXCore::NetworkProviderDeps::InitIntf Initializing class\");\n m_interfaces->Init();\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n * Clean up and release resources\n */\nvoid SCXCore::NetworkProviderDependencies::CleanUpIntf() \n{\n m_interfaces->CleanUp();\n m_interfaces = 0;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n * Update interfaces`\n * \\param[in] updateInstances Update existing instances only\n */\nvoid SCXCore::NetworkProviderDependencies::UpdateIntf(bool updateInstances, wstring interface, size_t *pos)\n{\n if(interface != L\"\")\n\tm_interfaces->UpdateSpecific(interface, pos);\n else\n m_interfaces->Update(updateInstances);\n}\n\n/*----------------------------------------------------b------------------------*/\n/** Retrive the number of interfaces\n * \\returns Number of interfaces\n */\nsize_t SCXCore::NetworkProviderDependencies::IntfCount() const \n{\n return m_interfaces->Size();\n}\n\n/*----------------------------------------------------------------------------*/\n/** Retrieve interface at index\n * \\param[in] pos Index to retrieve interface at\n * \\returns Interface at the index\n */\nSCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> SCXCore::NetworkProviderDependencies::GetIntf(size_t pos) const \n{\n return m_interfaces->GetInstance(pos);\n}\n\n/*----------------------------------------------------------------------------*/\n/** Retrieve interface by name. \n * \\param[in] intfId the interface name to retrieve interface at\n * \\returns Interface at the name \n */\nSCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> SCXCore::NetworkProviderDependencies::GetIntf(const std::wstring& intfId) const \n{\n return m_interfaces->GetInstance(intfId);\n}\n" }, { "alpha_fraction": 0.6899441480636597, "alphanum_fraction": 0.6899441480636597, "avg_line_length": 16.850000381469727, "blob_id": "f252748f7d4549e22ae92cdb781f2962f53aa84c", "content_id": "b35e0b02e3db966003773ff1b8fd208a18f7bf66", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 358, "license_type": "permissive", "max_line_length": 78, "num_lines": 20, "path": "/source/code/providers/module.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#ifndef _Module_t_h\n#define _Module_t_h\n\n#include <MI.h>\n#include <micxx/micxx.h>\n\nMI_BEGIN_NAMESPACE\n\n/* instance of this class is automatically created when library is loaded;\n it's a convenient place to store global data associated with the module */\nclass Module\n{\npublic:\n Module();\n ~Module();\n\n};\n\nMI_END_NAMESPACE\n#endif /* _Module_t_h */\n\n" }, { "alpha_fraction": 0.6444210410118103, "alphanum_fraction": 0.6526315808296204, "avg_line_length": 30.865772247314453, "blob_id": "feb5164303091cc7ea2feedc6b830ddd82aa32f1", "content_id": "f09f4137aadaedf007731bcb474704ab2f779935", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 4750, "license_type": "permissive", "max_line_length": 225, "num_lines": 149, "path": "/build/Makefile.gcc3", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#\n# Settings for all POSIX platforms. Each can be overridden in a platform-\n# specific file (Makefile.pf.<platform>, leaving this file to contain defaults.\n#\n#--------------------------------------------------------------------------------\n\n# Define flags. (These will be submitted to all commands that use the preprocesor)\nDEFINES=-DPF_DISTRO_$(PF_DISTRO) -DPF_MAJOR=$(PF_MAJOR) -DOS_MINOR=$(PF_MINOR) -D$(ARCH) -DPF_WIDTH=$(PF_WIDTH)\n\nifeq ($(ENABLE_SCX_SECURITY_HARDENING), 1)\n\tDEFINES += -z noexecstack -Wl,-z,relro -Wl,-z,now -Wformat -Wformat-security -Werror=format-security -pie -D_FORTIFY_SOURCE=2\nendif\n\nifeq ($(TRAVIS_CI), 1)\n\tDEFINES += -DTRAVIS\nendif\n\nifeq ($(SCX_STACK_ONLY), true)\n\tDEFINES += -DSCX_STACK_ONLY\nendif\n\n# Compiler flags that reglulates warning levels\n# OMI providers can't tolerate -pedantic (and, on RH4, -Wcast-qual as well)\nCXX_WARN_STRICT_FLAGS=-pedantic\nC_WARN_STRICT_FLAGS=-pedantic\n\nCXX_WARN_FLAGS=-Wall -fno-nonansi-builtins -Woverloaded-virtual -Wformat -Wformat-security -Wfloat-equal -Wcast-align -Wconversion -Wswitch-enum -Wundef -Wshadow -Wwrite-strings -Wredundant-decls $(CXX_WARN_STRICT_FLAGS)\nC_WARN_FLAGS=-Wall -fno-nonansi-builtins -Woverloaded-virtual -Wformat -Wformat-security -Wfloat-equal -Wcast-align -Wswitch-enum -Wundef -Wshadow -Wwrite-strings -Wredundant-decls $(C_WARN_STRICT_FLAGS)\n\nNEED_MINUS_CAST_QUAL=0\nNEED_MINUS_ERROR_CAST_QUAL=0\n\nifeq ($(PF_DISTRO)$(PF_MAJOR),SUSE12)\n NEED_MINUS_ERROR_CAST_QUAL=1\nelse\n ifneq ($(PFDISTRO)$(PF_MAJOR),REDHAT7)\n NEED_MINUS_CAST_QUAL=1\n endif\nendif\n\nifeq ($(NEED_MINUS_CAST_QUAL),1)\n CXX_WARN_STRICT_FLAGS += -Wcast-qual\n C_WARN_STRICT_FLAGS += -Wcast-qual\nendif\n\nifeq ($(NEED_MINUS_ERROR_CAST_QUAL),1)\n CXX_WARN_STRICT_FLAGS += -Werror=cast-qual\n C_WARN_STRICT_FLAGS += -Werror=cast-qual\nendif\n\n# Compiler code-generation options\nCXX_CGEN_FLAGS=-fPIC \n\n# Compiler Optimization flags \nCXX_OPTIMIZATION_FLAGS=-fstack-protector-all\n\n# Universal Agent switches\nifeq ($(PF_DISTRO_ULINUX_R), 1)\n\tDEFINES += -DPF_DISTRO_ULINUX_R\nendif\n\nifeq ($(PF_DISTRO_ULINUX_D), 1)\n\tDEFINES += -DPF_DISTRO_ULINUX_D\nendif\n\n# -fstack-protector-all not supported on Sles 9 - remove\nifeq ($(PF_DISTRO),SUSE)\n\tifeq ($(PF_MAJOR),9)\n\t\tCXX_OPTIMIZATION_FLAGS := $(CXX_OPTIMIZATION_FLAGS:-fstack-protector-all=)\n\tendif\nendif\n\n# -fstack-protector-all not supported on RH4 - remove\nifeq ($(PF_DISTRO),REDHAT)\n\tifeq ($(PF_MAJOR),4)\n\t\tCXX_OPTIMIZATION_FLAGS := $(CXX_OPTIMIZATION_FLAGS:-fstack-protector-all=)\n\tendif\nendif\n\n# Use -ggdb for release and debug build,and strip release binaries from debug binaries.\nCXXFLAGS += -ggdb\n\n# CXX Debug flags for debug builds\nifeq ($(BUILD_TYPE),Debug)\n\tDEFINES += -D_DEBUG\nelse\n\tDEFINES += -DNDEBUG\nendif \n\n# C and CXX Debug flags for release builds\nifeq ($(BUILD_TYPE),Release)\n\tCFLAGS += -Os\n\tCXXFLAGS += -Os -fno-enforce-eh-specs\nendif \n\n# Avoid stack frame corruption when throwing exceptions from \n# callbacks by not allowing the optimizer to omit frame pointers\n# (implicit with the -Os option). This bug was observed with the\n# GCC 3.4.3 compiler on Red Hat 3.4.3-9. See WI-11657 for more.\nCXXFLAGS += -fno-omit-frame-pointer\n\n# CXX Compiler flags, end result \nCXXFLAGS += $(DEFINES) $(CXX_OPTIMIZATION_FLAGS) $(CXX_WARN_FLAGS) $(CXX_CGEN_FLAGS)\nCFLAGS += $(DEFINES) $(CXX_OPTIMIZATION_FLAGS) $(C_WARN_FLAGS) $(CXX_CGEN_FLAGS)\n\n\n# Linker flags\nLINK_OUTFLAG=-o $@\nLINK_STATLIB_OUTFLAG=-o $@\n\n#--------------------------------------------------------------------------------\n# Tools for this platform\n\n# Compiler for CPP files\nCXX=g++\n\n# Link command for executables\n# Link an executable\n\nLINK=g++ -L. -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR) -L$(SCXOMI_LIBS)\n\n# Link command for static libraries (archives)\nLINK_STATLIB=ar -rc \n\n# Include paths for POSIX platforms\nINCLUDES=-I$(SCX_SHARED_INCLUDE_DIR) -I$(INT_INCLUDE_DIR) -I$(SCXPAL_INT_INCLUDE_DIR) -I$(SCX_BRD) -I$(SCXPAL_DIR) -isystem$(SCX_SHARED_TST_EXT_INCLUDE_DIR) -I$(SCXOMI_INCLUDE)\nUNITTEST_EXTRA_INCLUDES=-I$(SCXPAL_TEST_ROOT)/include -I$(SCX_SHARED_SRC_ROOT)\n\n# No operation, i.e. suppressing a command\nNOOP=@echo Step suppressed \n\n# Command for making dependecies\nMKDEP=g++ -MM\n\n#--------------------------------------------------------------------------------\n# File type suffixes\n\nPF_OBJ_FILE_SUFFIX=o\nPF_STAT_LIB_FILE_SUFFIX=a\nPF_DYN_LIB_FILE_SUFFIX=so\nPF_EXE_FILE_SUFFIX=\nPF_KIT_FILE_SUFFIX=tgz\n\n#-------------------------------- End of File -----------------------------------\n\n\n" }, { "alpha_fraction": 0.5050167441368103, "alphanum_fraction": 0.5150501728057861, "avg_line_length": 16.58823585510254, "blob_id": "2b7dec8aa455ae578cedd5105b71a56c2c18598b", "content_id": "a71f2458656ba57c89a86352e24a6e394aaee0bd", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 299, "license_type": "permissive", "max_line_length": 48, "num_lines": 17, "path": "/test/code/shared/testutils/closefiledescriptors/closefiledescriptors.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <unistd.h>\n#include <sys/select.h>\n\nint main()\n{\n int nrOpenDescriptors = 0;\n for (int fd = 3; fd < FD_SETSIZE; ++fd)\n {\n if (-1 != close(fd))\n {\n ++nrOpenDescriptors;\n }\n }\n\n std::cout << nrOpenDescriptors << std::endl;\n}\n" }, { "alpha_fraction": 0.5928874015808105, "alphanum_fraction": 0.5942421555519104, "avg_line_length": 31.62154769897461, "blob_id": "cb1e1386aa6bc4206fdf4371a810a628c5890e31", "content_id": "9be68879da02bf845e2b525e3f243ade618860a2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11810, "license_type": "permissive", "max_line_length": 118, "num_lines": 362, "path": "/source/code/shared/tools/scx_admin/cmdparser.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief scx configuration tool for SCX.\n\n \\date 8/22/2008\n\n*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxexception.h>\n\n\n#include <iostream>\n\n#include \"cmdparser.h\"\n\nusing namespace SCXCoreLib;\nusing namespace std;\n\nnamespace SCX_Admin {\n\n\n/*----------------------------------------------------------------------------*/\n/**\n checks if given command line parameter matches this Argument\n it updates \"out\" parameters only if it matches\n \n \\param[in] str command line parameter\n \\param[in,out] pos new position \n \\param[in,out] op operation to update with new value/name/type\n \\returns true if matches\n*/ \nbool Argument::DoesMatch( std::wstring str, int& pos, Operation& op )\n{\n switch( m_eType ){\n case eString:\n if ( StrToLower(m_strString) == StrToLower( str ) ){\n pos ++;\n return true;\n }\n break;\n\n case eComponent:\n if ( Str2Component( StrToLower(str) ) == Operation::eCompType_Unknown )\n break;\n\n op.m_eComponent = Str2Component( StrToLower(str) );\n pos++;\n return true;\n\n case eLogLevel:\n str = StrToLower(str);\n if ( L\"verbose\" == str )\n op.m_eLogLevel = SCX_AdminLogAPI::eLogLevel_Verbose;\n else if ( L\"intermediate\" == str )\n op.m_eLogLevel = SCX_AdminLogAPI::eLogLevel_Intermediate;\n else if ( L\"errors\" == str )\n op.m_eLogLevel = SCX_AdminLogAPI::eLogLevel_Errors;\n else\n break;\n\n pos++;\n return true;\n \n\n case ePair:\n { \n vector < std::wstring > tokens;\n \n StrTokenizeStr(str, tokens, L\"=\" );\n if ( tokens.size() == 2 ){\n op.m_strName = tokens[0];\n op.m_strValue = tokens[1];\n pos++;\n return true;\n }\n }\n break;\n\n case eName:\n op.m_strName = str;\n pos++;\n return true;\n\n default:\n return false;\n }\n\n // does not match; return true if optional\n return m_bOptional;\n}\n\n\n/**\n helper function to convert string to component type (scope)\n \n \\param[in] str string representation of the scope\n \\returns \"unknown\" if does not match anything or component type\n*/ \nOperation::enumComponentType Argument::Str2Component( std::wstring str )\n{\n str = StrToLower(str);\n if ( L\"all\" == str )\n return Operation::eCompType_All;\n else if ( L\"cimom\" == str )\n return Operation::eCompType_CIMom;\n else if ( L\"provider\" == str )\n return Operation::eCompType_Provider;\n\n return Operation::eCompType_Unknown;\n}\n\n/**\n this funciton tries to match first \"n\" cmd parameters with arguments\n skipping optional parameters if needed\n returns true, advances pos and fills in operation if match was found\n \n \\param[in] argc - number of arguments\n \\param[in] argv - array of arguments\n \\param[in,out] pos - current position in the array\n \\param[in,out] op - operation to update\n \n \\returns true, advances pos and fills in operation if match was found\n \n*/\nbool Command::DoesMatch( int argc, const char *argv[], int& pos, Operation& op )\n{\n // check all arguments that are required for given command\n int new_pos = pos;\n Operation new_op;\n new_op.m_eType = m_eOperationType;\n new_op.m_eComponent = Operation::eCompType_Default;\n \n for ( unsigned int i = 0; i < m_aArguments.size(); i++ ){\n if ( new_pos >= argc && HasMandatoryAfter( i ) )\n return false; // some parameter is missing\n\n if ( new_pos >= argc )\n break; // completed with default params.\n\n if ( !m_aArguments[i].DoesMatch( StrFromMultibyte(argv[new_pos]), new_pos, new_op ) )\n return false;\n\n }\n\n pos = new_pos;\n op = new_op;\n\n return true;\n \n}\n\n\n/**\n checks if there are any mandatory arguments in array strating with given position\n called when end of command line parameters list is reached\n \\param[in] pos - position in the array\n \\returns true if found\n*/ \n \nbool Command::HasMandatoryAfter( unsigned int pos ) const\n{\n for ( ; pos < m_aArguments.size(); pos++ ){\n if ( !m_aArguments[pos].m_bOptional )\n return true;\n }\n return false;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n internal function that fills in array of supported commands\n it also sets link between \"command\" and \"operation\"\n so several commands may result in the same operation: -h == -? == -help\n \\param[in,out] commands array of commands\n \n*/ \nstatic void InitParser( std::vector< Command >& commands )\n{\n std::vector< Argument > args;\n\n // \"-quiet\"\n args.push_back( Argument( Argument::eString, false, L\"-quiet\" ) );\n commands.push_back( Command( args, Operation::eOpType_GlobalOption_Quiet ) );\n args.clear();\n\n args.push_back( Argument( Argument::eString, false, L\"-q\" ) );\n commands.push_back( Command( args, Operation::eOpType_GlobalOption_Quiet ) );\n args.clear();\n\n // usage\n args.push_back( Argument( Argument::eString, false, L\"-help\" ) );\n commands.push_back( Command( args, Operation::eOpType_Global_Usage ) );\n args.clear();\n\n args.push_back( Argument( Argument::eString, false, L\"-h\" ) );\n commands.push_back( Command( args, Operation::eOpType_Global_Usage ) );\n args.clear();\n\n args.push_back( Argument( Argument::eString, false, L\"-?\" ) );\n commands.push_back( Command( args, Operation::eOpType_Global_Usage ) );\n args.clear();\n\n args.push_back( Argument( Argument::eString, false, L\"-usage\" ) );\n commands.push_back( Command( args, Operation::eOpType_Global_Usage ) );\n args.clear();\n\n // -log-set (provider)\n args.push_back( Argument( Argument::eString, false, L\"-log-set\" ) );\n args.push_back( Argument( Argument::eString, false, L\"provider\" ) );\n args.push_back( Argument( Argument::ePair, false ) );\n commands.push_back( Command( args, Operation::eOpType_Log_Prov_Set ) );\n args.clear();\n\n // -log-reset (provider)\n args.push_back( Argument( Argument::eString, false, L\"-log-reset\" ) );\n args.push_back( Argument( Argument::eString, false, L\"provider\" ) );\n args.push_back( Argument( Argument::eName, false ) );\n commands.push_back( Command( args, Operation::eOpType_Log_Prov_Reset ) );\n args.clear();\n\n // -log-remove (provider)\n args.push_back( Argument( Argument::eString, false, L\"-log-remove\" ) );\n args.push_back( Argument( Argument::eString, false, L\"provider\" ) );\n args.push_back( Argument( Argument::eName, true ) );\n commands.push_back( Command( args, Operation::eOpType_Log_Prov_Remove) );\n args.clear();\n \n // -log-list\n args.push_back( Argument( Argument::eString, false, L\"-log-list\" ) );\n args.push_back( Argument( Argument::eComponent, true ) );\n commands.push_back( Command( args, Operation::eOpType_Log_List ) );\n args.clear();\n\n // -log-rotate\n args.push_back( Argument( Argument::eString, false, L\"-log-rotate\" ) );\n args.push_back( Argument( Argument::eComponent, true ) );\n commands.push_back( Command( args, Operation::eOpType_Log_Rotate ) );\n args.clear();\n \n // -log-reset\n args.push_back( Argument( Argument::eString, false, L\"-log-reset\" ) );\n args.push_back( Argument( Argument::eComponent, true ) );\n commands.push_back( Command( args, Operation::eOpType_Log_Reset ) );\n args.clear();\n \n // -log-set\n args.push_back( Argument( Argument::eString, false, L\"-log-set\" ) );\n args.push_back( Argument( Argument::eComponent, true ) );\n args.push_back( Argument( Argument::eLogLevel, false ) );\n commands.push_back( Command( args, Operation::eOpType_Log_Set ) );\n args.clear();\n\n#if !defined(SCX_STACK_ONLY)\n\n // -config-list\n args.push_back( Argument( Argument::eString, false, L\"-config-list\" ) );\n args.push_back( Argument( Argument::eString, false, L\"runas\" ) );\n commands.push_back( Command( args, Operation::eOpType_Config_List) );\n args.clear();\n\n // -config-set\n args.push_back( Argument( Argument::eString, false, L\"-config-set\" ) );\n args.push_back( Argument( Argument::eString, false, L\"runas\" ) );\n args.push_back( Argument( Argument::ePair, false ) );\n commands.push_back( Command( args, Operation::eOpType_Config_Set) );\n args.clear();\n\n // -config-reset\n args.push_back( Argument( Argument::eString, false, L\"-config-reset\" ) );\n args.push_back( Argument( Argument::eString, false, L\"runas\" ) );\n args.push_back( Argument( Argument::eName, true ) );\n commands.push_back( Command( args, Operation::eOpType_Config_Reset) );\n args.clear();\n\n#endif\n\n // -start\n args.push_back( Argument( Argument::eString, false, L\"-start\" ) );\n args.push_back( Argument( Argument::eComponent, true ) );\n commands.push_back( Command( args, Operation::eOpType_Svc_Start) );\n args.clear();\n\n // -stop\n args.push_back( Argument( Argument::eString, false, L\"-stop\" ) );\n args.push_back( Argument( Argument::eComponent, true ) );\n commands.push_back( Command( args, Operation::eOpType_Svc_Stop) );\n args.clear();\n\n // -restart\n args.push_back( Argument( Argument::eString, false, L\"-restart\" ) );\n args.push_back( Argument( Argument::eComponent, true ) );\n commands.push_back( Command( args, Operation::eOpType_Svc_Restart) );\n args.clear();\n\n // -status\n args.push_back( Argument( Argument::eString, false, L\"-status\" ) );\n args.push_back( Argument( Argument::eComponent, true ) );\n commands.push_back( Command( args, Operation::eOpType_Svc_Status) );\n args.clear();\n\n // -version\n args.push_back( Argument( Argument::eString, false, L\"-version\" ) );\n commands.push_back( Command( args, Operation::eOpType_Show_Version ) );\n args.clear();\n\n args.push_back( Argument( Argument::eString, false, L\"-v\" ) );\n commands.push_back( Command( args, Operation::eOpType_Show_Version ) );\n args.clear();\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n parses command line options and returns array of operation.\n \\param[in] argc number of arguments\n \\param[in] argv pointer to arguments\n \\param[out] operations array of required operations\n \\param[out] error_msg human readable error message in case of parsing error\n \\returns \"true\" if success, \"false\" if failed to parse command line arguments\n \n \n*/ \nbool ParseAllParameters( int argc, const char *argv[], std::vector< Operation >& operations, std::wstring& error_msg )\n{\n std::vector< Command > commands;\n\n InitParser( commands );\n\n int pos = 0;\n \n while ( pos < argc ) {\n\n unsigned int i = 0;\n for ( ; i < commands.size(); i++ ){\n \n Operation op;\n \n if ( commands[i].DoesMatch( argc, argv, pos, op) ){\n operations.push_back( op );\n break;\n }\n }\n\n if ( i == commands.size() ){\n error_msg = L\"unknown option (or invalid command parameters) \";\n error_msg += StrFromMultibyte( argv[pos] );\n return false;\n }\n }\n\n return true;\n}\n\n}\n\n" }, { "alpha_fraction": 0.44760119915008545, "alphanum_fraction": 0.4773613214492798, "avg_line_length": 37.66666793823242, "blob_id": "79de190b33818ab82bddc3d7b6c7fcf9ff7ab048", "content_id": "f12744836cee83e3db09cb072cb29965fefc0e92", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13340, "license_type": "permissive", "max_line_length": 79, "num_lines": 345, "path": "/test/code/providers/appserver_provider/weblogicappserverinstance_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*---------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n */\n/**\n \\file weblogicappserverinstance_test.h\n\n \\brief Tests for the logic of the weblogic instance\n\n \\date 11-08-18 12:00:00\n\n */\n\n/*------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <testutils/scxunit.h>\n\n#include <appserverconstants.h>\n#include <appserverinstance.h>\n#include <weblogicappserverinstance.h>\n\n#include <cppunit/extensions/HelperMacros.h>\n\n#include <iostream>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\nusing namespace std;\n\nnamespace SCXUnitTests {\n /*\n * Unit Tests for the logic of WebLogic instances.\n * \n * WebLogic has a unique concept of versioning from the\n * Oracle Marketing department. These unit-tests will\n * verify that the mapping logic works correctly.\n */\n class WebLogicAppServerInstance_Test: public CPPUNIT_NS::TestFixture {\n CPPUNIT_TEST_SUITE( WebLogicAppServerInstance_Test);\n\n CPPUNIT_TEST( ExtractMajorVersionPriorTo10Maps);\n CPPUNIT_TEST( ExtractMajorVersion_10_0_MapsTo10g);\n CPPUNIT_TEST( ExtractMajorVersion_10_1_MapsTo10g);\n CPPUNIT_TEST( ExtractMajorVersion_10_2_MapsTo10g);\n CPPUNIT_TEST( ExtractMajorVersion_10_3_0_MapsTo10g);\n CPPUNIT_TEST( ExtractMajorVersion_10_3_2_MapsTo11g);\n CPPUNIT_TEST( ExtractMajorVersion_10_3_4_MapsTo11g);\n CPPUNIT_TEST( ExtractMajorVersion_10_3_5_MapsTo11g);\n CPPUNIT_TEST( ExtractMajorVersion_10_4_plus_MapsTo11g);\n CPPUNIT_TEST( ExtractMajorVersion11MapsTo11g);\n\n CPPUNIT_TEST_SUITE_END();\n\n public:\n /*--------------------------------------------------------*/\n /*\n * Unit Test setup method run before each test.\n */\n void setUp(void) {\n }\n\n /*--------------------------------------------------------*/\n /*\n * Unit Test tear down method run after each test.\n */\n void tearDown(void) {\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify all major version numbers prior to 10 map to 10g. \n */\n void ExtractMajorVersionPriorTo10Maps() {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n\n sut.SetVersion(L\"1.0.0\");\n CPPUNIT_ASSERT( L\"1\" ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"2.0.0\");\n CPPUNIT_ASSERT( L\"2\" ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"3.0.0\");\n CPPUNIT_ASSERT( L\"3\" ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"4.0.0\");\n CPPUNIT_ASSERT( L\"4\" ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"5.0.0\");\n CPPUNIT_ASSERT( L\"5\" ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"6.0.0\");\n CPPUNIT_ASSERT( L\"6\" ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"7.0.0\");\n CPPUNIT_ASSERT( L\"7\" ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"8.0.0\");\n CPPUNIT_ASSERT( L\"8\" ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"9.0.0\");\n CPPUNIT_ASSERT( L\"9\" ==\n sut.GetMajorVersion() );\n };\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 10.0.0.x maps to 10g. \n */\n void ExtractMajorVersion_10_0_MapsTo10g() {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n\n sut.SetVersion(L\"10.0.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_10 ==\n sut.GetMajorVersion() );\n\n // Right-most version (i.e. 10) should not matter\n sut.SetVersion(L\"10.0.10.10\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_10 ==\n sut.GetMajorVersion() );\n };\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 10.1.0.x maps to 10g. \n */\n void ExtractMajorVersion_10_1_MapsTo10g()\n {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n\n sut.SetVersion(L\"10.1.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_10 ==\n sut.GetMajorVersion() );\n\n // Right-most version (i.e. 1) should not matter\n sut.SetVersion(L\"10.1.10.111\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_10 ==\n sut.GetMajorVersion() );\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 10.2.0.x maps to 10g. \n */\n void ExtractMajorVersion_10_2_MapsTo10g()\n {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n\n sut.SetVersion(L\"10.2.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_10 ==\n sut.GetMajorVersion() );\n\n // Right-most version (i.e. 1) should not matter\n sut.SetVersion(L\"10.2.0.1\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_10 ==\n sut.GetMajorVersion() );\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 10.3.0.x maps to 10g. \n */\n void ExtractMajorVersion_10_3_0_MapsTo10g()\n {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n\n sut.SetVersion(L\"10.3.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_10 ==\n sut.GetMajorVersion() );\n\n // Right-most version (i.e. 25) should not matter\n sut.SetVersion(L\"10.3.0.25\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_10 ==\n sut.GetMajorVersion() );\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 10.3.2.x maps to 11g. \n */\n void ExtractMajorVersion_10_3_2_MapsTo11g()\n {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n\n sut.SetVersion(L\"10.3.2.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n // Right-most version (i.e. 4) should not matter\n sut.SetVersion(L\"10.3.2.4\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 10.3.5.x maps to 11g. \n */\n void ExtractMajorVersion_10_3_5_MapsTo11g()\n {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n \n sut.SetVersion(L\"10.3.5.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n // Right-most version (i.e. 8) should not matter\n sut.SetVersion(L\"10.3.5.8\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 10.3.4.x maps to 11g. \n */\n void ExtractMajorVersion_10_3_4_MapsTo11g()\n {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n \n sut.SetVersion(L\"10.3.4.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n // Right-most version (i.e. 18) should not matter\n sut.SetVersion(L\"10.3.4.18\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 10.4+.x maps to 11g. \n */\n void ExtractMajorVersion_10_4_plus_MapsTo11g()\n {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n\n sut.SetVersion(L\"10.4.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n // Right-most version (i.e. 18) should not matter\n sut.SetVersion(L\"10.4.10.18\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"10.5.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"10.6.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"10.7.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"10.8.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"10.9.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"10.10.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic's overriden functionality for\n * ExtractMajorVersion works as expected. The branded name\n * does not coincide with the numbered versioning.\n * \n * Verify major version 11.x maps to 11g\n */\n void ExtractMajorVersion11MapsTo11g()\n {\n WebLogicAppServerInstance sut(L\"/fake/path\");\n\n sut.SetVersion(L\"11.0.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"11.1.0\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n\n sut.SetVersion(L\"11.1.1\");\n CPPUNIT_ASSERT( WEBLOGIC_BRANDED_VERSION_11 ==\n sut.GetMajorVersion() );\n }\n\n }; // End WebLogicAppServerInstance_Test \n\n } // End namespace\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXUnitTests::WebLogicAppServerInstance_Test);\n" }, { "alpha_fraction": 0.592277467250824, "alphanum_fraction": 0.6217277646064758, "avg_line_length": 29.559999465942383, "blob_id": "27dbe7b739482e4795fd47f061c0b25479248705", "content_id": "a5a21324a65af07b903b23be89e29d92ef130271", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1528, "license_type": "permissive", "max_line_length": 92, "num_lines": 50, "path": "/test/util/testapp/Makefile", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n\n# Get the root of the SCXPAL directory (and other easy locations)\nSCXCORE_DIR=$(shell cd ../../..; pwd)\nSCXPAL_DIR := $(shell cd ../../../../pal; pwd)\n\n# Pull in the PAL's config.mak file, verify we have symbols\ninclude $(SCXPAL_DIR)/build/config.mak\n\nifndef BUILD_CONFIGURATION\n$(error \"BUILD_CONFIGURATION not defined. Please re-run configure\")\nendif\n\nTARGET_DIR := $(SCXCORE_DIR)/target/$(BUILD_CONFIGURATION)\n\n# Back to our regularly scheduled program ...\n\nUNAME=$(shell uname)\n\nifeq ($(UNAME),SunOS)\n\tCXX=CC -o $@\nendif\nifeq ($(UNAME),HP-UX)\n\tUNAME_M=$(shell uname -m)\n\tifeq ($(UNAME_M),ia64)\n\t\tCXX=aCC -Dhpux +DD64 -D_LARGE_FILES -AA -mt +We +W2236,2111,2815,2334 -o $@\n\telse\n\t\tCXX=aCC -Dhpux +DD64 -D_LARGE_FILES -AA -mt +W2236,2111,2815,2334 -o $@\n\tendif\nendif\nifeq ($(UNAME),Linux)\n\tCXX=g++ -Wall -D_FILE_OFFSET_BITS=64 -o $@\nendif \nifeq ($(UNAME),AIX)\n\tCXX=xlC_r -q64 -Daix -lperfstat -o $@\nendif \n\nall : $(TARGET_DIR)/testapp\n \n$(TARGET_DIR)/testapp : testapp.cpp memdata.cpp diskdata.cpp memdata.h diskdata.h diskinfo.h\n\t-cov01 -0\n\tmkdir -p $(TARGET_DIR)\n\t$(CXX) testapp.cpp memdata.cpp diskdata.cpp -lpthread -o $(TARGET_DIR)/testapp\n\nstub : \n\t@echo Stub file for testing tfsbuild > testapp\n\t@echo Testapp Makefile Stub Target Specified, Creating stubfile testapp\n\t@echo Returning Success\n" }, { "alpha_fraction": 0.5299145579338074, "alphanum_fraction": 0.5299145579338074, "avg_line_length": 16.549999237060547, "blob_id": "965d9cbe99be29e8d66302361f5bf99ebd72fefc", "content_id": "40bfe813218a2c4aadaff4ba5b356e5b53702fbb", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 351, "license_type": "permissive", "max_line_length": 80, "num_lines": 20, "path": "/test/util/testapp/diskdata.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n */\n#pragma once\n\n#include <vector>\n\nusing namespace std;\n\n#include \"diskinfo.h\"\n\nclass DiskData\n{\npublic:\n DiskData(void);\n virtual ~DiskData(void);\n\n int GetDiskInfo(vector<DiskInfo> &disks);\n};\n" }, { "alpha_fraction": 0.5765371322631836, "alphanum_fraction": 0.5789089798927307, "avg_line_length": 37.87234115600586, "blob_id": "f34abd61c5534e1e14f0670cde6da69ec3ab02e5", "content_id": "27550fe5c35f636f7b8cf5fee3fc8ed95bc86d56", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5481, "license_type": "permissive", "max_line_length": 133, "num_lines": 141, "path": "/source/code/providers/support/logfileutils.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n \n*/\n/**\n \\file logfileutils.h\n\n \\brief LogFile utility header file\n\n \\date 2011-3-09\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef LOGFILEUTILS_H\n#define LOGFILEUTILS_H\n\n#include <sys/stat.h>\n\n#include <string>\n#include <vector>\n#include <istream>\n\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/scxpersistence.h>\n#include <scxcorelib/scxpatternfinder.h>\n#include <scxcorelib/scxregex.h>\n\nnamespace SCXCore\n{\n class LogFileReader\n {\n public: /* Public only for test purposes ... */\n /**\n Persistable representation of a log file with a current position.\n The persistence key is the logfile path together with the qid.\n */\n class LogFilePositionRecord\n {\n public:\n LogFilePositionRecord(const SCXCoreLib::SCXFilePath& logfile,\n const std::wstring& qid,\n SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> persistMedia = SCXCoreLib::GetPersistMedia());\n const SCXCoreLib::SCXFilePath& GetLogFile() const;\n bool GetResetOnRead() const;\n void SetResetOnRead(bool fSet);\n std::streamoff GetPos() const;\n void SetPos(std::streamoff pos);\n scxulong GetStatStIno() const;\n void SetStatStIno(scxulong st_ino);\n scxulong GetStatStSize() const;\n void SetStatStSize(scxulong st_size);\n\n void Persist();\n bool Recover();\n bool UnPersist();\n\n private:\n SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> m_PersistMedia; //!< Handle to persistence framework.\n const SCXCoreLib::SCXFilePath m_LogFile; //!< Log file path.\n std::wstring m_Qid; //!< Query ID\n bool m_ResetOnRead; //!< ResetOnRead flag\n std::wstring m_IdString; //!< Persistence id string created from file name and qid.\n \n std::streamoff m_Pos; //!< file end pos\n scxulong m_StIno; //!< st_ino field of a stat struct.\n scxulong m_StSize; //!< st_size field of a stat struct.\n };\n\n /**\n Class with responsibility of maintaining opening a log file at the correct\n position depending on information in a LogFilePositionRecord.\n */\n class LogFileStreamPositioner\n {\n public:\n LogFileStreamPositioner(const SCXCoreLib::SCXFilePath& logfile,\n const std::wstring& qid,\n SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> persistMedia = SCXCoreLib::GetPersistMedia());\n SCXCoreLib::SCXHandle<std::wfstream> GetStream();\n void SetResetOnRead(bool fSet) { m_Record->SetResetOnRead(fSet); }\n void PersistState();\n\n private:\n SCXCoreLib::SCXHandle<LogFilePositionRecord> m_Record; //!< Handle to record with persistable data.\n SCXCoreLib::SCXHandle<std::wfstream> m_Stream; //!< Handle to currently open stream.\n SCXCoreLib::SCXLogHandle m_log; //!< Handle to log framework.\n\n bool IsFileNew() const;\n void UpdateStatData();\n };\n\n public:\n LogFileReader();\n ~LogFileReader() {}\n\n bool ReadLogFile(\n const std::wstring& filename,\n const std::wstring& qid,\n const std::vector<SCXCoreLib::SCXRegexWithIndex>& regexps,\n std::vector<std::wstring>& matchedLines);\n\n int ResetLogFileState(\n const std::wstring& filename,\n const std::wstring& qid,\n bool resetOnRead);\n\n int ResetAllLogFileStates(const std::wstring& path, bool resetOnRead);\n\n // Public solely for unit tests ...\n void SetPersistMedia(SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> persistMedia);\n\n protected:\n /**\n Internal representation of a log file.\n */\n class SCXLogFile\n {\n public:\n std::wstring name; //!< file name\n std::streamoff pos; //!< file end pos\n struct stat64 statinfo; //!< file information\n bool statvalid; //!< statinfo valid flag\n };\n\n private:\n std::wstring GetFileName(const std::wstring& query);\n SCXLogFile* GetLogFile(const std::wstring& filename);\n bool CheckFileWrap(const struct stat64& oldstatinfo, const struct stat64& newstatinfo);\n\n std::vector<SCXLogFile> m_files; //!< log files\n\n SCXCoreLib::SCXLogHandle m_log; //!< Handle to log framework.\n SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> m_persistMedia; //!< Persist media to use\n SCXCoreLib::SCXPatternFinder m_cqlPatterns; //!< Supported cql patterns finder.\n static const SCXCoreLib::SCXPatternFinder::SCXPatternCookie s_patternID; //!< Supported pattern identifier.\n static const std::wstring s_pattern; //!< The actual pattern supported\n static const std::wstring s_patternParameter; //!< name of parameter in pattern.\n };\n}\n\n#endif /* LOGFILEUTILS_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5625221133232117, "alphanum_fraction": 0.5674813985824585, "avg_line_length": 32.21176528930664, "blob_id": "c1c93b32432d8e1cb536b9af2463df4a4eba429e", "content_id": "9819e0ab796d1904ce87c587237b3134be6d4ef3", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2823, "license_type": "permissive", "max_line_length": 189, "num_lines": 85, "path": "/test/code/providers/disk_provider/testablediskprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Provides a way into the disk provider for testing purposes\n\n \\date 2008-09-23 12:54:20\n\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef TESTABLEDISKPROVIDER_H\n#define TESTABLEDISKPROVIDER_H\n\n#include <testutils/providertestutils.h>\n#include <source/code/providers/disk_provider/diskprovider.h>\n\n/*----------------------------------------------------------------------------*/\n/**\n Class that exposes the protected methods of the disk provider for\n testing purposes.\n*/\nclass TestableDiskProvider : public TestableProvider, public SCXCore::DiskProvider\n{\npublic:\n TestableDiskProvider()\n {\n DoInit();\n }\n\n virtual ~TestableDiskProvider()\n {\n DoCleanup();\n }\n\n void TestDoGetInstance(const SCXProviderLib::SCXCallContext& callContext,\n SCXProviderLib::SCXInstance& instance)\n {\n DoGetInstance(callContext, instance);\n }\n\n void TestDoEnumInstances(const SCXProviderLib::SCXCallContext& callContext,\n SCXProviderLib::SCXInstanceCollection &instances)\n {\n DoEnumInstances(callContext, instances);\n }\n\n void TestDoEnumInstanceNames(const SCXProviderLib::SCXCallContext& callContext,\n SCXProviderLib::SCXInstanceCollection &names)\n {\n DoEnumInstanceNames(callContext, names);\n }\n\n void TestDoEnumInstanceNames(const SCXProviderLib::SCXCallContext& callContext,\n SCXProviderLib::SCXInstanceCollection &names,\n bool useParentImpl)\n {\n if (useParentImpl)\n {\n DoEnumInstanceNames(callContext, names);\n }\n else\n {\n SCXCore::DiskProvider::SupportedCimClasses disktype = static_cast<SCXCore::DiskProvider::SupportedCimClasses>(m_ProviderCapabilities.GetCimClassId(callContext.GetObjectPath()));\n\n SCXCoreLib::SCXHandle<SCXCore::ProviderAlgorithmInterface> disks = GetProviderAlgIfc(disktype);\n\n disks->GetInstanceKeys(names);\n }\n }\n\n void TestDoInvokeMethod(const SCXProviderLib::SCXCallContext& callContext,\n const std::wstring& methodname,\n const SCXProviderLib::SCXArgs& args,\n SCXProviderLib::SCXArgs& outargs,\n SCXProviderLib::SCXProperty& result)\n {\n DoInvokeMethod(callContext, methodname, args, outargs, result);\n }\n};\n\n#endif /* TESTABLEDISKPROVIDER_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6162722110748291, "alphanum_fraction": 0.6211045384407043, "avg_line_length": 30.88679313659668, "blob_id": "157a3433281047aff84b5624736dc52298057e24", "content_id": "19e50125be4e5d26b653662d0f98950623eb12d4", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10140, "license_type": "permissive", "max_line_length": 134, "num_lines": 318, "path": "/source/code/providers/SCX_MemoryStatisticalInformation_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_MemoryStatisticalInformation_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-22-2013 17:48:44\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_MemoryStatisticalInformation_Class_Provider.h\"\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/stringaid.h>\n#include <scxsystemlib/memoryenumeration.h>\n#include <scxcorelib/scxmath.h>\n\n#include \"support/startuplog.h\"\n#include \"support/memoryprovider.h\"\n#include \"support/scxcimutils.h\"\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_MemoryStatisticalInformation_Class& inst,\n bool keysOnly,\n SCXCoreLib::SCXHandle<SCXSystemLib::MemoryInstance> meminst)\n{\n // Populate the key values\n inst.Name_value(\"Memory\");\n\n if (!keysOnly)\n {\n scxulong physmem = 0;\n scxulong resmem = 0;\n scxulong usermem = 0;\n scxulong avail = 0;\n scxulong data = 0;\n scxulong data2 = 0;\n\n inst.Caption_value(\"Memory information\");\n inst.Description_value(\"Memory usage and performance statistics\");\n\n inst.IsAggregate_value(meminst->IsTotal());\n\n if (meminst->GetTotalPhysicalMemory(physmem))\n {\n // Adjust numbers from PAL to Megabytes\n physmem = BytesToMegaBytes(physmem);\n\n if (meminst->GetReservedMemory(resmem))\n {\n resmem = BytesToMegaBytes(resmem);\n }\n else\n {\n resmem = 0;\n }\n\n // If available, get memory unavailable for user processes and remove it from physical memory\n usermem = physmem - resmem;\n }\n\n if (meminst->GetAvailableMemory(avail))\n {\n // Adjust numbers from PAL to Megabytes\n avail = BytesToMegaBytes(avail);\n inst.AvailableMemory_value(avail);\n\n // If we have a number for physical memory use it to compute a percentage\n if (usermem > 0)\n {\n // Need an unsigned char since this is what is required by the MOF\n unsigned char percent = static_cast<unsigned char> (GetPercentage(0, avail, 0, usermem));\n inst.PercentAvailableMemory_value(percent);\n }\n }\n\n if (meminst->GetUsedMemory(data))\n {\n // Adjust numbers from PAL to Megabytes\n data = BytesToMegaBytes(data);\n inst.UsedMemory_value(data);\n\n // If we have a number for physical memory use it to compute a percentage\n if (usermem > 0)\n {\n unsigned char percent = static_cast<unsigned char> (GetPercentage(0, data, 0, usermem));\n inst.PercentUsedMemory_value(percent);\n }\n }\n\n {\n data = 0;\n unsigned char percent = static_cast<unsigned char> (0);\n\n if (meminst->GetCacheSize(data) && usermem > 0)\n {\n percent = static_cast<unsigned char> (GetPercentage(0, BytesToMegaBytes(data), 0, usermem));\n }\n inst.PercentUsedByCache_value(percent);\n }\n\n bool pageReadsAvailable = meminst->GetPageReads(data);\n bool pageWritesAvailable = meminst->GetPageWrites(data2);\n if (pageReadsAvailable && pageWritesAvailable)\n {\n inst.PagesPerSec_value(data + data2);\n }\n \n if (pageReadsAvailable)\n {\n inst.PagesReadPerSec_value(data);\n }\n \n if (pageWritesAvailable)\n {\n inst.PagesWrittenPerSec_value(data2);\n }\n\n if (meminst->GetAvailableSwap(data))\n {\n // Adjust numbers from PAL to Megabytes\n data = BytesToMegaBytes(data);\n inst.AvailableSwap_value(data);\n\n if (meminst->GetTotalSwap(data2))\n {\n // Adjust numbers from PAL to Megabytes\n data2 = BytesToMegaBytes(data2);\n\n unsigned char percent = static_cast<unsigned char> (GetPercentage(0, data, 0, data2));\n inst.PercentAvailableSwap_value(percent);\n }\n }\n\n if (meminst->GetUsedSwap(data))\n {\n // Adjust numbers from PAL to Megabytes\n data = BytesToMegaBytes(data);\n\n inst.UsedSwap_value(data);\n\n if (meminst->GetTotalSwap(data2))\n {\n // Adjust numbers from PAL to Megabytes\n data2 = BytesToMegaBytes(data2);\n\n unsigned char percent = static_cast<unsigned char> (GetPercentage(0, data, 0, data2));\n inst.PercentUsedSwap_value(percent);\n }\n }\n }\n\n context.Post(inst);\n}\n\nSCX_MemoryStatisticalInformation_Class_Provider::SCX_MemoryStatisticalInformation_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_MemoryStatisticalInformation_Class_Provider::~SCX_MemoryStatisticalInformation_Class_Provider()\n{\n}\n\nvoid SCX_MemoryStatisticalInformation_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for MemoryProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::MemoryProvider::Lock\"));\n SCXCore::g_MemoryProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_MemoryProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_MemoryStatisticalInformation_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_MemoryStatisticalInformation_Class_Provider::Load\", SCXCore::g_MemoryProvider.GetLogHandle() );\n}\n\nvoid SCX_MemoryStatisticalInformation_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for MemoryProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::MemoryProvider::Lock\"));\n SCXCore::g_MemoryProvider.Unload();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_MemoryStatisticalInformation_Class_Provider::Unload\", SCXCore::g_MemoryProvider.GetLogHandle() );\n}\n\nvoid SCX_MemoryStatisticalInformation_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_MemoryProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"MemoryStat EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for MemoryProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::MemoryProvider::Lock\"));\n\n // Prepare MemoryStatisticalInformation Enumeration\n SCXCoreLib::SCXHandle<SCXSystemLib::MemoryEnumeration> memEnum = SCXCore::g_MemoryProvider.GetMemoryEnumeration();\n\n if ( !keysOnly )\n {\n memEnum->Update();\n }\n\n // There should be only one instance.\n SCXCoreLib::SCXHandle<SCXSystemLib::MemoryInstance> meminst = memEnum->GetTotalInstance();\n if (meminst != 0)\n {\n SCX_MemoryStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, keysOnly, meminst);\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_MemoryStatisticalInformation_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"MemoryStat EnumerateInstances end\");\n}\n\nvoid SCX_MemoryStatisticalInformation_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_MemoryStatisticalInformation_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for MemoryProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::MemoryProvider::Lock\"));\n\n if ( !instanceName.Name_exists() )\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n \n if ( strcmp(\"Memory\", instanceName.Name_value().Str()) )\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCXCoreLib::SCXHandle<SCXSystemLib::MemoryEnumeration> memEnum = SCXCore::g_MemoryProvider.GetMemoryEnumeration();\n memEnum->Update();\n\n // There should be only one instance.\n SCXCoreLib::SCXHandle<SCXSystemLib::MemoryInstance> meminst = memEnum->GetTotalInstance();\n if ( meminst == NULL )\n {\n context.Post(MI_RESULT_FAILED);\n return;\n }\n\n SCX_MemoryStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, false, meminst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_MemoryStatisticalInformation_Class_Provider::GetInstance\",\n SCXCore::g_MemoryProvider.GetLogHandle() );\n}\n\nvoid SCX_MemoryStatisticalInformation_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_MemoryStatisticalInformation_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_MemoryStatisticalInformation_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_MemoryStatisticalInformation_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_MemoryStatisticalInformation_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_MemoryStatisticalInformation_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.5406427383422852, "alphanum_fraction": 0.5438833236694336, "avg_line_length": 33.28703689575195, "blob_id": "5d336952e8b9359b622e40ddd888188325fa228c", "content_id": "1cc6867dfd2396e8d393bab74011de69da288f09", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3703, "license_type": "permissive", "max_line_length": 100, "num_lines": 108, "path": "/source/code/providers/support/appserver/appserverinstance.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file appserverinstance.h\n\n \\brief PAL representation of a Application Server\n\n \\date 11-05-18 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef APPSERVERINSTANCE_H\n#define APPSERVERINSTANCE_H\n\n#include <string>\n\n#include <scxsystemlib/entityinstance.h>\n#include <scxcorelib/scxlog.h>\n\nnamespace SCXSystemLib\n{\n /*----------------------------------------------------------------------------*/\n /**\n Class that represents an instances.\n\n Concrete implementation of an instance of a Application Server\n\n */\n class AppServerInstance : public EntityInstance\n {\n friend class AppServerEnumeration;\n\n public:\n\n AppServerInstance(const std::wstring& id,\n const std::wstring& type);\n\n virtual ~AppServerInstance();\n \n /*-------------------------------------------------------------------*/\n //! Check if two application server instances are equal\n //! \\param[in] first Instance to compare\n //! \\param[in] second Instance to compare\n //! \\returns true iff the application server instances are equal.\n bool operator==(const AppServerInstance& other) const;\n\n /*--------------------------------------------------------------------*/\n //! Check if two application server instances are not equal\n //! \\param[in] first Instance to compare\n //! \\param[in] second Instance to compare\n //! \\returns true iff the application server instances are equal.\n bool operator!=(const AppServerInstance& other) const;\n\n std::wstring GetHttpPort() const;\n std::wstring GetHttpsPort() const;\n std::wstring GetVersion() const;\n std::wstring GetMajorVersion() const;\n std::wstring GetDiskPath() const;\n std::wstring GetType() const;\n std::wstring GetProtocol() const;\n std::wstring GetPort() const;\n bool GetIsDeepMonitored() const;\n bool GetIsRunning() const;\n std::wstring GetProfile() const;\n std::wstring GetCell() const;\n std::wstring GetNode() const;\n std::wstring GetServer() const;\n\n virtual bool IsStillInstalled();\n\n void SetDiskPath(const std::wstring& diskPath);\n void SetHttpPort(const std::wstring& httpPort);\n void SetHttpsPort(const std::wstring& httpsPort);\n void SetIsDeepMonitored(bool isDeepMonitored, std::wstring protocol);\n void SetIsRunning(bool isRunning);\n void SetServer(const std::wstring& server);\n void SetType(const std::wstring& type);\n void SetVersion(const std::wstring& version);\n\n virtual void Update();\n\n protected:\n\n virtual std::wstring ExtractMajorVersion(const std::wstring& version);\n\n SCXCoreLib::SCXLogHandle m_log; //!< Log handle\n\n std::wstring m_httpPort;\n std::wstring m_httpsPort;\n std::wstring m_version;\n std::wstring m_majorVersion;\n std::wstring m_diskPath;\n std::wstring m_type;\n std::wstring m_protocol;\n std::wstring m_port;\n bool m_isDeepMonitored;\n bool m_isRunning;\n std::wstring m_profile;\n std::wstring m_cell;\n std::wstring m_node;\n std::wstring m_server;\n\n };\n\n}\n\n#endif /* APPSERVERINSTANCE_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5128921866416931, "alphanum_fraction": 0.5163094401359558, "avg_line_length": 26.279661178588867, "blob_id": "e2728c760218a55ce21b8334247f919f546160ab", "content_id": "4e2fe32298f5905f711472f90cb90b4a7f578e67", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3219, "license_type": "permissive", "max_line_length": 100, "num_lines": 118, "path": "/source/code/shared/tools/scx_admin/cimconfigurator.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief scx cim configuration tool for SCX. Configuration options in OMI.\n\n \\date 8/27/2008\n\n*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxstream.h>\n#include <scxcorelib/stringaid.h>\n\n#include <iostream>\n\n#include \"cimconfigurator.h\"\n\nusing namespace SCXCoreLib;\nusing namespace std;\n\n\n// Note: Currently, OMI logging is not very configurable (command-line options\n// only, nothing in .conf file). This is currently a placeholder, but doesn't\n// do much.\n//\n// For the time being, to get OMI-related logging (what little there is), we\n// would need to stop the server and restart it from the command line,\n// specifying --loglevel 4.\n\n\nnamespace SCXCoreLib\n{\n /*----------------------------------------------------------------------------*/\n /**\n Constructor for SCX_CimConfigurator class\n */\n SCX_CimConfigurator::SCX_CimConfigurator()\n {\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Destructor for SCX_CimConfigurator class\n */\n SCX_CimConfigurator::~SCX_CimConfigurator()\n {\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Performs log rotation for the CIM server\n\n \\returns TRUE if supported (and suceeded), FALSE if unsupported\n\n \\throws Exception if supported, but error occurred\n */\n bool SCX_CimConfigurator::LogRotate()\n {\n // OpenPegasus doesn't support log rotation at this time\n // (to the best of my knowledge) without server restart\n\n return false;\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Prints the current state of the CIM server\n\n \\param[out] buf Output of current log settings\n \\returns TRUE if supported (and suceeded), FALSE if unsupported\n\n \\throws Exception if supported, but error occurred\n */\n bool SCX_CimConfigurator::Print(std::wostringstream& buf) const\n {\n (void) buf;\n\n return false;\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Resets the logging level for the CIM server\n\n \\returns TRUE if supported (and suceeded), FALSE if unsupported\n\n \\throws Exception if supported, but error occurred\n */\n bool SCX_CimConfigurator::Reset()\n {\n return false;\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Sets the current logging configuration for CIM server\n\n \\param level Current logging level (0->None, 1->Some, 2->All)\n \\returns TRUE if supported (and suceeded), FALSE if unsupported\n\n \\throws Exception if supported, but error occurred\n */\n bool SCX_CimConfigurator::Set(LogLevelEnum level)\n {\n (void) level;\n\n return false;\n }\n}\n" }, { "alpha_fraction": 0.43207842111587524, "alphanum_fraction": 0.4334663450717926, "avg_line_length": 26.912832260131836, "blob_id": "490b02603243d416bf11a1d40386110f63034893", "content_id": "dd46836ff8a7b782e31b477d80dac88a408613f4", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11528, "license_type": "permissive", "max_line_length": 109, "num_lines": 413, "path": "/source/code/providers/support/appserver/appserverinstance.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file appserverinstance.cpp\n\n \\brief PAL representation of an application server\n\n \\date 11-05-18 12:00:00\n*/\n/*---------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n\n#include <string>\n#include <sstream>\n#include <vector>\n\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxdirectoryinfo.h>\n#include <scxcorelib/scxmath.h>\n\n#include \"appserverinstance.h\"\n#include \"appserverconstants.h\" \n\nusing namespace std;\nusing namespace SCXCoreLib;\n\nnamespace SCXSystemLib\n{\n\n /*------------------------------------------------------------------------*/\n /**\n Constructor\n\n Parameters: id - Identifier for the appserver (i.e. install path \n for the appserver)\n Parameters: type - Type of Application Server (i.e. JBoss, Tomcat, etc..)\n */\n AppServerInstance::AppServerInstance(\n const wstring& id, \n const wstring& type) : \n EntityInstance(id, false),\n m_httpPort(L\"\"), \n m_httpsPort(L\"\"), \n m_version(L\"\"), \n m_majorVersion(L\"\"), \n m_diskPath(id), \n m_type(type), \n m_protocol(L\"\"), \n m_port(L\"\"), \n m_isDeepMonitored(false),\n m_isRunning(true),\n m_profile(L\"\"), \n m_cell(L\"\"), \n m_node(L\"\"), \n m_server(L\"\")\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.common.pal.system.appserver.appserverinstance\");\n\n SCX_LOGTRACE(m_log, wstring(L\"AppServerInstance default constructor - \").append(id));\n }\n\n /*----------------------------------------------------------------------*/\n /**\n Destructor\n */\n AppServerInstance::~AppServerInstance()\n {\n SCX_LOGTRACE(m_log, wstring(L\"AppServerInstance destructor - \").append(GetId()));\n }\n \n /*--------------------------------------------------------------------*/\n //! Check if two application server instances are equal\n //! \\param[in] first Instance to compare\n //! \\param[in] second Instance to compare\n //! \\returns true iff the application server instances are equal.\n bool AppServerInstance::operator==(const AppServerInstance& other) const\n {\n return (this->GetDiskPath() == other.GetDiskPath()) &&\n (this->GetHttpPort() == other.GetHttpPort()) &&\n (this->GetHttpsPort() == other.GetHttpsPort()) &&\n (this->GetPort() == other.GetPort()) &&\n (this->GetProtocol() == other.GetProtocol()) &&\n (this->GetIsDeepMonitored() == other.GetIsDeepMonitored()) &&\n (this->GetIsRunning() == other.GetIsRunning()) &&\n (this->GetType() == other.GetType()) &&\n (this->GetVersion() == other.GetVersion()) &&\n (this->GetProfile() == other.GetProfile()) &&\n (this->GetCell() == other.GetCell()) &&\n (this->GetNode() == other.GetNode()) &&\n (this->GetServer() == other.GetServer());\n }\n\n /*--------------------------------------------------------------------*/\n //! Check if two application server instances are not equal\n //! \\param[in] first Instance to compare\n //! \\param[in] second Instance to compare\n //! \\returns true iff the application server instances are equal.\n bool AppServerInstance::operator!=(const AppServerInstance& other) const\n {\n return !(*this == other);\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get HTTP Port\n\n Retval: HTTP port of appserver instance\n */\n wstring AppServerInstance::GetHttpPort() const\n {\n return m_httpPort;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get HTTPS Port\n\n Retval: HTTPS port of appserver instance\n */\n wstring AppServerInstance::GetHttpsPort() const\n {\n return m_httpsPort;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get appser verversion\n\n Retval: version of appserver instance\n */\n wstring AppServerInstance::GetVersion() const\n {\n return m_version;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get appser major verversion\n\n Retval: major version of appserver instance\n */\n wstring AppServerInstance::GetMajorVersion() const\n {\n return m_majorVersion;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get disk path\n\n Retval: disk path of appserver instance\n */\n wstring AppServerInstance::GetDiskPath() const\n {\n return m_diskPath;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get type\n\n Retval: type of appserver instance\n */\n wstring AppServerInstance::GetType() const\n {\n return m_type;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get protocol\n\n Retval: protocol to use\n */\n wstring AppServerInstance::GetProtocol() const\n {\n return m_protocol;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get port\n\n Retval: port to use\n */\n wstring AppServerInstance::GetPort() const\n {\n return m_port;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get profile\n\n Retval: profile name\n */\n wstring AppServerInstance::GetProfile() const\n {\n return m_profile;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get cell\n\n Retval: cell name\n */\n wstring AppServerInstance::GetCell() const\n {\n return m_cell;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get node\n\n Retval: node name\n */\n wstring AppServerInstance::GetNode() const\n {\n return m_node;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get server\n\n Retval: server name\n */\n wstring AppServerInstance::GetServer() const\n {\n return m_server;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get IsDeepMonitored\n\n Retval: is deep monitoring enabled for this app server\n */\n bool AppServerInstance::GetIsDeepMonitored() const\n {\n return m_isDeepMonitored;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Get IsRunning\n\n Retval: is this app server process running\n */\n bool AppServerInstance::GetIsRunning() const\n {\n return m_isRunning;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Set disk path\n\n \\param[in] diskPath Disk Path\n */\n void AppServerInstance::SetDiskPath(const wstring& diskPath)\n {\n m_diskPath = diskPath;\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Set HTTP port\n\n \\param[in] httpPort HTTP port\n */\n void AppServerInstance::SetHttpPort(const wstring& httpPort)\n {\n m_httpPort = httpPort;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set HTTPS port\n\n \\param[in] httpsPort HTTPS port\n */\n void AppServerInstance::SetHttpsPort(const wstring& httpsPort)\n {\n m_httpsPort = httpsPort;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set IsDeepMonitored\n\n \\param[in] isDeepMonitored Should this app server be deep monitored\n */\n void AppServerInstance::SetIsDeepMonitored(bool isDeepMonitored, wstring protocol)\n {\n m_isDeepMonitored = isDeepMonitored;\n\n // Only check protocol when enabeling deep monitoring\n if (isDeepMonitored)\n {\n if (L\"HTTPS\" == protocol)\n {\n m_protocol = L\"HTTPS\";\n m_port = m_httpsPort;\n }\n else // Treat all non-HTTPS string as HTTP\n {\n m_protocol = L\"HTTP\";\n m_port = m_httpPort;\n }\n }\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Set IsRunning\n\n \\param[in] isRunning is this app server process running\n */\n void AppServerInstance::SetIsRunning(bool isRunning)\n {\n m_isRunning = isRunning;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set type\n\n \\param[in] type type\n */\n void AppServerInstance::SetType(const wstring& type)\n {\n m_type = type;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set Server\n\n \\param[in] type Server\n */\n void AppServerInstance::SetServer(const wstring& server)\n {\n m_server = server;\n }\n \n /*--------------------------------------------------------------------*/\n /**\n Set Version\n\n \\param[in] version version of the application server\n */\n void AppServerInstance::SetVersion(const wstring& version)\n {\n m_version = version;\n m_majorVersion = ExtractMajorVersion(version);\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Update values\n\n */\n void AppServerInstance::Update()\n {\n SCX_LOGTRACE(m_log, wstring(L\"AppServerInstance::Update() - \").append(GetId()));\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Extract the major version number from the complete version\n\n \\param[in] version version of the application server\n Retval: major version number\n */\n wstring AppServerInstance::ExtractMajorVersion(const wstring& version)\n {\n vector<wstring> parts;\n vector<wstring> majorVersionParts; \n StrTokenizeStr(version, parts, L\".\");\n if (parts.size() > 0)\n {\n StrTokenizeStr(parts[0], majorVersionParts, L\" \");\n if (majorVersionParts.size() > 0)\n {\n return majorVersionParts[majorVersionParts.size() - 1];\n }\n }\n\n return L\"\";\n }\n \n\n /*--------------------------------------------------------------------*/\n /**\n Check if the application server is still installed.\n \n By default, this will just check that the base directory\n exists on disk. Additionaly checking may be done by overriding\n logic per application server.\n\n */\n bool AppServerInstance::IsStillInstalled()\n {\n return SCXDirectory::Exists(SCXFilePath(m_diskPath));\n }\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.778294563293457, "alphanum_fraction": 0.7860465049743652, "avg_line_length": 47.61538314819336, "blob_id": "a388bb798ffbfc9b8cf5aebbf078633465986a19", "content_id": "85756d41b0f9afcf2fdaf380fcab551f57caed28", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 645, "license_type": "permissive", "max_line_length": 101, "num_lines": 13, "path": "/build/Windows/TeamBuildTypes/README.txt", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "Unix builds are run from a single build project under: TeamBuildTypes\\UnixBuildTemplate\\TFSBuild.proj\r\n\r\nTo use this project it's necessary to pass in the correct \"UnixBuildType\" \r\nparameter for which build you want to run. To create a TFS build definition \r\nyou must pass in this parameter through the \"MSBuild Arguments\" setting under \r\nthe \"Advanced\" section on the \"Process\" tab of the build definition, like so:\r\n\r\nEdit Build Definition... > Process > Advanced:\r\n\r\nMSBuild Arguments: /p:UnixBuildType=SUSE_10.0_x64\r\n\r\nCheck the file TeamBuildTypes\\UnixBuildTemplate\\UnixBuildSettings.proj for \r\nthe list of valid values for UnixBuildType.\r\n" }, { "alpha_fraction": 0.5323027968406677, "alphanum_fraction": 0.534680962562561, "avg_line_length": 25.82978630065918, "blob_id": "623b7bc1d920a1a27127a7896e7a4ba81b014e65", "content_id": "409518816cd2888c5d3d22c2f9689ed677418631", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2523, "license_type": "permissive", "max_line_length": 108, "num_lines": 94, "path": "/source/code/providers/support/appserver/appserverprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file appserverprovider.h\n\n \\brief App Server provider\n\n \\date 05-08-03\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef APPSERVERPROVIDER_H\n#define APPSERVERPROVIDER_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXCore\n{\n /*----------------------------------------------------------------------------*/\n /**\n Class representing all external dependencies from the AppServer PAL.\n\n */\n class AppServerProviderPALDependencies\n {\n public:\n virtual ~AppServerProviderPALDependencies() {};\n\n virtual SCXCoreLib::SCXHandle<SCXSystemLib::AppServerEnumeration> CreateEnum()\n {\n return SCXHandle<AppServerEnumeration>(new AppServerEnumeration());\n }\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Application Server provider\n\n Provide Application Services capabilities for OMI\n */\n class ApplicationServerProvider\n {\n public:\n ApplicationServerProvider()\n : m_deps(NULL),\n m_appservers(NULL)\n { }\n virtual ~ApplicationServerProvider() { }\n\n virtual const std::wstring DumpString() const\n {\n return L\"ApplicationServerProvider\";\n }\n\n void Load();\n\n void Unload();\n\n void UpdateDependencies(SCXCoreLib::SCXHandle<AppServerProviderPALDependencies> deps)\n {\n m_deps = deps;\n }\n\n SCXCoreLib::SCXHandle<SCXSystemLib::AppServerEnumeration> GetAppServers()\n {\n return m_appservers;\n }\n\n SCXLogHandle& GetLogHandle()\n {\n return m_log;\n }\n\n private:\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n\n SCXCoreLib::SCXHandle<AppServerProviderPALDependencies> m_deps;\n\n //! PAL implementation retrieving appserver information for local host\n SCXCoreLib::SCXHandle<SCXSystemLib::AppServerEnumeration> m_appservers;\n };\n\n extern ApplicationServerProvider g_AppServerProvider;\n}\n\n#endif /* APPSERVERPROVIDER_H */\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n\n" }, { "alpha_fraction": 0.5172579288482666, "alphanum_fraction": 0.5215724110603333, "avg_line_length": 30.606060028076172, "blob_id": "94c190048f4fdfd605bb2a6d13b078dd9702f902", "content_id": "9675ce328743c6ce637880a2618d84f175683c53", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2086, "license_type": "permissive", "max_line_length": 108, "num_lines": 66, "path": "/source/code/providers/support/diskprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n * \n * */\n /**\n \\file diskprovider.cpp\n\n \\brief Disk provider implementation\n\n \\date 03-21-13 \n*/\n/*----------------------------------------------------------------------------*/\n\n#include \"diskprovider.h\"\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXCore\n{\n void DiskProvider::Load()\n {\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.diskprovider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"DiskProvider::Load\");\n\n // Set up the dependencies;\n m_staticPhysicaldeps = new DiskDependDefault();\n m_statisticalPhysicsdeps = new DiskDependDefault();\n\n // Create the enumeration objects\n m_statisticalPhysicalDisks = new StatisticalPhysicalDiskEnumeration(m_statisticalPhysicsdeps);\n m_statisticalPhysicalDisks->Init();\n\n m_staticPhysicalDisks = new StaticPhysicalDiskEnumeration(m_staticPhysicaldeps);\n m_staticPhysicalDisks->Init();\n }\n }\n\n void DiskProvider::UnLoad()\n {\n SCX_LOGTRACE(m_log, L\"DiskProvider::Unload()\");\n if (0 == --ms_loadCount)\n {\n\n if (m_statisticalPhysicalDisks != NULL)\n {\n m_statisticalPhysicalDisks->CleanUp();\n m_statisticalPhysicalDisks = NULL;\n }\n\n if (m_staticPhysicalDisks != NULL)\n {\n m_staticPhysicalDisks->CleanUp();\n m_staticPhysicalDisks = NULL;\n }\n }\n }\n\n // Only construct DiskProvider class once - installation date/version never changes!\n SCXCore::DiskProvider g_DiskProvider;\n int SCXCore::DiskProvider::ms_loadCount = 0;\n}\n\n /*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5415573120117188, "alphanum_fraction": 0.5651793479919434, "avg_line_length": 33.6363639831543, "blob_id": "abe8db040e3f6b91f2ffa92595c14c77c3d400ec", "content_id": "56789baca194114cc0112e70f167c8f5fa34cf2e", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1143, "license_type": "permissive", "max_line_length": 147, "num_lines": 33, "path": "/source/code/providers/support/scxcimutils.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file scxcimutils.cpp\n\n \\brief SCX CIM Utility Functions\n\n \\date 2013-03-08 08:26:00\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcimutils.h>\n\nnamespace CIMUtils\n{\n bool ConvertToCIMDatetime( MI_Datetime& outDT, SCXCoreLib::SCXCalendarTime& inTime )\n {\n outDT.isTimestamp = true;\n\n outDT.u.timestamp.year = inTime.GetYear();\n outDT.u.timestamp.month = inTime.GetMonth();\n outDT.u.timestamp.day = inTime.GetDay();\n outDT.u.timestamp.hour = inTime.GetHour();\n outDT.u.timestamp.minute = inTime.GetMinute();\n outDT.u.timestamp.second = static_cast<MI_Uint32> (inTime.GetSecond());\n outDT.u.timestamp.microseconds = static_cast<MI_Uint32> ((inTime.GetSecond() - static_cast<double>(outDT.u.timestamp.second)) * 1000000.0);\n outDT.u.timestamp.utc = 0;\n\n return true;\n }\n}\n" }, { "alpha_fraction": 0.5668103694915771, "alphanum_fraction": 0.5732758641242981, "avg_line_length": 29.933332443237305, "blob_id": "56d1f217d8baf82878afdbe79ed7da0d629a869f", "content_id": "369968d15b206031987883f23725c816e137a17a", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2320, "license_type": "permissive", "max_line_length": 102, "num_lines": 75, "path": "/source/code/providers/support/scxcimutils.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file scxcimutils.h\n\n \\brief SCX CIM Utility Functions\n\n \\date 2013-03-08 08:26:00\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef SCXCIMUTILS_H\n#define SCXCIMUTILS_H\n\n#include <scxcorelib/scxcmn.h>\n\n#include <scxcorelib/scxtime.h>\n#include <scxcorelib/stringaid.h>\n\n#include <MI.h>\n\nnamespace CIMUtils\n{\n bool ConvertToCIMDatetime( MI_Datetime& outDT, SCXCoreLib::SCXCalendarTime& inTime );\n}\n\n\n//\n// The providers should have an exception handler wrapping all activity. This\n// helps guarantee that the agent won't crash if there's an unhandled exception.\n// In the Pegasus model, this was done in the base class. Since we don't have\n// that luxury here, we'll have macros to make it easier.\n//\n// PEX = Provider Exception\n//\n// There's an assumption here that, since this is used in the OMI-generated code,\n// \"context\" always exists for posting the result to.\n//\n\n#define SCX_PEX_BEGIN \\\n try\n\n#define SCX_PEX_END(module, log) \\\n catch (const SCXCoreLib::SCXException& e) \\\n { \\\n SCX_LOGWARNING((log), std::wstring(module).append(L\" - \"). \\\n append(e.What()).append(L\" - \").append(e.Where())); \\\n context.Post(MI_RESULT_FAILED); \\\n } \\\n catch (std::exception &e) { \\\n SCX_LOGERROR((log), std::wstring(module).append(L\" - \").append(SCXCoreLib::DumpString(e))); \\\n context.Post(MI_RESULT_FAILED); \\\n } \\\n catch (...) \\\n { \\\n SCX_LOGERROR((log), std::wstring(module).append(L\" - Unknown exception\")); \\\n context.Post(MI_RESULT_FAILED); \\\n }\n\n//\n// Have a little function to make it easy to break into a provider (as a debugging aid)\n//\n// The idea here is that we sleep indefinitely; if you break in with a debugger, then\n// you can set f_break to true and then step through the code.\n//\n\n#define SCX_PROVIDER_WAIT_FOR_ATTACH \\\n { \\\n volatile bool f_break = false; \\\n while ( !f_break ) \\\n sleep(1); \\\n }\n\n#endif // !defined(SCXCIMUTILS_H)\n" }, { "alpha_fraction": 0.6145985126495361, "alphanum_fraction": 0.6919708251953125, "avg_line_length": 44.599998474121094, "blob_id": "eb1cf8351bd127075a4e1166a5a125a49f42eaa6", "content_id": "39e6c6521170f553feb13799770b4adfd62aa8d2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 685, "license_type": "permissive", "max_line_length": 119, "num_lines": 15, "path": "/test/code/shared/testutils/TomcatVersionCheck.sh", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# Replicate output of tomcat file version.sh \n# /bin/bash\necho 'Using CATALINA_BASE: /root/apache-tomcat-8.0.9'\necho 'Usig CATALINA_HOME: /root/apache-tomcat-8.0.9'\necho 'Using CATALINA_TMPDIR: /root/apache-tomcat-8.0.9/temp'\necho 'Using JRE_HOME: /usr'\necho 'Using CLASSPATH: /root/apache-tomcat-8.0.9/bin/bootstrap.jar:/root/apache-tomcat-8.0.9/bin/tomcat-juli.jar'\necho 'Server version: Apache Tomcat/8.0.9'\necho 'Server built: Jun 19 2014 01:54:25'\necho 'Server number: 8.0.9.0'\necho 'OS Name: Linux'\necho 'OS Version: 3.13.0-24-generic'\necho 'Architecture: amd64'\necho 'JVM Version: 1.7.0_55-b14'\necho 'JVM Vendor: Oracle Corporation'\n\n" }, { "alpha_fraction": 0.5507053732872009, "alphanum_fraction": 0.555269718170166, "avg_line_length": 35.29518127441406, "blob_id": "07066b933864a9deb33ce72443a99bd1bad04f99", "content_id": "2bca18f88a6ea62efbba9db78b71c7489f6b4727", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12050, "license_type": "permissive", "max_line_length": 171, "num_lines": 332, "path": "/source/code/providers/support/appserver/tomcatappserverinstance.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file tomcatappserverinstance.cpp\n\n \\brief PAL representation of a Tomcat application server\n\n \\date 11-05-18 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n\n#include <string>\n\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/scxprocess.h>\n#include <util/XElement.h>\n#include <scxsystemlib/scxsysteminfo.h>\n\n#include \"appserverconstants.h\"\n#include \"tomcatappserverinstance.h\"\n\nusing namespace std;\nusing namespace SCXCoreLib;\nusing namespace SCX::Util::Xml;\n\nnamespace SCXSystemLib\n{\n\n /**\n Returns a stream for reading from RELEASE-NOTES text file\n\n \\param[in] filename Name of file to open\n */\n SCXHandle<istream> TomcatAppServerInstancePALDependencies::OpenVersionFile(wstring filename)\n {\n return SCXFile::OpenFstream(filename, ios::in);\n }\n\n /**\n Returns a stream for reading from server.xml\n\n \\param[in] filename Name of file to open\n */\n SCXHandle<istream> TomcatAppServerInstancePALDependencies::OpenXmlServerFile(wstring filename)\n {\n return SCXFile::OpenFstream(filename, ios::in);\n }\n\n\t/**\n Returns a command for running version script\n\n \\param[in] filename Name of file to open\n */\n\twstring TomcatAppServerInstancePALDependencies::GetVersionScriptCommand(SCXCoreLib::SCXFilePath filepath)\n\t{\n\t\tSCXCoreLib::SCXFilePath filename(filepath);\n\t\tfilename.Append(L\"version.sh\");\n\n\t\treturn filename.Get();\n\t}\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor\n\n \\param[in] id Identifier for the appserver (= install path for the appserver configuration)\n \\param[in] homePath Root install path for the application server\n \\param[in] deps Dependency instance to use\n */\n TomcatAppServerInstance::TomcatAppServerInstance(\n wstring id, wstring homePath, SCXHandle<TomcatAppServerInstancePALDependencies> deps) : \n AppServerInstance(id, APP_SERVER_TYPE_TOMCAT), m_deps(deps)\n {\n SCXFilePath installPath;\n SCXFilePath homeFilePath;\n\n installPath.SetDirectory(id);\n SetId(installPath.Get());\n m_diskPath = GetId();\n homeFilePath.SetDirectory(homePath);\n m_homePath = homeFilePath.Get();\n\n SCX_LOGTRACE(m_log, wstring(L\"TomcatAppServerInstance default constructor - \").append(GetId()));\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Destructor\n */\n TomcatAppServerInstance::~TomcatAppServerInstance()\n {\n SCX_LOGTRACE(m_log, wstring(L\"TomcatAppServerInstance destructor - \").append(GetId()));\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Update ports for Tomcat\n\n Load XML file <ConfigPath>/conf/server.xml\n\n Get node /Server/Service/Connector where attribute protocol is HTTP/1.1 and secure is true\n Get attribute named port for HTTPS Port\n Get node /Server/Service/Connector where attribute protocol is HTTP/1.1 and no attribute named secure exist\n Get attribute named port for HTTP Port\n */\n void TomcatAppServerInstance::UpdatePorts()\n {\n const string cDeploymentNodeName(\"deployment\");\n const string cServerNodeName(\"Server\");\n const string cServiceNodeName(\"Service\");\n const string cConnectorNodeName(\"Connector\");\n const string cProtocolAttributeName(\"protocol\");\n const string cSecureAttributeName(\"secure\");\n const string cPortAttributeName(\"port\");\n const string cHTTP11Name(\"HTTP/1.1\");\n\t\tconst string cTomcat8HTTP11Name(\"org.apache.coyote.http11.Http11NioProtocol\");\n const string cTrueName(\"true\");\n\n SCXFilePath filename(m_diskPath);\n\n string xmlcontent;\n filename.Append(L\"/conf/server.xml\");\n\n try {\n SCXHandle<istream> mystream = m_deps->OpenXmlServerFile(filename.Get());\n GetStringFromStream(mystream, xmlcontent);\n\n XElementPtr serverNode;\n XElement::Load(xmlcontent, serverNode);\n if (serverNode->GetName() == cServerNodeName)\n {\n XElementPtr serviceNode;\n\n if (serverNode->GetChild(cServiceNodeName, serviceNode))\n {\n XElementList connectorNodes;\n bool foundHTTPnode = false;\n bool foundHTTPSnode = false;\n\n serviceNode->GetChildren(connectorNodes);\n for (size_t idx = 0; !(foundHTTPnode && foundHTTPSnode) && idx < connectorNodes.size(); ++idx)\n {\n string protocolprop;\n if (connectorNodes[idx]->GetName() == cConnectorNodeName)\n {\n // For Tomcat 5 there is no 'Protocol' specified for the HTTP Connector\n\t\t\t\t\t\t\t// Tomcat 8 uses org.apache.coyote.http11.Http11NioProtocol as the protocol name.\n // we will use the Connectors as they appear in the file.\n bool hasAttribute = connectorNodes[idx]->GetAttributeValue(cProtocolAttributeName, protocolprop);\n\t\t\t\t\t\t\tif ((hasAttribute && (cHTTP11Name == protocolprop)) || \n\t\t\t\t\t\t\t\t(hasAttribute && (cTomcat8HTTP11Name == protocolprop)) ||\n !hasAttribute )\n {\n string secureprop;\n string portprop;\n\n if (connectorNodes[idx]->GetAttributeValue(cPortAttributeName, portprop))\n {\n if (connectorNodes[idx]->GetAttributeValue(cSecureAttributeName, secureprop) && \n cTrueName == secureprop)\n {\n m_httpsPort = StrFromUTF8(portprop);\n foundHTTPSnode = true;\n }\n else\n {\n m_httpPort = StrFromUTF8(portprop);\n foundHTTPnode = true;\n }\n }\n }\n }\n }\n }\n }\n }\n catch (SCXFilePathNotFoundException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"TomcatAppServerInstance::UpdateTomcatPorts() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\n }\n catch (SCXUnauthorizedFileSystemAccessException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"TomcatAppServerInstance::UpdateTomcatPorts() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\n }\n catch (XmlException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"TomcatAppServerInstance::UpdateTomcatPorts() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Update version\n\n Open text file RELEASE-NOTES from the home folder\n Find line that contains the string \"Apache Tomcat Version \" \n Get the rest of the text on that line as the version\n\n\t\tThis file does not exist when installed from package manager\n\t\tIn order to find the version without the RELEASE-NOTES we can use the\n\t\tversion.sh script inside the bin directory\n */\n void TomcatAppServerInstance::UpdateVersion()\n {\n const string cTomcatVersionPrecursor(\"Apache Tomcat Version \");\n\n SCXFilePath filename(m_homePath);\n\t\tSCXFilePath filename2(m_homePath);\n filename.Append(L\"RELEASE-NOTES\");\n\t\tbool tryTomcatVersionScript = false;\n\n try {\n string filecontent;\n SCXHandle<istream> mystream = m_deps->OpenVersionFile(filename.Get());\n bool foundVersion = false;\n\n while (!foundVersion && SCXStream::IsGood(*mystream))\n {\n string tmp;\n getline(*mystream, tmp);\n size_t pos = tmp.find(cTomcatVersionPrecursor);\n if (string::npos != pos)\n {\n foundVersion = true;\n string version = tmp.substr(pos + cTomcatVersionPrecursor.length());\n SetVersion(StrStrip(StrFromUTF8(version), L\" \\t\\n\\r\"));\n }\n }\n }\n catch (SCXFilePathNotFoundException&)\n {\n\t\t\ttryTomcatVersionScript = true;\n }\n catch (SCXUnauthorizedFileSystemAccessException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"TomcatAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\n }\n\t\tif(tryTomcatVersionScript)\n\t\t{\n\t\t\ttry \n\t\t\t{\n\t\t\t\tfilename2.Append(L\"bin/\");\n\n\t\t\t\tstd::istringstream in;\n\t\t\t\tstd::ostringstream out;\n\t\t\t\tstd::ostringstream err;\n\n\t\t\t\t// Get command line from function\n\t\t\t\t// Determine if version.sh exists\n\t\t\t\t// Only use SCProcess::Run If version.sh exists\n\t\t\t\twstring cli = m_deps->GetVersionScriptCommand(filename2);\n\t\t\t\tbool versionScriptFileExists = SCXFile::Exists(cli);\n\t\t\t\t\n\t\t\t\tif(cli.length() && versionScriptFileExists)\n\t\t\t\t{\n\t\t\t\t\tSystemInfo si;\n\t\t\t\t\twstring command = si.GetShellCommand(cli);\n\t\t\t\t\t\n\t\t\t\t\tint exitStatus = SCXCoreLib::SCXProcess::Run(command, in, out, err, 10000);\n\t\t\t\t\tif(exitStatus != 0 || err.str().length())\n\t\t\t\t\t{\n\t\t\t\t\t\twstring werr = SCXCoreLib::StrFromUTF8(err.str());\n\t\t\t\t\t\tSCX_LOGERROR(m_log, wstring(L\"TomcatAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - error in command line: \").append(werr));\n\t\t\t\t\t}\n\t\t\t\t\telse\n\t\t\t\t\t{\n\t\t\t\t\t\twstring commandOutput = SCXCoreLib::StrFromUTF8(out.str());\n\t\t\t\t\t\tvector<wstring> v_version;\n\n\t\t\t\t\t\tSCXRegex re(L\"Server number: (.*).(OS Name)\");\n\t\t\t\t\t\tif(re.ReturnMatch(commandOutput, v_version, 0))\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tSetVersion(v_version[1]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tSCX_LOGERROR(m_log, wstring(L\"No REGEX match\"));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (SCXUnauthorizedFileSystemAccessException&)\n\t\t\t{\n\t\t\t\tSCX_LOGERROR(m_log, wstring(L\"TomcatAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n SCX_LOGERROR(m_log, wstring(L\"TomcatAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\n\t\t}\n\t}\n\n /*----------------------------------------------------------------------------*/\n /**\n Update values\n\n */\n void TomcatAppServerInstance::Update()\n {\n SCX_LOGTRACE(m_log, wstring(L\"TomcatAppServerInstance::Update() - \").append(GetId()));\n\n UpdateVersion();\n UpdatePorts();\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Read all lines from a stream and save in a string\n\n \\param[in] mystream Stream to read from\n \\param[out] content String to return content in\n */\n void TomcatAppServerInstance::GetStringFromStream(SCXHandle<istream> mystream, string& content)\n {\n content = \"\";\n while (SCXStream::IsGood(*mystream))\n {\n string tmp;\n getline(*mystream, tmp);\n content.append(tmp);\n content.append(\"\\n\");\n }\n }\n\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6135392785072327, "alphanum_fraction": 0.616307258605957, "avg_line_length": 35.48752975463867, "blob_id": "ded696418d50b1b93ee5caecf6675c7e5afe3bdb", "content_id": "4492357cf212d82e37e1a399de8552e7724621b1", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 29263, "license_type": "permissive", "max_line_length": 145, "num_lines": 802, "path": "/source/code/providers/SCX_OperatingSystem_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_OperatingSystem_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-22-2013 17:48:44\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_OperatingSystem_Class_Provider.h\"\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/scxmath.h>\n#include <scxcorelib/scxnameresolver.h>\n#include <scxcorelib/scxprocess.h>\n#include <scxcorelib/scxuser.h>\n#include <scxsystemlib/osenumeration.h>\n#include <scxsystemlib/osinstance.h>\n#include <scxsystemlib/memoryenumeration.h>\n#include <scxsystemlib/processenumeration.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <scxsystemlib/scxsysteminfo.h>\n#include <util/Base64Helper.h>\n\n#include \"support/scxcimutils.h\"\n#include \"support/scxrunasconfigurator.h\"\n#include \"support/startuplog.h\"\n#include \"support/osprovider.h\"\n#include \"support/runasprovider.h\"\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nnamespace\n{\n scxlong BytesToKiloBytes(scxulong bytes)\n {\n // This will do - let's just fix the names\n return SCXCoreLib::KiloBytesToMegaBytes(bytes);\n }\n}\n\nMI_BEGIN_NAMESPACE\n\n/**\n Class that represents values passed between the threads for OMI methods\n*/\nclass SCX_OperatingSystem_ThreadParam : public SCXThreadParam\n{\npublic:\n /*----------------------------------------------------------------------------*/\n /**\n Constructor\n\n \\param[in] context Context pointer from OMI server\n */\n SCX_OperatingSystem_ThreadParam(MI_Context* context)\n : SCXThreadParam(), m_context(context)\n {\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Retrieves the context pointer for this thread to use\n\n \\returns Pointer to context for this thread to use\n */\n Context& GetContext()\n {\n return m_context;\n }\n\nprivate:\n Context m_context; //!< Context from OMI server\n};\n\nclass SCX_OperatingSystem_Command_ThreadParam : public SCX_OperatingSystem_ThreadParam\n{\npublic:\n SCX_OperatingSystem_Command_ThreadParam(MI_Context* context, const SCX_OperatingSystem_ExecuteCommand_Class in)\n : SCX_OperatingSystem_ThreadParam(context), m_input(in)\n {}\n const SCX_OperatingSystem_ExecuteCommand_Class& GetInput() { return m_input; }\n\nprivate:\n const SCX_OperatingSystem_ExecuteCommand_Class m_input;\n};\n\nclass SCX_OperatingSystem_ShellCommand_ThreadParam : public SCX_OperatingSystem_ThreadParam\n{\npublic:\n SCX_OperatingSystem_ShellCommand_ThreadParam(MI_Context* context, const SCX_OperatingSystem_ExecuteShellCommand_Class in)\n : SCX_OperatingSystem_ThreadParam(context), m_input(in)\n {}\n const SCX_OperatingSystem_ExecuteShellCommand_Class& GetInput() { return m_input; }\n\nprivate:\n const SCX_OperatingSystem_ExecuteShellCommand_Class m_input;\n};\n\nclass SCX_OperatingSystem_Script_ThreadParam : public SCX_OperatingSystem_ThreadParam\n{\npublic:\n SCX_OperatingSystem_Script_ThreadParam(MI_Context* context, const SCX_OperatingSystem_ExecuteScript_Class in)\n : SCX_OperatingSystem_ThreadParam(context), m_input(in)\n {}\n const SCX_OperatingSystem_ExecuteScript_Class& GetInput() { return m_input; }\n\nprivate:\n const SCX_OperatingSystem_ExecuteScript_Class m_input;\n};\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_OperatingSystem_Class& inst,\n bool keysOnly,\n SCXHandle<OSInstance> osinst,\n SCXHandle<MemoryInstance> meminst)\n{\n // Get some handles\n SCXHandle<SCXOSTypeInfo> osTypeInfo = SCXCore::g_OSProvider.GetOSTypeInfo();\n SCXLogHandle& log = SCXCore::g_OSProvider.GetLogHandle();\n\n SCX_LOGTRACE(log, L\"OSProvider EnumerateOneInstance()\");\n\n // Fill in the keys\n inst.Name_value( StrToMultibyte(osTypeInfo->GetOSName(true)).c_str() );\n inst.CSCreationClassName_value( \"SCX_ComputerSystem\" );\n\n try {\n NameResolver mi;\n inst.CSName_value( StrToMultibyte(mi.GetHostDomainname()).c_str() );\n } catch (SCXException& e) {\n SCX_LOGWARNING(log, StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n inst.CreationClassName_value( \"SCX_OperatingSystem\" );\n\n if ( !keysOnly )\n {\n SCXCalendarTime ASCXCalendarTime;\n scxulong Ascxulong, Ascxulong1;\n unsigned short Aunsignedshort;\n vector<string> Avector;\n vector<unsigned short> Aushortvector;\n wstring Awstring;\n signed short Ashort;\n unsigned int Auint;\n\n /*===================================================================================*/\n /* Defaulted Values (from MOF) */\n /*===================================================================================*/\n\n inst.EnabledDefault_value( 2 );\n inst.EnabledState_value( 5 );\n inst.RequestedState_value( 12 );\n\n /*===================================================================================*/\n /* Properties of CIM_ManagedElement */\n /*===================================================================================*/\n\n inst.Caption_value( StrToMultibyte(osTypeInfo->GetCaption()).c_str() );\n inst.Description_value( StrToMultibyte(osTypeInfo->GetDescription()).c_str() );\n\n /*===================================================================================*/\n /* Properties of CIM_ManagedSystemElement */\n /*===================================================================================*/\n\n // We don't support the following because there's no way to retrieve on any platforms:\n // InstallDate\n // Status\n // OperationalStatus\n // StatusDescriptions\n // HealthState\n\n /*===================================================================================*/\n /* Properties of CIM_OperatingSystem */\n /*===================================================================================*/\n\n // We don't support the following because there's no way to retrieve on any platforms:\n // EnabledState\n // OtherEnabledState\n // RequestedState\n // EnabledDefault\n // TimeOfLastStateChange\n // OverwritePolicy\n // Distributed\n\n /* CSCreationClassName is a key property and thus set in AddKeys */\n /* CSName is a key property and thus set in AddKeys */\n /* CreationClassName is a key property and thus set in AddKeys */\n\n if (osinst->GetOSType(Aunsignedshort))\n inst.OSType_value( Aunsignedshort );\n\n if (osinst->GetOtherTypeDescription(Awstring))\n inst.OtherTypeDescription_value( StrToMultibyte(Awstring).c_str() );\n\n if (osinst->GetVersion(Awstring))\n inst.Version_value( StrToMultibyte(Awstring).c_str() );\n\n if (osinst->GetLastBootUpTime(ASCXCalendarTime))\n {\n MI_Datetime bootTime;\n CIMUtils::ConvertToCIMDatetime( bootTime, ASCXCalendarTime );\n inst.LastBootUpTime_value( bootTime );\n }\n\n if (osinst->GetLocalDateTime(ASCXCalendarTime))\n {\n MI_Datetime localTime;\n CIMUtils::ConvertToCIMDatetime( localTime, ASCXCalendarTime );\n inst.LocalDateTime_value( localTime );\n }\n\n if (osinst->GetCurrentTimeZone(Ashort))\n inst.CurrentTimeZone_value( Ashort );\n\n if (osinst->GetNumberOfLicensedUsers(Auint))\n inst.NumberOfLicensedUsers_value( Auint );\n\n if (osinst->GetNumberOfUsers(Auint))\n inst.NumberOfUsers_value( Auint );\n\n if (ProcessEnumeration::GetNumberOfProcesses(Auint))\n inst.NumberOfProcesses_value( Auint );\n\n if (osinst->GetMaxNumberOfProcesses(Auint))\n inst.MaxNumberOfProcesses_value( Auint );\n\n if (meminst->GetTotalSwap(Ascxulong))\n {\n inst.TotalSwapSpaceSize_value( BytesToKiloBytes(Ascxulong) );\n }\n\n if (meminst->GetTotalPhysicalMemory(Ascxulong) && meminst->GetTotalSwap(Ascxulong1))\n {\n inst.TotalVirtualMemorySize_value( BytesToKiloBytes(Ascxulong) + BytesToKiloBytes(Ascxulong1) );\n }\n\n if (meminst->GetAvailableMemory(Ascxulong))\n {\n Ascxulong = BytesToKiloBytes(Ascxulong);\n\n if (meminst->GetAvailableSwap(Ascxulong1)) {\n inst.FreeVirtualMemory_value( Ascxulong + BytesToKiloBytes(Ascxulong1) );\n }\n\n inst.FreePhysicalMemory_value( Ascxulong );\n }\n\n if (meminst->GetTotalPhysicalMemory(Ascxulong))\n inst.TotalVisibleMemorySize_value( BytesToKiloBytes(Ascxulong) );\n\n if (meminst->GetTotalSwap(Ascxulong))\n inst.SizeStoredInPagingFiles_value( BytesToKiloBytes(Ascxulong) );\n\n if (meminst->GetAvailableSwap(Ascxulong))\n inst.FreeSpaceInPagingFiles_value( BytesToKiloBytes(Ascxulong) );\n\n if (osinst->GetMaxProcessMemorySize(Ascxulong))\n inst.MaxProcessMemorySize_value( Ascxulong );\n\n if (osinst->GetMaxProcessesPerUser(Auint))\n inst.MaxProcessesPerUser_value( Auint );\n\n /*===================================================================================*/\n /* Properties of SCX_OperatingSystem (Taken from PG_OperatingSystem) */\n /*===================================================================================*/\n\n SystemInfo sysInfo;\n if (sysInfo.GetNativeBitSize(Aunsignedshort))\n {\n std::ostringstream bitText;\n bitText << Aunsignedshort << \" bit\";\n\n inst.OperatingSystemCapability_value( bitText.str().c_str() );\n }\n\n if (osinst->GetSystemUpTime(Ascxulong))\n inst.SystemUpTime_value( Ascxulong );\n }\n\n context.Post(inst);\n}\n\nSCX_OperatingSystem_Class_Provider::SCX_OperatingSystem_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_OperatingSystem_Class_Provider::~SCX_OperatingSystem_Class_Provider()\n{\n}\n\nvoid SCX_OperatingSystem_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n SCXThreadLock lock(ThreadLockHandleGet(L\"SCXCore::OSProvider::Lock\"));\n SCXCore::g_OSProvider.Load();\n SCXCore::g_RunAsProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_OSProvider.GetLogHandle(),\n StrAppend(L\"SCX_OperatingSystem_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::Load\", SCXCore::g_OSProvider.GetLogHandle() );\n}\n\nvoid SCX_OperatingSystem_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n SCXThreadLock lock(ThreadLockHandleGet(L\"SCXCore::OSProvider::Lock\"));\n SCXCore::g_OSProvider.Unload();\n SCXCore::g_RunAsProvider.Unload();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::Unload\", SCXCore::g_OSProvider.GetLogHandle() );\n}\n\nvoid SCX_OperatingSystem_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_OSProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"OperatingSystem EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n SCXThreadLock lock(ThreadLockHandleGet(L\"SCXCore::OSProvider::Lock\"));\n\n // Refresh the collection\n SCXHandle<OSEnumeration> osEnum = SCXCore::g_OSProvider.GetOS_Enumerator();\n SCXHandle<MemoryEnumeration> memEnum = SCXCore::g_OSProvider.GetMemory_Enumerator();\n osEnum->Update();\n memEnum->Update();\n\n SCX_OperatingSystem_Class inst;\n EnumerateOneInstance( context, inst, keysOnly, osEnum->GetTotalInstance(), memEnum->GetTotalInstance() );\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"OperatingSystem EnumerateInstances end\");\n}\n\nvoid SCX_OperatingSystem_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n SCXThreadLock lock(ThreadLockHandleGet(L\"SCXCore::OSProvider::Lock\"));\n\n // Was have a 4-part key (on Redhat, it looks like this):\n // [Key] Name=Red Hat Distribution\n // [Key] CSCreationClassName=SCX_ComputerSystem\n // [Key] CSName=jeffcof64-rhel6-01.scx.com\n // [Key] CreationClassName=SCX_OperatingSystem\n // Considered returning our one instance without validation, but that's not following the rules\n //\n // Look up the values of the two non-fixed keys\n\n if (!instanceName.Name_exists() || !instanceName.CSCreationClassName_exists() ||\n !instanceName.CSName_exists() || !instanceName.CreationClassName_exists())\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::string osName = StrToMultibyte(SCXCore::g_OSProvider.GetOSTypeInfo()->GetOSName(true)).c_str();\n std::string csName;\n try {\n NameResolver mi;\n csName = StrToMultibyte(mi.GetHostDomainname()).c_str();\n } catch (SCXException& e) {\n SCX_LOGWARNING(SCXCore::g_OSProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n // Now compare (case insensitive for the class names, case sensitive for the others)\n if ( 0 != strcasecmp(\"SCX_ComputerSystem\", instanceName.CSCreationClassName_value().Str())\n || 0 != strcasecmp(\"SCX_OperatingSystem\", instanceName.CreationClassName_value().Str())\n || 0 != strcmp(osName.c_str(), instanceName.Name_value().Str())\n || 0 != strcmp(csName.c_str(), instanceName.CSName_value().Str()))\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n //\n // We have a match, so return the instance\n //\n\n // Refresh the collection\n SCXHandle<OSEnumeration> osEnum = SCXCore::g_OSProvider.GetOS_Enumerator();\n SCXHandle<MemoryEnumeration> memEnum = SCXCore::g_OSProvider.GetMemory_Enumerator();\n osEnum->Update();\n memEnum->Update();\n\n SCX_OperatingSystem_Class inst;\n EnumerateOneInstance( context, inst, false, osEnum->GetTotalInstance(), memEnum->GetTotalInstance() );\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::GetInstance\", SCXCore::g_OSProvider.GetLogHandle() );\n}\n\nvoid SCX_OperatingSystem_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_OperatingSystem_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_OperatingSystem_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_OperatingSystem_Class_Provider::Invoke_RequestStateChange(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_RequestStateChange_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_OperatingSystem_Class_Provider::Invoke_Reboot(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_Reboot_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_OperatingSystem_Class_Provider::Invoke_Shutdown(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_Shutdown_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nstatic void Invoke_ExecuteCommand_ThreadBody(SCXCoreLib::SCXThreadParamHandle& param)\n{\n if (param == 0)\n {\n SCXASSERT( ! \"No parameters to Invoke_ExecuteCommand_ThreadBody\");\n return;\n }\n\n SCX_OperatingSystem_Command_ThreadParam* params = static_cast<SCX_OperatingSystem_Command_ThreadParam*> (param.GetData());\n if (params == 0)\n {\n SCXASSERT( ! \"Invalid parameters to Invoke_ExecuteCommand_ThreadBody\");\n return;\n }\n\n SCXCoreLib::SCXLogHandle log = SCXCore::g_RunAsProvider.GetLogHandle();\n Context& context = params->GetContext();\n const SCX_OperatingSystem_ExecuteCommand_Class& in = params->GetInput();\n\n SCX_PEX_BEGIN\n {\n // We specifically do not lock here; we want multiple instances to run\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteCommand\" )\n\n // Parameters (from MOF file):\n // [IN] string Command, \n // [OUT] sint32 ReturnCode, \n // [OUT] string StdOut, \n // [OUT] string StdErr, \n // [IN] uint32 timeout,\n // [IN] string ElevationType (optional)\n\n // Validate that we have mandatory arguments\n if ( !in.Command_exists() || 0 == strlen(in.Command_value().Str()) || !in.timeout_exists() )\n {\n SCX_LOGTRACE( log, L\"Missing arguments to Invoke_ExecuteCommand method\" );\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::wstring command = StrFromMultibyte( in.Command_value().Str() );\n std::wstring return_out, return_err;\n\n std::wstring elevation = L\"\";\n if ( in.ElevationType_exists() )\n {\n elevation = StrToLower( StrFromMultibyte(in.ElevationType_value().Str()) );\n\n if (elevation != L\"sudo\" && elevation != L\"\")\n {\n SCX_LOGTRACE( log, L\"Wrong elevation type \" + elevation);\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n }\n\n std::wstring returnOut, returnErr;\n int returnCode;\n bool cmdok;\n\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteCommand - Executing command: \" + command);\n cmdok = SCXCore::g_RunAsProvider.ExecuteCommand(command, returnOut, returnErr, returnCode, in.timeout_value(), elevation);\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteCommand - Finished executing: \" + command);\n\n // Pass the results back up the chain\n\n SCX_OperatingSystem_ExecuteCommand_Class inst;\n\n inst.ReturnCode_value( returnCode );\n inst.StdOut_value( StrToMultibyte(returnOut).c_str() );\n inst.StdErr_value( StrToMultibyte(returnErr).c_str() );\n inst.MIReturn_value( cmdok );\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n } \n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteCommand\", log );\n}\n\nvoid SCX_OperatingSystem_Class_Provider::Invoke_ExecuteCommand(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_ExecuteCommand_Class& in)\n{\n SCXCoreLib::SCXLogHandle log = SCXCore::g_RunAsProvider.GetLogHandle();\n\n SCX_PEX_BEGIN\n {\n SCX_OperatingSystem_Command_ThreadParam* params = new SCX_OperatingSystem_Command_ThreadParam(context.context(), in);\n SCXCoreLib::SCXThread(Invoke_ExecuteCommand_ThreadBody, params);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteCommand\", log );\n}\n\nstatic void Invoke_ExecuteShellCommand_ThreadBody(SCXCoreLib::SCXThreadParamHandle& param)\n{\n if (param == 0)\n {\n SCXASSERT( ! \"No parameters to Invoke_ExecuteShellCommand_ThreadBody\");\n return;\n }\n\n SCX_OperatingSystem_ShellCommand_ThreadParam* params = static_cast<SCX_OperatingSystem_ShellCommand_ThreadParam*> (param.GetData());\n if (params == 0)\n {\n SCXASSERT( ! \"Invalid parameters to Invoke_ExecuteShellCommand_ThreadBody\");\n return;\n }\n\n SCXCoreLib::SCXLogHandle log = SCXCore::g_RunAsProvider.GetLogHandle();\n Context& context = params->GetContext();\n const SCX_OperatingSystem_ExecuteShellCommand_Class& in = params->GetInput();\n\n SCX_PEX_BEGIN\n {\n // We specifically do not lock here; we want multiple instances to run\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteShellCommand\" )\n\n // Parameters (from MOF file):\n // [IN] string Command, \n // [OUT] sint32 ReturnCode, \n // [OUT] string StdOut, \n // [OUT] string StdErr, \n // [IN] uint32 timeout,\n // [IN] string ElevationType (optional)\n // [IN] boolean b64encoded (optional)\n\n // Validate that we have mandatory arguments\n if ( !in.Command_exists() || 0 == strlen(in.Command_value().Str()) || !in.timeout_exists() )\n {\n SCX_LOGTRACE( log, L\"Missing arguments to Invoke_ExecuteShellCommand method\" );\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::string commandNarrow = in.Command_value().Str();\n\n std::wstring elevation = L\"\";\n if ( in.ElevationType_exists() )\n {\n elevation = StrToLower( StrFromMultibyte(in.ElevationType_value().Str()) );\n\n if (elevation != L\"sudo\" && elevation != L\"\")\n {\n SCX_LOGTRACE( log, L\"Wrong elevation type \" + elevation);\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n }\n\n // If we need to decode a Base64-encoded string, do so\n if ( in.b64encoded_exists() && in.b64encoded_value() )\n {\n bool result = util::Base64Helper::Decode(commandNarrow, commandNarrow);\n if ( ! result )\n {\n // Base64 conversion error - return failure\n context.Post(MI_RESULT_FAILED);\n return;\n }\n }\n\n std::wstring command = StrFromMultibyte( commandNarrow );\n std::wstring returnOut, returnErr;\n int returnCode;\n bool cmdok;\n\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteShellCommand - Executing command: \" + command);\n cmdok = SCXCore::g_RunAsProvider.ExecuteShellCommand(command, returnOut, returnErr, returnCode, in.timeout_value(), elevation);\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteShellCommand - Finished executing: \" + command);\n\n // Pass the results back up the chain\n\n SCX_OperatingSystem_ExecuteShellCommand_Class inst;\n\n inst.ReturnCode_value( returnCode );\n inst.StdOut_value( StrToMultibyte(returnOut).c_str() );\n inst.StdErr_value( StrToMultibyte(returnErr).c_str() );\n inst.MIReturn_value( cmdok );\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteShellCommand\", log );\n}\n\nvoid SCX_OperatingSystem_Class_Provider::Invoke_ExecuteShellCommand(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_ExecuteShellCommand_Class& in)\n{\n SCX_PEX_BEGIN\n {\n SCX_OperatingSystem_ShellCommand_ThreadParam* params = new SCX_OperatingSystem_ShellCommand_ThreadParam(context.context(), in);\n SCXCoreLib::SCXThread(Invoke_ExecuteShellCommand_ThreadBody, params);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteShellCommand\", SCXCore::g_RunAsProvider.GetLogHandle() );\n}\n\nstatic void Invoke_ExecuteScript_ThreadBody(SCXCoreLib::SCXThreadParamHandle& param)\n{\n if (param == 0)\n {\n SCXASSERT( ! \"No parameters to Invoke_ExecuteScript_ThreadBody\");\n return;\n }\n\n SCX_OperatingSystem_Script_ThreadParam* params = static_cast<SCX_OperatingSystem_Script_ThreadParam*> (param.GetData());\n if (params == 0)\n {\n SCXASSERT( ! \"Invalid parameters to Invoke_ExecuteScript_ThreadBody\");\n return;\n }\n\n SCXCoreLib::SCXLogHandle log = SCXCore::g_RunAsProvider.GetLogHandle();\n Context& context = params->GetContext();\n const SCX_OperatingSystem_ExecuteScript_Class& in = params->GetInput();\n\n SCX_PEX_BEGIN\n {\n // We specifically do not lock here; we want multiple instances to run\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteScript\" )\n\n // Parameters (from MOF file):\n // [IN] string Script, \n // [IN] string Arguments, \n // [OUT] sint32 ReturnCode, \n // [OUT] string StdOut, \n // [OUT] string StdErr, \n // [IN] uint32 timeout, \n // [IN] string ElevationType (optional)\n // [in] string b64encoded (optional)\n\n // Validate that we have mandatory arguments\n if ( !in.Script_exists() || 0 == strlen(in.Script_value().Str())\n || !in.Arguments_exists() || !in.timeout_exists() )\n {\n SCX_LOGTRACE( log, L\"Missing arguments to Invoke_ExecuteScript method\" );\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::wstring elevation = L\"\";\n if ( in.ElevationType_exists() )\n {\n elevation = StrToLower( StrFromMultibyte(in.ElevationType_value().Str()) );\n\n if (elevation != L\"sudo\" && elevation != L\"\")\n {\n SCX_LOGTRACE( log, L\"Wrong elevation type \" + elevation);\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n }\n\n std::string strScriptNarrow = in.Script_value().Str();\n std::wstring strArgs = StrFromMultibyte(in.Arguments_value().Str());\n std::wstring returnOut, returnErr;\n int returnCode;\n\n // If we need to decode a Base64-encoded script, do so (just the script, not the arguments)\n if ( in.b64encoded_exists() && in.b64encoded_value() )\n {\n bool result = util::Base64Helper::Decode(strScriptNarrow, strScriptNarrow);\n if ( ! result )\n {\n // Base64 conversion error - return failure\n context.Post(MI_RESULT_FAILED);\n return;\n }\n }\n\n std::wstring strScript = StrFromMultibyte( strScriptNarrow );\n\n // Historically, sometimes WSman/Pegasus removed '\\r' characters, sometimes not.\n // (Depended on the product.) Do so here to play it safe.\n\n std::wstring::size_type pos_slash_r = strScript.find( '\\r' );\n\n while ( std::wstring::npos != pos_slash_r ){\n strScript.erase( pos_slash_r, 1 );\n pos_slash_r = strScript.find( '\\r' );\n }\n\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteScript - Executing script: \" + strScript);\n bool cmdok = SCXCore::g_RunAsProvider.ExecuteScript(strScript, strArgs, returnOut, returnErr, returnCode, in.timeout_value(), elevation);\n SCX_LOGTRACE( log, L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteScript - Finshed executing: \" + strScript);\n\n SCX_OperatingSystem_ExecuteScript_Class inst;\n\n inst.ReturnCode_value( returnCode );\n inst.StdOut_value( StrToMultibyte(returnOut).c_str() );\n inst.StdErr_value( StrToMultibyte(returnErr).c_str() );\n inst.MIReturn_value( cmdok );\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteScript\", log );\n}\n\nvoid SCX_OperatingSystem_Class_Provider::Invoke_ExecuteScript(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_ExecuteScript_Class& in)\n{\n SCXCoreLib::SCXLogHandle log = SCXCore::g_RunAsProvider.GetLogHandle();\n\n SCX_PEX_BEGIN\n {\n SCX_OperatingSystem_Script_ThreadParam* params = new SCX_OperatingSystem_Script_ThreadParam(context.context(), in);\n SCXCoreLib::SCXThread(Invoke_ExecuteScript_ThreadBody, params);\n }\n SCX_PEX_END( L\"SCX_OperatingSystem_Class_Provider::Invoke_ExecuteScript\", log );\n}\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.599581778049469, "alphanum_fraction": 0.6010754704475403, "avg_line_length": 30.778480529785156, "blob_id": "2d6c64b1285a613de4878475b34a5f49f99840f6", "content_id": "be0a1726c535eb9b42e0cec6f1c68dba8251991c", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10042, "license_type": "permissive", "max_line_length": 138, "num_lines": 316, "path": "/source/code/providers/SCX_Agent_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_Agent_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-13-2013 13:27:47\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_Agent_Class_Provider.h\"\n\n#include <scxcorelib/scxcmn.h>\n\n#include <scxcorelib/scxnameresolver.h>\n#include <scxcorelib/stringaid.h>\n#include <scxsystemlib/cpuenumeration.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <scxsystemlib/scxsysteminfo.h>\n\n#include \"support/metaprovider.h\"\n#include \"support/scxcimutils.h\"\n\n#include \"buildversion.h\"\n\n#include <errno.h>\n#include <sstream>\n#include <iostream>\n\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\nusing namespace std;\n\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_Agent_Class& inst,\n bool keysOnly)\n{\n // Fill in the key\n inst.Name_value(\"scx\");\n\n if ( !keysOnly )\n {\n inst.Caption_value(\"SCX Agent meta-information\");\n\n //\n // Populate properties regarding the agent's build number\n // \n stringstream ss;\n\n ss << SCX_BUILDVERSION_MAJOR << \".\" << SCX_BUILDVERSION_MINOR << \".\" << SCX_BUILDVERSION_PATCH << \"-\" << SCX_BUILDVERSION_BUILDNR;\n\n inst.VersionString_value( ss.str().c_str() );\n inst.MajorVersion_value( static_cast<unsigned short>(SCX_BUILDVERSION_MAJOR) );\n inst.MinorVersion_value( static_cast<unsigned short>(SCX_BUILDVERSION_MINOR) );\n inst.RevisionNumber_value( static_cast<unsigned short>(SCX_BUILDVERSION_PATCH) );\n inst.BuildNumber_value( static_cast<unsigned short>(SCX_BUILDVERSION_BUILDNR) );\n\n string strDesc;\n strDesc = StrToMultibyte(StrAppend(StrAppend(SCX_BUILDVERSION_STATUS, L\" - \"), SCX_BUILDVERSION_DATE));\n inst.Description_value( strDesc.c_str() );\n\n string installVersion;\n MI_Datetime installTime;\n if ( SCXCore::g_MetaProvider.GetInstallInfoData(installVersion, installTime) )\n {\n inst.KitVersionString_value( installVersion.c_str() );\n // provide standard property as \"date-time\"\n inst.InstallDate_value( installTime );\n }\n\n // \n // Populate the build date - the value is looked up by constructor\n //\n string buildTime;\n if ( SCXCore::g_MetaProvider.GetBuildTime(buildTime) )\n {\n inst.BuildDate_value( buildTime.c_str() );\n }\n\n // \n // Populate the hostname date - the value is cached internally in the MachnieInfo code.\n //\n try {\n NameResolver mi;\n inst.Hostname_value( StrToMultibyte(mi.GetHostDomainname()).c_str() );\n } catch (SCXException& e) {\n SCX_LOGWARNING( SCXCore::g_MetaProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n\n // \n // Populate name, version and alias for the OS \n //\n\n // Keep an instance of class with static information about OS type\n static SCXSystemLib::SCXOSTypeInfo osTypeInfo;\n inst.OSName_value( StrToMultibyte(osTypeInfo.GetOSName()).c_str() );\n inst.OSVersion_value( StrToMultibyte(osTypeInfo.GetOSVersion()).c_str() );\n inst.OSAlias_value( StrToMultibyte(osTypeInfo.GetOSAlias()).c_str() );\n inst.OSType_value( StrToMultibyte(osTypeInfo.GetOSFamilyString()).c_str() );\n inst.Architecture_value( StrToMultibyte(osTypeInfo.GetArchitectureString()).c_str() );\n\n // \n // This property contains the architecture as uname reports it\n // \n inst.UnameArchitecture_value( StrToMultibyte(osTypeInfo.GetUnameArchitectureString()).c_str() );\n\n // \n // Set property indicating what the lowest log level currently in effect for \n // the agent is\n // \n inst.MinActiveLogSeverityThreshold_value(\n StrToMultibyte(SCXCoreLib::SCXLogHandleFactory::GetLogConfigurator()->GetMinActiveSeverityThreshold()).c_str() );\n\n //\n // Populate the type of machine this is (Physical, Virtual, or Unknown)\n //\n try {\n SystemInfo sysInfo;\n\n eVmType vmType;\n sysInfo.GetVirtualMachineState(vmType);\n\n string vmText;\n switch (vmType)\n {\n case eVmDetected:\n vmText = \"Virtual\";\n break;\n\n case eVmNotDetected:\n vmText = \"Physical\";\n break;\n\n case eVmUnknown:\n default:\n vmText = \"Unknown\";\n break;\n }\n\n inst.MachineType_value( vmText.c_str() );\n } catch (SCXException& e) {\n SCX_LOGWARNING(SCXCore::g_MetaProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read virtual machine state because \", e.What()),\n e.Where()));\n }\n\n //\n // Populate the number of physical and logical processors\n //\n try {\n scxulong count;\n if (SCXSystemLib::CPUEnumeration::GetProcessorCountPhysical(count, SCXCore::g_MetaProvider.GetLogHandle()))\n {\n inst.PhysicalProcessors_value(count);\n }\n } catch (SCXException& e) {\n SCX_LOGWARNING(SCXCore::g_MetaProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read physical processor count because \", e.What()),\n e.Where()));\n }\n\n try {\n scxulong count;\n if (SCXSystemLib::CPUEnumeration::GetProcessorCountLogical(count))\n {\n inst.LogicalProcessors_value(count);\n }\n } catch (SCXException& e) {\n SCX_LOGWARNING(SCXCore::g_MetaProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read logical processor count because \", e.What()),\n e.Where()));\n }\n }\n\n context.Post(inst);\n}\n\nSCX_Agent_Class_Provider::SCX_Agent_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_Agent_Class_Provider::~SCX_Agent_Class_Provider()\n{\n}\n\nvoid SCX_Agent_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for MetaProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::MetaProvider::Lock\"));\n SCXCore::g_MetaProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_MetaProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_Agent_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Agent_Class_Provider::Load\", SCXCore::g_MetaProvider.GetLogHandle() );\n}\n\nvoid SCX_Agent_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for MetaProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::MetaProvider::Lock\"));\n SCXCore::g_MetaProvider.Unload();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Agent_Class_Provider::Unload\", SCXCore::g_MetaProvider.GetLogHandle() );\n}\n\nvoid SCX_Agent_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_MetaProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"MetaProvider EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for MetaProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::MetaProvider::Lock\"));\n\n SCX_Agent_Class inst;\n EnumerateOneInstance( context, inst, keysOnly );\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Agent_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"MetaProvider EnumerateInstances end\");\n}\n\nvoid SCX_Agent_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_Agent_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for MetaProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::MetaProvider::Lock\"));\n\n // SCX_Agent has one fixed key: Name=scx\n if ( !instanceName.Name_exists() )\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n if (0 != strcasecmp(\"scx\", instanceName.Name_value().Str()))\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCX_Agent_Class inst;\n EnumerateOneInstance( context, inst, false );\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_Agent_Class_Provider::GetInstance\", SCXCore::g_MetaProvider.GetLogHandle() );\n}\n\nvoid SCX_Agent_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_Agent_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_Agent_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_Agent_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_Agent_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_Agent_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.4188311696052551, "alphanum_fraction": 0.4232954680919647, "avg_line_length": 24.38144302368164, "blob_id": "5f394dd70ed2be8595887b2a64eb702182faf503", "content_id": "26f16a4062c00d540f6d1413a04e354a47172cb2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2464, "license_type": "permissive", "max_line_length": 108, "num_lines": 97, "path": "/source/code/providers/support/osprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file osprovider.cpp\n\n \\brief OS provider implementation\n\n \\date 04-26-13 \n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxsystemlib/osenumeration.h>\n#include \"startuplog.h\"\n#include \"osprovider.h\"\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nnamespace SCXCore\n{\n //\n // OS Provider Implementation\n //\n\n /*----------------------------------------------------------------------------*/\n /**\n Default constructor\n */\n OSProvider::OSProvider() :\n m_osEnum(NULL),\n m_memEnum(NULL),\n m_OSTypeInfo(NULL)\n {\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Destructor\n */\n OSProvider::~OSProvider()\n {\n }\n\n void OSProvider::Load()\n {\n SCXASSERT( ms_loadCount >= 0 );\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.osprovider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"OSProvider::Load()\");\n\n // Operating system provider\n SCXASSERT( NULL == m_osEnum );\n m_osEnum = new OSEnumeration();\n m_osEnum->Init();\n\n // We need the memory provider for some stuff as well\n SCXASSERT( NULL == m_memEnum );\n m_memEnum = new MemoryEnumeration();\n m_memEnum->Init();\n\n // And OS type information\n SCXASSERT( NULL == m_OSTypeInfo );\n m_OSTypeInfo = new SCXOSTypeInfo();\n }\n }\n\n void OSProvider::Unload()\n {\n SCX_LOGTRACE(m_log, L\"OSProvider::Unload()\");\n\n SCXASSERT( ms_loadCount >= 1 );\n if (0 == --ms_loadCount)\n {\n if (m_osEnum != NULL)\n {\n m_osEnum->CleanUp();\n m_osEnum = NULL;\n }\n\n if (m_memEnum != NULL)\n {\n m_memEnum->CleanUp();\n m_memEnum = NULL;\n }\n\n m_OSTypeInfo = NULL;\n }\n }\n\n int OSProvider::ms_loadCount = 0;\n OSProvider g_OSProvider;\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n \n" }, { "alpha_fraction": 0.6366522908210754, "alphanum_fraction": 0.6398271322250366, "avg_line_length": 38.50870895385742, "blob_id": "bed61e9b9b7e1cb200e95c382cac68b1a4fdd76a", "content_id": "dc97064281297b7a2f589fc049302780a8199e6d", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 11339, "license_type": "permissive", "max_line_length": 205, "num_lines": 287, "path": "/build/Makefile.tests", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n# \n# Definition of all unit tests for SCXCore \n#\n#--------------------------------------------------------------------------------\n\n\n#--------------------------------------------------------------------------------\n# Support for Quantify from Rational Software (IBM now)\n\nifeq ($(BUILD_PROFILING),quantify)\n\tPROFILING=quantify\nelse\n\tPROFILING=\nendif\n\n\n#--------------------------------------------------------------------------------\n# Support for BullseyeCoverage from Bullseye Testing Technology \n# Note: this was also done in the Makefile.Pegasus - do in OMI build? - TODO\nifeq ($(BUILD_TYPE),Bullseye)\n\tBULLSEYE_LINK=-L/opt/Bullseye/lib -lcov\n\tCOVFILE=$(SCXPAL_INTERMEDIATE_DIR)/OpsMgr.cov\n\tPROFILING=COVFILE=$(COVFILE) covc --retain\n\texport COVFILE\nelse\n\tBULLSEYE_LINK=\n\tCOVFILE=\n\tPROFILING=\nendif\n\n#--------------------------------------------------------------------------------\n# Testrunner\n\nTESTRUNNER_SRCFILES = \\\n\t$(SCX_SHARED_TEST_ROOT)/testutils/testrunner.cpp \\\n\t$(SCX_SHARED_TEST_ROOT)/testutils/scxassert_cppunit.cpp \\\n\t$(SCX_SHARED_TEST_ROOT)/testutils/testrunnerlogpolicy.cpp \n\nTESTRUNNER_OBJFILES = $(call src_to_obj,$(TESTRUNNER_SRCFILES))\n# Extra include dir for test code\n$(INTERMEDIATE_DIR)/testrunner: INCLUDES += $(UNITTEST_EXTRA_INCLUDES)\n$(INTERMEDIATE_DIR)/testrunner_core: INCLUDES += $(UNITTEST_EXTRA_INCLUDES)\n\n\n#--------------------------------------------------------------------------------\n# Includes for tests\ninclude $(SCX_BRD)/build/Makefile.providerstests\ninclude $(SCX_BRD)/build/Makefile.scxadmintests\ninclude $(SCX_BRD)/build/Makefile.sslconfigtests\n\n#--------------------------------------------------------------------------------\n# All tests\nPOSIX_UNITTESTS_SRCFILES = \\\n\t$(POSIX_UNITTESTS_CORE_SRCFILES) \\\n\t$(POSIX_UNITTESTS_SYSTEM_SRCFILES) \\\n\t$(POSIX_UNITTESTS_SSLCONFIG_SRCFILES) \\\n\t$(POSIX_UNITTESTS_SCXADMIN_SRCFILES)\n\nPOSIX_UNITTESTS_PROVIDERS_OBJFILES = $(call src_to_obj,$(POSIX_UNITTESTS_PROVIDERS_SRCFILES))\nPOSIX_UNITTESTS_OBJFILES = $(call src_to_obj,$(POSIX_UNITTESTS_SRCFILES)) $(POSIX_UNITTESTS_PROVIDERS_OBJFILES)\nPOSIX_UNITTESTS_CORE_OBJFILES = $(call src_to_obj,$(POSIX_UNITTESTS_CORE_SRCFILES))\n\n\n# Extra include dir for test code\n$(INTERMEDIATE_DIR)/test/code/%.d: INCLUDES += $(UNITTEST_EXTRA_INCLUDES) -I$(PROVIDER_DIR)\n$(INTERMEDIATE_DIR)/test/code/%.$(PF_OBJ_FILE_SUFFIX): INCLUDES += $(UNITTEST_EXTRA_INCLUDES) -I$(PROVIDER_DIR)\n\n# Extra include dir for test code\n$(INTERMEDIATE_DIR)/test/%.d: INCLUDES += $(UNITTEST_EXTRA_INCLUDES) -I$(PROVIDER_DIR)\n$(INTERMEDIATE_DIR)/test/%.$(PF_OBJ_FILE_SUFFIX): INCLUDES += $(UNITTEST_EXTRA_INCLUDES) -I$(PROVIDER_DIR)\n\n#--------------------------------------------------------------------------------\n# Static dependencies on POSIX platforms\n\nPOSIX_UNITTESTS_CORE_STATICLIB_DEPS = \\\n\tpalsystem \\\n\tscxcore \\\n\tUtil\n\n# OM build (all components)\n\nLOGFILEREADER_TOOL=logfilereader-tool\nLOGFILEREADER_EXE=scxlogfilereader\n\nPOSIX_UNITTESTS_STATICLIB_DEPS = \\\n\tscxadmin \\\n\tscxsslconfig \\\n\tomprovider\n\nifeq (1,0)\n\tmetaprovider \\\n\tprovidersupport\n\nifneq ($(SCX_STACK_ONLY),true)\nPOSIX_UNITTESTS_STATICLIB_DEPS += \\\n\tcpuprovider \\\n\tmemoryprovider \\\n\trunasprovider \\\n\tprocessprovider \\\n\tdiskprovider \\\n\tnetworkprovider \\\n\tlogfileprovider \\\n\tasprovider \\\n\tosprovider\nendif\nendif # ifeq (1,0)\n\n# Foreach XYZ in the list above, build $(INTERMEDIATE_DIR)/libXYZ.a\nPOSIX_UNITTESTS_STATICLIB_DEPFILES = $(addprefix $(INTERMEDIATE_DIR)/lib, $(addsuffix .$(PF_STAT_LIB_FILE_SUFFIX), $(POSIX_UNITTESTS_STATICLIB_DEPS)))\n\nPOSIX_UNITTESTS_CORE_STATICLIB_DEPFILES = \\\n\t$(addprefix $(SCXPAL_TARGET_DIR)/lib, $(addsuffix .$(PF_STAT_LIB_FILE_SUFFIX), $(POSIX_UNITTESTS_CORE_STATICLIB_DEPS))) \\\n\t$(STATIC_PRODUCTDEPENDENCIES_DEPFILES)\n\n# Foreach XYZ in the list above, build -lXYZ\nPOSIX_UNITTESTS_LINK_STATICLIBS = $(addprefix -l, $(POSIX_UNITTESTS_STATICLIB_DEPS))\nPOSIX_UNITTESTS_CORE_LINK_STATICLIBS = \\\n\t$(addprefix -l, $(POSIX_UNITTESTS_CORE_STATICLIB_DEPS)) \\\n\t-lProductDependencies \\\n\t-lmicxx \\\n\t-lbase \\\n\t-lpal\n\n#--------------------------------------------------------------------------------\n# Check if user has requested a subset of the unit tests only \nifneq ($(UNITTESTS_SUBSET),)\nUNITTESTS_OBJFILES = $(TESTRUNNER_OBJFILES) $(call src_to_obj,$(UNITTESTS_SUBSET))\nUNITTESTS_CORE_OBJFILES = $(TESTRUNNER_OBJFILES) $(call src_to_obj,$(UNITTESTS_SUBSET))\nelse\nUNITTESTS_OBJFILES = $(TESTRUNNER_OBJFILES) $(POSIX_UNITTESTS_OBJFILES) \nUNITTESTS_CORE_OBJFILES = $(TESTRUNNER_OBJFILES) $(POSIX_UNITTESTS_CORE_OBJFILES) \nendif\n\n\n#--------------------------------------------------------------------------------\n# This is a small tool for usage in the testrunner\nCLOSEFILEDESCRIPTOR_SRCFILES = $(SCX_SHARED_TEST_ROOT)/testutils/closefiledescriptors/closefiledescriptors.cpp\nCLOSEFILEDESCRIPTOR_OBJFILES = $(call src_to_obj,$(CLOSEFILEDESCRIPTOR_SRCFILES))\n\n$(INTERMEDIATE_DIR)/closefiledescriptors : $(CLOSEFILEDESCRIPTOR_OBJFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)\n\t$(PROFILING) $(LINK) $(LINK_OUTFLAG) $(CLOSEFILEDESCRIPTOR_OBJFILES)\n\n#--------------------------------------------------------------------------------\n# The tool itself\ntestrunner-status:\n\t$(ECHO) \"========================= Performing make OM testrunner\"\n\n$(INTERMEDIATE_DIR)/testrunner : testrunner-status $(UNITTESTS_OBJFILES) $(POSIX_UNITTESTS_STATICLIB_DEPFILES) $(POSIX_UNITTESTS_CORE_STATICLIB_DEPFILES)\n\t$(MAKE) -s ccenable\n\t-$(MKPATH) $(INTERMEDIATE_DIR)\n\t$(LINK) $(LINK_OUTFLAG) $(UNITTESTS_OBJFILES) $(CPPUNIT_LIB_PATH)/libcppunit.a $(POSIX_UNITTESTS_LINK_STATICLIBS) $(POSIX_UNITTESTS_CORE_LINK_STATICLIBS) $(BULLSEYE_LINK) $(LDFLAGS_TESTRUNNER) $(SSL_LIBS)\n\t$(MAKE) -s ccdisable\n\ntestbuild : $(INTERMEDIATE_DIR)/testrunner\n\n\n# The tool itself\n$(INTERMEDIATE_DIR)/testrunner_core : testrunner-status $(UNITTESTS_CORE_OBJFILES) $(POSIX_UNITTESTS_CORE_STATICLIB_DEPFILES) \n\t-$(MKPATH) $(INTERMEDIATE_DIR)\n\t$(PROFILING) $(LINK) $(LINK_OUTFLAG) $(UNITTESTS_CORE_OBJFILES) $(CPPUNIT_LIB_PATH)/libcppunit.a $(POSIX_UNITTESTS_CORE_LINK_STATICLIBS) $(LDFLAGS_TESTRUNNER)\n\ntestbuild_core : $(INTERMEDIATE_DIR)/testrunner_core\n\ntestrun_copy : $(INTERMEDIATE_DIR)/closefiledescriptors\n\t$(ECHO) \"========================= Performing make testrun_copy OM\"\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/testfiles\n\t$(COPY) $(SCX_SHARED_TEST_ROOT)/testutils/report.xsl $(INTERMEDIATE_DIR)\n\t$(COPY) $(SCX_SHARED_TEST_ROOT)/testutils/createEnv.sh $(INTERMEDIATE_DIR)/testfiles/\n\t$(COPY) $(SCX_SHARED_TEST_ROOT)/testutils/TomcatVersionCheck.sh $(INTERMEDIATE_DIR)/testfiles/\n\t$(COPY) $(SCX_SHARED_TEST_ROOT)/testutils/testrun_wrapper $(INTERMEDIATE_DIR)/testfiles/\n\t$(COPY) $(SCX_UNITTEST_ROOT)/providers/logfile_provider/scxlogfilereader-test $(INTERMEDIATE_DIR)/testfiles/\n\tchmod u+w $(INTERMEDIATE_DIR)/report.xsl\n\tchmod u+wx $(INTERMEDIATE_DIR)/testfiles/createEnv.sh\n\tchmod u+wx $(INTERMEDIATE_DIR)/testfiles/TomcatVersionCheck.sh\n\tchmod u+wx $(INTERMEDIATE_DIR)/testfiles/testrun_wrapper\n\tchmod u+wx $(INTERMEDIATE_DIR)/testfiles/scxlogfilereader-test\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/testfiles/websphere_networkdeployment/profiles/profile1/configuration\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/testfiles/websphere_networkdeployment/profiles/profile1/servers/server1/configuration\n\ttouch $(INTERMEDIATE_DIR)/testfiles/websphere_networkdeployment/profiles/profile1/servers/server1/configuration/wsBundleMetadata\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/testfiles/websphere_badnetworkdeployment/profiles/profile1/configuration\n\t$(COPY) $(INTERMEDIATE_DIR)/closefiledescriptors $(INTERMEDIATE_DIR)/testfiles/\n\t$(RM) $(INTERMEDIATE_DIR)/libmicxx.*; $(COPY) $(SCXOMI_LIBS)/libmicxx.* $(INTERMEDIATE_DIR)\n\t$(shell [ $(OMI_LIBS)/libpal.s? ] && $(COPY) $(SCXOMI_LIBS)/libpal.s? $(INTERMEDIATE_DIR))\n\ncreate_environment_sh : \n ifeq ($(COMBINED_PACKAGES),1)\n\tcd $(INTERMEDIATE_DIR); LD_LIBRARY_PATH=`cd /usr/local_ssl_1.0.0/lib*; pwd` testfiles/createEnv.sh\n else\n\tcd $(INTERMEDIATE_DIR); testfiles/createEnv.sh\n endif\n\ntestrun_setup : $(INTERMEDIATE_DIR)/testrunner testrun_copy create_environment_sh $(LOGFILEREADER_TOOL)\n\ntestrun_pkg : testrun_setup\n\tcd $(INTERMEDIATE_DIR);rm -f testrun.tar;tar cvf testrun.tar testrunner $(LOGFILEREADER_EXE) testfiles\n\nifeq ($(BUILD_PRODUCTION),1)\nBUILD_TESTRUN_PACKAGE=testrun_pkg\nelse\nBUILD_TESTRUN_PACKAGE=\nendif\n\n# During code coverage run, the coverage file is OpsMgr.cov. That is also the name\n# of the empty coverage file in the package. Once run as unit test, copy the file \n# with unit test coverage data to the target folder. \ntestrun_copycovfile :\n\tif [ $(BUILD_TYPE) = Bullseye ]; then $(COPY) $(COVFILE) $(INTERMEDIATE_DIR)/UnitTest.cov; fi\n\ntestrun : pal_test testrun_setup $(BUILD_TESTRUN_PACKAGE)\n\t$(ECHO) \"========================= Performing OM testrun execution\"\n\tcd $(INTERMEDIATE_DIR);testfiles/testrun_wrapper .\n\t$(MAKE) testrun_copycovfile\n\npal_test :\nifeq ($(PAL_UNITTEST_DISABLE),)\n\t$(MAKE) -C ../../pal/build test\nendif\n\ntest : testrun\n\ntestrun_noslow : testrun_setup\n\t$(ECHO) \"========================= Performing OM testrun execution\"\n\tcd $(INTERMEDIATE_DIR); testfiles/testrun_wrapper . -attr=-SLOW -slow=25\n\t$(MAKE) testrun_copycovfile\n\ntestrun_nosudo : testrun_setup\n\t$(ECHO) \"========================= Performing OM testrun execution\"\n\tcd $(INTERMEDIATE_DIR);./testrunner\n\t$(MAKE) testrun_copycovfile\n\ntestrun_core : $(INTERMEDIATE_DIR)/testrunner_core testrun_copy\n\t$(ECHO) \"========================= Performing OM testrun execution\"\n\tcd $(INTERMEDIATE_DIR);./testrunner_core\n\n\n#================================================================================\n# Test parts of the installer builder framework\n#================================================================================\ntest_installerbuilder:\n\tcd ${SCX_BRD}/installer/InstallerBuilder/tests;python testrunner.py\n\n#================================================================================\n# Enable/disable profiling\n#================================================================================\n\nccbuild: ccbuild_testrun\n\nccenable:\n\t$(MAKE) -s ccdisable\n\tif [ $(BUILD_TYPE) = Bullseye ]; then cov01 -1; fi\n\n#\n# It is possible that BullseyeCoverage is not installed on the system\n# to make calling this instruction \"safe\", additional logic has been added\n# to prevent the warning of 'command not in path' from disrupting the build \n#\nccdisable:\n\tif [ $(BUILD_TYPE) != Bullseye ]; then $(MAKE) -s -k ccdisable_helper; fi\n\tif [ $(BUILD_TYPE) = Bullseye ]; then cov01 -0; fi\n\n#\n# Faux target that will always be silent about turning off the code coverage tool(s)\n#\nccdisable_helper:\n\t-cov01 -0 > /dev/null 2>&1\n\n\ntestrun_code_coverage: ccbuild_testrun\n\n#================================================================================\n# Dependency generation Targets\n#================================================================================\n\n# Rule for automatically generating dependencies.\nOBJFILES_TEST=$(POSIX_UNITTESTS_OBJFILES) \\\n\t$(POSIX_UNITTESTS_OBJFILES) \\\n\nDEPFILES_TEST=$(OBJFILES_TEST:.$(PF_OBJ_FILE_SUFFIX)=.d)\n\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.5182300806045532, "alphanum_fraction": 0.5217699408531189, "avg_line_length": 33.0361442565918, "blob_id": "7fe89db4cb61126d54168d78ee5271a70ae37eb2", "content_id": "1656f06d3eb66866936876937089efa6bab4dd90", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2825, "license_type": "permissive", "max_line_length": 125, "num_lines": 83, "path": "/source/code/providers/support/processprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file processprovider.h\n\n \\brief Declarations of the Process Provider class.\n\n \\date 12-03-27 14:15\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef PROCESSPROVIDER_H\n#define PROCESSPROVIDER_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n#include <scxsystemlib/processenumeration.h>\n#include \"startuplog.h\"\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXCore\n{\n class ProcessProvider\n {\n public:\n /*----------------------------------------------------------------------------*/\n /**\n Exception thrown when an unknown resource is requested.\n */\n class UnknownResourceException : public SCXCoreLib::SCXException\n {\n public: \n /*----------------------------------------------------------------------------*/\n /**\n Ctor \n \\param[in] resource Name of the resource requested.\n \\param[in] l Source code location object\n */\n UnknownResourceException(std::wstring resource, \n const SCXCoreLib::SCXCodeLocation& l) : SCXException(l), \n m_resource(resource)\n { \n }\n\n //! Exception description string.\n //! \\returns String representation of the exception.\n std::wstring What() const\n {\n return L\"Unknown resource: \" + m_resource;\n }\n\n protected:\n //! Contains the requested resource string.\n std::wstring m_resource;\n };\n\n ProcessProvider() : m_processes(NULL) { }\n virtual ~ProcessProvider() { };\n \n void Load();\n void Unload();\n SCXHandle<SCXSystemLib::ProcessEnumeration> GetProcessEnumerator() { return m_processes; }\n SCXLogHandle& GetLogHandle(){ return m_log; }\n\n void GetTopResourceConsumers(const std::wstring &resource, unsigned int count, std::wstring &result);\n\n private:\n //! PAL implementation retrieving processes information for local host\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessEnumeration> m_processes;\n\n static int ms_loadCount;\n SCXCoreLib::SCXLogHandle m_log; //!< Handle to log file.\n\n scxulong GetResource(const std::wstring &resource, SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> processinst);\n };\n\n extern ProcessProvider g_ProcessProvider;\n\n} // End of namespace SCXCore\n\n#endif\n" }, { "alpha_fraction": 0.5511611700057983, "alphanum_fraction": 0.5550813674926758, "avg_line_length": 30.29192543029785, "blob_id": "31753a63aab9867581b0895d2e55e268766da8fd", "content_id": "fcb3165ffe44b3cc3487be2b9782c5e7abf9a903", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20152, "license_type": "permissive", "max_line_length": 132, "num_lines": 644, "path": "/source/code/providers/support/logfilereader.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n \n*/\n/**\n \\file logfilereader.cpp\n \n \\brief Main routine for LogFileReader command line program.\n\n \\date 2011-04-14 17:10:00\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxdefaultlogpolicyfactory.h> // Using the default log policy.\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxmarshal.h>\n#include <scxcorelib/stringaid.h>\n#include \"source/code/scxcorelib/util/persist/scxfilepersistmedia.h\"\n\n#include <errno.h>\n#include <iostream>\n#include <unistd.h>\n\n#include \"buildversion.h\"\n#include \"logfileutils.h\"\n\n// dynamic_cast fix - wi 11220\n#ifdef dynamic_cast\n#undef dynamic_cast\n#endif\n\n// SCXCoreLib::SCXProductDependencies::SetLogFileHeaderSuppression() is specific\n// to the OM project, and thus isn't defined in PAL header files. Just define\n// the function here so it's usable (this is the only place it's called from).\n\nnamespace SCXCoreLib\n{\n namespace SCXProductDependencies\n {\n void SetLogFileHeaderSuppression(bool fSet);\n }\n}\n\nusing namespace SCXCore;\nusing namespace SCXCoreLib;\nusing namespace std;\n\nstatic void usage(const char * name, bool fBrief, int exitValue);\nstatic void show_version();\nstatic void PerformMarshalTest();\nstatic int ReadLogFile_Interactive();\nstatic int ReadLogFile_Provider();\nstatic int ResetLogFileState();\nstatic int ResetAllLogFileStates(bool fResetOnRead);\nstatic void ReadLogFile_TestSetup();\n\nSCXHandle<SCXPersistMedia> s_pmedia;\nSCXCoreLib::SCXHandle<LogFileReader> s_pReader;\nwstring s_basePath;\n\nconst int EXIT_LOGIC_ERROR = 64; /* Random exit code that is not ENOENT */\nstatic bool s_fTestMode = false;\n\n// For the getopt() function:\nextern char *optarg;\nextern int optind, opterr, optopt;\n\n// This is the main entry point for the logfilereader command line program.\n//\n// It will, by default, parse arguments, unmarshall input (from Logfile\n// Provider), perform processing, and marshall up the results.\n\n/*----------------------------------------------------------------------------*/\n/**\n logfilereader (main) function.\n\n \\param argc size of \\a argv[]\n \\param argv array of string pointers from the command line.\n \\returns 0 on success, otherwise, 1 on error.\n\n Usage: \n Result Code\n \\n 0 success\n \\n >1 an error occured while executing the command.\n*/\n\nint main(int argc, char * const argv[])\n{\n int exitStatus = 0;\n int c;\n\n bool fResetAllLogFileStates_onRead = false;\n\n // If no arguments, show brief usage help.\n\n if (1 == argc)\n {\n usage(argv[0], true, 0);\n }\n\n enum OperationType {\n UNSET,\n Marshal_Test,\n Reset_File,\n Reset_All_Files,\n Read_Log_File_Interactive,\n Read_Log_File,\n Show_Version\n } operation = UNSET;\n\n // Parse the arguments\n //\n // Illegal arguments are displayed slightly different across our platforms.\n // To help allow for consistent output, override error output and handle it\n // ourselves via the opterr variable.\n\n opterr = 0; // Disable printing errors for bad options\n while ((c = getopt(argc, argv, \"hi?g:mprtv\")) != -1) {\n const char * parameter = NULL;\n\n switch(c) {\n case 'h': /* Show extended help information */\n usage(argv[0], false, 0);\n /*NOTREACHED*/\n break;\n case 'g': /* Provider entry (reset all log file state files) */\n if (UNSET != operation)\n {\n cerr << argv[0] << \": Parsing error - operation already specified (\" << operation << \")\" << endl;\n usage(argv[0], true, EXIT_LOGIC_ERROR);\n }\n parameter = optarg;\n\n if ( !StrCompare(L\"0\", StrFromUTF8(parameter), true)\n || !StrCompare(L\"false\", StrFromUTF8(parameter), true) )\n {\n fResetAllLogFileStates_onRead = false;\n }\n else if ( !StrCompare(L\"1\", StrFromUTF8(parameter), true)\n || !StrCompare(L\"true\", StrFromUTF8(parameter), true) )\n {\n fResetAllLogFileStates_onRead = true;\n }\n else\n {\n cerr << argv[0] << \": Parsing error - Invalid argument for -g (\" << parameter << \")\" << endl;\n usage(argv[0], true, EXIT_LOGIC_ERROR);\n }\n operation = Reset_All_Files;\n break;\n case 'i': /* Interactive (prompted) use */\n if (UNSET != operation)\n {\n cerr << argv[0] << \": Parsing error - operation already specified (\" << operation << \")\" << endl;\n usage(argv[0], true, EXIT_LOGIC_ERROR);\n }\n operation = Read_Log_File_Interactive;\n break;\n case 'm':\n if (UNSET != operation)\n {\n cerr << argv[0] << \": Parsing error - operation already specified (\" << operation << \")\" << endl;\n usage(argv[0], true, EXIT_LOGIC_ERROR);\n }\n operation = Marshal_Test;\n break;\n case 'p': /* Provider entry (read log file) */\n if (UNSET != operation)\n {\n cerr << argv[0] << \": Parsing error - operation already specified (\" << operation << \")\" << endl;\n usage(argv[0], true, EXIT_LOGIC_ERROR);\n }\n operation = Read_Log_File;\n break;\n case 'r': /* Provider entry (reset log file state file) */\n if (UNSET != operation)\n {\n cerr << argv[0] << \": Parsing error - operation already specified (\" << operation << \")\" << endl;\n usage(argv[0], true, EXIT_LOGIC_ERROR);\n }\n operation = Reset_File;\n break;\n case 't': /* Test mode requested (check for testrunner) */\n s_fTestMode = true;\n break;\n case 'v': /* Show version info */\n if (UNSET != operation)\n {\n cerr << argv[0] << \": Parsing error - operation already specified (\" << operation << \")\" << endl;\n usage(argv[0], true, EXIT_LOGIC_ERROR);\n }\n operation = Show_Version;\n break;\n case '?': /* Show basic help information */\n // If invalid parameter, return error result\n if (0 != optopt && '\\?' != optopt)\n {\n cerr << argv[0]\n << \": invalid option -- '\"\n << (char) optopt \n << \"'\" << endl;\n usage(argv[0], true, EXIT_LOGIC_ERROR);\n }\n /*NOTREACHED*/\n default:\n usage(argv[0], true, 0);\n /*NOTREACHED*/\n break;\n }\n }\n\n // Since scxlogfilereader just uses the scx.log logfile, don't write header\n // each time we're called (makes log confusing thinking agent restarted)\n SCXCoreLib::SCXProductDependencies::SetLogFileHeaderSuppression(true);\n\n // Dispatch for the operation that was requested\n switch (operation)\n {\n case Marshal_Test:\n PerformMarshalTest();\n break;\n\n case Reset_File:\n exitStatus = ResetLogFileState();\n break;\n\n case Reset_All_Files:\n exitStatus = ResetAllLogFileStates(fResetAllLogFileStates_onRead);\n break;\n\n case Read_Log_File_Interactive:\n ReadLogFile_Interactive();\n break;\n\n case Read_Log_File:\n exitStatus = ReadLogFile_Provider();\n break;\n\n case Show_Version:\n show_version();\n break;\n\n case UNSET:\n default:\n // If invalid parameter, return error result\n cerr << argv[0] << \": Logic Error - invalid operation (\" << operation << \")\" << endl;\n exitStatus = EXIT_LOGIC_ERROR;\n break;\n }\n\n return exitStatus;\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Output a usage message.\n \n \\param name Application name (derived from argv[0]).\n \\param exitValue Value to return after writing the usage message.\n \\return Does not return.\n*/\nstatic void usage(char const * const name, bool fBrief, int exitValue)\n{\n if (fBrief)\n {\n wcout << name << L\": Try '\" << name << L\" -h' for more information.\" << endl;\n }\n else\n {\n wcout << L\"Usage: \" << name << endl\n << endl\n << L\"Options:\" << endl\n << L\" -h:\\tDisplay detailed help information\" << endl\n << L\" -g:\\tReset all log file states (for internal use only)\" << endl\n << L\" \\t(Requires parameter for ResetOnRead: 1/true/0/false)\" << endl\n << L\" -i:\\tInteractive use (for debugging purposes only)\" << endl\n << L\" -m:\\tRun marshal unit tests (debugging purposes only)\" << endl\n << L\" -p:\\tProvider interface (for internal use only)\" << endl\n << L\" -r:\\tReset log file state (for internal use only)\" << endl\n << L\" -t:\\tProvide hooks for testrunner environmental setup\" << endl\n << L\" -v:\\tDisplay version information\" << endl;\n }\n\n exit(exitValue);\n} \n\n\n/*----------------------------------------------------------------------------*/\n/**\n Output the version string\n*/\nstatic void show_version()\n{\n wcout << L\"Version: \" << SCX_BUILDVERSION_MAJOR << L\".\" << SCX_BUILDVERSION_MINOR\n << L\".\" << SCX_BUILDVERSION_PATCH << L\"-\" << SCX_BUILDVERSION_BUILDNR\n << L\" (\" << SCX_BUILDVERSION_STATUS << L\" - \" << SCX_BUILDVERSION_DATE << \"L)\\n\";\n\n return;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Perform low-level marshal tests for unit test purposes.\n*/\nvoid PerformMarshalTest()\n{\n // Unmarshal the parameters from the caller (passed via standard input)\n\n wstring filename;\n wstring qid;\n vector<SCXRegexWithIndex> regexps;\n int matchedLinesCount;\n\n UnMarshal receive(cin);\n receive.Read(filename);\n receive.Read(qid);\n receive.Read(regexps);\n receive.Read(matchedLinesCount);\n\n // Now marshal the results - everything we got plus a vector\n //\n // Populate the vector with some random data\n\n vector<wstring> matchedLines;\n\n for (int i = 0; i < matchedLinesCount; i++)\n {\n wstringstream wss;\n wss << L\"This is entry number \" << i << L\" in the vector\";\n matchedLines.push_back(wss.str());\n }\n\n // Marshal the results\n\n int wasPartialRead = 65536;\n\n Marshal send(cout);\n send.Write(filename);\n send.Write(qid);\n send.Write(regexps);\n send.Write(matchedLinesCount);\n send.Write(wasPartialRead);\n send.Write(matchedLines);\n send.Flush();\n\n return;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Implementation for interactive interface to read log files.\n\n Parameters are prompted for interactively.\n\n Input parameters are (as required by LogFileReader::ReadLogFile):\n filename: Filename to be read\n qid: ID (from property)\n regexps: Regular expressions to search for\n\n Output result (sent to stdout):\n matchedLines: Resulting lines that match the regular expressions\n\n \\return 0 (exit status for scxlogfilereader executable)\n*/\nint ReadLogFile_Interactive()\n{\n wstring filename;\n wstring qid;\n vector<SCXRegexWithIndex> regexps;\n\n // Get the filename and qid\n wcout << L\"Enter filename: \";\n getline(wcin, filename);\n if ( wcin.eof() ) return 0;\n wcout << L\" Filename: '\" << filename << L\"'\" << endl;\n\n wcout << L\"Enter QID: \";\n getline(wcin, qid);\n if ( wcin.eof() ) return 0;\n wcout << L\" QID: '\" << qid << L\"'\" << endl;\n\n // Read the list of regular expressions\n int count = 0;\n\n while (true)\n {\n wstring expression;\n\n wcout << L\"Enter regular expression #\" << count + 1\n << L\" (^D to end): \";\n getline(wcin, expression);\n if ( wcin.eof() ) break;\n\n try\n {\n SCXRegexWithIndex regind;\n regind.regex = new SCXRegex(expression);\n regind.index = ++count;\n regexps.push_back(regind);\n\n wcout << L\" Expression #\" << count << L\": '\" << expression\n << L\"'\" << endl;\n }\n catch (SCXInvalidRegexException& e)\n {\n wcout << L\" Regular expression '\" << expression\n << L\"' invalid; will be ignored\" << endl;\n }\n }\n\n wcout << endl;\n\n if (count == 0)\n {\n wcout << L\" No valid regular expressions entered - exiting\" << endl;\n return 0;\n }\n\n wcout << L\" Processing with \" << count << L\" expressions\" << endl << endl;\n\n // Finally, input is gathered - do the processing\n\n ReadLogFile_TestSetup();\n\n try\n {\n vector<wstring> matchedLines;\n\n s_pReader = new LogFileReader();\n s_pReader->SetPersistMedia(s_pmedia);\n bool bPartial = s_pReader->ReadLogFile(filename, qid, regexps,\n matchedLines);\n\n // Display the output interactively\n\n wcout << L\"Partial flag: \" << (bPartial ? L\"True\" : L\"False\") << endl;\n\n vector<wstring>::iterator it;\n for (it=matchedLines.begin(); it < matchedLines.end(); it++)\n {\n wcout << *it << endl;\n }\n }\n catch (SCXFilePathNotFoundException& e)\n {\n wcerr << L\"scxlogfilereader - File '\" << filename << \"' not found: \"\n << e.What() << endl;\n }\n\n return 0;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Implementation for provider interface to read log files.\n\n Ultimately, this is what the provider calls to process reading of log files.\n\n Parameters come in from STDIN (marshalled by the log file provider), and the\n results are returned (via STDOUT, marshalled).\n\n Input parameters are (as required by LogFileReader::ReadLogFile):\n filename: Filename to be read\n qid: ID (from property)\n regexps: Regular expressions to search for\n\n Output parameters are:\n wasPartialRead: This is incomplete (more data exists to return)\n matchedLines: Resulting lines that match the regular expressions\n\n \\return Resulting status (exit status for scxlogfilereader executable)\n*/\nint ReadLogFile_Provider()\n{\n SCXHandle<LogFileReader> logFileReader(new LogFileReader());\n if (s_fTestMode)\n {\n ReadLogFile_TestSetup();\n logFileReader->SetPersistMedia(s_pmedia);\n }\n\n SCXLogHandle logH = SCXLogHandleFactory::GetLogHandle(L\"scx.logfilereader.ReadLogFile\");\n\n // Unmarshal the parameters from the caller (passed via standard input)\n\n wstring filename;\n wstring qid;\n vector<SCXRegexWithIndex> regexps;\n\n UnMarshal receive(cin);\n receive.Read(filename);\n receive.Read(qid);\n receive.Read(regexps);\n\n try\n {\n vector<wstring> matchedLines;\n bool bWasPartialRead = logFileReader->ReadLogFile(filename, qid, regexps,\n matchedLines);\n\n // Marshal the results\n\n int wasPartialRead = bWasPartialRead;\n Marshal send(cout);\n send.Write(wasPartialRead);\n send.Write(matchedLines);\n send.Flush();\n }\n catch (SCXFilePathNotFoundException& e)\n {\n SCX_LOGWARNING(logH, StrAppend(L\"scxlogfilereader - File not found: \", filename).append(L\", exception: \").append(e.What()));\n\n // Return a special exit code so we know that the log file wasn't found\n return ENOENT;\n }\n catch (SCXException &e)\n {\n SCX_LOGWARNING(logH, StrAppend(L\"scxlogfilereader - Unexpected exception: \", e.What()));\n\n return EINTR;\n }\n\n return 0;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Implementation for provider interface to reset the state of a log file.\n\n Parameters come in from STDIN (marshalled by the log file provider), and the\n results are returned (via STDOUT, marshalled).\n\n Input parameters are (as required by LogFileReader::ReadLogFile):\n filename: Filename to be read\n qid: ID (from property)\n\n Output parameters are:\n <None>\n\n \\return Resulting status (exit status for scxlogfilereader executable)\n*/\nint ResetLogFileState()\n{\n int exitStatus = 0;\n\n SCXHandle<LogFileReader> logFileReader(new LogFileReader());\n if (s_fTestMode)\n {\n ReadLogFile_TestSetup();\n logFileReader->SetPersistMedia(s_pmedia);\n }\n\n SCXLogHandle logH = SCXLogHandleFactory::GetLogHandle(L\"scx.logfilereader.resetLogfilestate\");\n\n // Unmarshal the parameters from the caller (passed via standard input)\n\n wstring filename;\n wstring qid;\n int resetOnRead_asint;\n\n UnMarshal receive(cin);\n receive.Read(filename);\n receive.Read(qid);\n receive.Read(resetOnRead_asint);\n\n bool resetOnRead = (resetOnRead_asint ? true : false);\n\n try\n {\n exitStatus = logFileReader->ResetLogFileState(filename, qid, resetOnRead);\n }\n catch (SCXFilePathNotFoundException& e)\n {\n SCX_LOGWARNING(logH, StrAppend(L\"scxlogfilereader - File not found: \", filename).append(L\", exception: \").append(e.What()));\n\n // Return a special exit code so we know that the log file wasn't found\n return ENOENT;\n }\n catch (SCXException &e)\n {\n SCX_LOGWARNING(logH, StrAppend(L\"scxlogfilereader - Unexpected exception: \", e.What()));\n\n return EINTR;\n }\n\n return exitStatus;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Implementation for provider interface to reset all state of log files.\n\n Parameters come in from STDIN (marshalled by the log file provider), and the\n results are returned (via STDOUT, marshalled).\n\n Input parameters are (as required by LogFileReader::ReadLogFile):\n <None>\n\n Output parameters are:\n <None>\n\n \\return Resulting status (exit status for scxlogfilereader executable)\n*/\nint ResetAllLogFileStates(bool fResetOnRead)\n{\n SCXHandle<LogFileReader> logFileReader(new LogFileReader());\n if (s_fTestMode)\n {\n ReadLogFile_TestSetup();\n logFileReader->SetPersistMedia(s_pmedia);\n }\n else\n {\n s_basePath = L\"/var/opt/microsoft/scx/lib/state/\";\n }\n\n return logFileReader->ResetAllLogFileStates(s_basePath, fResetOnRead);\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Setup the environment for test purposes (for running under testrunner).\n\n This works in concert with the unit tests themselves, but some of the\n setup must be done in the context of scxlogfilereader itself. This\n will perform that setup.\n\n Note that the logfileprovider will only pass the -t flag (which results\n in this routine being called) if running unit tests at the time. Otherwise,\n this function is never called.\n*/\n\nvoid ReadLogFile_TestSetup()\n{\n s_pmedia = GetPersistMedia();\n SCXFilePersistMedia* m = dynamic_cast<SCXFilePersistMedia*> (s_pmedia.GetData());\n SCXASSERT(m != 0);\n s_basePath = L\"./\";\n m->SetBasePath(s_basePath);\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6869466304779053, "alphanum_fraction": 0.6896297335624695, "avg_line_length": 47.87868881225586, "blob_id": "0a3ad69cb5b91c2053a99b200259dda608aaa5b9", "content_id": "1cc822b25d63bfe1dacba50b094e110eddced2a6", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14908, "license_type": "permissive", "max_line_length": 124, "num_lines": 305, "path": "/test/code/providers/disk_provider/diskprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the disk provider\n\n \\date 2008-04-24 09:00\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <scxcorelib/scxexception.h>\n#include <cppunit/extensions/HelperMacros.h>\n#include <testutils/scxunit.h>\n#include <testutils/disktestutils.h>\n#include <testutils/providertestutils.h>\n#include \"support/diskprovider.h\"\n#include \"support/filesystemprovider.h\"\n\n#include \"SCX_DiskDrive.h\"\n#include \"SCX_DiskDrive_Class_Provider.h\"\n#include \"SCX_DiskDriveStatisticalInformation_Class_Provider.h\"\n#include \"SCX_FileSystem_Class_Provider.h\"\n#include \"SCX_FileSystemStatisticalInformation_Class_Provider.h\"\n\nclass SCXDiskProviderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXDiskProviderTest );\n CPPUNIT_TEST( TestCountsAndEnumerations );\n\n CPPUNIT_TEST( TestEnumInstanceNamesSanity );\n CPPUNIT_TEST( TestPhysicalLogicalDiskDecoupled );\n CPPUNIT_TEST( RemoveTotalInstanceShouldFail );\n CPPUNIT_TEST( RemoveDiskDriveAlsoRemovesStatisticalInstance );\n CPPUNIT_TEST( RemoveFileSystemAlsoRemovesStatisticalInstance );\n \n SCXUNIT_TEST_ATTRIBUTE(TestEnumInstanceNamesSanity, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestPhysicalLogicalDiskDecoupled, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(RemoveTotalInstanceShouldFail, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartial, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(RemoveDiskDriveAlsoRemovesStatisticalInstance, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(RemoveFileSystemAlsoRemovesStatisticalInstance, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_DiskDrive_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_FileSystem_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_DiskDrive_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_FileSystem_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n size_t DDCount()\n {\n SCXCoreLib::SCXHandle<SCXSystemLib::StaticPhysicalDiskEnumeration> diskEnum =\n SCXCore::g_DiskProvider.getEnumstaticPhysicalDisks();\n return diskEnum->Size();\n }\n\n size_t DDSCount()\n {\n SCXCoreLib::SCXHandle<SCXSystemLib::StatisticalPhysicalDiskEnumeration> diskEnum =\n SCXCore::g_DiskProvider.getEnumstatisticalPhysicalDisks();\n // In the case of statistical enumeration classes we set total to 1 because _Total instance is not actually stored\n // in the enumeration collection but is instead generated on the fly. in other cases we set total to 0.\n return diskEnum->Size() + 1;\n }\n\n size_t FSCount()\n {\n SCXCoreLib::SCXHandle<SCXSystemLib::StaticLogicalDiskEnumeration> diskEnum =\n SCXCore::g_FileSystemProvider.getEnumstaticLogicalDisks();\n return diskEnum->Size();\n }\n\n size_t FSSCount()\n {\n SCXCoreLib::SCXHandle<SCXSystemLib::StatisticalLogicalDiskEnumeration> diskEnum =\n SCXCore::g_FileSystemProvider.getEnumstatisticalLogicalDisks();\n // In the case of statistical enumeration classes we set total to 1 because _Total instance is not actually stored\n // in the enumeration collection but is instead generated on the fly. in other cases we set total to 0.\n return diskEnum->Size() + 1;\n }\n\n /*----------------------------------------------------------------------------*/\n //! Removes instance of a disk with a particular name.\n //! \\param T type of instance to be removed\n //! \\param TInstanceName type of the parameter with which the remover is called.\n //! \\param TParam type of the parameter object containing name with which the remover is called.\n //! \\param[in] errMsg String containing error messages.\n //! \\returns returns true if removal was sucessfull.\n template<class T, class TInstanceName, class TParam> bool InvokeRemoveDisk(const std::wstring& d,\n std::wstring errMsg)\n {\n TestableContext context;\n TInstanceName instanceName;\n TParam param;\n param.Name_value(SCXCoreLib::StrToMultibyte(d).c_str());\n\n mi::Module Module;\n T agent(&Module);\n agent.Invoke_RemoveByName(context, NULL, instanceName, param);\n if (context.GetResult() == MI_RESULT_OK)\n {\n const std::vector<TestableInstance> &instances = context.GetInstances();\n // We expect two instances to be returned, the instance of the object and then the instance of the return value.\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 2u, instances.size());\n return instances[1].GetMIReturn_MIBoolean(CALL_LOCATION(errMsg));\n }\n return false;\n }\n\n bool InvokeRemoveDiskDrive(const std::wstring& d, std::wstring errMsg)\n {\n return InvokeRemoveDisk<mi::SCX_DiskDrive_Class_Provider, mi::SCX_DiskDrive_Class,\n mi::SCX_DiskDrive_RemoveByName_Class>(d, CALL_LOCATION(errMsg));\n }\n \n bool InvokeRemoveFileSystem(const std::wstring& d, std::wstring errMsg)\n {\n return InvokeRemoveDisk<mi::SCX_FileSystem_Class_Provider, mi::SCX_FileSystem_Class,\n mi::SCX_FileSystem_RemoveByName_Class>(d, CALL_LOCATION(errMsg));\n }\n\n void TestCountsAndEnumerations()\n {\n std::wstring errMsg;\n if ( ! MeetsPrerequisites(L\"SCXDiskProviderTest::TestCountsAndEnumerations\"))\n {\n return;\n }\n if ( ! HasPhysicalDisks(L\"SCXDiskProviderTest::TestCountsAndEnumerations\") )\n {\n return;\n }\n\n TestableContext dd, dds, fs, fss;\n EnumInstances<mi::SCX_DiskDrive_Class_Provider>(dd, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(dds, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_FileSystem_Class_Provider>(fs, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(fss, CALL_LOCATION(errMsg));\n\n CPPUNIT_ASSERT_EQUAL(dd.Size(), DDCount());\n CPPUNIT_ASSERT_EQUAL(dds.Size(), DDSCount());\n CPPUNIT_ASSERT_EQUAL(fs.Size(), FSCount());\n CPPUNIT_ASSERT_EQUAL(fss.Size(), FSSCount());\n }\n\n void TestEnumInstanceNamesSanity()\n {\n std::wstring errMsg;\n if ( ! MeetsPrerequisites(L\"SCXDiskProviderTest::TestEnumInstanceNamesSanity\"))\n {\n return;\n }\n if ( ! HasPhysicalDisks(L\"SCXDiskProviderTest::TestEnumInstanceNamesSanity\") )\n {\n return;\n }\n\n TestableContext dd, dds, fs, fss;\n EnumInstances<mi::SCX_DiskDrive_Class_Provider>(dd, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(dds, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_FileSystem_Class_Provider>(fs, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(fss, CALL_LOCATION(errMsg));\n // There should be at least one disk/filesystem.\n CPPUNIT_ASSERT(0 < dd.Size()\n || !HasPhysicalDisks(L\"SCXDiskProviderTest::TestEnumInstanceNamesSanity\", true));\n CPPUNIT_ASSERT(0 < dds.Size());\n CPPUNIT_ASSERT(0 < fs.Size());\n CPPUNIT_ASSERT(0 < fss.Size());\n\n // Statistical collections have total instance - the others don't.\n CPPUNIT_ASSERT_EQUAL(dd.Size()+1, dds.Size());\n CPPUNIT_ASSERT_EQUAL(fs.Size()+1, fss.Size());\n }\n\n void RemoveTotalInstanceShouldFail()\n {\n std::wstring errMsg;\n CPPUNIT_ASSERT( ! InvokeRemoveDiskDrive(L\"_Total\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT( ! InvokeRemoveFileSystem(L\"_Total\", CALL_LOCATION(errMsg)));\n }\n\n void RemoveDiskDriveAlsoRemovesStatisticalInstance(void)\n {\n std::wstring errMsg;\n\n if ( ! MeetsPrerequisites(L\"SCXDiskProviderTest::RemoveDiskDriveAlsoRemovesStatisticalInstance\"))\n {\n return;\n }\n if ( ! HasPhysicalDisks(L\"SCXDiskProviderTest::RemoveDiskDriveAlsoRemovesStatisticalInstance\") )\n {\n return;\n }\n\n TestableContext dd, dds;\n EnumInstances<mi::SCX_DiskDrive_Class_Provider>(dd, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(dds, CALL_LOCATION(errMsg));\n const std::vector<TestableInstance> &instances = dd.GetInstances();\n CPPUNIT_ASSERT(instances.size() > 0);\n CPPUNIT_ASSERT( InvokeRemoveDiskDrive(instances[0].GetProperty(L\"Name\",\n CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)), CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL(dd.Size()-1, DDCount());\n CPPUNIT_ASSERT_EQUAL(dds.Size()-1, DDSCount());\n }\n\n void RemoveFileSystemAlsoRemovesStatisticalInstance(void)\n {\n std::wstring errMsg;\n\n TestableContext fs, fss;\n EnumInstances<mi::SCX_FileSystem_Class_Provider>(fs, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(fss, CALL_LOCATION(errMsg));\n const std::vector<TestableInstance> &instances = fs.GetInstances();\n CPPUNIT_ASSERT(instances.size() > 0);\n CPPUNIT_ASSERT( InvokeRemoveFileSystem(instances[0].GetProperty(L\"Name\",\n CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)), CALL_LOCATION(errMsg)));\n\n CPPUNIT_ASSERT_EQUAL(fs.Size()-1, FSCount());\n CPPUNIT_ASSERT_EQUAL(fss.Size()-1, FSSCount());\n }\n \n void TestPhysicalLogicalDiskDecoupled(void)\n {\n // This test ensures that DiskDrive and LogicalDisk providers are decoupled. No instances of\n // StaticPhysicalDiskInstance or StatisticalPhysicalDiskInstance should be created while LogicalDisk provider\n // is running.\n\n // Before we run our test we first shut down any existing DiskDrive objects so we can check if any were created\n // during the test.\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_DiskDrive_Class_Provider>(context, CALL_LOCATION(errMsg));\n TearDownAgent<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n\n // Get the state before the LogicalDisk provider is ran.\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"After shutting down SCX_DiskDrive_Class_Provider there \"\n \"are still StaticPhysicalDiskInstance-s present. Memory leak?\",\n 0u, SCXSystemLib::StaticPhysicalDiskInstance::GetCurrentInstancesCount());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"After shutting down SCX_DiskDriveStatisticalInformation_Class_Provider there \"\n \"are still StatisticalPhysicalDiskInstance-s present. Memory leak?\",\n 0u, SCXSystemLib::StatisticalPhysicalDiskInstance::GetCurrentInstancesCount());\n size_t staticPhysicalInstancesSinceStart =\n SCXSystemLib::StaticPhysicalDiskInstance::GetInstancesCountSinceModuleStart();\n size_t statisticalPhysicalInstancesSinceStart =\n SCXSystemLib::StatisticalPhysicalDiskInstance::GetInstancesCountSinceModuleStart();\n\n // Run the LogicalDisk provider.\n TestableContext fs, fss;\n EnumInstances<mi::SCX_FileSystem_Class_Provider>(fs, CALL_LOCATION(errMsg));\n EnumInstances<mi::SCX_FileSystemStatisticalInformation_Class_Provider>(fss, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_MESSAGE(\"There are no logical disks on this system?!\", 0 < fs.Size());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Mismatch between static and statistical disk drive counts\", fs.Size()+1, fss.Size());\n\n // Verify no DiskDrive disk instances were created.\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"After running FileSystem and FileSystemStatisticalInformation providers there \"\n \"are StaticPhysicalDiskInstance-s present.\",\n 0u, SCXSystemLib::StaticPhysicalDiskInstance::GetCurrentInstancesCount());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"After running FileSystem and FileSystemStatisticalInformation providers there \"\n \"are StatisticalPhysicalDiskInstance-s present.\",\n 0u, SCXSystemLib::StatisticalPhysicalDiskInstance::GetCurrentInstancesCount());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"While running FileSystem and FileSystemStatisticalInformation providers \"\n \"StaticPhysicalDiskInstance-s were created.\",\n staticPhysicalInstancesSinceStart,\n SCXSystemLib::StaticPhysicalDiskInstance::GetInstancesCountSinceModuleStart());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"While running FileSystem and FileSystemStatisticalInformation providers \"\n \"StatisticalPhysicalDiskInstance-s were created.\",\n statisticalPhysicalInstancesSinceStart,\n SCXSystemLib::StatisticalPhysicalDiskInstance::GetInstancesCountSinceModuleStart());\n\n // After the test we restore DiskDrive objects to make sure object counters match (for each destruction\n // there's creation and vice-versa).\n SetUpAgent<mi::SCX_DiskDrive_Class_Provider>(context, CALL_LOCATION(errMsg));\n SetUpAgent<mi::SCX_DiskDriveStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXDiskProviderTest );\n" }, { "alpha_fraction": 0.5898962020874023, "alphanum_fraction": 0.6210380792617798, "avg_line_length": 28.9792537689209, "blob_id": "0d7fb4b35e4aec9fb3aa2c01e607daede65c61e9", "content_id": "1bb9860d810db728e8e249181b864f0328c1e0ea", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": true, "language": "Shell", "length_bytes": 7225, "license_type": "permissive", "max_line_length": 199, "num_lines": 241, "path": "/build/configure", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nscxpal_dir=\"../../pal\"\nscxomi_dir=`(cd ../../omi/Unix; pwd -P)`\nbuild_type=\"Release\"\ndisable_listener=0\nenable_debug=\"\"\nenable_purify_agent=\"\"\nenable_purify_server=\"\"\nenable_bullseye=\"\"\ncombined_packages=0\nenable_scx_security_hardening=0\nenable_ulinux_qual=\"\"\nomi_configure_quals=\"--enable-microsoft\"\n\nif [ ! -d \"$scxpal_dir\" ]; then\n echo \"PAL directory ($scxpal_dir) does not exist\"\n exit 1\nfi\n\nif [ ! -d \"$scxomi_dir\" ]; then\n echo \"OMI directory ($scxomi_dir) does not exist\"\n exit 1\nfi\n\nperform_ulinux_build()\n{\n if [ ! -d \"/usr/local_ssl_0.9.8\" -o ! -d \"/usr/local_ssl_1.0.0\" -o \\( `uname -m` = \"x86_64\" -a ! -d \"/usr/local_ssl_1.1.0\" \\) -o \\( `uname -m` = \"x86_64\" -a ! -d \"/usr/local_ssl_3.0.0\" \\) ]; then\n echo \"Cannot build ULINUX without Universal SSL libraries\"\n exit 1\n fi\n\n enable_ulinux_qual=\"--enable-ulinux\"\n omi_configure_quals=\"$omi_configure_quals $enable_ulinux_qual $enable_security_hardening\"\n combined_packages=1\n}\n\nfor opt\ndo\n\n arg=`expr \"x$opt\" : 'x[^=]*=\\(.*\\)'`\n\n case $opt in\n\n -h | --help)\n help=1\n ;;\n\n --disable-listener)\n disable_listener=1\n ;;\n\n --enable-bullseye)\n if [ \"$build_type\" = \"Debug\" ]; then\n echo \"Cannot build Bullseye if debug is enabled\"\n exit 1\n fi\n build_type=\"Bullseye\"\n enable_bullseye=\"--enable-bullseye\"\n ;;\n\n --enable-debug)\n if [ \"$build_type\" = \"Bullseye\" ]; then\n echo \"Cannot build debug if Bullseye is enabled\"\n exit 1\n fi\n build_type=\"Debug\"\n enable_debug=\"--enable-debug\"\n ;;\n\n --enable-local-omi)\n omi_configure_quals=\"--prefix=. --disable-libpath\"\n local_omi=\"1\"\n ;;\n\n --enable-purify-agent)\n enable_purify_agent=\"--enable-purify-agent\"\n ;;\n\n --enable-purify-server)\n enable_purify_server=\"--enable-purify-server\"\n ;;\n\n --enable-security-hardening)\n enable_security_hardening=\"--enable-security-hardening\"\n enable_scx_security_hardening=1\n ;;\n\n --enable-system-build)\n if [ `uname -s` = \"Linux\" -a `uname -m` != \"ppc64le\" ]; then\n perform_ulinux_build\n fi\n ;;\n\n --enable-ulinux)\n perform_ulinux_build\n ;;\n\n *)\n echo \"configure: invalid option '$opt'\"\n echo \"Try configure --help' for more information.\"\n exit 1\n ;;\n\n esac\n\ndone\n\nif [ \"$help\" = \"1\" ]; then\n\n cat<<EOF\n\nUsage: ./configure [OPTIONS]\n\nOVERVIEW:\n\nThis script configures SCXOM for building. Type the following commands.\n\n $ ./configure\n $ make\n\nOPTIONS:\n -h, --help Print this help message.\n --disable-listener Disable listening on port 1270 (normally enabled by default)\n --enable-bullseye Enables the use of code coverage tools (Bullseye).\n --enable-debug Perform a debug build.\n --enable-local-omi Allow local OMI commands to be issued (not for use when building a kit)\n --enable-purify-agent Allow agent to be run with purify (memory leak detection)\n --enable-purify-server Allow server to be run with purify (memory leak detection)\n --enable-security-hardening Enable security flags for compiling.\n --enable-system-build Enable qualifiers necessary for a system build\n --enable-ulinux Build universal RPM/DEB kits\n\nEOF\n exit 0\nfi\n\n(cd $scxpal_dir/build/ && chmod ug+x ./configure; ./configure $enable_debug $enable_bullseye $enable_ulinux_qual $enable_security_hardening)\n\nomi_configure_quals=\"${enable_debug} ${enable_purify_agent} ${enable_purify_server} ${omi_configure_quals} ${enable_security_hardening}\"\n\n##==============================================================================\n##\n## openssl variables\n##\n##==============================================================================\n\npkgconfig=`which pkg-config`\n\nopenssl_cflags=`$pkgconfig --cflags openssl`\nopenssl_libs=`$pkgconfig --libs openssl`\nopenssl_libdir=`$pkgconfig --variable=libdir openssl`\n\nif [ $combined_packages -ne 0 ]; then\n case \"`uname -m`\" in \n\tx86_64 )\n openssl098_libdir=/usr/local_ssl_0.9.8/lib\n openssl100_libdir=/usr/local_ssl_1.0.0/lib64\n openssl110_libdir=/usr/local_ssl_1.1.0/lib\n openssl300_libdir=/usr/local_ssl_3.0.0/lib64\n ;;\n\t\n\t* )\n openssl098_libdir=/usr/local_ssl_0.9.8/lib\n openssl100_libdir=/usr/local_ssl_1.0.0/lib\n ;;\n esac\n openssl098_cflags=`PKG_CONFIG_PATH=$openssl098_libdir/pkgconfig $pkgconfig --cflags openssl`\n openssl098_libs=`PKG_CONFIG_PATH=$openssl098_libdir/pkgconfig $pkgconfig --libs openssl`\n openssl100_cflags=`PKG_CONFIG_PATH=$openssl100_libdir/pkgconfig $pkgconfig --cflags openssl`\n openssl100_libs=`PKG_CONFIG_PATH=$openssl100_libdir/pkgconfig $pkgconfig --libs openssl`\n if [ `uname -m` = \"x86_64\" ]; then\n openssl110_cflags=`PKG_CONFIG_PATH=$openssl110_libdir/pkgconfig $pkgconfig --cflags openssl`\n openssl110_libs=`PKG_CONFIG_PATH=$openssl110_libdir/pkgconfig $pkgconfig --libs openssl`\n openssl300_cflags=`PKG_CONFIG_PATH=$openssl300_libdir/pkgconfig $pkgconfig --cflags openssl`\n openssl300_libs=`PKG_CONFIG_PATH=$openssl300_libdir/pkgconfig $pkgconfig --libs openssl`\n fi\nfi\n\n##==============================================================================\n##\n## running on Travis?\n##\n##==============================================================================\n\ntravis_ci=0\nif [ \"$TRAVIS\" = \"true\" ]; then\n echo \"Currently running on Travis for Continuous Integration ...\"\n travis_ci=1\nfi\n\n##==============================================================================\n##\n## handle versions and write configuration\n##\n##==============================================================================\n\n# Do we have a version file from the super project? If not, make one\n\nif [ -f ../../scxcore.version ]; then\n rm -f Makefile.version\n ln -s ../../scxcore.version Makefile.version\nelse\n cat <<EOF > Makefile.version\nSCX_BUILDVERSION_MAJOR=0\nSCX_BUILDVERSION_MINOR=0\nSCX_BUILDVERSION_PATCH=0\nSCX_BUILDVERSION_BUILDNR=0\nSCX_BUILDVERSION_DATE=20150101\nSCX_BUILDVERSION_STATUS=Developer_Build\nEOF\nfi\n\ncat <<EOF > config.mak\nBUILD_TYPE=$build_type\nCOMBINED_PACKAGES=$combined_packages\nDISABLE_LISTENER=$disable_listener\nLOCAL_OMI=$local_omi\nOMI_CONFIGURE_QUALS=$omi_configure_quals\nOPENSSL_CFLAGS=$openssl_cflags\nOPENSSL_LIBS=$openssl_libs\nOPENSSL_LIBDIR=$openssl_libdir\nOPENSSL098_CFLAGS=$openssl098_cflags\nOPENSSL098_LIBS=$openssl098_libs\nOPENSSL098_LIBDIR=$openssl098_libdir\nOPENSSL100_CFLAGS=$openssl100_cflags\nOPENSSL100_LIBS=$openssl100_libs\nOPENSSL100_LIBDIR=$openssl100_libdir\nOPENSSL110_CFLAGS=$openssl110_cflags\nOPENSSL110_LIBS=$openssl110_libs\nOPENSSL110_LIBDIR=$openssl110_libdir\nOPENSSL300_CFLAGS=$openssl300_cflags\nOPENSSL300_LIBS=$openssl300_libs\nOPENSSL300_LIBDIR=$openssl300_libdir\nENABLE_SCX_SECURITY_HARDENING=$enable_scx_security_hardening\nTRAVIS_CI=$travis_ci\nEOF\n\n# Fix permissions in case they aren't executable - and then configure OMI\nchmod ug+x ${scxomi_dir}/configure ${scxomi_dir}/buildtool\n(cd ${scxomi_dir} && ./configure ${omi_configure_quals})\n" }, { "alpha_fraction": 0.48900169134140015, "alphanum_fraction": 0.5025380849838257, "avg_line_length": 20.10714340209961, "blob_id": "d42092e4d96da4ece16559bd903a949d0be11ce7", "content_id": "80d913fb3b723fb7ed2371384a690d6c2364c9d8", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 591, "license_type": "permissive", "max_line_length": 82, "num_lines": 28, "path": "/test/code/providers/testutilities.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Test code for SCX Core Provider\n\n \\date 2015-12-23\n\n Test support code for SCX Core Provider\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef TESTUTILITIES_H\n#define TESTUTILITIES_H\n\n#include <scxcorelib/scxcmn.h>\n#include <string>\n\nnamespace SCXCore\n{\n std::wstring GetActualDistributionName(std::wstring errMsg);\n}\n\n#endif // !defined(TESTUTILITIES_H)\n" }, { "alpha_fraction": 0.5779294371604919, "alphanum_fraction": 0.5870307087898254, "avg_line_length": 33.8775520324707, "blob_id": "fdf1f0f21251e4bd3076daa9ed150bad327d1707", "content_id": "10c44b4e36171757d4c7142ff2c6c39be867eb48", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1758, "license_type": "permissive", "max_line_length": 122, "num_lines": 49, "path": "/docs/int/template_files/example_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\r\n Copyright (c) Microsoft Corporation. All rights reserved. \r\n \r\n*/\r\n/**\r\n \\file \r\n\r\n \\brief Example test class.\r\n\r\n \\date 2007-06-04 12:34:56\r\n\r\n*/\r\n/*----------------------------------------------------------------------------*/\r\n#include <scxcorelib/scxcmn.h>\r\n#include <class_to_test.h> /* CUSTOMIZE: Include whatever you need to test here */\r\n#include <scxcorelib/scxunit.h> /* This will include CPPUNIT helper macros too */\r\n\r\n#include <scxcorelib/scxexception.h> /* CUSTOMIZE: Only needed if you want to test exception throwing */\r\n\r\nclass SCXExampleTest : public CPPUNIT_NS::TestFixture /* CUSTOMIZE: use a class name with relevant name */\r\n{\r\n CPPUNIT_TEST_SUITE( SCXExampleTest ); /* CUSTOMIZE: Name must be same as classname */\r\n CPPUNIT_TEST( TestSomething ); /* Will use the default test timeout */\r\n SCXUNIT_TEST( SomeOtherTest, 60 /* test timeout in seconds */ );\r\n /* CUSTOMIZE: Add more tests here */\r\n CPPUNIT_TEST_SUITE_END();\r\n\r\nprivate:\r\n /* CUSTOMIZE: Add any data commonly used in several tests as members here. */\r\n\r\npublic:\r\n void setUp(void)\r\n {\r\n /* CUSTOMIZE: This method will be called once before each test function. Use it to set up commonly used objects */\r\n }\r\n\r\n void tearDown(void)\r\n {\r\n /* CUSTOMIZE: This method will be called once after each test function with no regard of success or failure. */\r\n }\r\n\r\n void TestSomething(void)\r\n {\r\n /* CUSTOMIZE: Add your test code here. */\r\n CPPUNIT_ASSERT(! \"Not Implemented\");\r\n }\r\n};\r\n\r\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXExampleTest ); /* CUSTOMIZE: Name must be same as classname */\r\n" }, { "alpha_fraction": 0.4935930371284485, "alphanum_fraction": 0.5051255822181702, "avg_line_length": 24.1741943359375, "blob_id": "66e7c9ed778a104ecc5ec1952635e7dfba51ed27", "content_id": "1a5ad8028dd49dd77bf9db8328563d5702d34863", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3902, "license_type": "permissive", "max_line_length": 164, "num_lines": 155, "path": "/test/util/testapp/diskdata.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n */\n#include <stdio.h>\n\n#ifdef WIN32\n\n// Test code to make it compile on win32 \n\n#define MOUNTED \"C:\\\\AUTOEXEC.BAT\"\ntypedef unsigned long fsblkcnt_t;\nstruct mntent \n{\n char *mnt_dir;\n char *mnt_fsname;\n};\nstatic bool first = true;\nstatic struct mntent* getmntent(FILE*) { static struct mntent m = { \"/\", \"/dev/hda\" }; if (first) { first = false; return &m; } else { return NULL; } }\nstatic FILE* setmntent(char *f, char *s) { first = true; return fopen(f,s); }\nstruct statvfs {\n unsigned long f_frsize; /* fragment size */\n fsblkcnt_t f_bfree; /* # free blocks */\n fsblkcnt_t f_bavail; /* # free blocks for non-root */\n fsblkcnt_t f_blocks; /* size of fs in f_frsize units */\n};\nstatic int statvfs(const char *path, struct statvfs *buf) { path; buf->f_bfree = 100; buf->f_bavail = 100; buf->f_blocks = 200; buf->f_frsize = 0; return 0; }\n\n#else\n\n#if defined(sun)\n#include <sys/mntent.h>\n#include <sys/mnttab.h>\n#else\n#include <mntent.h>\n#endif\n\n#include <sys/statvfs.h>\n\n#endif\n\n#include \"diskdata.h\"\n\n#ifndef MIN\n#define MIN(a,b) ((a) < (b) ? (a) : (b))\n#endif\n\n// Make all numbers in kilobytes\nconst int BLOCKSIZE = 1024;\n\nDiskData::DiskData(void)\n{\n}\n\nDiskData::~DiskData(void)\n{\n}\n\n// Get info on all monuted disks.\n// Fills the vector with one entry per mountpoint\n// Return 0 if OK, else 1\nint DiskData::GetDiskInfo(vector<DiskInfo> &disks)\n{\n // Open file with mounted disks\n#if defined(sun)\n \n FILE *mounts = 0;\n mounts = ::fopen(\"/etc/mnttab\", \"r\");\n if(mounts == 0)\n {\n\t\t//error, no mounts found\n return 1;\n }\n#else\n\tFILE *mounts = setmntent(MOUNTED, \"r\");\n#endif\n\n if(mounts)\n {\n\n // Loop over all mounts\n#if defined(sun)\n\t\tstruct mnttab entry;\n\t\twhile (getmntent(mounts, &entry) == 0)\n\t\t{ \n string name = entry.mnt_special;\n#else\n\t\tstruct mntent *mount;\n while ((mount = getmntent(mounts)) != NULL) \n\t\t{\n\t\t\tstring name = mount->mnt_fsname; \n#endif \n\n\n // Check if mount is a physical device\n if(name.substr(0, 5).compare(\"/dev/\") == 0)\n {\n DiskInfo disk;\n struct statvfs buf;\n\n#if defined(sun)\n\t\t\t\tdisk.name = entry.mnt_mountp;\n#else\n\t\t\t\tdisk.name = mount->mnt_dir;\n#endif\n // Remove /dev/ prefix for physical device name\n disk.physical = name.substr(5);\n\n // Get info about the mounted file system\n#if defined(sun)\n\t\t\t\tif (statvfs(entry.mnt_mountp, &buf) == 0)\n#else\t\t\n\t\t\t\tif (statvfs(mount->mnt_dir, &buf) == 0)\n#endif\n { \n fsblkcnt_t blocks = buf.f_blocks;\n\n if(buf.f_frsize > 0)\n {\n blocks = blocks * (buf.f_frsize / BLOCKSIZE) ;\n }\n disk.size_kb = (unsigned int)blocks;\n\n blocks = buf.f_bavail;\n if(buf.f_frsize > 0)\n {\n blocks = blocks * (buf.f_frsize / BLOCKSIZE) ;\n }\n disk.free_kb = (unsigned int)blocks;\n\n if (buf.f_blocks == 0)\n {\n disk.usage = 0;\n }\n else\n {\n // Calculate disk usage percentage\n disk.usage = MIN(100, (int)((double(buf.f_blocks - buf.f_bfree) / double(buf.f_blocks - buf.f_bfree + buf.f_bavail)) * 100 + (double)0.5));\n }\n\n }\n\n disks.push_back(disk);\n\n }\n }\n\n fclose(mounts);\n\n // OK\n return 0;\n } \n // Error, return non-zero value\n return 1;\n}\n" }, { "alpha_fraction": 0.5609102845191956, "alphanum_fraction": 0.5740740895271301, "avg_line_length": 25.313112258911133, "blob_id": "941a1cb056c314e7de2d3842df8be193f6a66914", "content_id": "6b76f6b1501b870d3d1c499ac7c067e2cc5f0009", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 13446, "license_type": "permissive", "max_line_length": 101, "num_lines": 511, "path": "/installer/bundle/bundle_skel_SunOS.sh", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n#\n# Shell Bundle installer package for the SCX project\n#\n\nPATH=/usr/bin:/usr/sbin:/bin:/sbin\numask 022\n\n# Can't use something like 'readlink -e $0' because that doesn't work everywhere\n# And HP doesn't define $PWD in a sudo environment, so we define our own\ncase $0 in\n /*|~*)\n SCRIPT_INDIRECT=\"`dirname $0`\"\n ;;\n *)\n PWD=\"`pwd`\"\n SCRIPT_INDIRECT=\"`dirname $PWD/$0`\"\n ;;\nesac\n\nSCRIPT_DIR=\"`(cd \\\"$SCRIPT_INDIRECT\\\"; pwd -P)`\"\nSCRIPT=\"$SCRIPT_DIR/`basename $0`\"\nEXTRACT_DIR=\"`pwd -P`/scxbundle.$$\"\n\n# These symbols will get replaced during the bundle creation process.\n#\n# The OM_PKG symbol should contain something like:\n# scx-1.5.1-115.rhel.6.x64 (script adds .rpm or .deb, as appropriate)\n# Note that for non-Linux platforms, this symbol should contain full filename.\n#\n\nTAR_FILE=<TAR_FILE>\nOM_PKG=<OM_PKG>\nOMI_PKG=<OMI_PKG>\n\nSCRIPT_LEN=<SCRIPT_LEN>\nSCRIPT_LEN_PLUS_ONE=<SCRIPT_LEN+1>\n\n\nusage()\n{\n echo \"usage: $1 [OPTIONS]\"\n echo \"Options:\"\n echo \" --extract Extract contents and exit.\"\n echo \" --force Force upgrade (override version checks).\"\n echo \" --install Install the package from the system.\"\n echo \" --purge Uninstall the package and remove all related data.\"\n echo \" --remove Uninstall the package from the system.\"\n echo \" --restart-deps Reconfigure and restart dependent service\"\n echo \" --source-references Show source code reference hashes.\"\n echo \" --upgrade Upgrade the package in the system.\"\n echo \" --enable-opsmgr Enable port 1270 for usage with opsmgr.\"\n echo \" --version Version of this shell bundle.\"\n echo \" --debug use shell debug mode.\"\n echo \" -? | --help shows this usage text.\"\n}\n\nsource_references()\n{\n cat <<EOF\n-- Source code references --\nEOF\n}\n\ncleanup_and_exit()\n{\n # $1: Exit status\n # $2: Non-blank (if we're not to delete bundles), otherwise empty\n\n rm -f scx-admin scx-admin-upgrade\n rm -f /tmp/.ai.pkg.zone.lock*\n\n if [ -z \"$2\" -a -d \"$EXTRACT_DIR\" ]; then\n cd $EXTRACT_DIR/..\n rm -rf $EXTRACT_DIR\n fi\n\n if [ -n \"$1\" ]; then\n exit $1\n else\n exit 0\n fi\n}\n\ncheck_version_installable() {\n # POSIX Semantic Version <= Test\n # Exit code 0 is true (i.e. installable).\n # Exit code non-zero means existing version is >= version to install.\n #\n # Parameter:\n # Installed: \"x.y.z.b\" (like \"4.2.2.135\"), for major.minor.patch.build versions\n # Available: \"x.y.z.b\" (like \"4.2.2.135\"), for major.minor.patch.build versions\n\n if [ $# -ne 2 ]; then\n echo \"INTERNAL ERROR: Incorrect number of parameters passed to check_version_installable\" >&2\n cleanup_and_exit 1\n fi\n\n # Current version installed\n INS_MAJOR=`echo $1 | cut -d. -f1`\n INS_MINOR=`echo $1 | cut -d. -f2`\n INS_PATCH=`echo $1 | cut -d. -f3`\n INS_BUILD=`echo $1 | cut -d. -f4`\n\n # Available version number\n AVA_MAJOR=`echo $2 | cut -d. -f1`\n AVA_MINOR=`echo $2 | cut -d. -f2`\n AVA_PATCH=`echo $2 | cut -d. -f3`\n AVA_BUILD=`echo $2 | cut -d. -f4`\n\n # Check bounds on MAJOR\n if [ $INS_MAJOR -lt $AVA_MAJOR ]; then\n return 0\n elif [ $INS_MAJOR -gt $AVA_MAJOR ]; then\n return 1\n fi\n\n # MAJOR matched, so check bounds on MINOR\n if [ $INS_MINOR -lt $AVA_MINOR ]; then\n return 0\n elif [ $INS_MINOR -gt $AVA_MINOR ]; then\n return 1\n fi\n\n # MINOR matched, so check bounds on PATCH\n if [ $INS_PATCH -lt $AVA_PATCH ]; then\n return 0\n elif [ $INS_PATCH -gt $AVA_PATCH ]; then\n return 1\n fi\n\n # PATCH matched, so check bounds on BUILD\n if [ $INS_BUILD -lt $AVA_BUILD ]; then\n return 0\n elif [ $INS_BUILD -gt $AVA_BUILD ]; then\n return 1\n fi\n\n # Version available is idential to installed version, so don't install\n return 1\n}\n\ngetVersionNumber()\n{\n # Parse a version number from a string.\n #\n # Parameter 1: string to parse version number string from\n # (should contain something like mumble-4.2.2.135.universal.x86.tar)\n # Parameter 2: prefix to remove (\"mumble-\" in above example)\n\n if [ $# -ne 2 ]; then\n echo \"INTERNAL ERROR: Incorrect number of parameters passed to getVersionNumber\" >&2\n cleanup_and_exit 1\n fi\n\n echo $1 | sed -e \"s/$2//\" -e 's/\\.solaris\\..*$//' -e 's/-/./'\n}\n\nverifyNoInstallationOption()\n{\n if [ -n \"${installMode}\" ]; then\n echo \"$0: Conflicting qualifiers, exiting\" >&2\n cleanup_and_exit 1\n fi\n\n return;\n}\n\n# $1 - The name of the package to check as to whether it's installed\ncheck_if_pkg_is_installed() {\n /usr/bin/pkginfo MSFT$1 2> /dev/null 1> /dev/null\n return $?\n}\n\n# $1 - The filename of the package to be installed\n# $2 - The package name of the package to be installed\npkg_add() {\n pkg_filename=$1\n pkg_name=$2\n\n echo \"----- Installing package: $pkg_name ($pkg_filename) -----\"\n /usr/sbin/pkgadd -a scx-admin -n -d $pkg_filename MSFT$pkg_name\n}\n\n# $1 - The package name of the package to be uninstalled\n# $2 - Optional parameter. Only used when forcibly removing omi on SunOS\npkg_rm() {\n echo \"----- Removing package: $1 -----\"\n if [ \"$2\" = \"force\" ]; then\n /usr/sbin/pkgrm -a scx-admin-upgrade -n MSFT$1 # 1> /dev/null 2> /dev/null\n else\n /usr/sbin/pkgrm -a scx-admin -n MSFT$1 # 1> /dev/null 2> /dev/null\n fi\n}\n\n\n# $1 - The filename of the package to be installed\n# $2 - The package name of the package to be installed\n# $3 - Okay to upgrade the package? (Optional)\npkg_upd() {\n pkg_filename=$1\n pkg_name=$2\n pkg_allowed=$3\n\n echo \"----- Updating package: $pkg_name ($pkg_filename) -----\"\n\n if [ -z \"${forceFlag}\" -a -n \"$pkg_allowed\" ]; then\n if [ $pkg_allowed -ne 0 ]; then\n echo \"Skipping package since existing version >= version available\"\n return 0\n fi\n fi\n\n # No notion of \"--force\" since Sun package has no notion of update\n check_if_pkg_is_installed ${pkg_name}\n if [ $? -eq 0 ]; then\n pkg_rm $pkg_name force\n pkg_add $1 $pkg_name\n else\n pkg_add $1 $pkg_name\n fi \n}\n\ngetInstalledVersion()\n{\n # Parameter: Package to check if installed\n # Returns: Printable string (version installed or \"None\")\n if check_if_pkg_is_installed $1; then\n version=\"`pkginfo -l MSFT$1 | grep VERSION | awk '{ print $2 }'`\"\n getVersionNumber $version ${1}-\n else\n echo \"None\"\n fi\n}\n\nshouldInstall_omi()\n{\n versionInstalled=`getInstalledVersion omi`\n [ \"$versionInstalled\" = \"None\" ] && return 0\n versionAvailable=`getVersionNumber $OMI_PKG omi-`\n\n check_version_installable $versionInstalled $versionAvailable\n}\n\nshouldInstall_scx()\n{\n versionInstalled=`getInstalledVersion scx`\n [ \"$versionInstalled\" = \"None\" ] && return 0\n versionAvailable=`getVersionNumber $OM_PKG scx-`\n\n check_version_installable $versionInstalled $versionAvailable\n}\n\n#\n# Main script follows\n#\n\nset +e\n\nwhile [ $# -ne 0 ]\ndo\n case \"$1\" in\n --extract-script)\n # hidden option, not part of usage\n # echo \" --extract-script FILE extract the script to FILE.\"\n head -${SCRIPT_LEN} \"${SCRIPT}\" > \"$2\"\n local shouldexit=true\n shift 2\n ;;\n\n --extract-binary)\n # hidden option, not part of usage\n # echo \" --extract-binary FILE extract the binary to FILE.\"\n tail +${SCRIPT_LEN_PLUS_ONE} \"${SCRIPT}\" > \"$2\"\n local shouldexit=true\n shift 2\n ;;\n\n --extract)\n verifyNoInstallationOption\n installMode=E\n shift 1\n ;;\n\n --force)\n forceFlag=true\n shift 1\n ;;\n\n --install)\n verifyNoInstallationOption\n installMode=I\n shift 1\n ;;\n\n --purge)\n verifyNoInstallationOption\n installMode=P\n shouldexit=true\n shift 1\n ;;\n\n --remove)\n verifyNoInstallationOption\n installMode=R\n shouldexit=true\n shift 1\n ;;\n\n --restart-deps)\n restartDependencies=--restart-deps\n shift 1\n ;;\n\n --source-references)\n source_references\n cleanup_and_exit 0\n ;;\n\n --upgrade)\n verifyNoInstallationOption\n installMode=U\n shift 1\n ;;\n\n --enable-opsmgr)\n if [ ! -f /etc/scxagent-enable-port ]; then\n touch /etc/scxagent-enable-port\n fi\n shift 1\n ;;\n\n --version)\n echo \"Version: `getVersionNumber $OM_PKG scx-`\"\n exit 0\n ;;\n\n --debug)\n echo \"Starting shell debug mode.\" >&2\n echo \"\" >&2\n echo \"SCRIPT_INDIRECT: $SCRIPT_INDIRECT\" >&2\n echo \"SCRIPT_DIR: $SCRIPT_DIR\" >&2\n echo \"EXTRACT DIR: $EXTRACT_DIR\" >&2\n echo \"SCRIPT: $SCRIPT\" >&2\n echo >&2\n set -x\n shift 1\n ;;\n\n -? | --help)\n usage `basename $0` >&2\n cleanup_and_exit 0\n ;;\n\n *)\n usage `basename $0` >&2\n cleanup_and_exit 1\n ;;\n esac\ndone\n\nif [ -z \"${installMode}\" ]; then\n echo \"$0: No options specified, specify --help for help\" >&2\n cleanup_and_exit 3\nfi\n\n#\n# Note: From this point, we're in a temporary directory. This aids in cleanup\n# from bundled packages in our package (we just remove the diretory when done).\n#\n\nmkdir -p $EXTRACT_DIR\ncd $EXTRACT_DIR\n\n# Create installation administrative file for Solaris platform if needed\necho \"mail=\" > scx-admin\necho \"instance=overwrite\" >> scx-admin\necho \"partial=nocheck\" >> scx-admin\necho \"idepend=quit\" >> scx-admin\necho \"rdepend=quit\" >> scx-admin\necho \"conflict=nocheck\" >> scx-admin\necho \"action=nocheck\" >> scx-admin\necho \"basedir=default\" >> scx-admin\n\necho \"mail=\" > scx-admin-upgrade\necho \"instance=overwrite\" >> scx-admin-upgrade\necho \"partial=nocheck\" >> scx-admin-upgrade\necho \"idepend=quit\" >> scx-admin-upgrade\necho \"rdepend=nocheck\" >> scx-admin-upgrade\necho \"conflict=nocheck\" >> scx-admin-upgrade\necho \"action=nocheck\" >> scx-admin-upgrade\necho \"basedir=default\" >> scx-admin-upgrade\n\n# Do we need to remove the package?\nif [ \"$installMode\" = \"R\" -o \"$installMode\" = \"P\" ]\nthen\n if [ -f /opt/microsoft/scx/bin/uninstall ]; then\n /opt/microsoft/scx/bin/uninstall $installMode\n else\n pkg_rm scx\n pkg_rm omi\n fi\n\n if [ \"$installMode\" = \"P\" ]\n then\n echo \"Purging all files in cross-platform agent ...\"\n rm -rf /etc/opt/microsoft/scx /opt/microsoft/scx /var/opt/microsoft/scx\n rmdir /etc/opt/microsoft /opt/microsoft /var/opt/microsoft 1>/dev/null 2>/dev/null\n\n # If OMI is not installed, purge its directories as well.\n check_if_pkg_is_installed omi\n if [ $? -ne 0 ]; then\n rm -rf /etc/opt/omi /opt/omi /var/opt/omi\n fi\n fi\nfi\n\nif [ -n \"${shouldexit}\" ]\nthen\n # when extracting script/tarball don't also install\n cleanup_and_exit 0\nfi\n\n#\n# Do stuff before extracting the binary here, for example test [ `id -u` -eq 0 ],\n# validate space, platform, uninstall a previous version, backup config data, etc...\n#\n\n#\n# Extract the binary here.\n#\n\necho \"Extracting...\"\ntail +${SCRIPT_LEN_PLUS_ONE} \"${SCRIPT}\" | zcat - | tar xf -\nSTATUS=$?\nif [ ${STATUS} -ne 0 ]\nthen\n echo \"Failed: could not extract the install bundle.\"\n cleanup_and_exit ${STATUS}\nfi\n\n#\n# Do stuff after extracting the binary here, such as actually installing the package.\n#\n\nEXIT_STATUS=0\nSCX_EXIT_STATUS=0\nOMI_EXIT_STATUS=0\n\ncase \"$installMode\" in\n E)\n # Files are extracted, so just exit\n cleanup_and_exit 0 \"SAVE\"\n ;;\n\n I)\n echo \"Installing cross-platform agent ...\"\n check_if_pkg_is_installed scx\n if [ $? -eq 0 ]; then\n echo \"ERROR: SCX package is already installed\"\n cleanup_and_exit 2\n fi\n\n check_if_pkg_is_installed omi\n if [ $? -eq 0 ]; then\n shouldInstall_omi\n pkg_upd $OMI_PKG omi $?\n OMI_EXIT_STATUS=$?\n else\n pkg_add $OMI_PKG omi\n OMI_EXIT_STATUS=$?\n fi\n\n pkg_add $OM_PKG scx\n SCX_EXIT_STATUS=$?\n\n ;;\n\n U)\n echo \"Updating cross-platform agent ...\"\n check_if_pkg_is_installed omi\n if [ $? -eq 0 ]; then\n shouldInstall_omi\n pkg_upd $OMI_PKG omi $?\n OMI_EXIT_STATUS=$?\n else\n pkg_add $OMI_PKG omi\n OMI_EXIT_STATUS=$?\n fi\n\n shouldInstall_scx\n pkg_upd $OM_PKG scx $?\n SCX_EXIT_STATUS=$?\n\n ;;\n\n *)\n echo \"$0: Invalid setting of variable \\$installMode, exiting\" >&2\n cleanup_and_exit 2\nesac\n\n# Remove temporary files (now part of cleanup_and_exit) and exit\n\nif [ \"$SCX_EXIT_STATUS\" -ne 0 -o \"$OMI_EXIT_STATUS\" -ne 0 ]; then\n cleanup_and_exit 1\nelse\n cleanup_and_exit 0\nfi\n\n#####>>- This must be the last line of this script, followed by a single empty line. -<<#####\n" }, { "alpha_fraction": 0.5980901718139648, "alphanum_fraction": 0.6007426977157593, "avg_line_length": 38.7679328918457, "blob_id": "39e748cca6f8cf1e222e88380a75dd1e24dbbc3b", "content_id": "b7dc63da1407476eeb3bf5eba4149f701f30fcdc", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9425, "license_type": "permissive", "max_line_length": 126, "num_lines": 237, "path": "/source/code/providers/support/appserver/manipulateappserverinstances.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file manipulateappserverinstances.cpp\n\n \\brief Manipulates vectors of application server instances\n\n \\date 11-05-26 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n#include <algorithm>\n#include <string>\n#include <sstream>\n#include <vector>\n\n#include <scxcorelib/scxcmn.h>\n\n#include <scxcorelib/stringaid.h>\n\n#include \"appserverinstance.h\"\n#include \"manipulateappserverinstances.h\"\n\nusing namespace std;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXSystemLib\n{\n\n /*-----------------------------------------------------------------*/\n /**\n Merge the processes and cache to a single list and remove\n duplicates. This is done by using some of the STL vector methods.\n First, merge both of the arrays. The processes should be first. \n Next sort the items based-on the path. At this point, the duplicates\n (duplicates by means of the same path)\n\n \\param[in] processes - vector of Application Server Instances of \n running processes\n \\param[in] cache - vector of Application Server Instances from the cache\n \\param[out] result - vector where the merged results will be placed.\n\n */\n void ManipulateAppServerInstances::MergeProcessesAndCache(\n vector<SCXHandle<AppServerInstance> >& processes,\n vector<SCXHandle<AppServerInstance> >& cache,\n vector<SCXHandle<AppServerInstance> >& result)\n {\n result.clear();\n \n result.insert( result.end(), processes.begin(), processes.end() );\n result.insert( result.end(), cache.begin(), cache.end() );\n \n sort(result.begin(), result.end(), PathOrdering);\n vector<SCXHandle<AppServerInstance> >::iterator tmp =\n unique(result.begin(), result.end(), PathCompare);\n result.resize(tmp-result.begin());\n }\n\n /*-----------------------------------------------------------------*/\n /**\n Given the current list of instances as well as a list of the recently\n discovered processes, merge these together to provide an updated list of\n the running processes.\n\n Assumption #1: Disk Path is the unique identifier of an instance\n Assumption #2: the runningProcesses all have IsRunning set to true\n Assumption #3: 'someone else' has already called update on the instances\n\n The steps for doing so are as follows:\n\n 1) Remove any previously known instance that is no longer on disk\n 2) Cycle through the remaining known instances and set IsRunning to false\n 3) Add the list of running process to the front of the known instances\n 4) Sort the list based on disk path so that it is guaranteed that\n the process item is followed by it's previously known state (if there\n was one)\n 5) If the next item has the same path, then next item is the previously\n known state of the current one (and implicitly this item is from the list\n of running processes). It also means that the Deep Monitored flag should\n be copied from the previous known state to the current one.\n 6) Remove the duplicates (i.e. previously known states) from the list\n\n \\param[in/out] previouslyKnownInstances - vector of previously known\n Application Server Instances\n \\param[in] runningProcesses - vector of Application Server Instances\n representing a list of running processes\n \\param[in] remover - predicate object for removing non-existent\n application server instances. \n */\n void ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n vector<SCXHandle<AppServerInstance> >& previouslyKnownInstances,\n vector<SCXHandle<AppServerInstance> >& runningProcesses,\n SCXHandle<IRemoveNonexistentAppServerInstances> remover)\n {\n SCXLogHandle logger = SCXLogHandleFactory::GetLogHandle(L\"scx.core.common.pal.system.appserver.appserverenumeration\");\n SCX_LOGTRACE(logger, L\"Removing nonexistent instances\");\n\n remover->RemoveNonexistentInstances(previouslyKnownInstances);\n\n SCX_LOGTRACE(logger,\n StrAppend(L\"size after removing non-existent instances: \",\n previouslyKnownInstances.size()));\n\n // Set all items previously known to be not running\n SCX_LOGTRACE(logger, L\"Marking previously known to not running\");\n\n transform(\n previouslyKnownInstances.begin(),\n previouslyKnownInstances.end(),\n previouslyKnownInstances.begin(),\n SetIsRunningToFalse);\n\n SCX_LOGTRACE(logger, L\"Merging running processes to the front of the known instances\");\n\n // Insert the running process to the front of the known instance list\n previouslyKnownInstances.insert( \n previouslyKnownInstances.begin(),\n runningProcesses.begin(),\n runningProcesses.end() );\n\n SCX_LOGTRACE(logger, L\"Sort the list of known instances (with processes)\");\n\n // Sort the list \n sort(\n previouslyKnownInstances.begin(), \n previouslyKnownInstances.end(), \n PathOrdering);\n\n SCX_LOGTRACE(logger, L\"Setting Deep Monitored flags\");\n\n // Copy the state of the Deep Monitored flag from the previous entry\n // (this is a little confusing because we have a pointer to a pointer \n // [e.g. an iterator to a SCXHandle] and we are doing pointer arithmetic\n // on the iterator)\n for( vector< SCXHandle<AppServerInstance> >::iterator p =\n previouslyKnownInstances.begin(); \n previouslyKnownInstances.end() != p; \n ++p)\n {\n if ( (p+1 != previouslyKnownInstances.end()) && \n ((*p)->GetDiskPath() == (*(p+1))->GetDiskPath()) )\n {\n (*p)->SetIsDeepMonitored((*(p+1))->GetIsDeepMonitored(), (*(p+1))->GetProtocol());\n }\n }\n \n\n // remove duplicate entries\n SCX_LOGTRACE(logger, L\"Removing duplicate instances\");\n\n vector<SCXHandle<AppServerInstance> >::iterator newLastElement =\n unique(\n previouslyKnownInstances.begin(), \n previouslyKnownInstances.end(), \n PathCompare);\n\n previouslyKnownInstances.resize(\n newLastElement-previouslyKnownInstances.begin());\n \n SCX_LOGTRACE(logger,\n StrAppend(L\"size after removing duplicates: \",\n previouslyKnownInstances.size()));\n\n }\n\n /*\n Delegate method used comparing AppServerInstances based-on\n their path on disk. Other properties like running state and\n port are not used because only the path on disk is important\n for removing duplicates between the process list and the cache.\n\n \\param[in] i - handle to a AppServerInstance\n \\param[in] j - handle to another AppServerInstance\n \\returns true if a string comparision determines that \n path on disk for element i is equal to the \n path on disk for element j\n\n */\n bool ManipulateAppServerInstances::PathCompare (\n SCXHandle<AppServerInstance> i, \n SCXHandle<AppServerInstance> j) \n { \n return i->GetDiskPath() == j->GetDiskPath();\n }\n\n /*\n Delegate method used for ordering the AppServerInstances\n by their path.\n\n \\param[in] i - handle to a AppServerInstance\n \\param[in] j - handle to another AppServerInstance\n \\returns true if a string comparision determines that \n path on disk for element i is less than the\n path on disk for element j\n */\n bool ManipulateAppServerInstances::PathOrdering (\n SCXHandle<AppServerInstance> i, \n SCXHandle<AppServerInstance> j) \n { \n bool result = false;\n\n // In general, the sorting is done by comparing/deciding\n // the paths of the application server instances. In the\n // event that the paths are equal, then the sorting is\n // done by the IsRunning property (the running ones should\n // be in front).\n if (i->GetDiskPath() == j->GetDiskPath())\n {\n result = i->GetIsRunning();\n }\n else\n {\n result = i->GetDiskPath() < j->GetDiskPath();\n }\n\n return result;\n }\n\n /*\n Delegate method setting the IsRunning flag to false\n \n \\param[in] i - handle to a AppServerInstance\n \\returns a copy of the input element with the IsRunning flag\n set to false\n */\n SCXHandle<AppServerInstance> ManipulateAppServerInstances::SetIsRunningToFalse(\n SCXHandle<AppServerInstance> i) \n { \n i->SetIsRunning(false);\n return i;\n }\n\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6136382818222046, "alphanum_fraction": 0.6163489818572998, "avg_line_length": 33.31686019897461, "blob_id": "3427f2cd2c4b9d560e2ffdd819f1ac6edc699863", "content_id": "43be7a306e4e5796600a48e5e392beeaf011acc3", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11805, "license_type": "permissive", "max_line_length": 142, "num_lines": 344, "path": "/source/code/providers/SCX_LogFile_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_LogFile_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-22-2013 17:48:44\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_LogFile_Class_Provider.h\"\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxfilesystem.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/stringaid.h>\n\n#include \"support/logfileprovider.h\"\n#include \"support/scxcimutils.h\"\n\n#include <errno.h>\n#include <iostream>\n\nusing namespace SCXCoreLib;\n\nMI_BEGIN_NAMESPACE\n\nstatic void InsertOneString(\n Context& context,\n std::vector<mi::String>& stringArray,\n const std::wstring& in)\n{\n mi::String str( SCXCoreLib::StrToUTF8(in).c_str() );\n stringArray.push_back( str );\n}\n\nSCX_LogFile_Class_Provider::SCX_LogFile_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_LogFile_Class_Provider::~SCX_LogFile_Class_Provider()\n{\n}\n\nvoid SCX_LogFile_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::LogFileProvider::Lock\"));\n SCXCore::g_LogFileProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_LogFileProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_LogFile_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_LogFile_Class_Provider::Load\", SCXCore::g_LogFileProvider.GetLogHandle() );\n}\n\nvoid SCX_LogFile_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::LogFileProvider::Lock\"));\n SCXCore::g_LogFileProvider.Unload();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_LogFile_Class_Provider::Load\", SCXCore::g_LogFileProvider.GetLogHandle() );\n}\n\nvoid SCX_LogFile_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_LogFile_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_LogFile_Class& instanceName,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_LogFile_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_LogFile_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_LogFile_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_LogFile_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_LogFile_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_LogFile_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_LogFile_Class_Provider::Invoke_GetMatchedRows(\n Context& context,\n const String& nameSpace,\n const SCX_LogFile_Class& instanceName,\n const SCX_LogFile_GetMatchedRows_Class& in)\n{\n /*\n * To return data, we have to post a single instance that contains an array of strings\n * MOF format: [OUT, ArrayType(\"Ordered\")] string rows[]\n *\n * Here's some sample code that will do the trick:\n *\n * SCX_LogFile_GetMatchedRows_Class inst;\n * std::vector<mi::String> fakeData;\n *\n * fakeData.push_back( mi::String(\"data1\") );\n * fakeData.push_back( mi::String(\"data2\") );\n *\n * StringA rows(&fakeData[0], static_cast<MI_Uint32>(fakeData.size()));\n * inst.rows_value( rows );\n *\n * context.Post(inst);\n * context.Post(MI_RESULT_OK);\n */\n\n SCXCoreLib::SCXLogHandle log = SCXCore::g_LogFileProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"LogFile Provider Invoke begin\");\n\n SCX_PEX_BEGIN\n {\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::LogFileProvider::Lock\"));\n\n // Validate that we have mandatory arguments\n if ( !in.filename_exists() || !in.regexps_exists() || !in.qid_exists() )\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n // Get the arguments:\n // filename : string\n // regexps : string array\n // qid : string\n // elevationType : [Optional] string\n\n std::wstring filename = SCXCoreLib::StrFromMultibyte( in.filename_value().Str() );\n const StringA regexps_sa = in.regexps_value();\n std::wstring qid = SCXCoreLib::StrFromMultibyte( in.qid_value().Str() );\n std::wstring elevationType = SCXCoreLib::StrFromMultibyte( in.elevationType_value().Str() );\n\n bool fPerformElevation = false;\n if ( elevationType.length() )\n {\n if ( SCXCoreLib::StrToLower(elevationType) != L\"sudo\" )\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n fPerformElevation = true;\n }\n\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCXLogFileProvider::InvokeMatchedRows - filename = \", filename));\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCXLogFileProvider::InvokeMatchedRows - qid = \", qid));\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCXLogFileProvider::InvokeMatchedRows - regexp count = \", regexps_sa.GetSize()));\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCXLogFileProvider::InvokeMatchedRows - elevate = \", elevationType));\n\n // Extract and parse the regular expressions\n\n std::vector<SCXRegexWithIndex> regexps;\n std::wstring invalid_regex(L\"\");\n \n for (size_t i=0; i<regexps_sa.GetSize(); i++)\n {\n std::wstring regexp = SCXCoreLib::StrFromMultibyte(regexps_sa[static_cast<MI_Uint32>(i)].Str());\n\n SCX_LOGTRACE(log, StrAppend(L\"SCXLogFileProvider::InvokeMatchedRows - regexp = \", regexp));\n\n try\n {\n SCXRegexWithIndex regind;\n regind.regex = new SCXRegex(regexp);\n regind.index = i;\n regexps.push_back(regind);\n }\n catch (SCXInvalidRegexException& e)\n {\n SCX_LOGWARNING(log, StrAppend(L\"SCXLogFileProvider DoInvokeMethod - invalid regexp : \", regexp));\n invalid_regex = StrAppend(StrAppend(invalid_regex, invalid_regex.length()>0?L\" \":L\"\"), i);\n }\n }\n\n // We have to post a single instance that contains an array of strings\n // MOF format: [OUT, ArrayType(\"Ordered\")] string rows[]\n std::vector<mi::String> returnData;\n\n // If any regular expressions with invalid syntax, add special row to result\n if (invalid_regex.length() > 0)\n {\n InsertOneString( context, returnData, StrAppend(L\"InvalidRegexp;\", invalid_regex));\n }\n\n SCX_LogFile_GetMatchedRows_Class inst;\n try\n {\n // Call helper function to get the data\n std::vector<std::wstring> matchedLines;\n bool bWasPartialRead = SCXCore::g_LogFileProvider.InvokeLogFileReader(\n filename, qid, regexps, fPerformElevation, matchedLines);\n\n // Add each match to the result property set\n //\n // Reserve space in the vector for efficiency:\n // Current size + # of lines to add + 1 (for potential \"MoreRowsAvailable\")\n returnData.reserve( returnData.size() + matchedLines.size() + 1 );\n for (std::vector<std::wstring>::iterator it = matchedLines.begin();\n it != matchedLines.end();\n it++)\n {\n InsertOneString( context, returnData, *it );\n }\n\n // Set \"MoreRowsAvailable\" if we terminated early\n if (bWasPartialRead)\n {\n InsertOneString( context, returnData, L\"MoreRowsAvailable;true\" );\n }\n\n StringA rows(&returnData[0], static_cast<MI_Uint32>(returnData.size()));\n inst.rows_value( rows );\n }\n catch (SCXCoreLib::SCXFilePathNotFoundException& e)\n {\n SCX_LOGWARNING(log, SCXCoreLib::StrAppend(L\"LogFileProvider DoInvokeMethod - File not found: \", filename).append(e.What()));\n }\n\n // Set the return value (the number of lines returned)\n inst.MIReturn_value( static_cast<MI_Uint32> (returnData.size()) );\n\n context.Post(inst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_LogFile_Class_Provider::Load\", log );\n\n SCX_LOGTRACE(log, L\"LogFile Provider Invoke end\");\n}\n\nvoid SCX_LogFile_Class_Provider::Invoke_ResetStateFile(\n Context& context,\n const String& nameSpace,\n const SCX_LogFile_Class& instanceName,\n const SCX_LogFile_ResetStateFile_Class& in)\n{\n SCXCoreLib::SCXLogHandle log = SCXCore::g_LogFileProvider.GetLogHandle();\n\n SCX_PEX_BEGIN\n {\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::LogFileProvider::Lock\"));\n\n // Validate that we have mandatory arguments\n if ( !in.filename_exists() || !in.qid_exists() )\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n // Get the arguments:\n // filename : string\n // qid : string\n // resetOnRead: : boolean\n // elevationType : [Optional] string\n\n std::wstring filename = SCXCoreLib::StrFromMultibyte( in.filename_value().Str() );\n std::wstring qid = SCXCoreLib::StrFromMultibyte( in.qid_value().Str() );\n bool resetOnRead = in.resetOnRead_value();\n std::wstring elevationType = SCXCoreLib::StrFromMultibyte( in.elevationType_value().Str() );\n\n bool fPerformElevation = false;\n if ( elevationType.length() )\n {\n if ( SCXCoreLib::StrToLower(elevationType) != L\"sudo\" )\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n fPerformElevation = true;\n }\n\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCXLogFileProvider::InvokeResetStateFile - filename = \", filename));\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCXLogFileProvider::InvokeResetStateFile - qid = \", qid));\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCXLogFileProvider::InvokeResetStateFile - resetOnRead = \", resetOnRead));\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"SCXLogFileProvider::InvokeResetStateFile - elevate = \", elevationType));\n\n int returnStatus;\n SCX_LogFile_ResetStateFile_Class inst;\n try\n {\n // Call helper function to get the data\n returnStatus = SCXCore::g_LogFileProvider.InvokeResetStateFile(\n filename, qid, resetOnRead, fPerformElevation);\n }\n catch (SCXCoreLib::SCXFilePathNotFoundException& e)\n {\n SCX_LOGWARNING(log, SCXCoreLib::StrAppend(L\"LogFileProvider InvokeResetStateFile - File not found: \", filename).append(e.What()));\n returnStatus = ENOENT;\n }\n\n // Set the return value\n inst.MIReturn_value( returnStatus );\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_LogFile_Class_Provider::Load\", log );\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.5946614146232605, "alphanum_fraction": 0.6015818119049072, "avg_line_length": 24.923076629638672, "blob_id": "941bfe50c5f352a6bfd1b6336e4878a112f84ae1", "content_id": "4cfe5b737e56037db5f3b1780f8e16f3763f658f", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2023, "license_type": "permissive", "max_line_length": 112, "num_lines": 78, "path": "/test/code/shared/tools/scx_admin/cimconfigurator_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. \n \n*/\n/**\n \\file \n\n \\brief Tests for cim (i.e. openpegasus) configurator functionality which is part of the scx_admin tool\n\n \\date 2008-08-27 11:08:12\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <cimconfigurator.h> \n#include <testutils/scxunit.h> /* This will include CPPUNIT helper macros too */\n\n#include <scxcorelib/scxexception.h> \n\n#include <iostream>\n\nusing namespace std;\n\n\n//#define RUN_SERVER_TESTS\n\nclass CIMOMConfigTest : public CPPUNIT_NS::TestFixture, public SCX_CimConfigurator\n{\n CPPUNIT_TEST_SUITE( CIMOMConfigTest );\n\n CPPUNIT_TEST( TestLogRotate );\n CPPUNIT_TEST( TestPrint );\n CPPUNIT_TEST( TestReset );\n CPPUNIT_TEST( TestSet );\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\n\npublic:\n void setUp(void)\n {\n }\n\n void tearDown(void)\n {\n }\n\n void TestLogRotate(void)\n {\n // LogRotate isn't supported by OMI - be sure method returns false\n CPPUNIT_ASSERT_MESSAGE(\"Unexpected return value from method LogRotate()\", LogRotate() == false);\n }\n\n void TestPrint(void)\n {\n // Print isn't supported by OMI - be sure method returns false\n std::wostringstream buf;\n CPPUNIT_ASSERT_MESSAGE(\"Unexpected return value from method Print()\", Print(buf) == false);\n }\n\n void TestReset(void)\n {\n // Reset isn't supported by OMI - be sure method returns false\n CPPUNIT_ASSERT_MESSAGE(\"Unexpected return value from method Reset()\", Reset() == false);\n }\n\n void TestSet(void)\n {\n // Set isn't supported by OMI - be sure method returns false\n\n LogLevelEnum level = eLogLevel_Verbose;\n CPPUNIT_ASSERT_MESSAGE(\"Unexpected return value from method Set()\", Set(level) == false);\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( CIMOMConfigTest ); \n" }, { "alpha_fraction": 0.4406779706478119, "alphanum_fraction": 0.44703391194343567, "avg_line_length": 26.211538314819336, "blob_id": "eb12e13f244726f0b60d2bce92d9bf7c155dc6c8", "content_id": "7b2fad5e91207d8ce2b9806be42e4b2f04173877", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1416, "license_type": "permissive", "max_line_length": 108, "num_lines": 52, "path": "/source/code/providers/support/memoryprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n * \n * */\n /**\n \\file memoryprovider.cpp\n\n \\brief Memory provider implementation\n \n \\date 04-18-13 \n*/\n/*----------------------------------------------------------------------------*/\n\n#include \"startuplog.h\"\n#include \"memoryprovider.h\"\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nnamespace SCXCore\n{\n void MemoryProvider::Load()\n {\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.memoryprovider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"MemoryProvider::Load()\");\n\n m_memEnum = new MemoryEnumeration();\n m_memEnum->Init();\n }\n }\n\n void MemoryProvider::Unload()\n {\n SCX_LOGTRACE(m_log, L\"MemoryProvider::Unload()\");\n if (0 == --ms_loadCount)\n {\n if (m_memEnum != NULL)\n {\n m_memEnum->CleanUp();\n m_memEnum == NULL;\n }\n }\n }\n\n SCXCore::MemoryProvider g_MemoryProvider;\n int SCXCore::MemoryProvider::ms_loadCount = 0;\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n\n" }, { "alpha_fraction": 0.6459973454475403, "alphanum_fraction": 0.6479350924491882, "avg_line_length": 32.565040588378906, "blob_id": "24976d57804747679e8b02096c58b50e8c76651e", "content_id": "d92d70e4aecfc4cde56dedbe52aaaa3419ddad66", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8257, "license_type": "permissive", "max_line_length": 113, "num_lines": 246, "path": "/test/code/shared/tools/scx_admin/service_control_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. \n \n*/\n/**\n \\file \n\n \\brief Service control test class.\n\n \\date 2008-08-28 08:22:00\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <servicecontrol.h>\n#include <testutils/scxunit.h>\n\n#include <scxcorelib/scxexception.h>\n\nclass TestServiceControlCimom : public SCX_CimomServiceControl\n{\npublic:\n TestServiceControlCimom() \n : SCX_CimomServiceControl()\n {\n\n }\n \n virtual ~TestServiceControlCimom() { }\n\n std::wstring GetName() { return m_name; }\n std::wstring GetStart() { return m_start; }\n std::wstring GetStop() { return m_stop; }\n};\n\nclass TestServiceControlProvider : public SCX_ProviderServiceControl\n{\npublic:\n TestServiceControlProvider()\n : SCX_ProviderServiceControl()\n {\n\n }\n\n TestServiceControlProvider(const std::wstring& name)\n : SCX_ProviderServiceControl()\n {\n m_name = name;\n }\n\n virtual ~TestServiceControlProvider() { }\n\n std::wstring GetName() { return m_name; }\n};\n\nclass ServiceControlTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( ServiceControlTest );\n CPPUNIT_TEST( ServiceNamesCorrect );\n CPPUNIT_TEST( StartScriptForCimdOK );\n CPPUNIT_TEST( StopScriptForCimdOK );\n CPPUNIT_TEST( ServiceStartRunsScriptOK );\n CPPUNIT_TEST( ServiceStopRunsScriptOK );\n CPPUNIT_TEST( ServiceRestartRunsScriptOK );\n CPPUNIT_TEST( ServiceStatusForRunningProcessOK );\n CPPUNIT_TEST( ServiceStatusForStoppedProcessOK );\n CPPUNIT_TEST( ServiceCommandNotFound );\n CPPUNIT_TEST( ServiceCommandFails );\n CPPUNIT_TEST( StartProviderShouldFail );\n CPPUNIT_TEST( RestartProviderShouldOnlyStop );\n CPPUNIT_TEST( StatusProviderWhenNotRunningOK );\n CPPUNIT_TEST( StatusProviderWhenRunningOK );\n CPPUNIT_TEST( StopProviderWhenNotStartedOK );\n\n SCXUNIT_TEST_ATTRIBUTE(ServiceStartRunsScriptOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(ServiceStopRunsScriptOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(ServiceRestartRunsScriptOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(ServiceStatusForRunningProcessOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(ServiceStatusForStoppedProcessOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(ServiceCommandNotFound, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(ServiceCommandFails, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(RestartProviderShouldOnlyStop, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(StatusProviderWhenNotRunningOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(StatusProviderWhenRunningOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(StopProviderWhenNotStartedOK, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\npublic:\n void setUp(void)\n {\n\n }\n\n void tearDown(void)\n {\n\n }\n\n void ServiceNamesCorrect(void)\n {\n TestServiceControlCimom cimom;\n TestServiceControlProvider provider;\n CPPUNIT_ASSERT(cimom.GetName() == L\"omiserver\");\n CPPUNIT_ASSERT(provider.GetName() == L\"omiagent\");\n }\n\n void StartScriptForCimdOK(void)\n {\n TestServiceControlCimom svc;\n CPPUNIT_ASSERT(svc.GetStart() == L\"/opt/omi/bin/service_control start\");\n }\n\n void StopScriptForCimdOK(void)\n {\n TestServiceControlCimom svc;\n CPPUNIT_ASSERT(svc.GetStop() == L\"/opt/omi/bin/service_control stop\");\n }\n\n void ServiceStartRunsScriptOK(void)\n {\n SCX_AdminServiceControl svc(L\"dummy\", L\"echo START\", L\"echo STOP\");\n std::wstring info;\n CPPUNIT_ASSERT(svc.Start(info));\n CPPUNIT_ASSERT(info == L\"START\\n\");\n }\n\n void ServiceStopRunsScriptOK(void)\n {\n SCX_AdminServiceControl svc(L\"dummy\", L\"echo START\", L\"echo STOP\");\n std::wstring info;\n CPPUNIT_ASSERT(svc.Stop(info));\n CPPUNIT_ASSERT(info == L\"STOP\\n\");\n }\n\n void ServiceRestartRunsScriptOK(void)\n {\n SCX_AdminServiceControl svc(L\"dummy\", L\"echo START\", L\"echo STOP\");\n std::wstring info;\n CPPUNIT_ASSERT(svc.Restart(info));\n CPPUNIT_ASSERT(info == L\"STOP\\nSTART\\n\");\n }\n\n void ServiceStatusForRunningProcessOK(void)\n {\n SCX_AdminServiceControl svc(L\"testrunner\", L\"echo START\", L\"echo STOP\");\n std::wstring info;\n\n CPPUNIT_ASSERT(svc.Status(info));\n\n std::ostringstream msg;\n msg << \"Info: \" << StrToMultibyte(info) << std::endl;\n\n CPPUNIT_ASSERT_MESSAGE(msg.str().c_str(), info.find(L\"testrunner\") != std::wstring::npos);\n CPPUNIT_ASSERT_MESSAGE(msg.str().c_str(), info.find(L\"running\") != std::wstring::npos);\n CPPUNIT_ASSERT_MESSAGE(msg.str().c_str(), info.find(L\"stopped\") == std::wstring::npos);\n }\n\n void ServiceStatusForStoppedProcessOK(void)\n {\n SCX_AdminServiceControl svc(L\"process_not_started\", L\"echo START\", L\"echo STOP\");\n std::wstring info;\n CPPUNIT_ASSERT(svc.Status(info));\n CPPUNIT_ASSERT(info.find(L\"process_not_started\") != std::wstring::npos);\n CPPUNIT_ASSERT(info.find(L\"stopped\") != std::wstring::npos);\n CPPUNIT_ASSERT(info.find(L\"running\") == std::wstring::npos);\n }\n\n void ServiceCommandNotFound(void)\n {\n SCX_AdminServiceControl svc(L\"not_found\", L\"./script_not_found.sh start\", L\"./script_not_found.sh stop\");\n std::wstring info;\n CPPUNIT_ASSERT_THROW(svc.Start(info), SCXAdminException);\n CPPUNIT_ASSERT_THROW(svc.Stop(info), SCXAdminException);\n CPPUNIT_ASSERT_THROW(svc.Restart(info), SCXAdminException);\n }\n\n void ServiceCommandFails(void)\n {\n SCX_AdminServiceControl svc(L\"failing_process\", L\"grep dummy dummy.txt\", L\"grep dummy dummy.txt\");\n std::wstring info;\n CPPUNIT_ASSERT_THROW(svc.Start(info), SCXAdminException);\n CPPUNIT_ASSERT_THROW(svc.Stop(info), SCXAdminException);\n CPPUNIT_ASSERT_THROW(svc.Restart(info), SCXAdminException);\n // verify the return code is part of exception description\n try {\n svc.Start(info);\n CPPUNIT_FAIL(\"SCXAdminException not thrown\");\n } catch (SCXAdminException& e) {\n CPPUNIT_ASSERT(e.What().find(L\"RETURN CODE\") != std::wstring::npos);\n }\n }\n\n void StartProviderShouldFail()\n {\n SCX_ProviderServiceControl svc;\n std::wstring info;\n CPPUNIT_ASSERT_MESSAGE(\"Start is not supported for providers\", ! svc.Start(info));\n }\n\n void RestartProviderShouldOnlyStop()\n {\n TestServiceControlProvider svc(L\"process_not_started\");\n std::wstring info;\n CPPUNIT_ASSERT(svc.Restart(info));\n CPPUNIT_ASSERT(info.find(L\"process_not_started\") != std::wstring::npos);\n CPPUNIT_ASSERT(info.find(L\"0 instances stopped\") != std::wstring::npos);\n CPPUNIT_ASSERT(info.find(L\"not started\") != std::wstring::npos);\n }\n\n void StatusProviderWhenNotRunningOK()\n {\n TestServiceControlProvider svc(L\"process_not_started\");\n std::wstring info;\n CPPUNIT_ASSERT(svc.Status(info));\n CPPUNIT_ASSERT(info.find(L\"process_not_started\") != std::wstring::npos);\n CPPUNIT_ASSERT(info.find(L\"stopped\") != std::wstring::npos);\n CPPUNIT_ASSERT(info.find(L\"running\") == std::wstring::npos);\n }\n\n void StatusProviderWhenRunningOK()\n {\n TestServiceControlProvider svc(L\"testrunner\");\n std::wstring info;\n CPPUNIT_ASSERT(svc.Status(info));\n\n std::ostringstream msg;\n msg << \"Info: \" << StrToMultibyte(info) << std::endl;\n\n CPPUNIT_ASSERT_MESSAGE(msg.str().c_str(), info.find(L\"testrunner\") != std::wstring::npos);\n CPPUNIT_ASSERT_MESSAGE(msg.str().c_str(), info.find(L\"stopped\") == std::wstring::npos);\n CPPUNIT_ASSERT_MESSAGE(msg.str().c_str(), info.find(L\"running\") != std::wstring::npos);\n }\n\n void StopProviderWhenNotStartedOK()\n {\n TestServiceControlProvider svc(L\"process_not_started\");\n std::wstring info;\n CPPUNIT_ASSERT(svc.Stop(info));\n CPPUNIT_ASSERT(info.find(L\"process_not_started\") != std::wstring::npos);\n CPPUNIT_ASSERT(info.find(L\"0 instances stopped\") != std::wstring::npos);\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( ServiceControlTest );\n" }, { "alpha_fraction": 0.5314737558364868, "alphanum_fraction": 0.5370525121688843, "avg_line_length": 28.79224395751953, "blob_id": "5a7e6eed9181003fdaef45c8d73b6a26397a2ddb", "content_id": "33cb8820ff0028ba6e6afbe611b505f8dbff1675", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10755, "license_type": "permissive", "max_line_length": 136, "num_lines": 361, "path": "/source/code/shared/tools/scx_admin/servicecontrol.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n \n*/\n/**\n \\file \n\n \\brief Implements service start functions for SCX\n \n \\date 2008-08-28 08:52\n \n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxprocess.h>\n#include <scxcorelib/scxthread.h>\n#if !defined(SCX_STACK_ONLY) \n#include <scxsystemlib/processenumeration.h>\n#endif\n#include <servicecontrol.h>\n\n#include <signal.h>\n\n/*----------------------------------------------------------------------------*/\n/**\n Construcor for generic SCX service controller.\n \n \\param name Process name of service.\n \\param start_command A command that starts the service.\n \\param stop_command A command that stops the service.\n*/\nSCX_AdminServiceControl::SCX_AdminServiceControl( const std::wstring& name,\n const std::wstring& start_command,\n const std::wstring& stop_command)\n : m_name(name)\n , m_start(start_command)\n , m_stop(stop_command)\n{\n\n}\n \n/*----------------------------------------------------------------------------*/\n/**\n Virtual destructor.\n*/\nSCX_AdminServiceControl::~SCX_AdminServiceControl()\n{\n\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n \\copydoc SCX_AdminServiceManagementAPI::Start\n*/\nbool SCX_AdminServiceControl::Start( std::wstring& info ) const\n{\n ExecuteCommand(m_start, info);\n return true;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n \\copydoc SCX_AdminServiceManagementAPI::Stop\n*/\nbool SCX_AdminServiceControl::Stop( std::wstring& info ) const\n{\n static const unsigned int cMaxSleepTime = 10000;\n static const unsigned int cMaxTries = 20;\n\n unsigned int count = 0;\n ExecuteCommand(m_stop, info);\n\n // Wait max 10 seconds for process to die\n while (count < cMaxTries && CountProcessesAlive() > 0)\n {\n SCXThread::Sleep(cMaxSleepTime / cMaxTries);\n count++;\n }\n\n return true;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n \\copydoc SCX_AdminServiceManagementAPI::Restart\n*/\nbool SCX_AdminServiceControl::Restart( std::wstring& info ) const\n{\n std::wstring infoStart, infoStop;\n try\n {\n Stop(infoStop);\n }\n catch (SCXAdminException& /*ignored*/)\n {\n // This is ignored. Even if the stop command failed we will still try to\n // start it again.\n }\n\n bool r = Start(infoStart);\n info = SCXCoreLib::StrAppend(infoStop, infoStart);\n return r;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Check if the process name handled is alive\n\n \\returns true if process name is found, else false\n*/\nunsigned int SCX_AdminServiceControl::CountProcessesAlive( ) const\n{\n#if !defined(SCX_STACK_ONLY)\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessEnumeration> procEnum(\n new SCXSystemLib::ProcessEnumeration() );\n procEnum->SampleData();\n procEnum->Update(true);\n std::vector<SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> > procList = procEnum->Find(m_name);\n return static_cast<unsigned int>(procList.size());\n#else\n std::wstring info;\n#if defined(aix) || defined(hpux) || defined(sun)\n const std::wstring cmd1 = L\"/bin/sh -c \\\"ps -A -o command | grep \";\n#else\n const std::wstring cmd1 = L\"/bin/sh -c \\\"ps -A -w -o command | grep \";\n#endif\n const std::wstring cmd2 = L\" | grep -v grep | wc -l\\\"\";\n\n std::wstring cmd = cmd1 + m_name + cmd2;\n ExecuteCommand(cmd, info);\n\n return StrToUInt(info);\n#endif\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n \\copydoc SCX_AdminServiceManagementAPI::Status\n*/\nbool SCX_AdminServiceControl::Status( std::wstring& info ) const\n{\n info = SCXCoreLib::StrAppend(m_name, L\": is \");\n if (CountProcessesAlive() > 0) \n {\n info = SCXCoreLib::StrAppend(info, L\"running\");\n }\n else\n {\n info = SCXCoreLib::StrAppend(info, L\"stopped\");\n }\n \n return true;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Helper method to execute start/stop commands.\n \n \\param[in] command Command to execute.\n \\param[out] info Descriptive string of progress/completion.\n \\throws SCXAdminException if the command return value isn't zero.\n \n*/\nvoid SCX_AdminServiceControl::ExecuteCommand( const std::wstring& command, std::wstring& info ) const\n{\n std::istringstream mystdin;\n std::ostringstream mystdout;\n std::ostringstream mystderr;\n int r = -1;\n\n try {\n r = SCXCoreLib::SCXProcess::Run(command, mystdin, mystdout, mystderr);\n info = SCXCoreLib::StrAppend(SCXCoreLib::StrFromMultibyte(mystdout.str()),\n SCXCoreLib::StrFromMultibyte(mystderr.str()));\n } catch (SCXCoreLib::SCXException& e) {\n std::wstring msg = SCXCoreLib::StrAppend(L\"Exception: \", e.What());\n throw SCXAdminException(msg, SCXSRCLOCATION);\n }\n if (0 != r)\n {\n std::wstring msg(info);\n msg.append(L\"\\nRETURN CODE: \");\n msg = SCXCoreLib::StrAppend(msg, r);\n throw SCXAdminException(msg, SCXSRCLOCATION);\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Default costructor for Cimom service controller.\n*/\nSCX_CimomServiceControl::SCX_CimomServiceControl()\n : SCX_AdminServiceControl(L\"omiserver\", L\"/opt/omi/bin/service_control start\", L\"/opt/omi/bin/service_control stop\")\n{\n\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Virtual destructor. \n*/\nSCX_CimomServiceControl::~SCX_CimomServiceControl()\n{\n\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Default costructor for provider service controller.\n*/\nSCX_ProviderServiceControl::SCX_ProviderServiceControl()\n : SCX_AdminServiceControl(L\"omiagent\", L\"\", L\"\")\n{\n\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Virtual destructor.\n*/\nSCX_ProviderServiceControl::~SCX_ProviderServiceControl()\n{\n\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n \\copydoc SCX_AdminServiceManagementAPI::Start\n*/\nbool SCX_ProviderServiceControl::Start( std::wstring& info ) const\n{\n info = SCXCoreLib::StrAppend(m_name, L\": Cannot be started explicitly - start cimom\");\n return false;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n \\copydoc SCX_AdminServiceManagementAPI::Stop\n*/\nbool SCX_ProviderServiceControl::Stop( std::wstring& info ) const\n{\n info = SCXCoreLib::StrAppend(m_name, L\": \");\n#if !defined(SCX_STACK_ONLY)\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessEnumeration> procEnum(\n new SCXSystemLib::ProcessEnumeration() );\n procEnum->SampleData();\n procEnum->Update(true);\n std::vector<SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> > procList = procEnum->Find(m_name);\n std::vector<SCXSystemLib::scxpid_t> pids;\n for (std::vector<SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> >::iterator it = procList.begin(); it != procList.end(); it++)\n {\n if ((*it)->SendSignal(SIGTERM))\n {\n pids.push_back((*it)->getpid());\n }\n }\n info = SCXCoreLib::StrAppend(info, procList.size());\n time_t timeout = time(0) + 5; // 5s should be more than enough for cimprovagt to stop.\n while ( ! pids.empty() && timeout >= time(0))\n {\n procEnum->SampleData();\n procEnum->Update(true);\n std::vector<SCXSystemLib::scxpid_t>::iterator it = pids.begin(); \n while (it != pids.end())\n {\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> inst = procEnum->Find(*it);\n if (0 == inst)\n {\n it = pids.erase(it);\n }\n else\n {\n it++;\n }\n }\n if ( ! pids.empty())\n {\n SCXThread::Sleep(100);\n }\n }\n for (std::vector<SCXSystemLib::scxpid_t>::iterator it = pids.begin(); it != pids.end(); it++)\n {\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> inst = procEnum->Find(*it);\n inst->SendSignal(SIGKILL);\n }\n#else\n info = SCXCoreLib::StrAppend(info, CountProcessesAlive());\n\n const std::wstring cmd1 = L\"/bin/sh -c \\\"ps -A -o pid,command | awk '$2~/\";\n#if defined(linux)\n const std::wstring cmd2 = L\"/{print $1}' | xargs -r kill\";\n#else\n const std::wstring cmd2 = L\"/{print $1}' | xargs kill\";\n#endif\n\n std::wstring cmd = cmd1 + m_name + cmd2 + L\"\\\"\";\n std::wstring tmpstr;\n\n ExecuteCommand(cmd, tmpstr);\n\n time_t timeout = time(0) + 5; // 5s should be more than enough for cimprovagt to stop.\n while (CountProcessesAlive() > 0 && timeout >= time(0))\n {\n SCXThread::Sleep(100);\n }\n\n if (CountProcessesAlive() > 0)\n {\n cmd = cmd + m_name + cmd2 + L\" -9\\\"\";\n ExecuteCommand(cmd, tmpstr);\n }\n#endif\n info = SCXCoreLib::StrAppend(info, L\" instances stopped\");\n return true;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n \\copydoc SCX_AdminServiceManagementAPI::Restart\n*/\nbool SCX_ProviderServiceControl::Restart( std::wstring& info ) const\n{\n if ( ! Stop(info))\n {\n return false;\n }\n info = SCXCoreLib::StrAppend(info, L\"\\n\");\n info = SCXCoreLib::StrAppend(info, m_name);\n info = SCXCoreLib::StrAppend(info, L\": not started (will be started automatically by cimom when needed)\\n\");\n return true;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n \\copydoc SCX_AdminServiceManagementAPI::Status\n*/\nbool SCX_ProviderServiceControl::Status( std::wstring& info ) const\n{\n unsigned int count = CountProcessesAlive();\n\n info = SCXCoreLib::StrAppend(m_name, L\": \");\n if (0 == count)\n {\n info = SCXCoreLib::StrAppend(info, L\"is stopped\");\n }\n else\n {\n info = SCXCoreLib::StrAppend(info, count);\n info = SCXCoreLib::StrAppend(info, L\" instance\");\n if (count > 1)\n {\n info = SCXCoreLib::StrAppend(info, L\"s\");\n }\n info = SCXCoreLib::StrAppend(info, L\" running\");\n }\n \n return true;\n}\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6293413639068604, "alphanum_fraction": 0.6346600651741028, "avg_line_length": 41.34609603881836, "blob_id": "5f5145be662eb7713a273d1ba11af85583079e2d", "content_id": "7b2ca8ff0642845190e88c4cbf9d99499041eb05", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 56405, "license_type": "permissive", "max_line_length": 112, "num_lines": 1332, "path": "/test/code/providers/appserver_provider/manipulateappserverinstances_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. \n \n */\n/**\n \\file manipulateappserverinstances_test.cpp\n\n \\brief Tests merging two arrays that represent processes and a cache\n\n \\date 11-05-26 12:00:00\n\n */\n/*----------------------------------------------------------------------------*/\n#include <string>\n#include <vector>\n#include <testutils/scxunit.h>\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n\n#include \"appserverinstance.h\"\n#include \"manipulateappserverinstances.h\"\n#include \"removenonexistentappserverinstances.h\"\n\nusing namespace std;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXUnitTests\n{\n const static std::wstring JBOSS_A_PROCESS_PATH = L\"/opt/a/jboss-5.1.0/default\";\n const static std::wstring JBOSS_A_PROCESS_HTTP_PORT = L\"18080\";\n const static std::wstring JBOSS_A_PROCESS_HTTPS_PORT = L\"18443\";\n const static std::wstring JBOSS_A_PROTOCOL = L\"HTTP\";\n const static std::wstring JBOSS_A_PROCESS_TYPE = L\"JBOSS\";\n const static std::wstring JBOSS_A_PROCESS_VERSION = L\"5.1.0-GA\";\n const static std::wstring JBOSS_CACHED_BUT_RUNNING_PATH = L\"/b/jboss-5.1.0/default\";\n const static std::wstring JBOSS_CACHED_BUT_RUNNING_HTTP_PORT = L\"34080\";\n const static std::wstring JBOSS_CACHED_BUT_RUNNING_HTTPS_PORT = L\"34443\";\n const static std::wstring JBOSS_CACHED_BUT_RUNNING_PROTOCOL = L\"HTTP\";\n const static std::wstring JBOSS_CACHED_BUT_RUNNING_TYPE = L\"JBOSS\";\n const static std::wstring JBOSS_CACHED_BUT_RUNNING_VERSION = L\"5.1.0-GA\";\n const static std::wstring JBOSS_CACHED_PATH = L\"/a/H_H/a space/jboss-5.1.0/full\";\n const static std::wstring JBOSS_CACHED_HTTP_PORT = L\"28080\";\n const static std::wstring JBOSS_CACHED_HTTPS_PORT = L\"28443\";\n const static std::wstring JBOSS_CACHED_PROTOCOL = L\"HTTP\";\n const static std::wstring JBOSS_CACHED_TYPE = L\"JBOSS\";\n const static std::wstring JBOSS_CACHED_VERSION = L\"5.1.0-GA\";\n const static std::wstring JBOSS_MINIMAL_PATH = L\"/opt/jboss/jboss-5.1.0/minimal\";\n const static std::wstring JBOSS_MINIMAL_HTTP_PORT = L\"8080\";\n const static std::wstring JBOSS_MINIMAL_HTTPS_PORT = L\"8443\";\n const static std::wstring JBOSS_MINIMAL_PROTOCOL = L\"HTTP\";\n const static std::wstring JBOSS_MINIMAL_TYPE = L\"JBOSS\";\n const static std::wstring JBOSS_MINIMAL_VERSION = L\"5.1.0-GA\";\n const static std::wstring JBOSS_SIMPLE_PATH = L\"/opt/jboss/jboss-5.1.0/default\";\n const static std::wstring JBOSS_SIMPLE_HTTP_PORT = L\"8080\";\n const static std::wstring JBOSS_SIMPLE_HTTPS_PORT = L\"8443\";\n const static std::wstring JBOSS_SIMPLE_PROTOCOL = L\"HTTP\";\n const static std::wstring JBOSS_SIMPLE_TYPE = L\"JBOSS\";\n const static std::wstring JBOSS_SIMPLE_VERSION = L\"5.1.0-GA\";\n const static std::wstring JBOSS_NEW_RUNNING_PATH = L\"/var/home/dcrammo/jbossNotRunning/jboss-5.1.0/default\";\n const static std::wstring JBOSS_NEW_RUNNING_HTTP_PORT = L\"38082\";\n const static std::wstring JBOSS_NEW_RUNNING_HTTPS_PORT = L\"38445\";\n const static std::wstring JBOSS_NEW_RUNNING_PROTOCOL = L\"HTTP\";\n const static std::wstring JBOSS_NEW_RUNNING_TYPE = L\"JBOSS\";\n const static std::wstring JBOSS_NEW_RUNNING_VERSION = L\"5.1.2-GA\";\n const static std::wstring JBOSS_NOT_RUNNING_PATH = L\"/var/home/ccrammo/jbossNotRunning/jboss-5.1.0/default\";\n const static std::wstring JBOSS_NOT_RUNNING_HTTP_PORT = L\"8082\";\n const static std::wstring JBOSS_NOT_RUNNING_HTTPS_PORT = L\"8445\";\n const static std::wstring JBOSS_NOT_RUNNING_PROTOCOL = L\"HTTP\";\n const static std::wstring JBOSS_NOT_RUNNING_TYPE = L\"JBOSS\";\n const static std::wstring JBOSS_NOT_RUNNING_VERSION = L\"5.1.2-GA\";\n const static std::wstring JBOSS_WITH_SPACE_PATH = L\"/opt/app server/jboss/jboss-5.1.0/default number one\";\n const static std::wstring JBOSS_WITH_SPACE_HTTP_PORT = L\"8081\";\n const static std::wstring JBOSS_WITH_SPACE_HTTPS_PORT = L\"8444\";\n const static std::wstring JBOSS_WITH_SPACE_PROTOCOL = L\"HTTP\";\n const static std::wstring JBOSS_WITH_SPACE_TYPE = L\"JBOSS\";\n const static std::wstring JBOSS_WITH_SPACE_VERSION = L\"5.1.1-GA\";\n\n /*\n * Object that in production code should remove instances that\n * are not on disk, but in practice \n * \n */\n class FakeRemover : \n public SCXSystemLib::IRemoveNonexistentAppServerInstances\n {\n\n public:\n\n /*\n * Default constructor\n */\n FakeRemover(void) : \n m_removeAllInstances(false)\n {\n }\n\n /*\n * Constructor that toggles if all the instances are removed or not\n */\n FakeRemover(bool removeAllInstances) : \n m_removeAllInstances(removeAllInstances)\n {\n }\n\n /*-----------------------------------------------------------------------*/\n /*\n * Overriden Function from Base Class\n * \n * Depending on flags set in the constructor, this will or will not remove\n * all instances \n */\n void RemoveNonexistentInstances(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& instances)\n {\n if (m_removeAllInstances)\n {\n instances.clear();\n }\n }\n \n private:\n const bool m_removeAllInstances;\n };\n\n \n/*\n * The Unit Test class for the logic of merging two vectors\n * that represent a list of processes and a list of cache items\n */\nclass ManipulateAppServerInstancesTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( ManipulateAppServerInstancesTest);\n CPPUNIT_TEST( TestUpdatingKnownInstancesWithTwoEmptyInputs );\n CPPUNIT_TEST( TestUpdatingKnownInstancesThatIsInitiallyEmptyWithOneNewProcess );\n CPPUNIT_TEST( TestUpdatingKnownInstancesThatContains22RunningProcsWithTheSameProcs );\n CPPUNIT_TEST( TestUpdatingKnownInstancesWhenPreviouslyKnownStateOfNotRunningAndNoProcessesInput );\n CPPUNIT_TEST( TestUpdatingKnownInstancesWhenPreviouslyKnownStateOfRunningAndNoProcessesInput );\n CPPUNIT_TEST( TestUpdatingKnownInstancesForPortChangeOfSingleInstance );\n CPPUNIT_TEST( TestUpdatingKnownInstancesForDeepMonitoredOfSingleRunningInstance );\n CPPUNIT_TEST( TestUpdatingKnownInstancesForDeepMonitoredOfSingleNotRunningInstance );\n CPPUNIT_TEST( TestUpdatingKnownInstancesWithManyDuplicatesWhereThePreviousEntriesAreNotRunning );\n CPPUNIT_TEST( TestUpdatingKnownInstancesWithManyDuplicatesWhereSomePreviousEntriesAreRunning );\n CPPUNIT_TEST( TestUpdatingKnownInstancesWithManyDuplicatesChangesToAllFlags );\n CPPUNIT_TEST( TestUpdatingKnownInstancesWhenAllKnownInstancesAreNotOnDisk); \n CPPUNIT_TEST( TestManipulateAppServerInstancesBothEmpty );\n CPPUNIT_TEST( TestMergeOneProcessAndEmptyCache );\n CPPUNIT_TEST( TestMergeEmptyProcessAndOneCache );\n CPPUNIT_TEST( TestMergeOneProcessAndOneCache );\n CPPUNIT_TEST( TestMergeSameFromProcessAndCache );\n CPPUNIT_TEST( TestMergeManyDuplicateProcessesAndCacheItemsThatAreOutOfOrder );\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n /*\n * Default constructor\n */\n ManipulateAppServerInstancesTest(void)\n {\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Unit Test Setup: run before each test\n */\n void setUp(void)\n {\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Unit Test Teardown: run after each test\n * \n */\n void tearDown(void)\n {\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a sample of JBoss that is NOT running\n */\n SCXHandle<AppServerInstance> createANotRunningJBossInstance(void)\n {\n SCXHandle<AppServerInstance> instance(createARunningDeepMonitoredJBossInstance());\n instance->SetIsRunning(false);\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a sample of JBoss that should be inserted into the is running\n */\n SCXHandle<AppServerInstance> createCachedButRunningJBossInstance(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_CACHED_BUT_RUNNING_PATH,\n JBOSS_CACHED_BUT_RUNNING_TYPE));\n instance->SetHttpPort(JBOSS_CACHED_BUT_RUNNING_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_CACHED_BUT_RUNNING_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_CACHED_BUT_RUNNING_PROTOCOL);\n instance->SetIsRunning(true);\n instance->SetVersion(JBOSS_CACHED_BUT_RUNNING_VERSION);\n\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a sample of JBoss that is running and deep monitored\n */\n SCXHandle<AppServerInstance> createARunningDeepMonitoredJBossInstance(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_A_PROCESS_PATH,\n JBOSS_A_PROCESS_TYPE));\n instance->SetHttpPort(JBOSS_A_PROCESS_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_A_PROCESS_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_A_PROTOCOL);\n instance->SetIsRunning(true);\n instance->SetVersion(JBOSS_A_PROCESS_VERSION);\n\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a cached instance of JBoss\n */\n SCXHandle<AppServerInstance> createCachedJBossInstanceWithSpaceAndUnderscoreInPath(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_CACHED_PATH,\n JBOSS_CACHED_TYPE));\n instance->SetHttpPort(JBOSS_CACHED_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_CACHED_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_CACHED_PROTOCOL);\n instance->SetIsRunning(false);\n instance->SetVersion(JBOSS_CACHED_VERSION);\n\n return instance;\n }\n\n \n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a plain, vanilla instance of JBoss with a given id\n */\n SCXHandle<AppServerInstance> createRunningJBossInstance(std::wstring id)\n {\n std::wstring diskpath(L\"/u/hcswl1030/apps/\");\n diskpath.append(id).append(L\"/jboss/server/\").append(id);\n\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n diskpath,\n JBOSS_SIMPLE_TYPE));\n instance->SetHttpPort(JBOSS_SIMPLE_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_SIMPLE_HTTPS_PORT);\n instance->SetIsDeepMonitored(false, JBOSS_SIMPLE_PROTOCOL);\n instance->SetIsRunning(true);\n instance->SetVersion(JBOSS_SIMPLE_VERSION);\n\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a plain, vanilla instance of JBoss\n */\n SCXHandle<AppServerInstance> createDefaultRunningJBossInstance(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_SIMPLE_PATH,\n JBOSS_SIMPLE_TYPE));\n instance->SetHttpPort(JBOSS_SIMPLE_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_SIMPLE_HTTPS_PORT);\n instance->SetIsDeepMonitored(false, JBOSS_SIMPLE_PROTOCOL);\n instance->SetIsRunning(true);\n instance->SetVersion(JBOSS_SIMPLE_VERSION);\n\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a sample of the default JBOSS instance that is not running. \n * This cached item should disappear in the merge.\n */\n SCXHandle<AppServerInstance> createDefaultNotRunningJBossInstance(void)\n {\n SCXHandle<AppServerInstance> instance(createDefaultRunningJBossInstance());\n instance->SetIsRunning(false);\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a sample of the default JBOSS instance and change its ports and \n * it to not running. This cached item should disappear in the merge.\n */\n SCXHandle<AppServerInstance> createDefaultNotRunningJBossInstanceWithDifferentPorts(void)\n {\n SCXHandle<AppServerInstance> instance(createDefaultRunningJBossInstance());\n instance->SetIsRunning(false);\n instance->SetHttpPort(L\"12345\");\n instance->SetHttpsPort(L\"\");\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a MINIMAL instance of JBoss\n */\n SCXHandle<AppServerInstance> createMinimalNotRunningJBossInstance(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_MINIMAL_PATH,\n JBOSS_MINIMAL_TYPE));\n instance->SetHttpPort(JBOSS_MINIMAL_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_MINIMAL_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_MINIMAL_PROTOCOL);\n instance->SetIsRunning(false);\n instance->SetVersion(JBOSS_MINIMAL_VERSION);\n\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a NEW JBoss instance that is running. This represents a new\n * process that has not been previously cached.\n */\n SCXHandle<AppServerInstance> createNewRunningJBossInstance(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_NEW_RUNNING_PATH,\n JBOSS_NEW_RUNNING_TYPE));\n instance->SetHttpPort(JBOSS_NEW_RUNNING_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_NEW_RUNNING_HTTPS_PORT);\n instance->SetIsDeepMonitored(false, JBOSS_NEW_RUNNING_PROTOCOL);\n instance->SetIsRunning(true);\n instance->SetVersion(JBOSS_NEW_RUNNING_VERSION);\n\n return instance;\n }\n \n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a JBoss instance with a space in the path that is not running.\n * This is the same as the other JBoss instance with a space, but not running\n * (i.e. represent data from a cache)\n */\n SCXHandle<AppServerInstance> createNotRunningJBossInstanceWithSpaceInPath(void)\n {\n SCXHandle<AppServerInstance> instance(\n createRunningJBossInstanceWithSpaceInPath());\n instance->SetIsRunning(false);\n return instance;\n }\n\n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a JBoss instance with a space in the path that is running\n */\n SCXHandle<AppServerInstance> createRunningJBossInstanceWithSpaceInPath(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_WITH_SPACE_PATH,\n JBOSS_WITH_SPACE_TYPE));\n instance->SetHttpPort(JBOSS_WITH_SPACE_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_WITH_SPACE_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_WITH_SPACE_PROTOCOL);\n instance->SetIsRunning(true);\n instance->SetVersion(JBOSS_WITH_SPACE_VERSION);\n\n return instance;\n }\n\n \n /*----------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a JBoss instance that is not running\n */\n SCXHandle<AppServerInstance> createJBossInstanceNotRunning(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_NOT_RUNNING_PATH,\n JBOSS_NOT_RUNNING_TYPE));\n instance->SetHttpPort(JBOSS_NOT_RUNNING_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_NOT_RUNNING_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_NOT_RUNNING_PROTOCOL);\n instance->SetIsRunning(false);\n instance->SetVersion(JBOSS_NOT_RUNNING_VERSION);\n\n return instance;\n }\n\n /*\n * Verify that merging two empty lists results in with an empty list.\n */\n void TestUpdatingKnownInstancesWithTwoEmptyInputs(void)\n {\n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n vector<SCXHandle<AppServerInstance> > processList;\n\n // Verify input\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, previouslyKnownStates.size());\n CPPUNIT_ASSERT_EQUAL( zero, processList.size());\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( zero, previouslyKnownStates.size());\n }\n\n /*\n * Verify that merging an initially empty list with one running process \n * results in the known states being updated so that it is equal to the\n * process list.\n */\n void TestUpdatingKnownInstancesThatIsInitiallyEmptyWithOneNewProcess(void)\n {\n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n vector<SCXHandle<AppServerInstance> > processList;\n processList.push_back(createDefaultRunningJBossInstance());\n\n CPPUNIT_ASSERT_EQUAL( false, processList[0]->GetIsDeepMonitored());\n CPPUNIT_ASSERT_EQUAL( true, processList[0]->GetIsRunning());\n\n // Verify input\n size_t zero = 0;\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( zero, previouslyKnownStates.size());\n CPPUNIT_ASSERT_EQUAL( one, processList.size());\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT( \n *(createDefaultRunningJBossInstance()) == \n *(previouslyKnownStates[0]) );\n }\n\n /*\n * Verify that merging an initially empty list with one running process \n * results in the known states being updated so that it is equal to the\n * process list.\n */\n void TestUpdatingKnownInstancesThatContains22RunningProcsWithTheSameProcs(void)\n {\n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n vector<SCXHandle<AppServerInstance> > processList;\n\n processList.push_back(createRunningJBossInstance(L\"adminrx\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"adminrx\"));\n processList.push_back(createRunningJBossInstance(L\"contextagent\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"contextagent\"));\n processList.push_back(createRunningJBossInstance(L\"ha\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"ha\"));\n processList.push_back(createRunningJBossInstance(L\"hcservice\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hcservice\"));\n processList.push_back(createRunningJBossInstance(L\"hdm\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hdm\"));\n processList.push_back(createRunningJBossInstance(L\"hdv\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hdv\"));\n processList.push_back(createRunningJBossInstance(L\"hec\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hec\"));\n processList.push_back(createRunningJBossInstance(L\"hed\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hed\"));\n processList.push_back(createRunningJBossInstance(L\"hen\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hen\"));\n processList.push_back(createRunningJBossInstance(L\"hep\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hep\"));\n processList.push_back(createRunningJBossInstance(L\"hep_author\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hep_author\"));\n processList.push_back(createRunningJBossInstance(L\"hhs\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hhs\"));\n processList.push_back(createRunningJBossInstance(L\"hmrcs\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hmrcs\"));\n processList.push_back(createRunningJBossInstance(L\"hocs\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hocs\"));\n processList.push_back(createRunningJBossInstance(L\"hot\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hot\"));\n processList.push_back(createRunningJBossInstance(L\"hpcs\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hpcs\"));\n processList.push_back(createRunningJBossInstance(L\"hqmct\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hqmct\"));\n processList.push_back(createRunningJBossInstance(L\"hscs\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hscs\"));\n processList.push_back(createRunningJBossInstance(L\"hwc\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"hwc\"));\n processList.push_back(createRunningJBossInstance(L\"security\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"security\"));\n processList.push_back(createRunningJBossInstance(L\"updatemgr\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"updatemgr\"));\n processList.push_back(createRunningJBossInstance(L\"vfs\"));\n previouslyKnownStates.push_back(createRunningJBossInstance(L\"vfs\"));\n \n // Verify input\n CPPUNIT_ASSERT( 22 == previouslyKnownStates.size());\n CPPUNIT_ASSERT( 22 == processList.size());\n\n // Test the desired method\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output\n CPPUNIT_ASSERT( 22 == previouslyKnownStates.size());\n vector<SCXHandle<AppServerInstance> >::iterator it;\n for (it = previouslyKnownStates.begin(); it != previouslyKnownStates.end(); ++it)\n {\n CPPUNIT_ASSERT((*it)->GetIsRunning());\n }\n }\n\n /*\n * Verify that have a previously known state that id not running\n * looks the same after merging it with an empty set of running\n * processes.\n */\n void TestUpdatingKnownInstancesWhenPreviouslyKnownStateOfNotRunningAndNoProcessesInput(void)\n {\n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n previouslyKnownStates.push_back(createDefaultNotRunningJBossInstanceWithDifferentPorts());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsDeepMonitored());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsRunning());\n \n vector<SCXHandle<AppServerInstance> > processList;\n\n // Verify input\n size_t zero = 0;\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_EQUAL( zero, processList.size());\n\n // Test the desired method\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output - the instance should be the same (i.e. the known\n // state should not have been updated)\n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT( \n *(createDefaultNotRunningJBossInstanceWithDifferentPorts()) == \n *(previouslyKnownStates[0]) );\n }\n\n /*\n * Verify that have a previously known state that is running shows up in \n * the known state array but has been marked as not running\n */\n void TestUpdatingKnownInstancesWhenPreviouslyKnownStateOfRunningAndNoProcessesInput(void)\n {\n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n previouslyKnownStates.push_back(createDefaultRunningJBossInstance());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsDeepMonitored());\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[0]->GetIsRunning());\n \n vector<SCXHandle<AppServerInstance> > processList;\n\n // Verify input\n size_t zero = 0;\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_EQUAL( zero, processList.size());\n\n // Test the desired method\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output - the instance should be different than the input.\n // Specifically IsRunning should now be off \n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_MESSAGE( \"The IsRunning state should have changed\", \n *(createDefaultRunningJBossInstance()) != \n *(previouslyKnownStates[0]) );\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsRunning() );\n CPPUNIT_ASSERT( \n *(createDefaultNotRunningJBossInstance()) == \n *(previouslyKnownStates[0]) );\n }\n\n /*\n * Verify that port update works on a single instance\n */\n void TestUpdatingKnownInstancesForPortChangeOfSingleInstance(void)\n {\n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n previouslyKnownStates.push_back(createDefaultNotRunningJBossInstanceWithDifferentPorts());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsDeepMonitored());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsRunning());\n \n vector<SCXHandle<AppServerInstance> > processList;\n processList.push_back(createDefaultRunningJBossInstance());\n CPPUNIT_ASSERT_EQUAL( false, processList[0]->GetIsDeepMonitored());\n CPPUNIT_ASSERT_EQUAL( true, processList[0]->GetIsRunning());\n\n CPPUNIT_ASSERT( \n previouslyKnownStates[0]->GetHttpPort() !=\n processList[0]->GetHttpPort());\n CPPUNIT_ASSERT( \n previouslyKnownStates[0]->GetHttpsPort() !=\n processList[0]->GetHttpsPort());\n\n // Verify input\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_EQUAL( one, processList.size());\n\n // Test the desired method\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output - the instance should be different than the input.\n // Specifically IsRunning should now be off \n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_MESSAGE( \"The ports should be different\", \n *(createDefaultNotRunningJBossInstanceWithDifferentPorts()) != \n *(previouslyKnownStates[0]) );\n CPPUNIT_ASSERT( \n *(createDefaultRunningJBossInstance()) == \n *(previouslyKnownStates[0]) );\n }\n\n /*\n * Verify that the deep monitored flag is updated appropriately for\n * a single (running) instance.\n */\n void TestUpdatingKnownInstancesForDeepMonitoredOfSingleRunningInstance(void)\n {\n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n SCXHandle<AppServerInstance> desiredResult =\n createDefaultRunningJBossInstance();\n desiredResult->SetIsDeepMonitored(true, L\"HTTP\");\n previouslyKnownStates.push_back(desiredResult);\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[0]->GetIsRunning() );\n \n vector<SCXHandle<AppServerInstance> > processList;\n processList.push_back(createDefaultRunningJBossInstance());\n CPPUNIT_ASSERT_EQUAL( false, processList[0]->GetIsDeepMonitored());\n \n CPPUNIT_ASSERT( \n *(previouslyKnownStates[0]) !=\n *(processList[0]));\n\n // Verify input\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_EQUAL( one, processList.size());\n\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output - the instance should be different than the input.\n // Specifically IsRunning should now be off \n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_MESSAGE( \"The IsDeepMonitored state should have changed\", \n *(createDefaultRunningJBossInstance()) != \n *(previouslyKnownStates[0]) );\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[0]->GetIsDeepMonitored() );\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[0]->GetIsRunning() );\n }\n\n /*\n * Verify that the deep monitored flag is updated appropriately for\n * a single (not running) instance.\n */\n void TestUpdatingKnownInstancesForDeepMonitoredOfSingleNotRunningInstance(void)\n {\n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n SCXHandle<AppServerInstance> desiredResult =\n createDefaultNotRunningJBossInstance();\n desiredResult->SetIsDeepMonitored(true, L\"HTTP\");\n previouslyKnownStates.push_back(desiredResult);\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsRunning() );\n \n vector<SCXHandle<AppServerInstance> > processList;\n processList.push_back(createDefaultRunningJBossInstance());\n CPPUNIT_ASSERT_EQUAL( false, processList[0]->GetIsDeepMonitored());\n \n CPPUNIT_ASSERT( \n *(previouslyKnownStates[0]) !=\n *(processList[0]));\n\n // Verify input\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_EQUAL( one, processList.size());\n\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output - the instance should be different than the input.\n // Specifically IsRunning should now be off \n CPPUNIT_ASSERT_EQUAL( one, previouslyKnownStates.size());\n CPPUNIT_ASSERT_MESSAGE( \"The IsDeepMonitored state should have changed\", \n *(createDefaultRunningJBossInstance()) != \n *(previouslyKnownStates[0]) );\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[0]->GetIsDeepMonitored() );\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[0]->GetIsRunning() );\n }\n\n /*\n * Just a warning, this is a complex test. This combines several of the\n * simplier tests so that they are all handled at once.\n */\n void TestUpdatingKnownInstancesWithManyDuplicatesWhereThePreviousEntriesAreNotRunning(void)\n {\n vector<SCXHandle<AppServerInstance> > processList;\n processList.push_back(createARunningDeepMonitoredJBossInstance());\n processList.push_back(createRunningJBossInstanceWithSpaceInPath());\n processList.push_back(createDefaultRunningJBossInstance());\n processList.push_back(createNewRunningJBossInstance());\n \n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n \n // Duplicate\n previouslyKnownStates.push_back(createNotRunningJBossInstanceWithSpaceInPath());\n \n // Duplicate\n previouslyKnownStates.push_back(createDefaultNotRunningJBossInstanceWithDifferentPorts());\n \n // Unique\n previouslyKnownStates.push_back(createMinimalNotRunningJBossInstance());\n \n // Duplicate\n previouslyKnownStates.push_back(createANotRunningJBossInstance());\n \n // Unique\n previouslyKnownStates.push_back(createCachedJBossInstanceWithSpaceAndUnderscoreInPath());\n\n // Verify all previous entries are off\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[1]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[2]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[3]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[4]->GetIsRunning());\n\n // Verify input\n size_t four = 4;\n size_t five = 5;\n CPPUNIT_ASSERT_EQUAL( four, processList.size());\n CPPUNIT_ASSERT_EQUAL( five, previouslyKnownStates.size());\n\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output\n size_t six= 6;\n CPPUNIT_ASSERT_EQUAL( six, previouslyKnownStates.size());\n CPPUNIT_ASSERT( \n *(createCachedJBossInstanceWithSpaceAndUnderscoreInPath()) ==\n *(previouslyKnownStates[0]));\n CPPUNIT_ASSERT( \n *(createARunningDeepMonitoredJBossInstance()) == \n *(previouslyKnownStates[1]));\n CPPUNIT_ASSERT( \n *(createRunningJBossInstanceWithSpaceInPath()) == \n *(previouslyKnownStates[2]));\n CPPUNIT_ASSERT( \n *(createDefaultRunningJBossInstance()) == \n *(previouslyKnownStates[3]));\n CPPUNIT_ASSERT( \n *(createMinimalNotRunningJBossInstance()) == \n *(previouslyKnownStates[4]));\n CPPUNIT_ASSERT( \n *(createNewRunningJBossInstance()) == \n *(previouslyKnownStates[5]));\n }\n\n /*\n * Merge two lists where things are out-of-order and some of the \n * previous entries were marked as running.\n * \n * Just a warning, this is a complex test. This combines several of the\n * simplier tests so that they are all handled at once.\n */\n void TestUpdatingKnownInstancesWithManyDuplicatesWhereSomePreviousEntriesAreRunning(void)\n {\n vector<SCXHandle<AppServerInstance> > processList;\n processList.push_back(createARunningDeepMonitoredJBossInstance());\n processList.push_back(createRunningJBossInstanceWithSpaceInPath());\n processList.push_back(createDefaultRunningJBossInstance());\n processList.push_back(createNewRunningJBossInstance());\n \n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n \n // Duplicate (0)\n previouslyKnownStates.push_back(createRunningJBossInstanceWithSpaceInPath());\n \n // Duplicate (1)\n previouslyKnownStates.push_back(createDefaultNotRunningJBossInstanceWithDifferentPorts());\n \n // Unique (2)\n previouslyKnownStates.push_back(createMinimalNotRunningJBossInstance());\n \n // Unique (3)\n previouslyKnownStates.push_back(createCachedButRunningJBossInstance());\n \n // Duplicate (4)\n previouslyKnownStates.push_back(createARunningDeepMonitoredJBossInstance());\n \n // Unique (5)\n previouslyKnownStates.push_back(createCachedJBossInstanceWithSpaceAndUnderscoreInPath());\n\n // Verify IsRunning for the previous states\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[0]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[1]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[2]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[3]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[4]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[5]->GetIsRunning());\n\n // Verify input\n size_t four = 4;\n size_t six = 6;\n CPPUNIT_ASSERT_EQUAL( four, processList.size());\n CPPUNIT_ASSERT_EQUAL( six, previouslyKnownStates.size());\n\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output\n size_t seven = 7;\n CPPUNIT_ASSERT_EQUAL( seven, previouslyKnownStates.size());\n CPPUNIT_ASSERT( \n *(createCachedJBossInstanceWithSpaceAndUnderscoreInPath()) ==\n *(previouslyKnownStates[0]));\n \n // This instance was previously running (hence the not equals!)\n SCXHandle<AppServerInstance> flippedIsRunning = \n createCachedButRunningJBossInstance();\n CPPUNIT_ASSERT( \n *(flippedIsRunning) != \n *(previouslyKnownStates[1]));\n flippedIsRunning->SetIsRunning(false);\n CPPUNIT_ASSERT( \n *(flippedIsRunning) == \n *(previouslyKnownStates[1]));\n \n CPPUNIT_ASSERT( \n *(createARunningDeepMonitoredJBossInstance()) == \n *(previouslyKnownStates[2]));\n \n CPPUNIT_ASSERT( \n *(createRunningJBossInstanceWithSpaceInPath()) == \n *(previouslyKnownStates[3]));\n CPPUNIT_ASSERT( \n *(createDefaultRunningJBossInstance()) == \n *(previouslyKnownStates[4]));\n CPPUNIT_ASSERT( \n *(createMinimalNotRunningJBossInstance()) == \n *(previouslyKnownStates[5]));\n CPPUNIT_ASSERT( \n *(createNewRunningJBossInstance()) == \n *(previouslyKnownStates[6]));\n }\n\n /*\n * Merge two lists where things are out-of-order, some of the \n * previous entries were marked as running, and changes to the \n * deep monitored flag too. In short, this has everything.\n * \n * Just a warning, this is a complex test. This combines several of the\n * simplier tests so that they are all handled at once.\n */\n void TestUpdatingKnownInstancesWithManyDuplicatesChangesToAllFlags(void)\n {\n vector<SCXHandle<AppServerInstance> > processList;\n processList.push_back(createARunningDeepMonitoredJBossInstance());\n processList[0]->SetIsDeepMonitored(false, L\"\");\n processList.push_back(createRunningJBossInstanceWithSpaceInPath());\n processList.push_back(createDefaultRunningJBossInstance());\n processList.push_back(createNewRunningJBossInstance());\n \n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n \n // Duplicate (0)\n previouslyKnownStates.push_back(createRunningJBossInstanceWithSpaceInPath());\n \n // Duplicate (1)\n previouslyKnownStates.push_back(createDefaultNotRunningJBossInstanceWithDifferentPorts());\n \n // Unique (2)\n previouslyKnownStates.push_back(createMinimalNotRunningJBossInstance());\n \n // Unique (3)\n previouslyKnownStates.push_back(createCachedButRunningJBossInstance());\n \n // Duplicate (4)\n previouslyKnownStates.push_back(createARunningDeepMonitoredJBossInstance());\n \n // Unique (5)\n previouslyKnownStates.push_back(createCachedJBossInstanceWithSpaceAndUnderscoreInPath());\n\n // Verify IsRunning for the previous states\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[0]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[1]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[2]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[3]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[4]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[5]->GetIsRunning());\n\n // Verify input\n size_t four = 4;\n size_t six = 6;\n CPPUNIT_ASSERT_EQUAL( four, processList.size());\n CPPUNIT_ASSERT_EQUAL( six, previouslyKnownStates.size());\n\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesNotRemove(new FakeRemover(false));\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesNotRemove));\n\n // Verify output\n size_t seven = 7;\n CPPUNIT_ASSERT_EQUAL( seven, previouslyKnownStates.size());\n CPPUNIT_ASSERT( \n *(createCachedJBossInstanceWithSpaceAndUnderscoreInPath()) ==\n *(previouslyKnownStates[0]));\n \n // This instance was previously running (hence the not equals!)\n SCXHandle<AppServerInstance> flippedIsRunning = \n createCachedButRunningJBossInstance();\n CPPUNIT_ASSERT_MESSAGE(\"This instance should no longer be marked as running\", \n *(flippedIsRunning) != \n *(previouslyKnownStates[1]));\n flippedIsRunning->SetIsRunning(false);\n CPPUNIT_ASSERT( \n *(flippedIsRunning) == \n *(previouslyKnownStates[1]));\n \n // This was manually set to not be deep monitored in\n // the process list. The IsDeepMonitored flag should have\n // been picked up by the previous state\n CPPUNIT_ASSERT_MESSAGE( \"Failed to pick-up the deep monitored flag from the previously known state\",\n *(createARunningDeepMonitoredJBossInstance()) == \n *(previouslyKnownStates[2]));\n \n CPPUNIT_ASSERT( \n *(createRunningJBossInstanceWithSpaceInPath()) == \n *(previouslyKnownStates[3]));\n CPPUNIT_ASSERT( \n *(createDefaultRunningJBossInstance()) == \n *(previouslyKnownStates[4]));\n CPPUNIT_ASSERT( \n *(createMinimalNotRunningJBossInstance()) == \n *(previouslyKnownStates[5]));\n CPPUNIT_ASSERT( \n *(createNewRunningJBossInstance()) == \n *(previouslyKnownStates[6]));\n }\n\n /*\n * Merge two lists where things are out-of-order, some of the \n * previous entries were marked as running, and changes to the \n * deep monitored flag too. In short, this has everything.\n * \n * Just a warning, this is a complex test. This combines several of the\n * simplier tests so that they are all handled at once.\n */\n void TestUpdatingKnownInstancesWhenAllKnownInstancesAreNotOnDisk(void)\n {\n vector<SCXHandle<AppServerInstance> > processList;\n processList.push_back(createRunningJBossInstanceWithSpaceInPath());\n processList.push_back(createNewRunningJBossInstance());\n \n vector<SCXHandle<AppServerInstance> > previouslyKnownStates;\n \n // Duplicate (0)\n previouslyKnownStates.push_back(createDefaultNotRunningJBossInstanceWithDifferentPorts());\n \n // Unique (1)\n previouslyKnownStates.push_back(createMinimalNotRunningJBossInstance());\n \n // Unique (2)\n previouslyKnownStates.push_back(createCachedButRunningJBossInstance());\n \n // Unique (3)\n previouslyKnownStates.push_back(createCachedJBossInstanceWithSpaceAndUnderscoreInPath());\n\n // Verify IsRunning for the previous states\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[0]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[1]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( true, previouslyKnownStates[2]->GetIsRunning());\n CPPUNIT_ASSERT_EQUAL( false, previouslyKnownStates[3]->GetIsRunning());\n\n // Verify input\n size_t two = 2;\n size_t four = 4;\n CPPUNIT_ASSERT_EQUAL( two, processList.size());\n CPPUNIT_ASSERT_EQUAL( four, previouslyKnownStates.size());\n\n // This is different, will get rid of all the cache entries\n // that are not on disk\n SCXHandle<IRemoveNonexistentAppServerInstances> \n removerThatDoesRemove(new FakeRemover(true));\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(\n previouslyKnownStates, \n processList,\n removerThatDoesRemove));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( two, previouslyKnownStates.size());\n\n CPPUNIT_ASSERT( \n *(createRunningJBossInstanceWithSpaceInPath()) == \n *(previouslyKnownStates[0]));\n CPPUNIT_ASSERT( \n *(createNewRunningJBossInstance()) == \n *(previouslyKnownStates[1]));\n }\n\n /*\n * Verify that merging an empty process list and empty cache\n * results in nothing.\n */\n void TestManipulateAppServerInstancesBothEmpty()\n {\n vector<SCXHandle<AppServerInstance> > processes;\n vector<SCXHandle<AppServerInstance> > cache;\n vector<SCXHandle<AppServerInstance> > result;\n\n // Verify input\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, processes.size());\n CPPUNIT_ASSERT_EQUAL( zero, cache.size());\n CPPUNIT_ASSERT_EQUAL( zero, result.size());\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::MergeProcessesAndCache(processes, cache, result));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( zero, processes.size());\n CPPUNIT_ASSERT_EQUAL( zero, cache.size());\n CPPUNIT_ASSERT_EQUAL( zero, result.size());\n }\n\n /*\n * Verify that merging a non-empty process list and empty cache\n * results in one item (just that from the process list).\n */\n void TestMergeOneProcessAndEmptyCache()\n {\n vector<SCXHandle<AppServerInstance> > processes;\n processes.push_back(createDefaultRunningJBossInstance());\n vector<SCXHandle<AppServerInstance> > cache;\n vector<SCXHandle<AppServerInstance> > result;\n\n // Verify input\n size_t zero = 0;\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, processes.size());\n CPPUNIT_ASSERT_EQUAL( zero, cache.size());\n CPPUNIT_ASSERT_EQUAL( zero, result.size());\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::MergeProcessesAndCache(processes, cache, result));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( one, processes.size());\n CPPUNIT_ASSERT( *(createDefaultRunningJBossInstance()) == *(processes[0]));\n CPPUNIT_ASSERT_EQUAL( zero, cache.size());\n CPPUNIT_ASSERT_EQUAL( one, result.size());\n CPPUNIT_ASSERT( *(createDefaultRunningJBossInstance()) == *(result[0]));\n }\n \n /*\n * Verify that merging a non-empty process list and empty cache\n * results in one item (just that from the process list).\n */\n void TestMergeEmptyProcessAndOneCache(void)\n {\n vector<SCXHandle<AppServerInstance> > processes;\n vector<SCXHandle<AppServerInstance> > cache;\n cache.push_back(createJBossInstanceNotRunning());\n vector<SCXHandle<AppServerInstance> > result;\n\n // Verify input\n size_t zero = 0;\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( zero, processes.size());\n CPPUNIT_ASSERT_EQUAL( one, cache.size());\n CPPUNIT_ASSERT_EQUAL( zero, result.size());\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::MergeProcessesAndCache(processes, cache, result));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( zero, processes.size());\n CPPUNIT_ASSERT_EQUAL( one, cache.size());\n CPPUNIT_ASSERT( *(createJBossInstanceNotRunning()) == *(cache[0]));\n CPPUNIT_ASSERT_EQUAL( one, result.size());\n CPPUNIT_ASSERT( *(createJBossInstanceNotRunning()) == *(result[0]));\n }\n\n /*\n * Verify a very simple merge scenario: a unique process and a \n * unique cache item are merged, the result is both items. \n */\n void TestMergeOneProcessAndOneCache()\n {\n vector<SCXHandle<AppServerInstance> > processes;\n processes.push_back(createDefaultRunningJBossInstance());\n vector<SCXHandle<AppServerInstance> > cache;\n cache.push_back(createJBossInstanceNotRunning());\n vector<SCXHandle<AppServerInstance> > result;\n\n // Verify input\n size_t zero = 0;\n size_t one = 1;\n size_t two = 2;\n CPPUNIT_ASSERT_EQUAL( one, processes.size());\n CPPUNIT_ASSERT_EQUAL( one, cache.size());\n CPPUNIT_ASSERT_EQUAL( zero, result.size());\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::MergeProcessesAndCache(processes, cache, result));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( one, processes.size());\n CPPUNIT_ASSERT( *(createDefaultRunningJBossInstance()) == *(processes[0]));\n CPPUNIT_ASSERT_EQUAL( one, cache.size());\n CPPUNIT_ASSERT( *(createJBossInstanceNotRunning()) == *(cache[0]));\n CPPUNIT_ASSERT_EQUAL( two, result.size());\n CPPUNIT_ASSERT( *(createDefaultRunningJBossInstance()) == *(result[0]));\n CPPUNIT_ASSERT( *(createJBossInstanceNotRunning()) == *(result[1]));\n }\n \n /*\n * Verify the a merge overlap of a process and it's cached \n * representation. The result should just be a copy of the item\n * from the list of running processes.\n */\n void TestMergeSameFromProcessAndCache()\n {\n vector<SCXHandle<AppServerInstance> > processes;\n processes.push_back(createRunningJBossInstanceWithSpaceInPath());\n vector<SCXHandle<AppServerInstance> > cache;\n cache.push_back(createNotRunningJBossInstanceWithSpaceInPath());\n vector<SCXHandle<AppServerInstance> > result;\n\n // Verify input\n size_t zero = 0;\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, processes.size());\n CPPUNIT_ASSERT_EQUAL( one, cache.size());\n CPPUNIT_ASSERT_EQUAL( zero, result.size());\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::MergeProcessesAndCache (processes, cache, result));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( one, processes.size());\n CPPUNIT_ASSERT( *(createRunningJBossInstanceWithSpaceInPath()) == *(processes[0]));\n CPPUNIT_ASSERT_EQUAL( one, cache.size());\n CPPUNIT_ASSERT( *(createNotRunningJBossInstanceWithSpaceInPath()) == *(cache[0]));\n CPPUNIT_ASSERT_EQUAL( one, result.size());\n CPPUNIT_ASSERT( *(createRunningJBossInstanceWithSpaceInPath()) == *(result[0]));\n }\n\n /*\n * Verify a complex merge. The inputs have several duplicate process and \n * cache items as well as some unique ones. Another factor is that the\n * vectors supplied are out-of-order. \n */\n void TestMergeManyDuplicateProcessesAndCacheItemsThatAreOutOfOrder()\n {\n vector<SCXHandle<AppServerInstance> > processes;\n processes.push_back(createARunningDeepMonitoredJBossInstance());\n processes.push_back(createRunningJBossInstanceWithSpaceInPath());\n processes.push_back(createDefaultRunningJBossInstance());\n processes.push_back(createNewRunningJBossInstance());\n \n vector<SCXHandle<AppServerInstance> > cache;\n \n // Duplicate\n cache.push_back(createNotRunningJBossInstanceWithSpaceInPath());\n \n // Duplicate\n cache.push_back(createDefaultNotRunningJBossInstanceWithDifferentPorts());\n \n // Unique\n cache.push_back(createMinimalNotRunningJBossInstance());\n \n // Duplicate\n cache.push_back(createANotRunningJBossInstance());\n \n // Unique\n cache.push_back(createCachedJBossInstanceWithSpaceAndUnderscoreInPath());\n\n vector<SCXHandle<AppServerInstance> > result;\n\n // Verify input\n size_t zero = 0;\n size_t four = 4;\n size_t five = 5;\n CPPUNIT_ASSERT_EQUAL( four, processes.size());\n CPPUNIT_ASSERT_EQUAL( five, cache.size());\n CPPUNIT_ASSERT_EQUAL( zero, result.size());\n\n // Test the desired method\n CPPUNIT_ASSERT_NO_THROW(\n ManipulateAppServerInstances::MergeProcessesAndCache (processes, cache, result));\n\n // Verify output\n CPPUNIT_ASSERT_EQUAL( four, processes.size());\n CPPUNIT_ASSERT_EQUAL( five, cache.size());\n size_t six= 6;\n CPPUNIT_ASSERT_EQUAL( six, result.size());\n CPPUNIT_ASSERT( *(createCachedJBossInstanceWithSpaceAndUnderscoreInPath()) == *(result[0]));\n CPPUNIT_ASSERT( *(createARunningDeepMonitoredJBossInstance()) == *(result[1]));\n CPPUNIT_ASSERT( *(createRunningJBossInstanceWithSpaceInPath()) == *(result[2]));\n CPPUNIT_ASSERT( *(createDefaultRunningJBossInstance()) == *(result[3]));\n CPPUNIT_ASSERT( *(createMinimalNotRunningJBossInstance()) == *(result[4]));\n CPPUNIT_ASSERT( *(createNewRunningJBossInstance()) == *(result[5]));\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( ManipulateAppServerInstancesTest );\n}\n" }, { "alpha_fraction": 0.49388378858566284, "alphanum_fraction": 0.5076452493667603, "avg_line_length": 24.647058486938477, "blob_id": "5cac32a7d061a1804bdf9f4fa0b6b1f23e223717", "content_id": "76765a6fdf173dfed40740d997694f3c67e7259f", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1308, "license_type": "permissive", "max_line_length": 82, "num_lines": 51, "path": "/build/Makefile.pal", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#--------------------------------------------------------------------------------\n\n# Tool descriptions\n# RM - Remove a file\n# RMDIR - Remove a directory\n# MKPATH - Create a directory and all necessary dirs along the way\n# NOOP - Command which is not executed on this platform\n# pf_tp(path_list) - Transform the paths in the list to paths accepted by platform\n# pf_fwrite(text,filename) - Creates/replaces a new file with 'text' as content\n# pf_fappend(text,filename) - Append text to file at the end\n\nifdef PF_WINDOWS\n\tpf_tp=$(subst /,\\,$(patsubst %,\"%\",$1))\n\tRM=cmd /c del /f /q\n\tRMDIR=cmd /c rmdir /S /Q\n\tMKPATH=cmd /c mkdir\n\tECHO=cmd /c echo\n\tCOPY=cmd /c copy\n\tCOPYDIR=cmd /c robocopy\n\tpf_fwrite=echo $(1) > $(2) \n\tpf_fappend=echo $(1) >> $(2)\n\n\tNOOP=rem NOOP \n\nendif\n\n\nifdef PF_POSIX\n\tpf_tp=$1\n\tRM=rm -f\n\tRMDIR=rm -rf\n\tMKPATH=mkdir -p\n\tECHO=@echo\n\tCOPY=cp\n\tCOPYDIR=cp -r\n\tpf_fwrite=echo $(1) > $(2)\n\tpf_fappend=echo $(1) >> $(2)\n\n\tNOOP=echo\n\tMV=mv\nendif\n\n\n\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.5590240359306335, "alphanum_fraction": 0.5622532963752747, "avg_line_length": 32.56626510620117, "blob_id": "ab9448864e32c32eae5eeab050e4e3d58147add8", "content_id": "079bfc004c504381b675054386873b761bd7c396", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2787, "license_type": "permissive", "max_line_length": 120, "num_lines": 83, "path": "/source/code/providers/support/runasprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file runasprovider.h\n\n \\brief RunAs provider\n\n \\date 05-15-03\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef RUNASPROVIDER_H\n#define RUNASPROVIDER_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n\nusing namespace SCXCoreLib;\n\nnamespace SCXCore\n{\n //\n // RunAs Provider\n //\n // The RunAs Provider is a separate implementation because we're strongly\n // considering separating the RunAs provider into it's own CIM class.\n //\n\n class RunAsProvider\n {\n public:\n RunAsProvider() : m_Configurator(NULL) { }\n ~RunAsProvider() { };\n\n void Load();\n void Unload();\n\n bool ExecuteCommand(const std::wstring &command, std::wstring &resultOut,\n std::wstring &resultErr, int& returncode, unsigned timeout = 0,\n const std::wstring &elevationtype = L\"\");\n\n bool ExecuteShellCommand(const std::wstring &command, std::wstring &resultOut,\n std::wstring &resultErr, int& returncode, unsigned timeout = 0,\n const std::wstring &elevationtype = L\"\");\n\n bool ExecuteScript(const std::wstring &script, const std::wstring &arguments,\n std::wstring &resultOut, std::wstring &resultErr,\n int& returncode, unsigned timeout = 0, const std::wstring &elevationtype = L\"\");\n \n SCXLogHandle& GetLogHandle() { return m_log; }\n \n void SetConfigurator(SCXCoreLib::SCXHandle<RunAsConfigurator> configurator)\n {\n m_Configurator = configurator;\n }\n \n void SetTemporaryDirectory(std::wstring tmpDir)\n {\n \tm_defaultTmpDir = tmpDir;\n }\n\n private:\n void ParseConfiguration() { m_Configurator->Parse(); }\n\n std::wstring ConstructCommandWithElevation(const std::wstring &command, const std::wstring &elevationtype);\n std::wstring ConstructShellCommandWithElevation(const std::wstring &command, const std::wstring &elevationtype);\n bool OutputLimiter(std::wstring& resultOut, std::wstring& resultErr);\n\n //! Configurator.\n SCXCoreLib::SCXHandle<RunAsConfigurator> m_Configurator;\n\n SCXCoreLib::SCXLogHandle m_log;\n std::wstring m_defaultTmpDir;\n static int ms_loadCount;\n };\n\n extern RunAsProvider g_RunAsProvider;\n}\n\n#endif /* RUNASPROVIDER_H */\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n\n" }, { "alpha_fraction": 0.7054840922355652, "alphanum_fraction": 0.7183480262756348, "avg_line_length": 31.10869598388672, "blob_id": "1a107d118348182324a854cbdd7302a93d56b10a", "content_id": "4cf554644772d4ab6033eabb423319c0893fc095", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1477, "license_type": "permissive", "max_line_length": 100, "num_lines": 46, "path": "/source/code/shared/tools/scx_prune_repository/main.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n#\n##\n# Contains main program to generate a \"pruned\" repository.\n#\n# This program should be called with parameters like this:\n#\n# python main.py --cim_schema_dir=\"/some/path/dmtf/cimv2171\" \"/some/other/path/scx.mof\"\n#\n# Date: 2008-10-28 16:16:59\n#\n\nfrom commandlineparser import CommandLineParser\nfrom moffilerepository import MofFileRepository\nfrom moffile import MofFile\nfrom dependencywalker import DependencyWalker\n\n##\n# Main entry point\n#\nif __name__ == '__main__':\n\n # Parse command line parameters\n cmdLineParser = CommandLineParser()\n\n # Parse the complete mof file repository\n mofRepository = MofFileRepository(cmdLineParser.getCIMSchemaDir())\n\n # Parse the mof files supplied as arguments\n moffiles = []\n for filename in cmdLineParser.getArguments():\n moffiles.append(MofFile(filename))\n\n # This will generate the dependency list.\n depWalker = DependencyWalker(mofRepository, moffiles)\n\n # The paths in the generated output will be stripped of the --cim_schema_dir part of the path.\n includeDir = cmdLineParser.getCIMSchemaDir()\n if not includeDir.endswith('/'):\n includeDir = includeDir + '/'\n\n # Print to standard output in mof format.\n for moffile in depWalker.GetRequiredFiles():\n filename = moffile.GetFileName().replace(includeDir, '', 1)\n print '#pragma include (\\\"' + filename + '\\\")'\n" }, { "alpha_fraction": 0.5193938612937927, "alphanum_fraction": 0.5257265567779541, "avg_line_length": 33.81496047973633, "blob_id": "92b7dc363f6026b8561fa64fad797e3474adb5b8", "content_id": "7c330cb10fc3bd11c7deed050bc76d1e56262c21", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8843, "license_type": "permissive", "max_line_length": 102, "num_lines": 254, "path": "/source/code/providers/support/appserver/weblogicappserverenumeration.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file weblogicappserverenumeration.h\n\n \\brief Enumeration of weblogic application servers\n\n \\date 11-05-18 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef WEBLOGICAPPSERVERENUMERATION_H\n#define WEBLOGICAPPSERVERENUMERATION_H\n\n#include <vector>\n\n#include <scxsystemlib/entityenumeration.h>\n#include <scxcorelib/scxlog.h>\n#include <util/XElement.h>\n\n#include \"appserverconstants.h\"\n#include \"weblogicappserverinstance.h\"\n\nnamespace SCXSystemLib {\n /*--------------------------------------------------------*/\n /**\n Sort object for use with a comparison operation run against\n a vector of SCXFilePaths.\n */\n struct SortPath : \n public std::binary_function<SCXCoreLib::SCXFilePath,\n SCXCoreLib::SCXFilePath, bool> {\n inline bool operator()(const SCXCoreLib::SCXFilePath& a,\n const SCXCoreLib::SCXFilePath& b) {\n return a.Get() < b.Get();\n }\n };\n\n /*--------------------------------------------------------*/\n /**\n Class that represents an interface for accessing the filesystem\n of a WebLogic installation.\n \n */\n class IWebLogicFileReader {\n public:\n virtual ~IWebLogicFileReader() {};\n\n virtual std::vector<SCXCoreLib::SCXFilePath> GetDomains() = 0;\n\n /*--------------------------------------------------------*/\n /*\n * Get a list of instances associated with this installation\n * of WebLogic.\n * \n */\n virtual void\n GetInstances(\n const SCXCoreLib::SCXFilePath& domain,\n std::vector<\n SCXCoreLib::SCXHandle<AppServerInstance> >& instances) = 0;\n\n virtual void SetPath(const std::wstring& path) = 0;\n };\n\n /*--------------------------------------------------------------*/\n /**\n Class representing the piece of logic for obtaining the\n necessary information from the filesystem regarding files and\n directories about WebLogic installs.\n\n */\n class WebLogicFileReader: public IWebLogicFileReader {\n protected:\n\n std::wstring m_installationPath;\n\n /*\n * Handle for the class Logger\n */\n SCXCoreLib::SCXLogHandle m_log;\n\n public:\n WebLogicFileReader();\n\n virtual ~WebLogicFileReader() {};\n\n virtual std::vector<SCXCoreLib::SCXFilePath> GetDomains();\n\n virtual void\n GetInstances(\n const SCXCoreLib::SCXFilePath& domain,\n std::vector<\n SCXCoreLib::SCXHandle<AppServerInstance> >& instances);\n\n virtual void SetPath(const std::wstring& path);\n\n protected:\n virtual bool\n DoesConfigXmlExist(const SCXCoreLib::SCXFilePath& path);\n\n virtual bool DoesDomainRegistryXmlExist(\n const SCXCoreLib::SCXFilePath& path);\n\n virtual bool DoesNodemanagerDomainsExist(\n const SCXCoreLib::SCXFilePath& path);\n\n virtual bool DoesServerDirectoryExist(\n const SCXCoreLib::SCXFilePath& path);\n\n virtual SCXCoreLib::SCXHandle<std::istream> OpenConfigXml(\n const std::wstring& filename);\n\n virtual SCXCoreLib::SCXHandle<std::istream> OpenDomainRegistryXml(\n const std::wstring& filename);\n\n virtual SCXCoreLib::SCXHandle<std::istream> OpenNodemanagerDomains(\n const std::wstring& filename);\n\n void\n ReadConfigXml(\n const SCXCoreLib::SCXFilePath& domainDir,\n const SCXCoreLib::SCXFilePath& configXml,\n std::vector<\n SCXCoreLib::SCXHandle<AppServerInstance> >& instances);\n\n /*-------------------------------------------------------------*/\n /**\n Read the domain-registry.xml file to get a list of the\n WebLogic 11g domains associated with the installation.\n \n Note: this file is located in the base installation folder\n i.e. /opt/Oracle/Middleware/domain-registry.xml\n */\n void ReadDomainRegistryXml(\n const SCXCoreLib::SCXFilePath& domainRegistryXml,\n std::vector<SCXCoreLib::SCXFilePath>& domains);\n\n /*-------------------------------------------------------------*/\n /**\n Read the nodemanager.domains file to get a list of the\n WebLogic 10g domains associated with the installation.\n \n Note: this file is located up the tree in a 'well-known'\n location.\n i.e. /opt/Oracle/Middleware/wlserver_10.3/common/nodemanager/nodemanager.domains\n \n */\n void ReadNodemanagerDomains(\n const SCXCoreLib::SCXFilePath& domainRegistryXml,\n std::vector<SCXCoreLib::SCXFilePath>& domains);\n\n private:\n void GetStringFromStream(\n SCXCoreLib::SCXHandle<std::istream> mystream,\n std::string& content);\n\n void ReadConfigXmlForAdminServerName(\n const SCX::Util::Xml::XElementPtr& domainNode,\n std::string& adminServerName);\n\n void ReadConfigXmlForSslInformation(\n const SCX::Util::Xml::XElementPtr& sslNode,\n bool& sslEnabled, string& httpsPort);\n\n void ReadConfigXmlForVersion(\n const SCX::Util::Xml::XElementPtr& domainNode,\n std::string& version);\n };\n\n /*--------------------------------------------------------------*/\n /**\n Class that given a set of directories, will review each on for \n the appropriate XML files that describe Admin and Managed \n WebLogic servers.\n\n On WebLogic 11gR1, the expectation is that the path given is \n the location of the installation. From this location there is\n a XML file domain-registry.xml that contains a list of the \n domains. For each of these domains, it is then necessary\n to location the config/config.xml file that has the XML blob\n to parse.\n\n <domain ... >\n <name>base_domain</name>\n <domain-version>10.3.2.0</domain-version>\n <security-configuration ... >\n <name>base_domain</name>\n ...\n <server>\n <name>AdminServer</name>\n <ssl>\n <name>AdminServer</name>\n <enabled>true</enabled>\n <listen-port>7012</listen-port>\n </ssl>\n <machine>new_UnixMachine_1</machine>\n <listen-port>7011</listen-port>\n <listen-address/>\n </server>\n <server>\n <name>new_ManagedServer_1</name>\n <ssl>\n <name>new_ManagedServer_1</name>\n <enabled>true</enabled>\n <listen-port>7513</listen-port>\n </ssl>\n <machine>new_UnixMachine_1</machine>\n <listen-port>7013</listen-port>\n <listen-address/>\n </server>\n ...\n </domain>\n\n On WebLogic 10gR3, the configuration file is the same; however,\n the name/format/location of the file containing the domains\n is different. The file to look for is a INI file (i.e. text\n file of name/value pairs) located in the 'well-known' location.\n \n ${root}/wlserver_10.3/common/nodemanager/nodemanager.domains\n \n */\n class WebLogicAppServerEnumeration {\n public:\n WebLogicAppServerEnumeration(SCXCoreLib::SCXHandle<\n IWebLogicFileReader>);\n\n virtual ~WebLogicAppServerEnumeration();\n\n void\n GetInstances(\n std::vector<std::wstring>& installations,\n std::vector<\n SCXCoreLib::SCXHandle<AppServerInstance> >& result);\n\n protected:\n /*\n * Filesystem abstraction for interacting with XML and Text\n * Configuration files.\n */\n SCXCoreLib::SCXHandle<IWebLogicFileReader> m_reader;\n\n private:\n\n /*\n * Handle for the class Logger\n */\n SCXCoreLib::SCXLogHandle m_log;\n };\n\n}\n\n#endif /* WEBLOGICAPPSERVERENUMERATION_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5643564462661743, "alphanum_fraction": 0.5742574334144592, "avg_line_length": 37.47618865966797, "blob_id": "b82b02a02bff772f989bd3d3f3dc951ee6cff7d5", "content_id": "c25b82b10e30e8b98af35d286591e680e688f443", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3232, "license_type": "permissive", "max_line_length": 84, "num_lines": 84, "path": "/test/code/shared/tools/scx_prune_repository/moffilerepository_test.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "import unittest\nimport os\nimport shutil\nimport sys\nsys.path.append('../../../../source/code/tools/scx_prune_repository')\nfrom moffilerepository import MofFileRepository\nfrom moffile import MofFile\n\nclass MofFileRepositoryTestCase(unittest.TestCase):\n def setUp(self):\n try:\n os.mkdir('./repository')\n except OSError:\n pass\n \n def tearDown(self):\n shutil.rmtree('./repository', 1)\n\n def testEmptyRepository(self):\n repository = MofFileRepository('./repository/')\n self.assertEqual(repository.GetAllMofFiles(), [])\n\n def testRepositoryWithOneFile(self):\n self.GivenRepositoryStructure(['File1.mof'])\n\n repository = MofFileRepository('./repository/')\n moffiles = repository.GetAllMofFiles()\n moffilenames = self.GetMofFileNames(moffiles)\n self.assertEqual(moffilenames, ['./repository/File1.mof'])\n\n def testRecursiveRepositoryWith3Files(self):\n self.GivenRepositoryStructure(['File1.mof',\n 'directory1/File2.mof',\n 'directory2/File3.mof'])\n\n repository = MofFileRepository('./repository/')\n self.assertEqual(self.GetMofFileNames(repository.GetAllMofFiles()).sort(),\n ['./repository/File1.mof',\n './repository/directory1/File2.mof',\n './repository/directory2/File3.mof'].sort())\n\n def testNonMofFilesAreIgnored(self):\n self.GivenRepositoryStructure(['File1.mof',\n 'directory1/File2.mof',\n 'directory2/File3.notmof'])\n\n repository = MofFileRepository('./repository/')\n self.assertEqual(self.GetMofFileNames(repository.GetAllMofFiles()).sort(),\n ['./repository/File1.mof',\n './repository/directory1/File2.mof'].sort())\n \n def testGetFileDefiningClass(self):\n self.GivenRepositoryStructure(['File1.mof',\n 'directory1/File2.mof',\n 'directory2/File3.mof'])\n out = open('./repository/directory1/File4.mof', 'w')\n out.write('class TestClass {\\n')\n out.write('}')\n out.close()\n \n repository = MofFileRepository('./repository/')\n self.assertEqual(repository.GetFileDefiningClass('TestClass').GetFileName(),\n './repository/directory1/File4.mof')\n self.assertEqual(repository.GetFileDefiningClass('NoSuchClass'), None)\n\n\n def GivenRepositoryStructure(self, filenames):\n for filename in filenames:\n path = os.path.join('./repository', filename)\n try:\n os.makedirs(os.path.dirname(path))\n except OSError:\n pass\n out = open(path, 'w')\n out.write('class Class1 {\\n')\n out.write('}')\n out.close()\n\n def GetMofFileNames(self, moffiles):\n filenames = []\n for moffile in moffiles:\n self.assert_(isinstance(moffile, MofFile))\n filenames.append(moffile.GetFileName())\n return filenames\n" }, { "alpha_fraction": 0.5998058915138245, "alphanum_fraction": 0.6023940443992615, "avg_line_length": 34.94186019897461, "blob_id": "38bc09425b9b2bf2edef2677d3806644498b6e4c", "content_id": "8fbe1ccdce65cec29a9e4438db849412e30e96fb", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3091, "license_type": "permissive", "max_line_length": 125, "num_lines": 86, "path": "/test/code/providers/testutilities.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Test code for SCX Core Provider\n\n \\date 2015-12-23\n\n Test support code for SCX Core Provider\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/stringaid.h>\n#include <scxsystemlib/scxostypeinfo.h>\n\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n\nusing namespace SCXCoreLib;\n\nnamespace SCXCore\n{\n /**\n Gets the actual O/S distribution for the current installation\n\n \\returns The actual O/S distribution for current installation\n\n \\notes Returning the actual O/S type, on Linux, is difficult. The main\n \t issue is that it can vary based on numerous factors (not the\n least of which includes: Is the kit currently installed, and\n what kit was installed prior to this kit installation). These\n issues make reliable tests extraordinarily difficult, partly\n because the code that fetches this is up in the PAL (one level\n up, and thus not mockable very easily).\n\n Solution: On non-linux platforms, just rely on our trusty call\n to GetDistributionName(), which works very reliably. On Linux,\n however, call the actual code to return the distro name (what\n the provider will do), validate for a list of valid responses,\n and continue along our merry way.\n */\n\n std::wstring GetActualDistributionName(std::wstring errMsg)\n {\n#if !defined(linux)\n return GetDistributionName(errMsg);\n#else\n // Add a list of possible responses (add to list if needed)\n std::vector<std::wstring> possibleResponses;\n possibleResponses.push_back(L\"Unknown Linux Distribution\");\n possibleResponses.push_back(L\"Linux Distribution\");\n possibleResponses.push_back(L\"Red Hat Distribution\");\n possibleResponses.push_back(L\"SuSE Distribution\");\n\n // Call the actual routine to fetch the system name\n std::wstring actualName;\n try {\n SCXSystemLib::SCXOSTypeInfo osinfo;\n actualName = osinfo.GetOSName(true);\n } catch (SCXException& e) {\n std::wstringstream err;\n err << L\"Can't read OS name because of exception: \" << e.What() << e.Where();\n //CPPUNIT_ASSERT_MESSAGE(err, false);\n }\n\n bool matchFound = false;\n for (std::vector<std::wstring>::const_iterator it = possibleResponses.begin(); it != possibleResponses.end(); ++it) {\n if (actualName == *it) {\n matchFound = true;\n break;\n }\n }\n\n CPPUNIT_ASSERT_MESSAGE(\"Unknown OSName returned: \" + StrToMultibyte(actualName), matchFound);\n\n return actualName;\n#endif // !defined(linux)\n }\n}\n" }, { "alpha_fraction": 0.6354876756668091, "alphanum_fraction": 0.6580493450164795, "avg_line_length": 25.121795654296875, "blob_id": "a8cd77e0c04982e19d663631b955ecb65ac94e19", "content_id": "06b7d5f6c3a081f42f55857f4dac2069b710ed5b", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 4255, "license_type": "permissive", "max_line_length": 102, "num_lines": 156, "path": "/tools/chroot/suse-sles10/mkjail-wsmand.sh", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/bash\r\n\r\n#\r\n# Copyright (c) Microsoft Corporation. All rights reserved.\r\n#\r\n\r\nSCX_WSMAND_CHROOT=/var/opt/microsoft/scx/chroot/wsmand\r\n\r\nif [ -d ${SCX_WSMAND_CHROOT} ]; then\r\n echo \"Jail already exist in ${SCX_WSMAND_CHROOT}\"\r\n echo \"\"\r\n exit 1\r\nfi\r\n\r\n\r\nexecute() {\r\n echo \"*** Executing: $*\"\r\n `$*`\r\n}\r\n\r\nfunction createdir() {\r\n if [ ! -d $1 ]; then\r\n echo \"*** Creating directory $1\"\r\n mkdir -p $1\r\n fi\r\n}\r\n\r\nfunction copyfile() {\r\n while [ \"$1\" ]; do\r\n createdir ${SCX_WSMAND_CHROOT}`dirname $1`\r\n echo \"*** Copying file $1 to ${SCX_WSMAND_CHROOT}$1\"\r\n cp $1 ${SCX_WSMAND_CHROOT}$1\r\n shift\r\n done\r\n}\r\n\r\nfunction copydir() {\r\n while [ \"$1\" ]; do\r\n if [ -d $1 ]; then\r\n createdir ${SCX_WSMAND_CHROOT}`dirname $1`\r\n echo \"*** Copying directory $1 to ${SCX_WSMAND_CHROOT}$1\"\r\n cp -R $1 ${SCX_WSMAND_CHROOT}$1\r\n shift\r\n else\r\n echo \"*** Not a directory: $1\"\r\n fi\r\n done\r\n}\r\n\r\nfunction copylink() {\r\n if [ -h $1 ]; then\r\n linksource=`ls -l $1 | grep -o -P \"[-_+.\\w]+$\"`\r\n copyfile `dirname $1`/$linksource\r\n pushd ${SCX_WSMAND_CHROOT}`dirname $1` >/dev/null 2>&1\r\n execute ln -s $linksource `basename $1`\r\n popd >/dev/null\r\n else\r\n if [ -f $1 ]; then\r\n copyfile $1\r\n fi\r\n fi\r\n}\r\n\r\n\r\n# Make devices\r\ncreatedir ${SCX_WSMAND_CHROOT}/dev\r\nexecute mknod -m 666 ${SCX_WSMAND_CHROOT}/dev/null c 1 3\r\nexecute mknod -m 444 ${SCX_WSMAND_CHROOT}/dev/random c 1 8\r\nexecute mknod -m 444 ${SCX_WSMAND_CHROOT}/dev/urandom c 1 9\r\n\r\n# etc\r\ncreatedir ${SCX_WSMAND_CHROOT}/etc\r\ncopyfile /etc/opt/microsoft/scx/conf/openwsman.conf \r\ncopyfile /etc/opt/microsoft/scx/ssl/scx-seclevel1-key.pem /etc/opt/microsoft/scx/ssl/scx-seclevel1.pem\r\ncopyfile /etc/passwd /etc/group /etc/shadow /etc/nsswitch.conf\r\ncopydir /etc/security\r\ncopyfile /etc/pam.d/scx\r\n\r\n# PAM\r\npushd /etc/pam.d > /dev/null 2>&1\r\npam_includes=`grep -o -P \"include\\W+[-\\w]+\" /etc/pam.d/scx | awk '{print $2}' | xargs`\r\npam_modules=`grep -v -P \"^#\" /etc/pam.d/scx | grep -o -P \"pam_[-\\w]+\\.so\" | xargs`\r\n\r\npam_includedmodules=\"\"\r\nfor pam_file in $pam_includes; do\r\n pam_includedmodules+=\"`grep -v -P \"^#\" $pam_file | grep -o -P \"pam_[-\\w]+\\.so\" | xargs` \"\r\ndone\r\n\r\npam_allmodules=\"`echo \\\"$pam_modules $pam_includedmodules\\\" | xargs -n 1 | sort | uniq | xargs`\"\r\npopd > /dev/null 2>&1\r\n\r\nfor pam_file in $pam_allmodules; do\r\n copyfile /lib/security/$pam_file\r\ndone\r\nfor pam_file in $pam_includes; do\r\n copyfile /etc/pam.d/$pam_file\r\ndone\r\n\r\n# lib\r\ncopylink /lib/ld-linux.so.2 \r\ncopylink /lib/libaudit.so.0 \r\ncopylink /lib/libc.so.6 \r\ncopylink /lib/libcrypt.so.1 \r\ncopylink /lib/libdl.so.2 \r\ncopylink /lib/libgcc_s.so.1 \r\ncopylink /lib/libhistory.so.5\r\ncopylink /lib/libm.so.6\r\ncopylink /lib/libncurses.so.5\r\ncopylink /lib/libnsl.so.1\r\ncopylink /lib/libnss_compat-2.4.so \r\ncopylink /lib/libnss_compat.so.2 \r\ncopylink /lib/libnss_files-2.4.so \r\ncopylink /lib/libnss_files.so.2\r\ncopylink /lib/libpam.so.0 \r\ncopylink /lib/libpam.so.0.81.5 \r\ncopylink /lib/libpam_misc.so.0 \r\ncopylink /lib/libpam_misc.so.0.81.2 \r\ncopylink /lib/libpamc.so.0 \r\ncopylink /lib/libpamc.so.0.81.0\r\ncopylink /lib/libpthread.so.0\r\ncopylink /lib/libreadline.so.5\r\ncopylink /lib/libxcrypt.so.1\r\ncopylink /lib/libz.so.1\r\n\r\n# opt\r\ncopyfile /opt/microsoft/scx/COPYRIGHT\r\ncopyfile /opt/microsoft/scx/LICENSE\r\ncopyfile /opt/microsoft/scx/bin/openwsmand\r\ncopylink /opt/microsoft/scx/lib/libpegclient.so\r\ncopylink /opt/microsoft/scx/lib/libpegcommon.so\r\ncopylink /opt/microsoft/scx/lib/libwsman.so\r\ncopylink /opt/microsoft/scx/lib/libwsman_server.so\r\ncopylink /opt/microsoft/scx/lib/openwsman/authenticators/libwsman_pam_auth.so\r\ncopylink /opt/microsoft/scx/lib/openwsman/plugins/libwsman_cim_plugin.so\r\n\r\n# usr\r\ncopylink /usr/lib/libcrack.so.2\r\ncopylink /usr/lib/libcrypto.so.0.9.8\r\ncopylink /usr/lib/libssl.so.0.9.8\r\ncopylink /usr/lib/libstdc++.so.6\r\ncopylink /usr/lib/libxml2.so.2\r\n\r\n# var\r\ncreatedir ${SCX_WSMAND_CHROOT}/var/opt/microsoft/scx/log\r\ncreatedir ${SCX_WSMAND_CHROOT}/var/opt/microsoft/scx/tmp\r\nexecute touch ${SCX_WSMAND_CHROOT}/var/opt/microsoft/scx/log/wsmand.log\r\n\r\n# create startup script\r\nexecute cp `dirname ${SCX_WSMAND_CHROOT}`/scx-wsmand.chroot /etc/init.d/\r\n\r\n\r\necho \"\"\r\necho \"done.\"\r\necho \"\"\r\n\r\nexit 0\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.46710333228111267, "alphanum_fraction": 0.471410870552063, "avg_line_length": 49.4375, "blob_id": "405f491eb48e3be1b92f652b6cae7a560b1cc87e", "content_id": "04463b34a2f87825aa4425904c4979439ebda43e", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 16947, "license_type": "permissive", "max_line_length": 124, "num_lines": 336, "path": "/test/code/providers/os_provider/osprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n Created date 2008-09-22 15:22:00\n\n Operating System provider test class.\n\n Only tests the functionality of the provider class.\n The actual data gathering is tested by a separate class.\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <scxsystemlib/osenumeration.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n#include <cppunit/extensions/HelperMacros.h>\n#include <testutils/scxunit.h>\n#include \"support/osprovider.h\"\n#include \"SCX_OperatingSystem_Class_Provider.h\"\n\n#include \"testutilities.h\"\n\n#if defined(TRAVIS)\nconst bool s_fTravis = true;\n#else\nconst bool s_fTravis = false;\n#endif\n\nusing namespace SCXCore;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nclass OSProvider_Test : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( OSProvider_Test );\n CPPUNIT_TEST( callDumpStringForCoverage );\n CPPUNIT_TEST( TestEnumerateInstancesKeysOnly );\n CPPUNIT_TEST( TestEnumerateInstances );\n CPPUNIT_TEST( TestGetInstance );\n CPPUNIT_TEST( TestVerifyKeyCompletePartial );\n\n SCXUNIT_TEST_ATTRIBUTE(callDumpStringForCoverage, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestEnumerateInstancesKeysOnly, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestEnumerateInstances, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestGetInstance, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartial, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector<std::wstring> m_keyNames;\n\npublic:\n\n OSProvider_Test()\n {\n m_keyNames.push_back(L\"Name\");\n m_keyNames.push_back(L\"CSCreationClassName\");\n m_keyNames.push_back(L\"CSName\");\n m_keyNames.push_back(L\"CreationClassName\");\n }\n\n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_OperatingSystem_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_OperatingSystem_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void callDumpStringForCoverage()\n {\n CPPUNIT_ASSERT(g_OSProvider.DumpString().find(L\"OSProvider\") != std::wstring::npos);\n }\n\n void TestEnumerateInstancesKeysOnly()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_OperatingSystem_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n }\n\n void TestEnumerateInstances()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_OperatingSystem_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void TestGetInstance()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestGetInstance<mi::SCX_OperatingSystem_Class_Provider,\n mi::SCX_OperatingSystem_Class>(context, m_keyNames.size(), CALL_LOCATION(errMsg));\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartial()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_OperatingSystem_Class_Provider,\n mi::SCX_OperatingSystem_Class>(m_keyNames, CALL_LOCATION(errMsg));\n }\n\n void ValidateInstance(const TestableContext &context, std::wstring errMsg)\n {\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 1u, context.Size());\n \n const TestableInstance &instance = context[0];\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE,\n SCXCore::GetActualDistributionName(CALL_LOCATION(errMsg)), instance.GetKeyValue(0, CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"SCX_ComputerSystem\", instance.GetKeyValue(1, CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE,\n GetFQHostName(CALL_LOCATION(errMsg)), instance.GetKeyValue(2, CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"SCX_OperatingSystem\", instance.GetKeyValue(3, CALL_LOCATION(errMsg)));\n#if defined(linux)\n std::wstring tmpExpectedProperties[] = {L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"EnabledState\",\n L\"RequestedState\",\n L\"EnabledDefault\",\n L\"CSCreationClassName\",\n L\"CSName\",\n L\"CreationClassName\",\n L\"OSType\",\n L\"OtherTypeDescription\",\n L\"Version\",\n L\"LastBootUpTime\",\n L\"LocalDateTime\",\n L\"CurrentTimeZone\",\n L\"NumberOfLicensedUsers\",\n L\"NumberOfUsers\",\n L\"NumberOfProcesses\",\n L\"MaxNumberOfProcesses\",\n L\"TotalSwapSpaceSize\",\n L\"TotalVirtualMemorySize\",\n L\"FreeVirtualMemory\",\n L\"FreePhysicalMemory\",\n L\"TotalVisibleMemorySize\",\n L\"SizeStoredInPagingFiles\",\n L\"FreeSpaceInPagingFiles\",\n L\"MaxProcessMemorySize\",\n L\"MaxProcessesPerUser\",\n L\"OperatingSystemCapability\",\n L\"SystemUpTime\"\n };\n#elif defined(aix)\n std::wstring tmpExpectedProperties[] = {L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"EnabledState\",\n L\"RequestedState\",\n L\"EnabledDefault\",\n L\"CSCreationClassName\",\n L\"CSName\",\n L\"CreationClassName\",\n L\"OSType\",\n L\"OtherTypeDescription\",\n L\"Version\",\n L\"LastBootUpTime\",\n L\"LocalDateTime\",\n L\"CurrentTimeZone\",\n L\"NumberOfLicensedUsers\",\n L\"NumberOfUsers\",\n L\"NumberOfProcesses\",\n L\"TotalSwapSpaceSize\",\n L\"TotalVirtualMemorySize\",\n L\"FreeVirtualMemory\",\n L\"FreePhysicalMemory\",\n L\"TotalVisibleMemorySize\",\n L\"SizeStoredInPagingFiles\",\n L\"FreeSpaceInPagingFiles\",\n L\"OperatingSystemCapability\",\n L\"MaxProcessMemorySize\",\n L\"MaxProcessesPerUser\",\n L\"SystemUpTime\"\n };\n#elif defined(hpux)\n std::wstring tmpExpectedProperties[] = {L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"EnabledState\",\n L\"RequestedState\",\n L\"EnabledDefault\",\n L\"CSCreationClassName\",\n L\"CSName\",\n L\"CreationClassName\",\n L\"OSType\",\n L\"OtherTypeDescription\",\n L\"Version\",\n L\"LastBootUpTime\",\n L\"LocalDateTime\",\n L\"CurrentTimeZone\",\n L\"NumberOfLicensedUsers\",\n L\"NumberOfUsers\",\n L\"NumberOfProcesses\",\n L\"MaxNumberOfProcesses\",\n L\"TotalSwapSpaceSize\",\n L\"TotalVirtualMemorySize\",\n L\"FreeVirtualMemory\",\n L\"FreePhysicalMemory\",\n L\"TotalVisibleMemorySize\",\n L\"SizeStoredInPagingFiles\",\n L\"FreeSpaceInPagingFiles\",\n L\"MaxProcessMemorySize\",\n L\"MaxProcessesPerUser\",\n L\"OperatingSystemCapability\",\n L\"SystemUpTime\"\n };\n#elif defined(sun)\n std::wstring tmpExpectedProperties[] = {L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"EnabledState\",\n L\"RequestedState\",\n L\"EnabledDefault\",\n L\"CSCreationClassName\",\n L\"CSName\",\n L\"CreationClassName\",\n L\"OSType\",\n L\"OtherTypeDescription\",\n L\"Version\",\n L\"LastBootUpTime\",\n L\"LocalDateTime\",\n L\"CurrentTimeZone\",\n L\"NumberOfLicensedUsers\",\n L\"NumberOfUsers\",\n L\"NumberOfProcesses\",\n L\"TotalSwapSpaceSize\",\n L\"TotalVirtualMemorySize\",\n L\"FreeVirtualMemory\",\n L\"FreePhysicalMemory\",\n L\"TotalVisibleMemorySize\",\n L\"SizeStoredInPagingFiles\",\n L\"FreeSpaceInPagingFiles\",\n L\"MaxProcessMemorySize\",\n L\"MaxProcessesPerUser\",\n L\"OperatingSystemCapability\",\n L\"SystemUpTime\"\n };\n#else\n#error Platform not supported\n#endif\n const size_t numprops = sizeof(tmpExpectedProperties) / sizeof(tmpExpectedProperties[0]);\n std::set<std::wstring> expectedProperties(tmpExpectedProperties, tmpExpectedProperties + numprops);\n\n for (MI_Uint32 i = 0; i < instance.GetNumberOfProperties(); ++i)\n {\n TestableInstance::PropertyInfo info;\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, MI_RESULT_OK, instance.FindProperty(i, info));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE + \"Property mismatch: \" + SCXCoreLib::StrToMultibyte(info.name),\n 1u, expectedProperties.count(info.name));\n }\n\n // Be sure that all of the properties in our set exist in the property list\n for (std::set<std::wstring>::const_iterator iter = expectedProperties.begin();\n iter != expectedProperties.end(); ++iter)\n {\n#if defined(PF_DISTRO_ULINUX)\n // Universal system OS provider looks at installed path to run GetLinuxOS.sh.\n // If the kit isn't installed, \"Version\" is not set. For this reason we skip the \"Version\" property.\n if (L\"Version\" == *iter)\n {\n continue;\n }\n#endif // defined(PF_DISTRO_ULINUX)\n TestableInstance::PropertyInfo info;\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE + \"Missing property: \" + SCXCoreLib::StrToMultibyte(*iter),\n MI_RESULT_OK, instance.FindProperty((*iter).c_str(), info));\n }\n \n std::wstring strCaption = instance.GetProperty(L\"Caption\", CALL_LOCATION(errMsg)).\n GetValue_MIString(CALL_LOCATION(errMsg));\n scxulong uiCountProcesses = instance.GetProperty(L\"NumberOfProcesses\", CALL_LOCATION(errMsg)).\n GetValue_MIUint32(CALL_LOCATION(errMsg));\n scxulong ulTotalSwap = instance.GetProperty(L\"TotalSwapSpaceSize\", CALL_LOCATION(errMsg)).\n GetValue_MIUint64(CALL_LOCATION(errMsg));\n scxulong ulTotalVM = instance.GetProperty(L\"TotalVirtualMemorySize\", CALL_LOCATION(errMsg)).\n GetValue_MIUint64(CALL_LOCATION(errMsg));\n scxulong ulFreeVM = instance.GetProperty(L\"FreeVirtualMemory\", CALL_LOCATION(errMsg)).\n GetValue_MIUint64(CALL_LOCATION(errMsg));\n scxulong ulFreeMem = instance.GetProperty(L\"FreePhysicalMemory\", CALL_LOCATION(errMsg)).\n GetValue_MIUint64(CALL_LOCATION(errMsg));\n scxulong ulTotalMem = instance.GetProperty(L\"TotalVisibleMemorySize\", CALL_LOCATION(errMsg)).\n GetValue_MIUint64(CALL_LOCATION(errMsg));\n scxulong ulTotalPage = instance.GetProperty(L\"SizeStoredInPagingFiles\", CALL_LOCATION(errMsg)).\n GetValue_MIUint64(CALL_LOCATION(errMsg));\n scxulong ulFreePage = instance.GetProperty(L\"FreeSpaceInPagingFiles\", CALL_LOCATION(errMsg)).\n GetValue_MIUint64(CALL_LOCATION(errMsg));\n std::wstring strOSCapability = instance.GetProperty(L\"OperatingSystemCapability\", CALL_LOCATION(errMsg)).\n GetValue_MIString(CALL_LOCATION(errMsg));\n\n // On ULINUX, we may be running on an installed machine\n#if !defined(PF_DISTRO_ULINUX)\n CPPUNIT_ASSERT(6 <= strCaption.length());\n#endif\n\n CPPUNIT_ASSERT(uiCountProcesses > 0);\n\n // Travis CI systems don't appear to have a pagefile. Lots of RAM, but\n // no pagefile. Test assumed a multi-user system with a pagefile, so\n // ease up on that if we're running on a Travis CI system.\n if ( ! s_fTravis )\n {\n CPPUNIT_ASSERT(256000 <= ulTotalSwap);\n CPPUNIT_ASSERT(512000 <= ulTotalVM);\n CPPUNIT_ASSERT(ulFreeVM <= ulTotalVM);\n CPPUNIT_ASSERT(256000 <= ulTotalPage);\n CPPUNIT_ASSERT(ulFreePage <= ulTotalPage);\n }\n\n CPPUNIT_ASSERT(ulFreeMem <= ulTotalMem);\n CPPUNIT_ASSERT(128000 <= ulTotalMem);\n CPPUNIT_ASSERT(strOSCapability == L\"32 bit\" || strOSCapability == L\"64 bit\");\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( OSProvider_Test );\n" }, { "alpha_fraction": 0.6242806315422058, "alphanum_fraction": 0.6242806315422058, "avg_line_length": 26.223880767822266, "blob_id": "f4d0f2c87fa99ca46ff606033328ef721f083762", "content_id": "ffc8b23bf928b977bf93ec7996aa71f81346e8be", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3649, "license_type": "permissive", "max_line_length": 80, "num_lines": 134, "path": "/source/code/providers/SCX_DiskDrive_Class_Provider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/* @migen@ */\n#ifndef _SCX_DiskDrive_Class_Provider_h\n#define _SCX_DiskDrive_Class_Provider_h\n\n#include \"SCX_DiskDrive.h\"\n#ifdef __cplusplus\n# include <micxx/micxx.h>\n# include \"module.h\"\n\nMI_BEGIN_NAMESPACE\n\n/*\n**==============================================================================\n**\n** SCX_DiskDrive provider class declaration\n**\n**==============================================================================\n*/\n\nclass SCX_DiskDrive_Class_Provider\n{\n/* @MIGEN.BEGIN@ CAUTION: PLEASE DO NOT EDIT OR DELETE THIS LINE. */\nprivate:\n Module* m_Module;\n\npublic:\n SCX_DiskDrive_Class_Provider(\n Module* module);\n\n ~SCX_DiskDrive_Class_Provider();\n\n void Load(\n Context& context);\n\n void Unload(\n Context& context);\n\n void EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter);\n\n void GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instance,\n const PropertySet& propertySet);\n\n void CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& newInstance);\n\n void ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& modifiedInstance,\n const PropertySet& propertySet);\n\n void DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instance);\n\n void Invoke_RequestStateChange(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_RequestStateChange_Class& in);\n\n void Invoke_SetPowerState(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_SetPowerState_Class& in);\n\n void Invoke_Reset(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_Reset_Class& in);\n\n void Invoke_EnableDevice(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_EnableDevice_Class& in);\n\n void Invoke_OnlineDevice(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_OnlineDevice_Class& in);\n\n void Invoke_QuiesceDevice(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_QuiesceDevice_Class& in);\n\n void Invoke_SaveProperties(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_SaveProperties_Class& in);\n\n void Invoke_RestoreProperties(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_RestoreProperties_Class& in);\n\n void Invoke_LockMedia(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_LockMedia_Class& in);\n\n void Invoke_RemoveByName(\n Context& context,\n const String& nameSpace,\n const SCX_DiskDrive_Class& instanceName,\n const SCX_DiskDrive_RemoveByName_Class& in);\n\n/* @MIGEN.END@ CAUTION: PLEASE DO NOT EDIT OR DELETE THIS LINE. */\n};\n\nMI_END_NAMESPACE\n\n#endif /* __cplusplus */\n\n#endif /* _SCX_DiskDrive_Class_Provider_h */\n\n" }, { "alpha_fraction": 0.5242365598678589, "alphanum_fraction": 0.5269734859466553, "avg_line_length": 36.77959060668945, "blob_id": "a7949f53740ea79e1dd1ed78236b4777c2a1336d", "content_id": "e6c4c2acc8e9e2940ddc707fd93650574a380593", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 27768, "license_type": "permissive", "max_line_length": 169, "num_lines": 735, "path": "/source/code/providers/support/logfileutils.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n \n*/\n/**\n \\file logfileutils.cpp\n\n \\brief Main implementation file for Log File Provider\n\n \\date 2008-0-08 09:35:36\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n\n#include <errno.h>\n#include <fstream>\n#include <iostream>\n#include <locale>\n\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxdirectoryinfo.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/scxmath.h>\n#include <scxcorelib/scxuser.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxstream.h>\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/scxfile.h>\n\n#include \"logfileutils.h\"\n\nusing namespace SCXCoreLib;\nusing namespace std;\n\nnamespace SCXCore {\n const SCXCoreLib::SCXPatternFinder::SCXPatternCookie LogFileReader::s_patternID = 1;\n const std::wstring LogFileReader::s_pattern = L\"SELECT * FROM SCX_LogFileRecord WHERE FileName=%PATH\";\n const std::wstring LogFileReader::s_patternParameter = L\"PATH\";\n const unsigned int cMaxMatchedRows = 500; //!< max number of matched log rows return limit, 1000 rows from scx log file does not work, 750 does\n const size_t cMaxTotalBytes = 60 * 1024; //!< max number of bytes to return in a single instance\n\n /*----------------------------------------------------------------------------*/\n /* LogFileReader::LogFilePositionRecord */\n /*----------------------------------------------------------------------------*/\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor\n Creates a new LogFilePositionRecord with default values.\n\n \\param[in] logfile Log file for this record.\n \\param[in] qid Q ID of this record.\n \\param[in] persistMedia Used to inject persistence media to use for persisting this record. \n */\n LogFileReader::LogFilePositionRecord::LogFilePositionRecord(\n const SCXCoreLib::SCXFilePath& logfile,\n const std::wstring& qid,\n SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> persistMedia /* = SCXCoreLib::GetPersistMedia()*/)\n : m_PersistMedia(persistMedia),\n m_LogFile(logfile),\n m_Qid(qid),\n m_ResetOnRead(false),\n m_Pos(0),\n m_StIno(0),\n m_StSize(0)\n {\n SCXUser user;\n m_IdString = L\"LogFileProvider_\" + user.GetName() + logfile.Get() + qid;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get the log file associated with this record.\n \\returns File path to log file.\n */\n const SCXFilePath& LogFileReader::LogFilePositionRecord::GetLogFile() const\n {\n return m_LogFile;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get current \"ResetOnRead\" flag for the logfile and qid.\n \\returns Current reset-on-read flag.\n */\n bool LogFileReader::LogFilePositionRecord::GetResetOnRead() const\n {\n return m_ResetOnRead;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set current \"ResetOnRead\" flag for the logfile and qid.\n \\param[in] fSet New reset-on-read flag.\n */\n void LogFileReader::LogFilePositionRecord::SetResetOnRead(bool fSet)\n {\n m_ResetOnRead = fSet;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get current file position for the logfile and qid.\n \\returns Current file position.\n */\n std::streamoff LogFileReader::LogFilePositionRecord::GetPos() const\n {\n return m_Pos;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set current file position for the logfile and qid.\n \\param[in] pos Current file position.\n */\n void LogFileReader::LogFilePositionRecord::SetPos(std::streamoff pos)\n {\n m_Pos = pos;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get the st_ino filed of a stat struct for this file.\n \\returns st_ino field of a stat structure.\n */\n scxulong LogFileReader::LogFilePositionRecord::GetStatStIno() const\n {\n return m_StIno;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set the st_ino filed of a stat struct for this file.\n \\param[in] st_ino st_ino field of a stat structure.\n */\n void LogFileReader::LogFilePositionRecord::SetStatStIno(scxulong st_ino)\n {\n m_StIno = st_ino;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get the st_size filed of a stat struct for this file.\n \\returns st_size field of a stat structure.\n */\n scxulong LogFileReader::LogFilePositionRecord::GetStatStSize() const\n {\n return m_StSize;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set the st_size filed of a stat struct for this file.\n \\param[in] st_size st_size field of a stat structure.\n */\n void LogFileReader::LogFilePositionRecord::SetStatStSize(scxulong st_size)\n {\n m_StSize = st_size;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Persist data\n */\n void LogFileReader::LogFilePositionRecord::Persist()\n {\n if (static_cast<scxulong>(m_Pos) > m_StSize)\n {\n m_StSize = static_cast<scxulong>(m_Pos);\n }\n SCXHandle<SCXPersistDataWriter> pwriter = m_PersistMedia->CreateWriter(m_IdString, 1);\n pwriter->WriteValue(L\"Filename\", SCXCoreLib::StrFrom(m_LogFile.Get()));\n pwriter->WriteValue(L\"QID\", SCXCoreLib::StrFrom(m_Qid));\n pwriter->WriteValue(L\"Reset\", SCXCoreLib::StrFrom(m_ResetOnRead));\n pwriter->WriteValue(L\"Pos\", SCXCoreLib::StrFrom(m_Pos));\n pwriter->WriteStartGroup(L\"Stat\");\n pwriter->WriteValue(L\"StIno\", SCXCoreLib::StrFrom(m_StIno));\n pwriter->WriteValue(L\"StSize\", SCXCoreLib::StrFrom(m_StSize));\n pwriter->WriteEndGroup();\n pwriter->DoneWriting();\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Recover persisted data\n \\returns false if no data had previously been persisted.\n */\n bool LogFileReader::LogFilePositionRecord::Recover()\n {\n try\n {\n SCXHandle<SCXPersistDataReader> preader = m_PersistMedia->CreateReader(m_IdString);\n int version = preader->GetVersion();\n if (0 != version && 1 != version)\n {\n // Wrong version. Just ignore. It will be re-persisted later.\n return false;\n }\n\n // Version 0 does not include Filename, QID, or Reset; Version 1 does\n // By being version-aware, we always recover properly\n\n if (version >= 1)\n {\n // We already have filename, but consume to avoid errors\n preader->ConsumeValue(L\"Filename\");\n m_Qid = preader->ConsumeValue(L\"QID\");\n m_ResetOnRead = SCXCoreLib::StrToLong(preader->ConsumeValue(L\"Reset\"));\n }\n\n m_Pos = SCXCoreLib::StrToULong(preader->ConsumeValue(L\"Pos\"));\n preader->ConsumeStartGroup(L\"Stat\");\n m_StIno = SCXCoreLib::StrToULong(preader->ConsumeValue(L\"StIno\"));\n m_StSize = SCXCoreLib::StrToULong(preader->ConsumeValue(L\"StSize\"));\n preader->ConsumeEndGroup();\n return true;\n }\n catch (SCXNotSupportedException&)\n {\n // Data is corrupt (a value could not be parsed). Just ignore. It will be re-persisted later.\n return false;\n }\n catch (PersistUnexpectedDataException&)\n {\n // Data is corrupt. Just ignore. It will be re-persisted later.\n return false;\n }\n catch (PersistDataNotFoundException&)\n {\n // No persisted data found.\n return false;\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Remove persisted data\n \\returns false if no data had previously been persisted.\n */\n bool LogFileReader::LogFilePositionRecord::UnPersist()\n {\n try\n {\n m_PersistMedia->UnPersist(m_IdString);\n }\n catch (PersistDataNotFoundException&)\n {\n // No persisted data found.\n return false;\n }\n return true;\n }\n\n /*----------------------------------------------------------------------------*/\n /* LogFileReader::LogFileStreamPositioner */\n /*----------------------------------------------------------------------------*/\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor\n\n \\param[in] logfile Log file for this record.\n \\param[in] qid Q ID of this record.\n \\param[in] persistMedia Used to inject persistence media to use for persisting this record. \n \\throws SCXFilePathNotFoundException if log file does not exist.\n */\n LogFileReader::LogFileStreamPositioner::LogFileStreamPositioner(\n const SCXCoreLib::SCXFilePath& logfile,\n const std::wstring& qid,\n SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> persistMedia /* = SCXCoreLib::GetPersistMedia()*/)\n : m_Record(0),\n m_Stream(0),\n m_log(SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.logfileprovider.logfilestreampositioner\"))\n {\n m_Record = new LogFilePositionRecord(logfile, qid, persistMedia);\n m_Stream = SCXFile::OpenWFstream(logfile, std::ios_base::in);\n\n // Set the locale on the stream to the system locale (based on environment variables)\n // Note: This overrides SCXLocale settings (which is used for everything else)\n //\n // If we get an exception, just let it fly (hopefully things will still work okay)\n // This is better than dying because some bizarre locale is set\n\n try {\n std::locale newLocale(\"\");\n m_Stream->imbue(newLocale);\n }\n catch (...)\n {\n }\n\n // On all platforms (even Linux), tellg() can return -1 (see test case testTellgBehavior() in unit test).\n // To try and protect against that, we position to EOF and save the position, and we'll use that position\n // if tellg() returns -1.\n //\n // There's a race condition here were we can return the same lines multiple times depending on concurrency\n // issues. And there's a WI for that, wi 16772.\n\n m_Stream->seekg(0, std::ios_base::end);\n std::streamoff pos = m_Stream->tellg();\n\n if ( ! m_Record->Recover() )\n {\n // First time (i.e when no persisted data exists) we just go to end of file.\n SCX_LOGTRACE(m_log, L\"OpenStream \" + m_Record->GetLogFile().Get() + L\" - First time - Seek to end\");\n SCX_LOGTRACE(m_log, StrAppend(L\"LogFileProvider OpenStream last pos = \", pos));\n }\n else\n {\n if ( m_Record->GetResetOnRead() )\n {\n // We were requested to reset on the next read; now's the time\n SCX_LOGTRACE(m_log, L\"OpenStream \" + m_Record->GetLogFile().Get() + L\" - ResetOnRead - Seek to end\");\n SCX_LOGTRACE(m_log, StrAppend(L\"LogFileProvider OpenStream last pos = \", pos));\n m_Record->SetResetOnRead(false);\n }\n else if ( ! IsFileNew() )\n {\n // File has not wrapped so we seek to last position.\n SCX_LOGTRACE(m_log, StrAppend(L\"LogFileProvider OpenLogFile \" + m_Record->GetLogFile().Get()\n + L\"- Seek to: \", m_Record->GetPos()));\n SCXFile::SeekG(*m_Stream, m_Record->GetPos());\n }\n else\n {\n // File has wrapped so we find new last position.\n SCX_LOGTRACE(m_log, L\"LogFileProvider OpenLogFile \" + m_Record->GetLogFile().Get() + L\" - File has wrapped\");\n SCXFile::SeekG(*m_Stream, 0);\n SCX_LOGTRACE(m_log, StrAppend(L\"LogFileProvider OpenStream save last pos = \", pos));\n }\n }\n\n m_Record->SetPos(pos);\n UpdateStatData();\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Return a stream pointing at the correct reading position.\n\n \\returns Handle to stream opened at the correct position.\n */\n SCXHandle<std::wfstream> LogFileReader::LogFileStreamPositioner::GetStream()\n {\n return m_Stream;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Save the state of a logfile.\n */\n void LogFileReader::LogFileStreamPositioner::PersistState()\n {\n std::streamoff pos = m_Stream->tellg();\n SCX_LOGTRACE(m_log, StrAppend(L\"LogFileProvider PersistState() - pos = \", pos));\n\n // Never persist -1, happens on some platforms (AIX) when reading past end of file. It can\n // even happen on Linux platforms in certain cases (see unit test testTellgBehavior()).\n //\n // Real end of file position has been saved when opening the file. If we can't get the true\n // current location, we fall back to the size of the file at open() time.\n //\n // Note: We could use the size from SCXFileSystem::Stat(), but this is non-atomic. Safer to\n // use the actual file size from the file at the time that we've opened it.\n\n if (pos > 0)\n {\n m_Record->SetPos(pos);\n }\n m_Record->Persist();\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Check if the log file is actually a new file with the same name.\n This will happen if the file has wrapped since last update for example.\n\n \\returns true if the file is actually a new file.\n \\throws SCXFilePathNotFoundException if log file does not exist.\n */\n bool LogFileReader::LogFileStreamPositioner::IsFileNew() const\n {\n SCXFileSystem::SCXStatStruct statstruct;\n SCXFileSystem::Stat(m_Record->GetLogFile(), &statstruct);\n \n // If inode has changed it is a new file\n if (statstruct.st_ino != m_Record->GetStatStIno())\n {\n SCX_LOGTRACE(m_log, L\"IsNewFile - inode changed - new file\");\n return true;\n }\n\n // If the new size is smaller it is a new file\n if ((scxulong) statstruct.st_size < m_Record->GetStatStSize())\n {\n SCX_LOGTRACE(m_log, L\"IsNewFile - size smaller - new file\");\n return true;\n }\n\n SCX_LOGTRACE(m_log, L\"IsNewFile - not new file\");\n\n return false;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Update stat fields in record with values read from disk.\n \\throws SCXFilePathNotFoundException if log file does not exist.\n */\n void LogFileReader::LogFileStreamPositioner::UpdateStatData()\n {\n SCXFileSystem::SCXStatStruct statstruct;\n SCXFileSystem::Stat(m_Record->GetLogFile(), &statstruct);\n \n m_Record->SetStatStIno(statstruct.st_ino);\n m_Record->SetStatStSize(statstruct.st_size);\n }\n\n /*----------------------------------------------------------------------------*/\n /* LogFileReader::LogFileReader */\n /*----------------------------------------------------------------------------*/\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor\n Creates a new LogFileReader class\n */\n LogFileReader::LogFileReader()\n : m_log(SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.logfileprovider\"))\n {\n m_persistMedia = GetPersistMedia();\n m_cqlPatterns.RegisterPattern(s_patternID, s_pattern);\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get filename from query\n\n \\param[in] query The CQL/WQL query to parse\n\n \\returns Log file name\n\n \\throws SCXNotSupportedException If query not on recognized format\n \\throws SCXInternalErrorException If an unexpected pattern was matched.\n\n */\n std::wstring LogFileReader::GetFileName(const std::wstring& query)\n {\n SCXCoreLib::SCXPatternFinder::SCXPatternCookie id = 0;\n SCXCoreLib::SCXPatternFinder::SCXPatternMatch param;\n if ( ! m_cqlPatterns.Match(query, id, param))\n {\n throw SCXNotSupportedException(L\"LogFileProvider Query not on format: \" + s_pattern, SCXSRCLOCATION);\n }\n if (id != s_patternID || param.end() == param.find(s_patternParameter))\n {\n throw SCXInternalErrorException(L\"Wrong pattern matched!\", SCXSRCLOCATION);\n }\n SCX_LOGTRACE(m_log, L\"LogFileProvider GetFileName: \" + param.find(s_patternParameter)->second);\n\n return param.find(s_patternParameter)->second;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get SCXLogFile class for a given log file name\n\n \\param[in] filename Name of log file\n\n \\returns Pointer to corresponding SCXLogFile class or NULL if none found\n\n */\n LogFileReader::SCXLogFile* LogFileReader::GetLogFile(const std::wstring& filename)\n {\n for(size_t i=0; i<m_files.size(); i++)\n {\n if (m_files[i].name == filename)\n {\n SCX_LOGTRACE(m_log, StrAppend(L\"LogFileProvider GetLogFile found filename - \", filename));\n return &m_files[i];\n }\n }\n\n SCX_LOGTRACE(m_log, StrAppend(L\"LogFileProvider GetLogFile did NOT find filename - \", filename));\n return NULL;\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Check if the log file has wrapped and we need to start reading from line 1 again\n\n \\param[in] oldstatinfo Old saved stat info\n \\param[in] newstatinfo New stat info\n\n \\returns true if file has wrapped, otherwise false\n\n */\n bool LogFileReader::CheckFileWrap(const struct stat64& oldstatinfo, const struct stat64& newstatinfo)\n {\n // If inode has changed it is a new file\n if (oldstatinfo.st_ino != newstatinfo.st_ino)\n {\n SCX_LOGTRACE(m_log, L\"LogFileProvider CheckFileWrap - inode changed - new file\");\n return true;\n }\n \n // If the new size is smaller it is a new file\n if (oldstatinfo.st_size > newstatinfo.st_size)\n {\n SCX_LOGTRACE(m_log, L\"LogFileProvider CheckFileWrap - size smaller - new file\");\n return true;\n }\n\n SCX_LOGTRACE(m_log, L\"LogFileProvider CheckFileWrap - inode not changed and size not smaller - not new file\");\n return false;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Set persist media to use.\n Only used for tests\n\n \\param[in] persistMedia persistance media to use\n */\n void LogFileReader::SetPersistMedia(SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> persistMedia) \n { \n m_persistMedia = persistMedia; \n }\n\n bool LogFileReader::ReadLogFile(\n const std::wstring& filename,\n const std::wstring& qid,\n const std::vector<SCXRegexWithIndex>& regexps,\n std::vector<std::wstring>& matchedLines)\n {\n LogFileStreamPositioner positioner(filename, qid, m_persistMedia);\n SCXHandle<std::wfstream> logfile = positioner.GetStream();\n\n bool partialRead = false;\n\n unsigned int rows = 0;\n unsigned int matched_rows = 0;\n size_t total_bytes = 0;\n\n // Read rows from log file\n while ((matched_rows < cMaxMatchedRows && total_bytes < cMaxTotalBytes)\n && SCXStream::IsGood(*logfile))\n {\n wstring line;\n SCXStream::NLF nlf;\n\n rows++;\n\n SCX_LOGHYSTERICAL(m_log, StrAppend(L\"LogFileProvider DoInvokeMethod - Reading row: \", rows));\n\n SCXStream::ReadLine(*logfile, line, nlf);\n\n // Check line against regular expressions and add to result if any matches\n std::wstring res(L\"\");\n int matches = 0;\n\n for (size_t j=0; j<regexps.size(); j++)\n {\n if (regexps[j].regex->IsMatch(line))\n {\n SCX_LOGHYSTERICAL(m_log, StrAppend(StrAppend(StrAppend(L\"LogFileProvider DoInvokeMethod - row: \", rows), \n L\" Matched regexp: \"), regexps[j].index));\n matches++;\n res = StrAppend(StrAppend(res, res.length()>0?L\" \":L\"\"), regexps[j].index);\n }\n }\n\n if (matches > 0)\n {\n wstring retEntry = StrAppend(StrAppend(res, L\";\"), line);\n matchedLines.push_back(retEntry);\n matched_rows++;\n total_bytes += retEntry.size();\n }\n }\n\n // Check if we read all rows, if not add special row to beginning of result\n if ((matched_rows >= cMaxMatchedRows || total_bytes >= cMaxTotalBytes)\n && SCXStream::IsGood(*logfile))\n {\n//TODO: logging policy not set so by default may write into stdout and therefore interfere with the normal operation.\n// SCX_LOGINFO(m_log, StrAppend(L\"LogFileProvider DoInvokeMethod - Breaking after matching max number of rows : \", cMaxMatchedRows));\n\n partialRead = true;\n }\n\n positioner.PersistState();\n return partialRead;\n }\n\n int LogFileReader::ResetLogFileState(\n const std::wstring& filename,\n const std::wstring& qid,\n bool resetOnRead)\n {\n wstringstream ss;\n ss << L\"LogFileProvider ResetLogFileState: \"\n << L\"Filename: \" << filename\n << L\", qid: \" << qid\n << L\", resetOnRead: \" << resetOnRead;\n SCX_LOGTRACE(m_log, ss.str())\n\n LogFileStreamPositioner positioner(filename, qid, m_persistMedia);\n SCXHandle<std::wfstream> logfile = positioner.GetStream();\n\n if (false == resetOnRead)\n {\n logfile->seekg(0, std::ios_base::end);\n }\n\n positioner.SetResetOnRead(resetOnRead);\n positioner.PersistState();\n return 0;\n }\n\n int LogFileReader::ResetAllLogFileStates(const std::wstring& path, bool resetOnRead)\n {\n int exitStatus = 0;\n\n SCX_LOGTRACE(m_log, L\"LogFileProvider ResetAllLogFileStates - entry\");\n\n // Determine the directory where the state files live\n SCXFilePath basePath(path);\n SCXUser user;\n\n if (!user.IsRoot())\n {\n basePath.AppendDirectory(user.GetName());\n }\n\n // Enumerate the state files\n // If exception occurs, items vector will be empty, so just fall through\n vector<SCXFilePath> items;\n try {\n items = SCXDirectory::GetFiles(basePath);\n }\n catch (SCXFilePathNotFoundException& e)\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"LogFileProvider ResetAllLogFileStates - Base path not found: \", basePath.Get()).append(L\", exception: \").append(e.What()));\n\n // Return a special exit code so we know that the log file wasn't found\n exitStatus = ENOENT;\n }\n catch (SCXException &e)\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"LogFileProvider ResetAllLogFileStates - Unexpected exception: \", e.What()));\n\n // Return a special exit code so we know that an exception occurred\n exitStatus = EINTR;\n }\n\n for (vector<SCXFilePath>::iterator i(items.begin()); i != items.end(); ++i)\n {\n const std::wstring stateFilename = i->GetFilename();\n SCX_LOGHYSTERICAL(m_log, StrAppend(L\"LogFileProvider ResetAllLogFileStates - Considering file: \", stateFilename));\n\n // If this isn't a state file, ignore it ...\n if (! StrIsPrefix(stateFilename, L\"LogFileProvider_\", true))\n {\n continue;\n }\n\n SCX_LOGTRACE(m_log, StrAppend(L\"LogFileProvider ResetAllLogFileStates - Found file: \", stateFilename));\n\n SCXStream::NLFs nlfs;\n vector<wstring> lines;\n SCXFile::ReadAllLinesAsUTF8(*i, lines, nlfs);\n wstring filename, qid;\n\n SCX_LOGHYSTERICAL(m_log, L\"LogFileProvider ResetAllLogFileStates - State file contents start\");\n for (vector<wstring>::iterator l(lines.begin()); l != lines.end(); ++l)\n {\n SCX_LOGHYSTERICAL(m_log, StrAppend(L\"LogFileProvider ResetAllLogFileStates - Line: \", *l));\n\n SCXRegex re(L\"Value Name=\\\"(.*)\\\" Value=\\\"(.*)\\\"\");\n vector<wstring> matches;\n\n if (re.ReturnMatch(*l, matches, 0))\n {\n if ( L\"Filename\" == matches[1] )\n {\n filename = matches[2];\n }\n else if ( L\"QID\" == matches[1] )\n {\n qid = matches[2];\n }\n }\n }\n SCX_LOGHYSTERICAL(m_log, L\"LogFileProvider ResetAllLogFileStates - State file contents completed\");\n\n // If we found the data that we needed, then reset the log file\n if (filename.length() && qid.length())\n {\n SCX_LOGTRACE(m_log, StrAppend(StrAppend(L\"LogFileProvider ResetAllLogFileStates - Filename: \", filename).append(L\", QID: \"), qid));\n\n try\n {\n int localStatus = ResetLogFileState(filename, qid, resetOnRead);\n\n if (localStatus != 0)\n {\n exitStatus = localStatus;\n }\n }\n catch (SCXFilePathNotFoundException& e)\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"LogFileProvider ResetAllLogFileStates - File not found: \", filename).append(L\", exception: \").append(e.What()));\n\n // Return a special exit code so we know that the log file wasn't found\n exitStatus = ENOENT;\n }\n catch (SCXException &e)\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"LogFileProvider ResetAllLogFileStates - Unexpected exception: \", e.What()));\n\n // Return a special exit code so we know that an exception occurred\n exitStatus = EINTR;\n }\n }\n }\n\n SCX_LOGTRACE(m_log, L\"LogFileProvider ResetAllLogFileStates - exit\");\n return exitStatus;\n }\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5768892765045166, "alphanum_fraction": 0.5821616649627686, "avg_line_length": 31.514286041259766, "blob_id": "a7d25518cd5658e809645e37a0c3a01db1f9bc94", "content_id": "6df79f592ca14ffc68fff2cda2a200e713b7d9f1", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2276, "license_type": "permissive", "max_line_length": 190, "num_lines": 70, "path": "/source/code/providers/support/appserver/tomcatappserverinstance.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file tomcatappserverinstance.h\n\n \\brief PAL representation of a Tomcat Application Server\n\n \\date 11-05-18 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef TOMCATAPPSERVERINSTANCE_H\n#define TOMCATAPPSERVERINSTANCE_H\n\n#include <string>\n\n#include \"appserverinstance.h\"\n\nnamespace SCXSystemLib\n{\n /*----------------------------------------------------------------------------*/\n /**\n Class representing all external dependencies from the AppServer PAL.\n\n */\n class TomcatAppServerInstancePALDependencies\n {\n public:\n virtual SCXCoreLib::SCXHandle<std::istream> OpenVersionFile(std::wstring filename);\n virtual SCXCoreLib::SCXHandle<std::istream> OpenXmlServerFile(std::wstring filename);\n\t\tvirtual std::wstring GetVersionScriptCommand(SCXCoreLib::SCXFilePath filepath);\n virtual ~TomcatAppServerInstancePALDependencies() {};\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Class that represents an instances.\n\n Concrete implementation of an instance of a Tomcat Application Server\n\n */\n class TomcatAppServerInstance : public AppServerInstance\n {\n friend class AppServerEnumeration;\n\n public:\n\n TomcatAppServerInstance(\n std::wstring id, \n std::wstring homePath,\n SCXCoreLib::SCXHandle<TomcatAppServerInstancePALDependencies> deps = SCXCoreLib::SCXHandle<TomcatAppServerInstancePALDependencies>(new TomcatAppServerInstancePALDependencies()));\n virtual ~TomcatAppServerInstance();\n\n virtual void Update();\n\n private:\n\n void UpdateVersion();\n void UpdatePorts();\n void GetStringFromStream(SCXCoreLib::SCXHandle<std::istream> mystream, std::string& content);\n\n std::wstring m_homePath;\n\n SCXCoreLib::SCXHandle<TomcatAppServerInstancePALDependencies> m_deps;\n };\n\n}\n\n#endif /* TOMCATAPPSERVERINSTANCE_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5035016536712646, "alphanum_fraction": 0.5079247951507568, "avg_line_length": 37.75714111328125, "blob_id": "8ef1dacbdb926e47d4508f29726839270b5997c9", "content_id": "314fdffbe11797d831dc97171f0cc921578bc432", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2713, "license_type": "permissive", "max_line_length": 109, "num_lines": 70, "path": "/build/Makefile.rules", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#--------------------------------------------------------------------------------\n\n# No default rules, please\n.SUFFIX: \n\n# Rule for compiling cpp files in source tree, ouptut in mirrored intermediate dir\n$(INTERMEDIATE_DIR)/%.$(PF_OBJ_FILE_SUFFIX) : $(SCX_BRD)/%.cpp\n\t$(MKPATH) $(@D)\n\t$(PROFILING) $(CXX) -c $(CXXFLAGS) $(INCLUDES) -I$(<D) -o $@ $<\n\n$(INTERMEDIATE_DIR)/%.$(PF_OBJ_FILE_SUFFIX) : $(SCX_BRD)/%.c\n\t$(MKPATH) $(@D)\n\t$(PROFILING) $(CXX) -c $(CFLAGS) $(INCLUDES) -I$(<D) -o $@ $<\n\n$(INTERMEDIATE_DIR)/%.$(PF_OBJ_FILE_SUFFIX) : $(SCX_BRD)/%.s\n\t$(MKPATH) $(@D)\n\t$(PROFILING) $(CXX) -c $(CXXFLAGS) $(INCLUDES) -I$(<D) -o $@ $<\n\n# buildversion.h is a generated file so we need to have explicit dependencies on it for all files that use it\n# to make sure it exists before the .d files are generated\n$(SCX_SRC_ROOT)/providers/SCX_Agent_Class_Provider.cpp: $(INT_INCLUDE_DIR)/buildversion.h \n$(SCX_SRC_ROOT)/providers/support/productdependencies.cpp: $(INT_INCLUDE_DIR)/buildversion.h \n$(SCX_SRC_ROOT)/providers/support/scx_admin.cpp: $(INT_INCLUDE_DIR)/buildversion.h \n\n# TODO: Need to modify this slightly once appserver is ported for OMI\n$(SCX_SRC_ROOT)/providers/appserver_provider/appserverprovider.cpp: $(INT_INCLUDE_DIR)/buildversion.h \n\n# Rule for creating dependency files in intermediate dir\n# See info make Automatic Prerequisites\n# The XLC++ dependency generator can't produce output to stdout\nifeq ($(PF),AIX)\n\n$(INTERMEDIATE_DIR)/%.d: $(SCX_BRD)/%.cpp\n\t$(MKPATH) $(INT_INCLUDE_DIR)\n\t$(MKPATH) $(@D)\n\t$(MKDEP) $(CXXFLAGS) $(INCLUDES) -I$(<D) $< -MF $@.$$$$ >/dev/null; \\\n\tsed 's,\\($(*F)\\)\\.o[ :]*,$(@D)/\\1.o $@ : ,g' < $@.$$$$ > $@; \\\n\trm -f $@.$$$$\n\n$(INTERMEDIATE_DIR)/%.d: $(SCX_BRD)/%.c\n\t$(MKPATH) $(INT_INCLUDE_DIR)\n\t$(MKPATH) $(@D)\n\t$(MKDEP) $(CFLAGS) $(INCLUDES) -I$(<D) $< -MF $@.$$$$ >/dev/null; \\\n\tsed 's,\\($(*F)\\)\\.o[ :]*,$(@D)/\\1.o $@ : ,g' < $@.$$$$ > $@; \\\n\trm -f $@.$$$$\n\nelse\n\n$(INTERMEDIATE_DIR)/%.d: $(SCX_BRD)/%.cpp\n\t$(MKPATH) $(INT_INCLUDE_DIR)\n\t$(MKPATH) $(@D)\n\t$(MKDEP) $(CXXFLAGS) $(INCLUDES) -I$(<D) $< > $@.$$$$; \\\n\tsed 's,\\($(*F)\\)\\.o[ :]*,$(@D)/\\1.o $@ : ,g' < $@.$$$$ > $@; \\\n\trm -f $@.$$$$\n\n$(INTERMEDIATE_DIR)/%.d: $(SCX_BRD)/%.c\n\t$(MKPATH) $(INT_INCLUDE_DIR)\n\t$(MKPATH) $(@D)\n\t$(MKDEP) $(CFLAGS) $(INCLUDES) -I$(<D) $< > $@.$$$$; \\\n\tsed 's,\\($(*F)\\)\\.o[ :]*,$(@D)/\\1.o $@ : ,g' < $@.$$$$ > $@; \\\n\trm -f $@.$$$$\n\nendif\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.6406471729278564, "alphanum_fraction": 0.6446210741996765, "avg_line_length": 31.620370864868164, "blob_id": "0a22914313594a68462ba9c7f8c5bd2494f4d073", "content_id": "bda026eadb6e5e45a1d441754a311612f4b6d80c", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 3523, "license_type": "permissive", "max_line_length": 81, "num_lines": 108, "path": "/build/Makefile", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# Bootstrap Makefile for: Operations Manager UNIX/Linux agent\n# 2007-08-23\n#--------------------------------------------------------------------------------\n\n# Set up architecture and Build Root Directory\n# PF (i.e. PlatForm) is either linux, solaris\nSHELL=/bin/bash\nPWD:=$(shell pwd)\nSCX_BRD=$(shell dirname $(PWD))\nPF_POSIX=true\n\n# Get the root of the SCXPAL directory (and other easy locations)\nSCXPAL_DIR := $(shell cd ../../pal; pwd)\nSCXOMI_DIR := $(shell cd ../../omi/Unix; pwd -P)\nOMIKITS_DIR := $(shell cd ../../omi-kits/release; pwd)\n\ninclude $(SCXPAL_DIR)/build/config.mak\ninclude $(SCX_BRD)/build/config.mak\n\nifndef OMI_CONFIGURE_QUALS\n$(error \"OMI_CONFIGURE_QUALS is not set. Please re-run configure\")\nendif\n\n# Include the real stuff\ninclude $(SCX_BRD)/build/Makefile.version\n\nifndef SCX_BUILDVERSION_STATUS\n$(error \"Is Makefile.version missing? Please re-run configure\")\nendif\n\nifeq ($(COMBINED_PACKAGES),1)\nSCXOMI_DEV_ROOT := $(SCXOMI_DIR)/output_openssl_1.0.0\nelse\nSCXOMI_DEV_ROOT := $(SCXOMI_DIR)/output\nendif\n\nSCXOMI_INCLUDE := $(SCXOMI_DEV_ROOT)/include\nSCXOMI_LIBS := $(SCXOMI_DEV_ROOT)/lib\n\n# Figure out if we're doing a production build or a developer build\n\nifeq ($(SCX_BUILDVERSION_STATUS),Release_Build)\n\tBUILD_PRODUCTION=1\nelse\nifeq ($(SCX_BUILDVERSION_STATUS),Developer_Build)\n\tBUILD_PRODUCTION=0\nelse\n$(error Unrecognized build type: $(SCX_BUILDVERSION_STATUS))\nendif # Developer Build\nendif # Release Build\n\nall : ccenable pal_all omi_all installerPackage devel-deps ccdisable\ninstallerPackage: pal_all omi_all\n\npal_all :\n\t$(MAKE) -C $(SCXPAL_DIR)/build all\n\nclean: clean-status doxygen_clean\n\t-$(RMDIR) $(INTERMEDIATE_DIR)/include\n\t-$(RMDIR) $(INTERMEDIATE_DIR)/source\n\t-$(RMDIR) $(INTERMEDIATE_DIR)/test\n\t-$(RMDIR) $(SCX_BRD)/installer/intermediate\n\t-$(RMDIR) $(INTERMEDIATE_DIR)/lib*.a\n\t-$(RMDIR) $(INTERMEDIATE_DIR)/*.exp\n\t-$(RMDIR) $(INTERMEDIATE_DIR)/*.map\n\t-$(RMDIR) $(INTERMEDIATE_DIR)/*.cov\n\t-$(RMDIR) $(TARGET_DIR)\n\t-$(RM) $(SCX_BRD)/source/code/shared/tools/omi_preexec/strerror.cpp\n\t-$(RM) $(SCX_UNITTEST_ROOT)/providers/providertestutils.cpp\n\t-find $(SCX_BRD) -name \\*~ -exec rm {} \\;\n\n# Clean the PAL as well as OM with distclean target\ndistclean: clean\n\t-$(MAKE) -C $(SCXPAL_DIR)/build clean\n\t-$(MAKE) -C $(SCXOMI_DIR) distclean\n\t-$(RMDIR) $(SCXOMI_DIR)/output*\n\t-$(RM) $(SCX_BRD)/build/config.mak\n\t-$(RM) $(SCXPAL_DIR)/build/config.mak\n\t-$(RM) $(SCXPAL_DIR)/build/Makefile.config_cache\n\t-$(RM) $(SCX_BRD)/build/Makefile.config_cache\n\t-$(RM) $(SCX_BRD)/build/Makefile.version\n\t-$(RM) -rf $(SCX_BRD)/intermediate $(SCX_BRD)/target\n\t-$(RM) -rf $(SCXPAL_DIR)/intermediate $(SCXPAL_DIR)/target\n\nclean-status:\n\t$(ECHO) \"========================= Performing make clean\"\n\n# Include the rest of the stuff we need\n\ninclude $(SCX_BRD)/build/Makefile.pal\ninclude $(SCX_BRD)/build/Makefile.macros\ninclude $(SCX_BRD)/build/Makefile.pf.$(PF)\ninclude $(SCX_BRD)/build/Makefile.rules\ninclude $(SCX_BRD)/build/Makefile.components\ninclude $(SCX_BRD)/build/Makefile.kits\ninclude $(SCX_BRD)/build/Makefile.tests\ninclude $(SCX_BRD)/build/Makefile.stub\n\nifeq (,$(findstring clean,$(MAKECMDGOALS)))\nifeq (,$(findstring cache,$(MAKECMDGOALS)))\n-include $(DEPFILES) $(DEPFILES_TEST)\nendif\nendif\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.6359781622886658, "alphanum_fraction": 0.6473538279533386, "avg_line_length": 44.16758728027344, "blob_id": "b36c6cc4a5030de3be68fe2d5362d95228719676", "content_id": "cdf6ef4568ae361bb9e28747fe45c9f3a929a9e6", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 24535, "license_type": "permissive", "max_line_length": 178, "num_lines": 543, "path": "/test/code/shared/tools/scx_ssl_config/scxsslcert_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the ssl cert generation\n\n \\date 2009-12-14 12:00\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <source/code/shared/tools/scx_ssl_config/scxsslcert.h> \n#include <testutils/scxunit.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxstream.h>\n#include <scxcorelib/scxprocess.h>\n#include <testutils/scxtestutils.h>\n#include <scxcorelib/scxnameresolver.h>\n\n#include <iostream>\n#include <string>\n\n#if defined(linux)\n static const bool s_fIsLinux = true;\n#else\n static const bool s_fIsLinux = false;\n#endif\n\n\nusing std::cout;\nusing std::wcout;\nusing std::endl;\n\nclass ScxSSLCertTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( ScxSSLCertTest );\n CPPUNIT_TEST( testLoadRndNumberWithGoodRandomFromAllFiles );\n CPPUNIT_TEST( testLoadRndNumberWithGoodRandomFromOnlyUserFile );\n CPPUNIT_TEST( testLoadRndNumberWithGoodRandomFromOnlyDevRandom );\n CPPUNIT_TEST( testLoadRndNumberWithGoodRandomFromUserFileAndDevRandom );\n CPPUNIT_TEST( testLoadRndNumberWithNotEnoughGoodRandom );\n CPPUNIT_TEST( testLoadRndNumberWithRandomFromOnlyDevURandom );\n CPPUNIT_TEST( testLoadRndNumberWithNoRandomAtAll );\n CPPUNIT_TEST( testCertGeneration7Bit );\n CPPUNIT_TEST( testCertGeneration8Bit );\n CPPUNIT_TEST( test7BitCertGenerationAndCheckFiles );\n CPPUNIT_TEST( test8BitCertGenerationAndCheckFiles );\n CPPUNIT_TEST( testClientCertGeneration );\n CPPUNIT_TEST( testNonRFCcompliantDomainFailure );\n CPPUNIT_TEST( testNonRFCcompliantHostnameFailure );\n CPPUNIT_TEST( testNonRFCcompliantDomainFallback );\n CPPUNIT_TEST( testNonRFCcompliantDomainNoRecovery );\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n class SCXSSLCertificateTest : public SCXSSLCertificate\n {\n public:\n SCXSSLCertificateTest(size_t userrandom, size_t devrandom, size_t udevrandom) : \n SCXSSLCertificate(L\".\", L\".\", 0, 0, L\"hostname\", L\"domainname\", 512), \n m_userrandom(userrandom), m_devrandom(devrandom), m_udevrandom(udevrandom), m_warningdisplayed(false),\n m_readuserfile(false), m_readdevrandom(false), m_readdevurandom(false)\n {}\n size_t m_userrandom;\n size_t m_devrandom;\n size_t m_udevrandom;\n bool m_warningdisplayed;\n bool m_readuserfile;\n bool m_readdevrandom;\n bool m_readdevurandom;\n\n private:\n virtual size_t LoadRandomFromDevRandom(size_t /*randomNeeded*/)\n {\n m_readdevrandom = true;\n return m_devrandom;\n }\n virtual size_t LoadRandomFromDevUrandom(size_t /*randomNeeded*/)\n {\n m_readdevurandom = true;\n return m_udevrandom;\n }\n virtual size_t LoadRandomFromUserFile()\n {\n m_readuserfile = true;\n return m_userrandom;\n }\n virtual void DisplaySeedWarning(size_t /*goodRandomNeeded*/)\n {\n m_warningdisplayed = true;\n }\n };\n\n static const size_t m_randomneeded = 256;\n\npublic:\n\n void testLoadRndNumberWithGoodRandomFromAllFiles(void)\n {\n SCXSSLCertificateTest* cert = new SCXSSLCertificateTest(m_randomneeded, m_randomneeded, m_randomneeded);\n CPPUNIT_ASSERT_NO_THROW(cert->LoadRndNumber());\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from user rnd file\", cert->m_readuserfile == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/random\", cert->m_readdevrandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did read data from dev/urandom when not neccesary\", cert->m_readdevurandom == false);\n CPPUNIT_ASSERT_MESSAGE(\"Warning message displayed when it should not be\", cert->m_warningdisplayed == false); \n delete cert;\n }\n\n void testLoadRndNumberWithGoodRandomFromOnlyUserFile(void)\n {\n SCXSSLCertificateTest* cert = new SCXSSLCertificateTest(m_randomneeded, 0, 0);\n CPPUNIT_ASSERT_NO_THROW(cert->LoadRndNumber());\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from user rnd file\", cert->m_readuserfile == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/random\", cert->m_readdevrandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did read data from dev/urandom when not neccesary\", cert->m_readdevurandom == false);\n CPPUNIT_ASSERT_MESSAGE(\"Warning message displayed when it should not be\", cert->m_warningdisplayed == false);\n delete cert;\n }\n \n void testLoadRndNumberWithGoodRandomFromOnlyDevRandom(void)\n {\n SCXSSLCertificateTest* cert = new SCXSSLCertificateTest(0, m_randomneeded, 0);\n CPPUNIT_ASSERT_NO_THROW(cert->LoadRndNumber());\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from user rnd file\", cert->m_readuserfile == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/random\", cert->m_readdevrandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did read data from dev/urandom when not neccesary\", cert->m_readdevurandom == false);\n CPPUNIT_ASSERT_MESSAGE(\"Warning message displayed when it should not be\", cert->m_warningdisplayed == false);\n delete cert;\n }\n\n void testLoadRndNumberWithGoodRandomFromUserFileAndDevRandom()\n {\n SCXSSLCertificateTest* cert = new SCXSSLCertificateTest(m_randomneeded-64, 64, 0);\n CPPUNIT_ASSERT_NO_THROW(cert->LoadRndNumber());\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from user rnd file\", cert->m_readuserfile == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/random\", cert->m_readdevrandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did read data from dev/urandom when not neccesary\", cert->m_readdevurandom == false);\n CPPUNIT_ASSERT_MESSAGE(\"Warning message displayed when it should not be\", cert->m_warningdisplayed == false);\n delete cert;\n }\n\n void testLoadRndNumberWithNotEnoughGoodRandom()\n {\n SCXSSLCertificateTest* cert = new SCXSSLCertificateTest(m_randomneeded-64, 32, m_randomneeded);\n CPPUNIT_ASSERT_NO_THROW(cert->LoadRndNumber());\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from user rnd file\", cert->m_readuserfile == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/random\", cert->m_readdevrandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/urandom\", cert->m_readdevurandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Warning message not displayed when it should be\", cert->m_warningdisplayed == true);\n delete cert;\n }\n\n void testLoadRndNumberWithRandomFromOnlyDevURandom(void)\n {\n SCXSSLCertificateTest* cert = new SCXSSLCertificateTest(0, 0, m_randomneeded);\n CPPUNIT_ASSERT_NO_THROW(cert->LoadRndNumber());\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from user rnd file\", cert->m_readuserfile == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/random\", cert->m_readdevrandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/urandom\", cert->m_readdevurandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Warning message not displayed when it should be\", cert->m_warningdisplayed == true);\n delete cert;\n }\n\n void testLoadRndNumberWithNoRandomAtAll(void)\n {\n SCXSSLCertificateTest* cert = new SCXSSLCertificateTest(0, 0, 0);\n CPPUNIT_ASSERT_THROW_MESSAGE(\"\", cert->LoadRndNumber(), SCXCoreLib::SCXResourceExhaustedException);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from user rnd file\", cert->m_readuserfile == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/random\", cert->m_readdevrandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Did not read data from dev/urandom\", cert->m_readdevurandom == true);\n CPPUNIT_ASSERT_MESSAGE(\"Warning message not displayed when it should be\", cert->m_warningdisplayed == true);\n delete cert;\n }\n\npublic:\n void testCertGeneration7Bit(void)\n {\n // This should work on all platforms\n std::ostringstream debugChatter;\n \n // The class splices file names &c. so we will handle cleanup ourselves\n\n SCXCoreLib::SCXFilePath keyPath; \n keyPath.SetDirectory(L\"./testfiles\"); \n keyPath.SetFilename(L\"scx-test-key.pem\"); \n\n SCXCoreLib::SCXFilePath certPath; \n certPath.SetDirectory(L\"./testfiles\"); \n certPath.SetFilename(L\"scx-test-cert.pem\"); \n\n SCXSSLCertificateLocalizedDomain cert(keyPath, certPath, -365, 7300, L\"hostname\", L\"domainname.com\", 2048);\n\n std::wstring certKeyPath, certCertPath; \n try\n {\n cert.Generate(debugChatter);\n \n // Will self delete to clean up \n SCXCoreLib::SelfDeletingFilePath sdCertPath(cert.m_CertPath.Get());\n SCXCoreLib::SelfDeletingFilePath sdKeyPath(cert.m_KeyPath.Get());\n\n cout << debugChatter.str();\n\n CPPUNIT_ASSERT_MESSAGE(\"Output certificate file not found\", SCXCoreLib::SCXFile::Exists(cert.m_CertPath));\n CPPUNIT_ASSERT_MESSAGE(\"Output key file not found\", SCXCoreLib::SCXFile::Exists(cert.m_KeyPath));\n }\n catch(SCXSSLException &e)\n {\n std::string msg(\"Exception: \" + debugChatter.str() + SCXCoreLib::StrToMultibyte(e.Where()) + std::string(\"\\n\") + SCXCoreLib::StrToMultibyte(e.What()));\n CPPUNIT_ASSERT_MESSAGE(msg, false);\n }\n }\n\n void testCertGeneration8Bit(void)\n {\n bool bConverted = false;\n std::ostringstream debugChatter;\n \n SCXCoreLib::SCXFilePath keyPath; \n keyPath.SetDirectory(L\"./testfiles\"); \n keyPath.SetFilename(L\"scx-test-key.pem\"); \n\n SCXCoreLib::SCXFilePath certPath; \n certPath.SetDirectory(L\"./testfiles\"); \n certPath.SetFilename(L\"scx-test-cert.pem\"); \n \n SCXSSLCertificateLocalizedDomain cert(keyPath, certPath, -365, 7300, L\"hostname\", L\"ümĺäüts.ïß.us\", 2048);\n\n try\n {\n // Will self delete to clean up \n SCXCoreLib::SelfDeletingFilePath sdCertPath(cert.m_CertPath.Get());\n SCXCoreLib::SelfDeletingFilePath sdKeyPath(cert.m_KeyPath.Get());\n cert.Generate(debugChatter);\n\n CPPUNIT_ASSERT_MESSAGE(\"Output certificate file not found\", SCXCoreLib::SCXFile::Exists(cert.m_CertPath));\n CPPUNIT_ASSERT_MESSAGE(\"Output key file not found\", SCXCoreLib::SCXFile::Exists(cert.m_KeyPath));\n\n cout << debugChatter.str();\n bConverted = true;\n }\n catch(SCXSSLException &e)\n {\n // All Linux platforms should have the IDN libraries installed\n if (s_fIsLinux)\n {\n std::string msg(\"Exception: \" + debugChatter.str() + SCXCoreLib::StrToMultibyte(e.Where()) + std::string(\"\\n\") + SCXCoreLib::StrToMultibyte(e.What()));\n CPPUNIT_ASSERT_MESSAGE(msg, false);\n }\n\n // A unix platform can drop through here, we expect an exception .. \n }\n\n // If the UNIX system doesn't have the libidn libraries, we shouldn't have worked ... verify that\n if( bConverted )\n {\n void * hLib = SCXSSLCertificateLocalizedDomain::GetLibIDN();\n SCXSSLCertificateLocalizedDomain::AutoClose aclib(hLib);\n\n CPPUNIT_ASSERT_MESSAGE(\"Expected a failure to convert on this platform, but it succeeded (\" + debugChatter.str() + \")\", hLib != NULL);\n }\n }\n\n\n bool CheckCertificate(std::wstring filePath, std::string domainname, std::string hostname)\n {\n std::istringstream in;\n std::ostringstream out, err;\n \n if (SCXCoreLib::SCXProcess::Run(std::wstring(L\"openssl x509 -noout -subject -issuer -in \" + filePath), in, out, err))\n {\n std::string msg(\"Not able to run openssl, error message is: \" + err.str()); \n CPPUNIT_ASSERT_MESSAGE(msg, false);\n }\n\n std::string strSubject(\"subject= /DC=com/DC=\" + domainname + std::string(\"/CN=\") + hostname + std::string(\"/CN=\") + hostname + \".\" + domainname + \".com\");\n if(out.str().find(strSubject) == std::string::npos)\n return false; \n\n std::string strIssuer(\"issuer= /DC=com/DC=\" + domainname + std::string(\"/CN=\") + hostname + std::string(\"/CN=\") + hostname + \".\" + domainname + \".com\");\n if(out.str().find(strIssuer) == std::string::npos)\n return false; \n \n return true;\n }\n \n void test7BitCertGenerationAndCheckFiles(void)\n {\n std::ostringstream debugChatter;\n \n SCXCoreLib::SCXFilePath keyPath; \n keyPath.SetDirectory(L\"./testfiles\"); \n keyPath.SetFilename(L\"scx-test-key.pem\"); \n\n SCXCoreLib::SCXFilePath certPath; \n certPath.SetDirectory(L\"./testfiles\"); \n certPath.SetFilename(L\"scx-test-cert.pem\"); \n\n std::string hostname(\"myhostname\");\n SCXSSLCertificateLocalizedDomain cert(keyPath, certPath, -365, 7300, SCXCoreLib::StrFromUTF8(hostname), L\"vanilladomain.com\", 2048);\n \n try\n {\n cert.Generate(debugChatter);\n\n // Will self delete to clean up \n SCXCoreLib::SelfDeletingFilePath sdCertPath(cert.m_CertPath.Get());\n SCXCoreLib::SelfDeletingFilePath sdKeyPath(cert.m_KeyPath.Get());\n\n //xn--bcher-kva.com is what bücher.com should be in punycode\n CPPUNIT_ASSERT_MESSAGE(\"Punycode function produced incorrect output\", 0 == cert.m_domainname.compare(L\"vanilladomain.com\"));\n CPPUNIT_ASSERT_MESSAGE(\"Output certificate file not found\", SCXCoreLib::SCXFile::Exists(cert.m_CertPath));\n CPPUNIT_ASSERT_MESSAGE(\"Certificate mismatch or corruption\", CheckCertificate(cert.m_CertPath.Get(), std::string(\"vanilladomain\"), hostname)); \n CPPUNIT_ASSERT_MESSAGE(\"Output key file not found\", SCXCoreLib::SCXFile::Exists(cert.m_KeyPath));\n \n cout << debugChatter.str();\n }\n catch(SCXSSLException &e)\n {\n // Should succeed everywhere\n std::string msg(\"Exception: \" + debugChatter.str() + SCXCoreLib::StrToMultibyte(e.Where()) + std::string(\"\\n\") + SCXCoreLib::StrToMultibyte(e.What()));\n CPPUNIT_ASSERT_MESSAGE(msg, false);\n }\n }\n\n void test8BitCertGenerationAndCheckFiles(void)\n {\n bool bConverted = false;\n std::ostringstream debugChatter;\n \n SCXCoreLib::SCXFilePath keyPath;\n keyPath.SetDirectory(L\"./testfiles\");\n keyPath.SetFilename(L\"scx-test-key.pem\");\n\n SCXCoreLib::SCXFilePath certPath;\n certPath.SetDirectory(L\"./testfiles\");\n certPath.SetFilename(L\"scx-test-cert.pem\");\n\n std::string hostname(\"myhostname\");\n SCXSSLCertificateLocalizedDomain cert(keyPath, certPath, -365, 7300, SCXCoreLib::StrFromUTF8(hostname), L\"bücher.com\", 2048);\n\n try\n {\n cert.Generate(debugChatter);\n\n // Will self delete to clean up\n SCXCoreLib::SelfDeletingFilePath sdCertPath(cert.m_CertPath.Get());\n SCXCoreLib::SelfDeletingFilePath sdKeyPath(cert.m_KeyPath.Get());\n#if !defined(sun)\n //xn--bcher-kva.com is what bücher.com should be in punycode\n CPPUNIT_ASSERT_MESSAGE(\"Punycode function produced incorrect output\", 0 == cert.m_domainname.compare(L\"xn--bcher-kva.com\"));\n CPPUNIT_ASSERT_MESSAGE(\"Certificate mismatch or corruption\", CheckCertificate(cert.m_CertPath.Get(), std::string(\"xn--bcher-kva\"), hostname));\n#endif\n CPPUNIT_ASSERT_MESSAGE(\"Output certificate file not found\", SCXCoreLib::SCXFile::Exists(cert.m_CertPath));\n CPPUNIT_ASSERT_MESSAGE(\"Output key file not found\", SCXCoreLib::SCXFile::Exists(cert.m_KeyPath));\n\n cout << debugChatter.str();\n bConverted = true;\n }\n catch(SCXSSLException &e)\n {\n // All Linux platforms should have the IDN libraries installed\n if (s_fIsLinux)\n {\n std::string msg(\"Exception: \" + debugChatter.str() + SCXCoreLib::StrToMultibyte(e.Where()) + std::string(\"\\n\") + SCXCoreLib::StrToMultibyte(e.What()));\n CPPUNIT_ASSERT_MESSAGE(msg, false);\n }\n\n // A unix platform can drop through here, we expect an exception .. \n }\n\n // If the UNIX system doesn't have the libidn libraries, we shouldn't have worked ... verify that\n if( bConverted )\n {\n void * hLib = SCXSSLCertificateLocalizedDomain::GetLibIDN();\n SCXSSLCertificateLocalizedDomain::AutoClose aclib(hLib);\n\n CPPUNIT_ASSERT_MESSAGE(\"Expected a failure to convert on this platform, but it succeeded (\" + debugChatter.str() + \")\", hLib != NULL);\n }\n }\n \n void testClientCertGeneration()\n {\n \tstd::ostringstream debugChatter;\n \t\n \tstd::istringstream in;\n \tstd::ostringstream out, err;\n \t\n \tSCXCoreLib::SelfDeletingFilePath keyPath(L\"./testfiles/scx-client-key.pem\");\n \tSCXCoreLib::SelfDeletingFilePath certPath(L\"./testfiles/scx-test-cert.pem\");\n \tstd::wstring hostname(L\"testhost\");\n \tstd::wstring domainname(L\"testcompany.com\");\n \t\n \tSCXSSLCertificateLocalizedDomain cert(keyPath, certPath, -365, 7300, hostname, domainname, 2048, true);\n \t\n try\n {\n cert.Generate(debugChatter);\n if (SCXCoreLib::SCXProcess::Run(L\"openssl x509 -noout -text -in \" + certPath.Get(), in, out, err))\n {\n std::string msg(\"Error running openssl, error message is: \" + err.str()); \n CPPUNIT_ASSERT_MESSAGE(msg, false);\n }\n std::string keyString(\"TLS Web Client Authentication\");\n if(out.str().find(keyString) == std::string::npos)\n {\n \tCPPUNIT_ASSERT_MESSAGE(\"Expected extended key usage not present\", false);\n }\n }\n catch(SCXSSLException &e)\n {\n CPPUNIT_ASSERT_MESSAGE(\"Unexpected Exception=\" + SCXCoreLib::StrToMultibyte(e.What()),false); \n }\n }\n\n void testNonRFCcompliantDomainFailure()\n {\n std::ostringstream debugChatter;\n \n SCXCoreLib::SelfDeletingFilePath keyPath(L\"./testfiles/scx-test-key.pem\");\n SCXCoreLib::SelfDeletingFilePath certPath(L\"./testfiles/scx-test-cert.pem\");\n\n // This is an actual example we received.\n std::wstring hostname(L\"Instance0-406484d6-6dba-46cb-b21f-93be8e2588b2-serresdev\");\n std::wstring domainname(L\"406484d6-6dba-46cb-b21f-93be8e2588b2-serresdev.d4.internal.cloudapp.net\");\n SCXSSLCertificateLocalizedDomain cert(keyPath, certPath, -365, 7300, hostname, domainname, 2048);\n\n try\n {\n cert.Generate(debugChatter);\n }\n catch(SCXSSLException &e)\n {\n CPPUNIT_ASSERT_MESSAGE(\"Adding a non RFC compliant domain name did not produce the expected exception. Exception=\" + SCXCoreLib::StrToMultibyte(e.What()),\n e.What().find(L\"Unable to add the domain name to the subject.\") != std::string::npos);\n return;\n }\n CPPUNIT_ASSERT_MESSAGE(\"Adding a non RFC compliant domain name did not produce an exception.\", false);\n }\n\n void testNonRFCcompliantHostnameFailure()\n {\n std::ostringstream debugChatter;\n \n SCXCoreLib::SelfDeletingFilePath keyPath(L\"./testfiles/scx-test-key.pem\");\n SCXCoreLib::SelfDeletingFilePath certPath(L\"./testfiles/scx-test-cert.pem\");\n\n // This is an actual example we received.\n std::wstring hostname(L\"Instance0-406484d6-6dba-46cb-b21f-93be8e2588b2-serresdev-longer-than-64-bytes\");\n std::wstring domainname(L\"internal.cloudapp.net\");\n SCXSSLCertificateLocalizedDomain cert(keyPath, certPath, -365, 7300, hostname, domainname, 2048);\n\n try\n {\n cert.Generate(debugChatter);\n }\n catch(SCXSSLException &e)\n {\n CPPUNIT_ASSERT_MESSAGE(\"Adding a non RFC compliant domain name did not produce the expected exception. Exception=\" + SCXCoreLib::StrToMultibyte(e.What()),\n e.What().find(L\"Unable to add hostname to the subject.\") != std::string::npos);\n return;\n }\n CPPUNIT_ASSERT_MESSAGE(\"Adding a non RFC compliant hostname did not produce an exception.\", false);\n }\n\n void testNonRFCcompliantDomainFallback()\n {\n std::istringstream in;\n std::ostringstream out, err;\n \n std::wstring hostname(L\"hostname\");\n std::wstring domainname(L\"406484d6-6dba-46cb-b21f-93be8e2588b2-serresdev.d4.internal.cloudapp.net\");\n\n SCXCoreLib::SelfDeletingFilePath sdCertPath(L\"./testfiles/omi-host-localhost.pem\");\n SCXCoreLib::SelfDeletingFilePath sdLinkPath(L\"./testfiles/omi.pem\");\n SCXCoreLib::SelfDeletingFilePath sdKeyPath(L\"./testfiles/omikey.pem\");\n \n std::wstring scxsslconfigPath(L\"./scxsslconfig\");\n if (SCXCoreLib::SCXFile::Exists(L\"./openssl_1.0.0/scxsslconfig\"))\n {\n scxsslconfigPath = L\"./openssl_1.0.0/scxsslconfig\";\n }\n\n // Because we pass the undocummented -t flag, scxsslconfig will try the fallback even though hostname and domain are specified.\n int ret = SCXCoreLib::SCXProcess::Run(scxsslconfigPath + L\" -f -v -t -g testfiles/ -h \" + hostname + L\" -d \" + domainname, in, out, err);\n\n std::ostringstream errorCodeMsg;\n errorCodeMsg << \"Error running: \" << SCXCoreLib::StrToUTF8(scxsslconfigPath) << \", error message is: \" << err.str() \n << \", error code is: \" << ret;\n CPPUNIT_ASSERT_MESSAGE(errorCodeMsg.str(), ret == 0);\n\n CPPUNIT_ASSERT_MESSAGE(\"Fallback message was not detected in output:\\n\" + out.str(), out.str().find(\"trying fallback: \\\"localhost.local\\\"\") != std::string::npos);\n CPPUNIT_ASSERT_MESSAGE(\"Output certificate file not found\", SCXCoreLib::SCXFile::Exists(sdCertPath.Get()));\n CPPUNIT_ASSERT_MESSAGE(\"Output key file not found\", SCXCoreLib::SCXFile::Exists(sdKeyPath.Get()));\n\n out.str(\"\");\n err.str(\"\");\n\n if (SCXCoreLib::SCXProcess::Run(L\"openssl x509 -noout -subject -issuer -in \" + sdCertPath.Get(), in, out, err))\n {\n std::string msg(\"Error running openssl, error message is: \" + err.str()); \n CPPUNIT_ASSERT_MESSAGE(msg, false);\n }\n\n CPPUNIT_ASSERT_MESSAGE(\"Cert subject not as expected. Received: \" + out.str(), out.str().find(\"subject= /DC=local/CN=localhost/CN=localhost.local\") != std::string::npos);\n CPPUNIT_ASSERT_MESSAGE(\"Cert issuer not as expected. Received: \" + out.str(), out.str().find(\"issuer= /DC=local/CN=localhost/CN=localhost.local\") != std::string::npos);\n }\n\n void testNonRFCcompliantDomainNoRecovery()\n {\n std::istringstream in;\n std::ostringstream out, err;\n \n std::wstring hostname(L\"Instance0-406484d6-6dba-46cb-b21f-93be8e2588b2-serresdev\");\n std::wstring domainname(L\"406484d6-6dba-46cb-b21f-93be8e2588b2-serresdev.d4.internal.cloudapp.net\");\n\n SCXCoreLib::SelfDeletingFilePath sdCertPath(L\"./testfiles/omi-host-\" + hostname + L\".pem\");\n SCXCoreLib::SelfDeletingFilePath sdLinkPath(L\"./testfiles/omi.pem\");\n SCXCoreLib::SelfDeletingFilePath sdKeyPath(L\"./testfiles/omikey.pem\");\n \n std::wstring scxsslconfigPath(L\"./scxsslconfig\");\n if (SCXCoreLib::SCXFile::Exists(L\"./openssl_1.0.0/scxsslconfig\"))\n {\n scxsslconfigPath = L\"./openssl_1.0.0/scxsslconfig\";\n }\n\n // When we pass a non RFC compliant hostname or domain, scxsslconfig will not try to recover and should fail.\n int ret = SCXCoreLib::SCXProcess::Run(scxsslconfigPath + L\" -f -v -g testfiles/ -h \" + hostname + L\" -d \" + domainname, in, out, err);\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"scxsslconfig did not fail with a non RFC compliant domain name\", 3, ret);\n CPPUNIT_ASSERT_MESSAGE(\"Adding a non RFC compliant domain name did not produce the expected error message: \\\"\" + err.str() +\"\\\"\",\n err.str().find(\"Unable to add the domain name to the subject.\") != std::string::npos);\n\n CPPUNIT_ASSERT_MESSAGE(\"Certificate found but it should not have been generated\", SCXCoreLib::SCXFile::Exists(sdCertPath.Get()) == false);\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( ScxSSLCertTest );\n" }, { "alpha_fraction": 0.624103307723999, "alphanum_fraction": 0.6345376372337341, "avg_line_length": 27.93207550048828, "blob_id": "015aaf27b587a077f2874ec1b1c7c6d1437f76a1", "content_id": "4fd3e5bd8820a3ef90e5cdd1b78b6a8baaf23bde", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 7667, "license_type": "permissive", "max_line_length": 104, "num_lines": 265, "path": "/installer/bundle/create_bundle.sh", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#\n#\n# This script will create a bundle file given an existing kit.\n#\n# See usage for parameters that must be passed to this script.\n#\n# We expect this script to run from the BUILD directory (i.e. scxcore/build).\n# Directory paths are hard-coded for this location.\n\n# Notes for file bundle_skel_<PLATFORM>.sh (included here since we don't want to ship\n# these comments in shell bundle):\n#\n# The bundle_skel_<PLATFORM>.sh file is a shell bundle for <PLATFORM> (PLATFORM = Linux, AIX, HP, SunOS\n# The platforms and the relevant shell bundles are as listed below:\n# Redhat, SUSE and Universal Linux => bundle_skel_Linux.sh\n# AIX => bundle_skel_AIX.sh\n# HP => bundle_skel_HPUX.sh\n# Solaris => bundle_skel_SunOS.sh\n#\n# Use this script by concatenating it with some binary package.\n#\n# The bundle is created by cat'ing the script in front of the binary, so for\n# the gzip'ed tar example, a command like the following will build the bundle:\n#\n# tar -czvf - <target-dir> | cat sfx.skel - > my.bundle\n#\n# The bundle can then be copied to a system, made executable (chmod +x) and\n# then run.\n#\n# This script has some useful helper options to split out the script and/or\n# binary in place, and to turn on shell debugging.\n#\n# This script is paired with create_bundle.sh, which will edit constants in\n# this script for proper execution at runtime. The \"magic\", here, is that\n# create_bundle.sh encodes the length of this script in the script itself.\n# Then the script can use that with 'tail' in order to strip the script from\n# the binary package.\n#\n# Developer note: A prior incarnation of this script used 'sed' to strip the\n# script from the binary package. That didn't work on AIX 5, where 'sed' did\n# strip the binary package - AND null bytes, creating a corrupted stream.\n\n\nSOURCE_DIR=`(cd ../installer/bundle; pwd -P)`\nINTERMEDIATE_DIR=`(cd ../installer/intermediate; pwd -P)`\n\n# Exit on error\nset -e\n\n# Don't display output\nset +x\n\nusage()\n{\n echo \"usage: $0 platform directory tar-file scx-package-name omi-package-name <provider-only>\"\n echo \" where\"\n echo \" platform is one of: linux, aix, hpux, sun\"\n echo \" directory is directory path to package file\"\n echo \" tar-file is the name of the tar file that contains the following packages\"\n echo \" scx-package-name is the name of the scx installation package\"\n echo \" omi-package-name is the name of the omi installation package\"\n echo \" provider-only is 1 (scx-cimprov style kit) or 0 (scx combined kit)\"\n echo \" If omi-package-name is empty, then we assume universal SSL directories for OMI\"\n exit 1\n}\n\ndo_sed()\n{\n # Linux supports sed -i, but non-Linux does not\n # Code looks cleaner to use -i, so use it when we can via this function\n #\n # Parameters:\n # 1: Filename to edit\n # 2-10: Parameters to sed\n #\n # We arbitrarily stop at 10 parameters. This can be added to if needed.\n # I tried to use a for loop to work with any number of parameters, but\n # this proved tricky with bash quoting.\n\n local filename=$1\n local params=\"$2 $3 $4 $5 $6 $7 $8 $9 ${10}\"\n\n if [ `uname -s` = \"Linux\" ]; then\n sed -i $params $filename\n else\n local tempfile=/tmp/create_bundle_$$\n\n sed $params $filename > $tempfile\n mv $tempfile $filename\n fi\n}\n\n# Validate parameters\n\nPLATFORM_TYPE=\"$1\"\nif [ -z \"$PLATFORM_TYPE\" ]; then\n echo \"Missing parameter: Platform type\" >&2\n echo \"\"\n usage\n exit 1\nfi\n\ncase \"$PLATFORM_TYPE\" in\n Linux|AIX|HPUX|SunOS|PPC-RHEL|PPC-SUSE)\n\t;;\n\n *)\n\techo \"Invalid platform type specified: $PLATFORM_TYPE\" >&2\n\texit 1\nesac\n\nif [ -z \"$2\" ]; then\n echo \"Missing parameter: Directory to platform file\" >&2\n echo \"\"\n usage\n exit 1\nfi\n\nif [ ! -d \"$2\" ]; then\n echo \"Directory \\\"$2\\\" does not exist\" >&2\n exit 1\nfi\n\nif [ -z \"$3\" ]; then\n echo \"Missing parameter: tar-file\" >&2\n echo \"\"\n usage\n exit 1\nfi\n\nif [ -z \"$4\" ]; then\n echo \"Missing parameter: scx-package-name\" >&2\n echo \"\"\n usage\n exit 1\nfi\n\nif [ -z \"$6\" ]; then\n echo \"Missing parameter: provider-only\" >&2\n echo \"\"\n usage\n exit 1\nfi\n\nSCX_PACKAGE=`echo $4 | sed -e 's/.rpm$//' -e 's/.deb$//'`\nOMI_PACKAGE=`echo $5 | sed -e 's/.rpm$//' -e 's/.deb$//'`\nPROVIDER_ONLY=$6\n\nif [ ! -f \"$2/$3\" ]; then\n echo \"Tar file \\\"$2/$3\\\" does not exist\"\n exit 1\nfi\n\n# Determine the output file name\nOUTPUT_DIR=`(cd $2; pwd -P)`\n\n# Work from the temporary directory from this point forward\n\ncd $INTERMEDIATE_DIR\n\nif [ ! -f $SOURCE_DIR/bundle_skel_${PLATFORM_TYPE}.sh ]\nthen\n echo \"shell bundle skeleton file bundle_skel_${PLATFORM_TYPE}.sh does not exist in ${SOURCE_DIR}\"\n exit 1\nfi\n# Fetch the bundle skeleton file\ncp $SOURCE_DIR/bundle_skel_${PLATFORM_TYPE}.sh ./bundle_skel.sh\nchmod u+w bundle_skel.sh\n\n# See if we can resolve git references for output\n# (See if we can find the master project)\nif git --version > /dev/null 2> /dev/null; then\n if [ -f ../../../.gitmodules ]; then\n TEMP_FILE=/tmp/create_bundle.$$\n\n # Get the git reference hashes in a file\n (\n\t cd ../../..\n\t echo \"Entering 'superproject'\" > $TEMP_FILE\n\t git rev-parse HEAD >> $TEMP_FILE\n\t git submodule foreach git rev-parse HEAD >> $TEMP_FILE\n )\n\n # Change lines like: \"Entering 'omi'\\n<refhash>\" to \"omi: <refhash>\"\n perl -i -pe \"s/Entering '([^\\n]*)'\\n/\\$1: /\" $TEMP_FILE\n\n # Grab the reference hashes in a variable\n SOURCE_REFS=`cat $TEMP_FILE`\n rm $TEMP_FILE\n\n # Update the bundle file w/the ref hash (much easier with perl since multi-line)\n perl -i -pe \"s/-- Source code references --/${SOURCE_REFS}/\" bundle_skel.sh\n else\n echo \"Unable to find git superproject!\" >& 2\n exit 1\n fi\nelse\n echo \"git client does not appear to be installed\" >& 2\n exit 1\nfi\n\n# Edit the bundle file for hard-coded values\ndo_sed bundle_skel.sh \"s/TAR_FILE=<TAR_FILE>/TAR_FILE=$3/\"\ndo_sed bundle_skel.sh \"s/OM_PKG=<OM_PKG>/OM_PKG=$SCX_PACKAGE/\"\ndo_sed bundle_skel.sh \"s/OMI_PKG=<OMI_PKG>/OMI_PKG=$OMI_PACKAGE/\"\n\ndo_sed bundle_skel.sh \"s/PROVIDER_ONLY=0/PROVIDER_ONLY=$PROVIDER_ONLY/\"\n\n\nSCRIPT_LEN=`wc -l < bundle_skel.sh | sed -e 's/ //g'`\nSCRIPT_LEN_PLUS_ONE=\"$((SCRIPT_LEN + 1))\"\n\ndo_sed bundle_skel.sh \"s/SCRIPT_LEN=<SCRIPT_LEN>/SCRIPT_LEN=${SCRIPT_LEN}/\"\ndo_sed bundle_skel.sh \"s/SCRIPT_LEN_PLUS_ONE=<SCRIPT_LEN+1>/SCRIPT_LEN_PLUS_ONE=${SCRIPT_LEN_PLUS_ONE}/\"\n\n\n# Fetch the kit\ncp $OUTPUT_DIR/$3 .\n\n# Build the bundle\ncase \"$PLATFORM_TYPE\" in\n Linux)\n\tBUNDLE_FILE=`echo $3 | sed -e \"s/.rpm//\" -e \"s/.deb//\" -e \"s/.tar//\"`.sh\n\tgzip -c $3 | cat bundle_skel.sh - > $BUNDLE_FILE\n\t;;\n\n AIX)\n\tBUNDLE_FILE=`echo $3 | sed -e \"s/.lpp//\" -e \"s/.tar//\"`.sh\n\tgzip -c $3 | cat bundle_skel.sh - > $BUNDLE_FILE\n\t;;\n\n HPUX)\n\tBUNDLE_FILE=`echo $3 | sed -e \"s/.depot//\" -e \"s/.tar//\"`.sh\n\tcompress -c $3 | cat bundle_skel.sh - > $BUNDLE_FILE\n\t;;\n\n SunOS)\n\tBUNDLE_FILE=`echo $3 | sed -e \"s/.pkg//\" -e \"s/.tar//\"`.sh\n\tcompress -c $3 | cat bundle_skel.sh - > $BUNDLE_FILE\n\t;;\n\t\n PPC-RHEL)\n\tBUNDLE_FILE=`echo $3 | sed -e \"s/.rpm//\" -e \"s/.tar//\"`.sh\n\tgzip -c $3 | cat bundle_skel.sh - > $BUNDLE_FILE\n\t;;\n\n PPC-SUSE)\n BUNDLE_FILE=`echo $3 | sed -e \"s/.rpm//\" -e \"s/.tar//\"`.sh\n gzip -c $3 | cat bundle_skel.sh - > $BUNDLE_FILE\n ;;\n\t\n *)\n\techo \"Invalid platform encoded in variable \\$PACKAGE; aborting\" >&2\n\texit 2\nesac\n\nchmod +x $BUNDLE_FILE\nrm bundle_skel.sh\n\n# Remove the kit and copy the bundle to the kit location\nrm $3\nmv $BUNDLE_FILE $OUTPUT_DIR/\n\nexit 0\n" }, { "alpha_fraction": 0.6322529315948486, "alphanum_fraction": 0.6493653655052185, "avg_line_length": 30.97101402282715, "blob_id": "503d73d474bcf75c715049ad561259a136712965", "content_id": "27b6e54d531ef381b70fadc2edae0e75dd26a453", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8824, "license_type": "permissive", "max_line_length": 126, "num_lines": 276, "path": "/test/util/testapp/memdata.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n */\n#include <string>\n#include <vector>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n\n#include <stdio.h>\n#include <math.h>\n\n#ifndef WIN32\n#include <unistd.h> // for sysconf()\n#endif\n\n#include \"memdata.h\"\n\nusing namespace std;\n\n#ifndef MIN\n#define MIN(a,b) ((a) < (b) ? (a) : (b))\n#endif\n\n#ifdef WIN32\n\nconst string meminfoFileName = \"C:\\\\meminfo.txt\";\n\n#else\n\nconst string meminfoFileName = \"/proc/meminfo\";\n\n#endif\n#if defined(hpux)\n#include <sys/pstat.h>\n#endif\n#if defined(sun)\n#include <sys/swap.h>\n#include <sys/sysinfo.h>\n#endif\n\n#if defined(aix)\n#include <libperfstat.h>\n#endif\n\nMEMData::MEMData(void) : \n MEMTotalMB(0), MEMUsedPercent(0), MEMUsedMB(0), MEMFreePercent(0), MEMFreeMB(0),\n MEMSwapTotalMB(0), MEMSwapUsedPercent(0), MEMSwapUsedMB(0), MEMSwapFreePercent(0), MEMSwapFreeMB(0)\n{\n}\n\nMEMData::~MEMData(void)\n{\n}\n\n#if defined(linux)\nstatic void Tokenize(const string& str, vector<string>& tokens, const string& delimiters = \" \\n\")\n{\n // Skip delimiters at beginning.\n string::size_type lastPos = str.find_first_not_of(delimiters, 0);\n // Find first \"non-delimiter\".\n string::size_type pos = str.find_first_of(delimiters, lastPos);\n\n while (string::npos != pos || string::npos != lastPos)\n {\n // Found a token, add it to the vector.\n tokens.push_back(str.substr(lastPos, pos - lastPos));\n // Skip delimiters. Note the \"not_of\"\n lastPos = str.find_first_not_of(delimiters, pos);\n // Find next \"non-delimiter\"\n pos = str.find_first_of(delimiters, lastPos);\n }\n}\n\nstatic int ToInt(string str)\n{\n int tmp;\n stringstream ss(str);\n\n ss >> tmp;\n\n return tmp;\n}\n#endif\n\ndouble BytesToMegaBytes(double bytes)\n{\n return bytes / 1024.0 / 1024.0;\n}\n\nstatic unsigned int GetPercentage(unsigned int total, unsigned int val)\n{\n int ans = 0;\n\n if ((total > 0))\n {\n ans = MIN(100, (int)(((double)val / (double)total) * 100 + (double)0.5));\n }\n\n return ans;\n}\n\nint MEMData::UpdateData(void)\n{\n#if defined(linux)\n ifstream meminfoFile;\n string line;\n int found = 0;\n\n meminfoFile.open(meminfoFileName.c_str());\n\n if (meminfoFile.fail())\n {\n return 1;\n }\n\n/*\nMemTotal: 516428 kB\nMemFree: 52400 kB\nSwapTotal: 779112 kB\nSwapFree: 779028 kB\n*/\n\n while (getline(meminfoFile, line) && found < 4)\n {\n vector<string> tokens;\n\n Tokenize(line, tokens);\n\n if (tokens[0].compare(\"MemTotal:\") == 0)\n {\n MEMTotalMB = ToInt(tokens[1])/1024;\n }\n else if (tokens[0].compare(\"MemFree:\") == 0)\n {\n MEMFreeMB = ToInt(tokens[1])/1024;\n }\n else if (tokens[0].compare(\"SwapTotal:\") == 0)\n {\n MEMSwapTotalMB = ToInt(tokens[1])/1024;\n }\n else if (tokens[0].compare(\"SwapFree:\") == 0)\n {\n MEMSwapFreeMB = ToInt(tokens[1])/1024;\n }\n }\n\n MEMUsedMB = MEMTotalMB - MEMFreeMB;\n MEMUsedPercent = GetPercentage(MEMTotalMB, MEMUsedMB);\n MEMFreePercent = 100-MEMUsedPercent;\n\n MEMSwapUsedMB = MEMSwapTotalMB - MEMSwapFreeMB;\n MEMSwapUsedPercent = GetPercentage(MEMSwapTotalMB, MEMSwapUsedMB);\n MEMSwapFreePercent = 100-MEMSwapUsedPercent;\n\n#elif defined(sun)\n long pageSizeL = sysconf(_SC_PAGESIZE);\n\t\t//Calculating pageSize in Megabytes to fix Solaris SPARC memory calculation issue\n\t\tdouble pageSizeMB=BytesToMegaBytes(pageSizeL);\n\n long physPagesL = sysconf(_SC_PHYS_PAGES); \n //MEMTotalMB = BytesToMegaBytes(physPagesL * pageSizeL); - Fix Sparc Memory calculation issue\n\t\tMEMTotalMB = physPagesL * pageSizeMB;\n\n long availPhysPagesL = sysconf(_SC_AVPHYS_PAGES); \n //MEMFreeMB = BytesToMegaBytes(availPhysPagesL * pageSizeL); - Fix Sparc Memory calculation issue\n\t\tMEMFreeMB = availPhysPagesL * pageSizeMB;\n\n MEMUsedMB = MEMTotalMB - MEMFreeMB;\n MEMUsedPercent = GetPercentage(MEMTotalMB, MEMUsedMB);\n MEMFreePercent = 100-MEMUsedPercent;\n\n struct anoninfo swapinfo;\n\n MEMSwapTotalMB = BytesToMegaBytes(swapinfo.ani_max * pageSizeL);\n MEMSwapFreeMB = BytesToMegaBytes((swapinfo.ani_max - swapinfo.ani_resv) * pageSizeL);\n MEMSwapUsedMB = BytesToMegaBytes(swapinfo.ani_resv * pageSizeL);\n MEMSwapUsedPercent = GetPercentage(MEMSwapTotalMB, MEMSwapUsedMB);\n MEMSwapFreePercent = 100-MEMSwapUsedPercent;\n\n\n#elif defined(hpux)\n /*\n HP kindly provides an easy way to read all kind of system and kernel data.\n This is collectively known as the pstat interface.\n It's supposed to be relatively upgrade friendly, even without recompilation.\n What is lacking however, is documentation. There is a whitepaper on pstat that\n you can look for at HP's site, which is very readable. But the exact semantics of\n each and every parameter is subject to experimentation and guesswork. I read\n somewhere that, to truly understand them you would need to have access to the\n kernel source. Needless to say, we don't. I've written a document called\n \"Memory monitoring on HPUX.docx\" that summarizes the needs and what's available.\n */\n struct pst_static psts;\n struct pst_dynamic pstd;\n struct pst_vminfo pstv;\n\n /* Get information the system static variables (guaranteed to remain constant until reboot) */\n if (pstat_getstatic(&psts, sizeof(psts), 1, 0) < 0) {\n return -1;\n }\n\n /* Get information about the system dynamic variables */\n if (pstat_getdynamic(&pstd, sizeof(pstd), 1, 0) != 1) {\n return -1;\n }\n\n /* Get information about the system virtual memory variables */\n if (pstat_getvminfo(&pstv, sizeof(pstv), 1, 0) != 1) {\n return -1;\n }\n\n // These are the system variables that we use together with ALL the documentation that HP provide\n // psts.page_size - page size in bytes/page\n // psts.physical_memory - system physical memory in 4K pages\n // pstd.psd_rm - total real memory\n // pstd.psd_free - free memory pages\n // pstv.psv_swapspc_max - max pages of on-disk backing store\n // pstv.psv_swapspc_cnt - pages of on-disk backing store\n // pstv.psv_swapmem_max - max pages of in-memory backing store\n // pstv.psv_swapmem_cnt - pages of in-memory backing store\n // pstv.psv_swapmem_on - in-memory backing store enabled\n\n // For usedMemory we use a measure of all real (physical) memory assigned to processes\n // For availableMemory we use the size of unassigned memory\n MEMTotalMB = BytesToMegaBytes(psts.physical_memory * (double)psts.page_size);\n MEMFreeMB = BytesToMegaBytes(pstd.psd_free * (double)psts.page_size);\n\n // totalSwap is the total size of all external swap devices plus swap memory, if enabled\n // availableSwap is the size of remaining device swap (with reserved memory subtracted)\n // plus remaining swap memory, if that was enabled in system configuration.\n // usedSwap is the difference between those. This is consistent with the 'total'\n // numbers when you do 'swapinfo -t'.\n MEMSwapTotalMB = BytesToMegaBytes(pstv.psv_swapspc_max + pstv.psv_swapmem_on * pstv.psv_swapmem_max * psts.page_size);\n MEMSwapFreeMB = BytesToMegaBytes(pstv.psv_swapspc_cnt + pstv.psv_swapmem_on * pstv.psv_swapmem_cnt * psts.page_size);\n\n MEMUsedMB = MEMTotalMB - MEMFreeMB;\n MEMUsedPercent = GetPercentage(MEMTotalMB, MEMUsedMB);\n MEMFreePercent = 100-MEMUsedPercent;\n\n MEMSwapUsedMB = MEMSwapTotalMB - MEMSwapFreeMB;\n MEMSwapUsedPercent = GetPercentage(MEMSwapTotalMB, MEMSwapUsedMB);\n MEMSwapFreePercent = 100-MEMSwapUsedPercent;\n\n#elif defined(aix)\n\n int retcode;\n perfstat_memory_total_t mem;\n \n retcode = perfstat_memory_total(NULL, &mem, sizeof(perfstat_memory_total_t), 1);\n\n if (retcode != 1)\n {\n\t return -1;\n }\n\n // All memory data given in 4KB pages\n\n MEMTotalMB = (mem.real_total / 1024) * 4;\n MEMFreeMB = (mem.real_free / 1024) * 4;\n MEMUsedMB = MEMTotalMB - MEMFreeMB;\n MEMUsedPercent = GetPercentage(MEMTotalMB, MEMUsedMB);\n MEMFreePercent = 100-MEMUsedPercent;\n\n MEMSwapTotalMB = (mem.pgsp_total / 1024) * 4;\n MEMSwapFreeMB = (mem.pgsp_free / 1024) * 4;\n MEMSwapUsedMB = MEMSwapTotalMB - MEMSwapFreeMB;\n MEMSwapUsedPercent = GetPercentage(MEMSwapTotalMB, MEMSwapUsedMB);\n MEMSwapFreePercent = 100-MEMSwapUsedPercent;\n\n#else\n#error \"Not implemented for this platform.\"\n#endif\n return 0;\n}\n" }, { "alpha_fraction": 0.7007877230644226, "alphanum_fraction": 0.7457514405250549, "avg_line_length": 27.280349731445312, "blob_id": "ab9d1260e9e872d56aa28c00b247c7c8e283af00", "content_id": "4661adc0d4fe11bef812373f3511641f3c529baa", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 22596, "license_type": "permissive", "max_line_length": 302, "num_lines": 799, "path": "/README.md", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# SCXcore [![Build Status](https://travis-ci.org/Microsoft/SCXcore.svg?branch=master)](https://travis-ci.org/Microsoft/SCXcore)\n\nSCXcore, started as the [Microsoft Operations Manager][] UNIX/Linux Agent,\nis now used in a host of products including\n[Microsoft Operations Manager][].\n[Microsoft Azure][], and\n[Microsoft Operations Management Suite][].\n\n[Microsoft Operations Manager]: https://technet.microsoft.com/library/hh205987.aspx\n[Microsoft Azure]: https://azure.microsoft.com\n[Microsoft Operations Management Suite]: https://www.microsoft.com/en-us/cloud-platform/operations-management-suite\n\nThe SCXcore provides a CIMOM provider, based on [OMI][], to return\nlogging and statistical information for a UNIX or Linux system. The\nSCXcore provider runs on AIX 6.1 and later, HP/UX 11.31 and later,\nSolaris 5.10 and later, and most versions of Linux as far back as\nRedHat 5.0, SuSE 10.1, and Debian 5.0.\n\n[OMI]: https://github.com/Microsoft/omi\n\nThe SCXcore provider provides the following classes (note that\nperformance measurements were taken on an idle machine, so performance\nmeasurements were of little value):\n\n- [SCX_Agent](#enumeration-of-scx_agent)\n- [SCX_Application_Server](#enumeration-of-scx_application_server)\n- [SCX_DiskDrive](#enumeration-of-scx_diskdrive)\n- [SCX_DiskDriveStatisticalInformation](#enumeration-of-scx_diskdrivestatisticalinformation)\n- [SCX_EthernetPortStatistics](#enumeration-of-scx_ethernetportstatistics)\n- [SCX_FileSystem](#enumeration-of-scx_filesystem)\n- [SCX_FileSystemStatisticalInformation](#enumeration-of-scx_filesystemstatisticalinformation)\n- [SCX_IPProtocolEndpoint](#enumeration-of-scx_ipprotocolendpoint)\n- [SCX_LANEndpoint](#enumeration-of-scx_lanendpoint)\n- [SCX_LogFile](#enumeration-of-scx_logfile)\n- [SCX_MemoryStatisticalInformation](#enumeration-of-scx_memorystatisticalinformation)\n- [SCX_OperatingSystem](#enumeration-of-scx_operatingsystem)\n- [SCX_ProcessorStatisticalInformation](#enumeration-of-scx_processorstatisticalinformation)\n- [SCX_RTProcessorStatisticalInformation](#enumeration-of-scx_rtprocessorstatisticalinformation)\n- [SCX_UnixProcess](#enumeration-of-scx_unixprocess)\n- [SCX_UnixProcess TopResourceConsumers](#topresourceconsumers-provider)\n- [SCX_UnixProcessStatisticalInformation](#enumeration-of-scx_unixprocessstatisticalinformation)\n\nRunAs Provider:\n\n- [ExecuteCommand](#runas-provider-executecommand)\n- [ExecuteShellCommand](#runas-provider-executeshellcommand)\n- [ExecuteScript](#runas-provider-executescript)\n\n-----\n\nThe following output shows the results of enumeration of classes:\n\n\n### Enumeration of SCX_Agent\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_Agent\ninstance of SCX_Agent\n{\n Caption=SCX Agent meta-information\n Description=Release_Build - 20160901\n InstallDate=20160902085021.000000+000\n [Key] Name=scx\n VersionString=1.6.2-416\n MajorVersion=1\n MinorVersion=6\n RevisionNumber=2\n BuildNumber=416\n BuildDate=2016-09-01T00:00:00Z\n Architecture=x64\n OSName=CentOS Linux\n OSType=Linux\n OSVersion=7.0\n KitVersionString=1.6.2-416\n Hostname=jeffcof64-cent7x-01.scx.com\n OSAlias=UniversalR\n UnameArchitecture=x86_64\n MinActiveLogSeverityThreshold=INFO\n MachineType=Virtual\n PhysicalProcessors=1\n LogicalProcessors=2\n}\n```\n\n### Enumeration of SCX_Application_Server\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_Application_Server\ninstance of SCX_Application_Server\n{\n Caption=SCX Application Server\n Description=Represents a JEE Application Server\n [Key] Name=/root/tomcat/apache-tomcat-7.0.11/\n HttpPort=8080\n HttpsPort=8443\n Port=\n Protocol=\n Version=7.0.11\n MajorVersion=7\n DiskPath=/root/tomcat/apache-tomcat-7.0.11/\n Type=Tomcat\n Profile=\n Cell=\n Node=\n Server=\n IsDeepMonitored=false\n IsRunning=true\n}\n```\n\n### Enumeration of SCX_DiskDrive\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_DiskDrive\ninstance of SCX_DiskDrive\n{\n Caption=Disk drive information\n Description=Information pertaining to a physical unit of secondary storage\n Name=sda\n [Key] SystemCreationClassName=SCX_ComputerSystem\n [Key] SystemName=jeffcof64-cent7x-01.scx.com\n [Key] CreationClassName=SCX_DiskDrive\n [Key] DeviceID=sda\n MaxMediaSize=34359738368\n InterfaceType=SCSI\n Manufacturer=Msft\n Model=Virtual Disk\n TotalCylinders=4177\n TotalHeads=255\n TotalSectors=67108864\n}\n```\n\n### Enumeration of SCX_DiskDriveStatisticalInformation\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_DiskDriveStatisticalInformation\ninstance of SCX_DiskDriveStatisticalInformation\n{\n Caption=Disk drive information\n Description=Performance statistics related to a physical unit of secondary storage\n [Key] Name=sda\n IsAggregate=false\n IsOnline=true\n BytesPerSecond=0\n ReadBytesPerSecond=0\n WriteBytesPerSecond=0\n TransfersPerSecond=0\n ReadsPerSecond=0\n WritesPerSecond=0\n AverageReadTime=0\n AverageWriteTime=0\n AverageTransferTime=0\n AverageDiskQueueLength=0\n}\ninstance of SCX_DiskDriveStatisticalInformation\n{\n Caption=Disk drive information\n Description=Performance statistics related to a physical unit of secondary storage\n [Key] Name=_Total\n IsAggregate=true\n IsOnline=true\n BytesPerSecond=0\n ReadBytesPerSecond=0\n WriteBytesPerSecond=0\n TransfersPerSecond=0\n ReadsPerSecond=0\n WritesPerSecond=0\n AverageReadTime=0\n AverageWriteTime=0\n AverageTransferTime=0\n AverageDiskQueueLength=0\n}\n```\n\n### Enumeration of SCX_EthernetPortStatistics\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_EthernetPortStatistics\ninstance of SCX_EthernetPortStatistics\n{\n [Key] InstanceID=eth0\n Caption=Ethernet port information\n Description=Statistics on transfer performance for a port\n BytesTransmitted=1779042797\n BytesReceived=10709989843\n PacketsTransmitted=7899737\n PacketsReceived=67705882\n BytesTotal=12489032640\n TotalRxErrors=0\n TotalTxErrors=0\n TotalCollisions=0\n}\ninstance of SCX_EthernetPortStatistics\n{\n [Key] InstanceID=virbr0\n Caption=Ethernet port information\n Description=Statistics on transfer performance for a port\n BytesTransmitted=0\n BytesReceived=0\n PacketsTransmitted=0\n PacketsReceived=0\n BytesTotal=0\n TotalRxErrors=0\n TotalTxErrors=0\n TotalCollisions=0\n}\n```\n\n### Enumeration of SCX_FileSystem\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_FileSystem\ninstance of SCX_FileSystem\n{\n Caption=File system information\n Description=Information about a logical unit of secondary storage\n [Key] Name=/\n [Key] CSCreationClassName=SCX_ComputerSystem\n [Key] CSName=jeffcof64-cent7x-01.scx.com\n [Key] CreationClassName=SCX_FileSystem\n Root=/\n BlockSize=4096\n FileSystemSize=31622189056\n AvailableSpace=17586249728\n ReadOnly=false\n EncryptionMethod=Not Encrypted\n CompressionMethod=Not Compressed\n CaseSensitive=true\n CasePreserved=true\n MaxFileNameLength=255\n FileSystemType=xfs\n PersistenceType=2\n NumberOfFiles=322736\n IsOnline=true\n TotalInodes=30896128\n FreeInodes=30573392\n}\ninstance of SCX_FileSystem\n{\n Caption=File system information\n Description=Information about a logical unit of secondary storage\n [Key] Name=/boot\n [Key] CSCreationClassName=SCX_ComputerSystem\n [Key] CSName=jeffcof64-cent7x-01.scx.com\n [Key] CreationClassName=SCX_FileSystem\n Root=/boot\n BlockSize=4096\n FileSystemSize=517713920\n AvailableSpace=312877056\n ReadOnly=false\n EncryptionMethod=Not Encrypted\n CompressionMethod=Not Compressed\n CaseSensitive=true\n CasePreserved=true\n MaxFileNameLength=255\n FileSystemType=xfs\n PersistenceType=2\n NumberOfFiles=337\n IsOnline=true\n TotalInodes=512000\n FreeInodes=511663\n}\n```\n\n### Enumeration of SCX_FileSystemStatisticalInformation\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_FileSystemStatisticalInformation\ninstance of SCX_FileSystemStatisticalInformation\n{\n Caption=File system information\n Description=Performance statistics related to a logical unit of secondary storage\n [Key] Name=/\n IsAggregate=false\n IsOnline=true\n FreeMegabytes=16772\n UsedMegabytes=13386\n PercentFreeSpace=56\n PercentUsedSpace=44\n PercentFreeInodes=99\n PercentUsedInodes=1\n BytesPerSecond=0\n ReadBytesPerSecond=0\n WriteBytesPerSecond=0\n TransfersPerSecond=0\n ReadsPerSecond=0\n WritesPerSecond=0\n}\ninstance of SCX_FileSystemStatisticalInformation\n{\n Caption=File system information\n Description=Performance statistics related to a logical unit of secondary storage\n [Key] Name=/boot\n IsAggregate=false\n IsOnline=true\n FreeMegabytes=299\n UsedMegabytes=196\n PercentFreeSpace=60\n PercentUsedSpace=40\n PercentFreeInodes=100\n PercentUsedInodes=0\n BytesPerSecond=0\n ReadBytesPerSecond=0\n WriteBytesPerSecond=0\n TransfersPerSecond=0\n ReadsPerSecond=0\n WritesPerSecond=0\n}\ninstance of SCX_FileSystemStatisticalInformation\n{\n Caption=File system information\n Description=Performance statistics related to a logical unit of secondary storage\n [Key] Name=_Total\n IsAggregate=true\n IsOnline=true\n FreeMegabytes=17071\n UsedMegabytes=13582\n PercentFreeSpace=56\n PercentUsedSpace=44\n PercentFreeInodes=100\n PercentUsedInodes=0\n BytesPerSecond=0\n ReadBytesPerSecond=0\n WriteBytesPerSecond=0\n TransfersPerSecond=0\n ReadsPerSecond=0\n WritesPerSecond=0\n}\n```\n\n### Enumeration of SCX_IPProtocolEndpoint\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_IPProtocolEndpoint\ninstance of SCX_IPProtocolEndpoint\n{\n Caption=IP protocol endpoint information\n Description=Properties of an IP protocol connection endpoint\n ElementName=eth0\n [Key] Name=eth0\n EnabledState=2\n [Key] SystemCreationClassName=SCX_ComputerSystem\n [Key] SystemName=jeffcof64-cent7x-01.scx.com\n [Key] CreationClassName=SCX_IPProtocolEndpoint\n IPv4Address=157.59.154.35\n SubnetMask=255.255.252.0\n IPv4BroadcastAddress=157.59.155.255\n}\ninstance of SCX_IPProtocolEndpoint\n{\n Caption=IP protocol endpoint information\n Description=Properties of an IP protocol connection endpoint\n ElementName=virbr0\n [Key] Name=virbr0\n EnabledState=2\n [Key] SystemCreationClassName=SCX_ComputerSystem\n [Key] SystemName=jeffcof64-cent7x-01.scx.com\n [Key] CreationClassName=SCX_IPProtocolEndpoint\n IPv4Address=192.168.122.1\n SubnetMask=255.255.255.0\n IPv4BroadcastAddress=192.168.122.255\n}\n```\n\n### Enumeration of SCX_LANEndpoint\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_LANEndpoint \ninstance of SCX_LANEndpoint\n{\n InstanceID=eth0\n Caption=LAN endpoint caption information\n Description=LAN Endpoint description information\n ElementName=eth0\n [Key] Name=eth0\n [Key] SystemCreationClassName=SCX_ComputerSystem\n [Key] SystemName=jeffcof64-cent7x-01.scx.com\n [Key] CreationClassName=SCX_LANEndpoint\n MACAddress=00155dae1c00\n FormattedMACAddress=00-15-5D-AE-1C-00\n}\ninstance of SCX_LANEndpoint\n{\n InstanceID=virbr0\n Caption=LAN endpoint caption information\n Description=LAN Endpoint description information\n ElementName=virbr0\n [Key] Name=virbr0\n [Key] SystemCreationClassName=SCX_ComputerSystem\n [Key] SystemName=jeffcof64-cent7x-01.scx.com\n [Key] CreationClassName=SCX_LANEndpoint\n MACAddress=525400235dce\n FormattedMACAddress=52-54-00-23-5D-CE\n}\n```\n\n### Enumeration of SCX_LogFile\n\nThe LogFile provider uses a marker file to show differences in log\nfiles between enumerations. Thus, the first enumeration returned no\nmatched rows, but created the marker file. Future enumerations\nreturned the proper results (log file lines since last enumeration).\n\n```\n> /opt/omi/bin/omicli iv root/scx { SCX_LogFile } GetMatchedRows { filename /var/log/cron regexps \".*\" qid myQID } \ninstance of GetMatchedRows\n{\n ReturnValue=0\n rows={}\n}\n\n> crontab -l\n@reboot /home/jeffcof/dev/git/updatedns/updatedns.sh\n*/15 * * * * /home/jeffcof/dev/git/updatedns/updatedns.sh\n2 0 * * 0 /usr/sbin/logrotate --state /home/jeffcof/dev/git/updatedns/.updatedns.logrotatestate /home/jeffcof/dev/git/updatedns/.updatedns.logrotate\n\n> /opt/omi/bin/omicli iv root/scx { SCX_LogFile } GetMatchedRows { filename /var/log/cron regexps \".*\" qid myQID }\ninstance of GetMatchedRows\n{\n ReturnValue=1\n rows={0;Sep 2 09:14:16 jeffcof64-cent7x-01 crontab[2761]: (jeffcof) LIST (jeffcof)}\n}\n```\n\n### Enumeration of SCX_MemoryStatisticalInformation\n\n```\n> /opt/omi/bin/omicli ei root/scx SCx_MemoryStatisticalInformation\ninstance of SCX_MemoryStatisticalInformation\n{\n Caption=Memory information\n Description=Memory usage and performance statistics\n [Key] Name=Memory\n IsAggregate=true\n AvailableMemory=875\n PercentAvailableMemory=64\n UsedMemory=498\n PercentUsedMemory=36\n PercentUsedByCache=0\n PagesPerSec=0\n PagesReadPerSec=0\n PagesWrittenPerSec=0\n AvailableSwap=2038\n PercentAvailableSwap=100\n UsedSwap=9\n PercentUsedSwap=0\n}\n```\n\n### Enumeration of SCX_OperatingSystem\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_OperatingSystem\ninstance of SCX_OperatingSystem\n{\n Caption=CentOS Linux 7.0 (x86_64)\n Description=CentOS Linux 7.0 (x86_64)\n [Key] Name=Linux Distribution\n EnabledState=5\n RequestedState=12\n EnabledDefault=2\n [Key] CSCreationClassName=SCX_ComputerSystem\n [Key] CSName=jeffcof64-cent7x-01.scx.com\n [Key] CreationClassName=SCX_OperatingSystem\n OSType=36\n OtherTypeDescription=3.10.0-327.18.2.el7.x86_64 #1 SMP Thu May 12 11:03:55 UTC 2016 x86_64 \n Version=7.0\n LastBootUpTime=20160819060426.000000+000\n LocalDateTime=20160902092201.014880+000\n CurrentTimeZone=-420\n NumberOfLicensedUsers=0\n NumberOfUsers=5\n NumberOfProcesses=263\n MaxNumberOfProcesses=5633\n TotalSwapSpaceSize=2097148\n TotalVirtualMemorySize=3503828\n FreeVirtualMemory=2983252\n FreePhysicalMemory=896156\n TotalVisibleMemorySize=1406680\n SizeStoredInPagingFiles=2097148\n FreeSpaceInPagingFiles=2087096\n MaxProcessMemorySize=0\n MaxProcessesPerUser=2816\n OperatingSystemCapability=64 bit\n SystemUpTime=2584608\n}\n```\n\n### Enumeration of SCX_ProcessorStatisticalInformation\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_ProcessorStatisticalInformation\ninstance of SCX_ProcessorStatisticalInformation\n{\n Caption=Processor information\n Description=CPU usage statistics\n [Key] Name=0\n IsAggregate=false\n PercentIdleTime=0\n PercentUserTime=0\n PercentNiceTime=0\n PercentPrivilegedTime=0\n PercentInterruptTime=0\n PercentDPCTime=0\n PercentProcessorTime=0\n PercentIOWaitTime=0\n}\ninstance of SCX_ProcessorStatisticalInformation\n{\n Caption=Processor information\n Description=CPU usage statistics\n [Key] Name=1\n IsAggregate=false\n PercentIdleTime=0\n PercentUserTime=0\n PercentNiceTime=0\n PercentPrivilegedTime=0\n PercentInterruptTime=0\n PercentDPCTime=0\n PercentProcessorTime=0\n PercentIOWaitTime=0\n}\ninstance of SCX_ProcessorStatisticalInformation\n{\n Caption=Processor information\n Description=CPU usage statistics\n [Key] Name=_Total\n IsAggregate=true\n PercentIdleTime=0\n PercentUserTime=0\n PercentNiceTime=0\n PercentPrivilegedTime=0\n PercentInterruptTime=0\n PercentDPCTime=0\n PercentProcessorTime=0\n PercentIOWaitTime=0\n}\n```\n\n### Enumeration of SCX_RTProcessorStatisticalInformation\n\n```\n> /opt/omi/bin/omicli ei root/scx SCX_RTProcessorStatisticalInformation\ninstance of SCX_RTProcessorStatisticalInformation\n{\n Caption=Processor information\n Description=CPU usage statistics\n [Key] Name=0\n IsAggregate=false\n PercentIdleTime=0\n PercentUserTime=0\n PercentNiceTime=0\n PercentPrivilegedTime=0\n PercentInterruptTime=0\n PercentDPCTime=0\n PercentProcessorTime=0\n PercentIOWaitTime=0\n}\ninstance of SCX_RTProcessorStatisticalInformation\n{\n Caption=Processor information\n Description=CPU usage statistics\n [Key] Name=1\n IsAggregate=false\n PercentIdleTime=0\n PercentUserTime=0\n PercentNiceTime=0\n PercentPrivilegedTime=0\n PercentInterruptTime=0\n PercentDPCTime=0\n PercentProcessorTime=0\n PercentIOWaitTime=0\n}\ninstance of SCX_RTProcessorStatisticalInformation\n{\n Caption=Processor information\n Description=CPU usage statistics\n [Key] Name=_Total\n IsAggregate=true\n PercentIdleTime=0\n PercentUserTime=0\n PercentNiceTime=0\n PercentPrivilegedTime=0\n PercentInterruptTime=0\n PercentDPCTime=0\n PercentProcessorTime=0\n PercentIOWaitTime=0\n}\n```\n\n### Enumeration of SCX_UnixProcess\n\nRather than enumerating all processes on the system (with **ei**\noption to omicli), this will enumerate one single process for brevity:\n\n```\n> /opt/omi/bin/omicli gi root/scx { SCX_UnixProcess CSCreationClassName SCX_ComputerSystem CSName jeffcof64-cent7x-01.scx.com OSCreationClassName SCX_OperatingSystem OSName \"Linux Distribution\" CreationClassName SCX_UnixProcess Handle 1 } \ninstance of SCX_UnixProcess\n{\n Caption=Unix process information\n Description=A snapshot of a current process\n Name=systemd\n [Key] CSCreationClassName=SCX_ComputerSystem\n [Key] CSName=jeffcof64-cent7x-01.scx.com\n [Key] OSCreationClassName=SCX_OperatingSystem\n [Key] OSName=Linux Distribution\n [Key] CreationClassName=SCX_UnixProcess\n [Key] Handle=1\n Priority=7\n ExecutionState=6\n CreationDate=20160803112512.566494+000\n KernelModeTime=332600\n UserModeTime=376000\n ParentProcessID=0\n RealUserID=0\n ProcessGroupID=1\n ProcessSessionID=1\n ModulePath=/usr/lib/systemd/systemd\n Parameters={/usr/lib/systemd/systemd, --switched-root, --system, --deserialize, 21}\n ProcessNiceValue=20\n ProcessWaitingForEvent=ep_poll\n PercentBusyTime=0\n UsedMemory=9196\n}\n```\n\n### TopResourceConsumers Provider\n\nThe TopResourceConsumers provider (part of SCX_UnixProcess provider)\nwill show the top resource consumers for any of:\n\n- CPUTime\n- BlockReadsPerSecond\n- BlockWritesPerSecond\n- BlockTransfersPerSecond\n- PercentUserTime\n- PercentPrivilegedTime\n- UsedMemory\n- PercentUsedMemory\n- PagesReadPerSec\n\nSince the test system didn't have any CPU load, CPUTime is of little\nvalue:\n\n```\n> /opt/omi/bin/omicli iv root/scx { SCX_UnixProcess } TopResourceConsumers { resource \"CPUTime\" count 5 } \ninstance of TopResourceConsumers\n{\n ReturnValue=\nPID Name CPUTime\n-------------------------------------------------------------\n 1702 master 0\n 1717 qmgr 0\n 1902 dnsmasq 0\n 1903 dnsmasq 0\n 2204 tfprox 0\n\n}\n```\n\nHowever, UsedMemory is somewhat more useful:\n\n```\n> /opt/omi/bin/omicli iv root/scx { SCX_UnixProcess } TopResourceConsumers { resource \"UsedMemory\" count 5 } \ninstance of TopResourceConsumers\n{\n ReturnValue=\nPID Name UsedMemory\n-------------------------------------------------------------\n21951 emacs 50464\n18376 dhclient 15792\n 1069 tuned 13052\n 857 polkitd 10984\n 1073 libvirtd 9864\n\n}\n```\n\n### Enumeration of SCX_UnixProcessStatisticalInformation\n\nRather than enumerating all processes on the system (with **ei**\noption to omicli), this will enumerate one single process for brevity:\n\n```\n> /opt/omi/bin/omicli gi root/scx { SCX_UnixProcessStatisticalInformation name systemd CSCreationClassName SCX_ComputerSystem CSName jeffcof64-cent7x-01.scx.com OSCreationClassName SCX_OperatingSystem OSName \"Linux Distribution\" ProcessCreationClassName SCX_UnixProcessStatisticalInformation Handle 1 }\ninstance of SCX_UnixProcessStatisticalInformation\n{\n Caption=Unix process information\n Description=A snapshot of a current process\n [Key] Name=systemd\n [Key] CSCreationClassName=SCX_ComputerSystem\n [Key] CSName=jeffcof64-cent7x-01.scx.com\n [Key] OSCreationClassName=SCX_OperatingSystem\n [Key] OSName=Linux Distribution\n [Key] Handle=1\n [Key] ProcessCreationClassName=SCX_UnixProcessStatisticalInformation\n CPUTime=0\n VirtualText=1335296\n VirtualData=6676480\n VirtualSharedMemory=3216\n CpuTimeDeadChildren=142223\n SystemTimeDeadChildren=47871\n PercentUserTime=0\n PercentPrivilegedTime=0\n UsedMemory=9196\n PercentUsedMemory=19\n PagesReadPerSec=0\n}\n```\n\n### RunAs Provider: ExecuteCommand\n\nThe `ExecuteComand` RunAs provider will execute any UNIX/Linux native\ncommand:\n\n```\n> /opt/omi/bin/omicli iv root/scx { SCX_OperatingSystem } ExecuteCommand { command /bin/true timeout 0 }\ninstance of ExecuteCommand\n{\n ReturnValue=true\n ReturnCode=0\n StdOut=\n StdErr=\n}\n\n> /opt/omi/bin/omicli iv root/scx { SCX_OperatingSystem } ExecuteCommand { command /bin/false timeout 0 } \ninstance of ExecuteCommand\n{\n ReturnValue=false\n ReturnCode=1\n StdOut=\n StdErr=\n}\n```\n\n### RunAs Provider: ExecuteShellCommand\n\nThe `ExecuteShellCommand` RunAs provider will execute any UNIX/Linux\ncommand using the /bin/sh shell:\n\n```\n> /opt/omi/bin/omicli iv root/scx { SCX_OperatingSystem } ExecuteShellCommand { command 'echo Hello World' timeout 0 } \ninstance of ExecuteShellCommand\n{\n ReturnValue=true\n ReturnCode=0\n StdOut=Hello World\n\n StdErr=\n}\n```\n\n### RunAs Provider: ExecuteScript\n\nThe `ExecuteScript` RunAs provider will execute any UNIX/Linux script\nusing the /bin/sh shell.\n\nUnfortunately, it is difficult to get a multi-line shell script\nentered via the omicli test program (rather than the OMI\nAPI). Fortunately, the `ExecuteScript` provider allows for scripts to\nbe passed via [Base64][] encoding.\n\nThe simple shell script:\n\n```\necho \"\"\necho \"Hello\"\necho \"Goodbye\"\n```\n\nwill yield `ZWNobyAiIg0KZWNobyAiSGVsbG8iDQplY2hvICJHb29kYnllIg==` when\nconverted to [Base64][]. As a result, the following is a simple invocation\nof the `ExecuteScript` RunAs provider:\n\n```\n> /opt/omi/bin/omicli iv root/scx { SCX_OperatingSystem } ExecuteScript { Script \"ZWNobyAiIg0KZWNobyAiSGVsbG8iDQplY2hvICJHb29kYnllIg==\" Arguments \"\" timeout 0 b64encoded \"true\" }\ninstance of ExecuteScript\n{\n ReturnValue=true\n ReturnCode=0\n StdOut=\nHello\nGoodbye\n\n StdErr=\n}\n```\n\n[Base64]: https://en.wikipedia.org/wiki/Base64\n\n## Code of Conduct\n\nThis project has adopted the [Microsoft Open Source Code of Conduct]\n(https://opensource.microsoft.com/codeofconduct/). For more\ninformation see the [Code of Conduct FAQ]\n(https://opensource.microsoft.com/codeofconduct/faq/) or contact\n[[email protected]](mailto:[email protected]) with any\nadditional questions or comments.\n" }, { "alpha_fraction": 0.6141079068183899, "alphanum_fraction": 0.6211133003234863, "avg_line_length": 40.053096771240234, "blob_id": "75c3e56e2dd0884f2da77a689caf35e88fc56b05", "content_id": "c25db85d5f2b38384d06dad85641811cd6d79128", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18557, "license_type": "permissive", "max_line_length": 116, "num_lines": 452, "path": "/test/code/shared/tools/scx_admin/cmdparser_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for configurator functionality which is part of the scx_admin tool\n\n \\date 2008-08-28 13:48\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <cmdparser.h> \n#include <testutils/scxunit.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n\n\nusing namespace SCX_Admin;\n// using namespace SCXCoreLib;\n// using namespace SCXSystemLib;\n\n\nclass CmdParserTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( CmdParserTest );\n CPPUNIT_TEST( testQuiet );\n CPPUNIT_TEST( testLogList );\n CPPUNIT_TEST( testLogRotate );\n CPPUNIT_TEST( testLogReset );\n CPPUNIT_TEST( testLogSet );\n CPPUNIT_TEST( testLogSetProv );\n CPPUNIT_TEST( testLogResetProv );\n CPPUNIT_TEST( testLogRemoveProv );\n#if !defined(SCX_STACK_ONLY)\n CPPUNIT_TEST( testConfigList );\n CPPUNIT_TEST( testConfigSet );\n CPPUNIT_TEST( testConfigReset );\n CPPUNIT_TEST( testProviderNameIsCaseSensitive );\n CPPUNIT_TEST( testProviderParametersPreservesCase );\n#endif\n CPPUNIT_TEST( testStartStop );\n CPPUNIT_TEST( testStatus );\n CPPUNIT_TEST( testProviderService );\n CPPUNIT_TEST( testShowVersion );\n CPPUNIT_TEST( testArgumentIsCaseInsensitive );\n CPPUNIT_TEST( testServiceIsCaseInsensitive );\n CPPUNIT_TEST( testGenericLogLevelIsCaseInsensitive );\n CPPUNIT_TEST( testLogSetProviderArgumentPreservesCase );\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector< Operation > GivenParsedParameters(int argc, const char** argv)\n {\n std::vector< Operation > operations;\n std::wstring error_msg;\n\n CPPUNIT_ASSERT( ParseAllParameters( argc, argv, operations, error_msg ) );\n\n // no error message\n CPPUNIT_ASSERT( error_msg.empty() );\n\n return operations;\n }\n\n std::wstring GivenParseFailure(int argc, const char** argv)\n {\n std::vector< Operation > operations;\n std::wstring error_msg;\n \n CPPUNIT_ASSERT( ! ParseAllParameters( argc, argv, operations, error_msg ) );\n\n return error_msg;\n }\n\n\npublic:\n void setUp(void)\n {\n /* This method will be called once before each test function. */\n }\n\n void tearDown(void)\n {\n /* This method will be called once after each test function. */\n }\n\n typedef const char* PCHAR;\n \n void testQuiet(void)\n {\n PCHAR argv[] = {\"-q\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_GlobalOption_Quiet );\n }\n\n void testLogList()\n {\n PCHAR argv[] = {\"-log-list\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_List);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Default);\n\n PCHAR argv2[] = {\"-log-list\", \"CImoM\"};\n\n operations = GivenParsedParameters(DIM(argv2), argv2);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_List);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_CIMom);\n }\n\n void testLogRotate()\n {\n PCHAR argv[] = {\"-log-rotate\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Rotate);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Default);\n\n PCHAR argv2[] = {\"-log-rotate\", \"provIder\"};\n\n operations = GivenParsedParameters(DIM(argv2), argv2);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Rotate);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Provider);\n }\n\n void testLogReset()\n {\n PCHAR argv[] = {\"-log-reset\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Reset);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Default);\n\n PCHAR argv2[] = {\"-log-reset\", \"alL\"};\n\n operations = GivenParsedParameters(DIM(argv2), argv2);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Reset);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_All);\n }\n \n void testLogSet()\n {\n PCHAR argv[] = {\"-log-set\", \"verbose\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Set);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Default);\n CPPUNIT_ASSERT( operations[0].m_eLogLevel == SCX_AdminLogAPI::eLogLevel_Verbose);\n\n PCHAR argv3[] = {\"-log-set\", \"provider\", \"erroRs\"};\n\n operations = GivenParsedParameters(DIM(argv3), argv3);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Set);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Provider);\n CPPUNIT_ASSERT( operations[0].m_eLogLevel == SCX_AdminLogAPI::eLogLevel_Errors);\n }\n \n void testLogSetProv()\n {\n PCHAR argv[] = {\"-log-set\", \"provider\", \"FILE:/var/opt/microsoft/scx/log/scx.log=TRACE\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Prov_Set);\n CPPUNIT_ASSERT( operations[0].m_strName == L\"FILE:/var/opt/microsoft/scx/log/scx.log\");\n CPPUNIT_ASSERT( operations[0].m_strValue == L\"TRACE\");\n\n PCHAR argv2[] = {\"-log-set\", \"provider\", \"FILE:/var/opt/microsoft/scx/log/scx.log\"};\n\n std::wstring error_msg = GivenParseFailure(DIM(argv2), argv2);\n CPPUNIT_ASSERT( ! error_msg.empty() );\n }\n\n void testLogResetProv()\n {\n PCHAR argv[] = {\"-log-reset\", \"provider\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Reset);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Provider);\n\n PCHAR argv2[] = {\"-log-reset\", \"provider\", \"FILE:/var/opt/microsoft/scx/log/scx.log\"};\n\n operations = GivenParsedParameters(DIM(argv2), argv2);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Prov_Reset);\n CPPUNIT_ASSERT( operations[0].m_strName == L\"FILE:/var/opt/microsoft/scx/log/scx.log\");\n }\n \n void testLogRemoveProv()\n {\n PCHAR argv[] = {\"-log-remove\", \"provider\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Prov_Remove);\n CPPUNIT_ASSERT( operations[0].m_strName == L\"\");\n\n PCHAR argv2[] = {\"-log-remove\", \"provider\", \"STDOUT\"};\n\n operations = GivenParsedParameters(DIM(argv2), argv2);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Log_Prov_Remove);\n CPPUNIT_ASSERT( operations[0].m_strName == L\"STDOUT\");\n }\n \n#if !defined(SCX_STACK_ONLY)\n\n void testConfigList()\n {\n PCHAR argv[] = {\"-config-list\", \"rUnas\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Config_List);\n }\n \n void testConfigSet()\n {\n PCHAR argv[] = {\"-config-set\", \"rUnas\", \"cwd=/opt\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Config_Set);\n CPPUNIT_ASSERT( operations[0].m_strName == L\"cwd\" );\n CPPUNIT_ASSERT( operations[0].m_strValue == L\"/opt\" );\n }\n \n void testConfigReset()\n {\n PCHAR argv[] = {\"-config-reset\", \"rUnas\", \"allowRoot\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Config_Reset);\n CPPUNIT_ASSERT( operations[0].m_strName == L\"allowRoot\" );\n }\n\n /**\n Tests that the provider name (runas) for provider config\n is case insensitive.\n */\n void testProviderNameIsCaseSensitive()\n {\n PCHAR argv[] = {\"-config-list\", \"runas\",\n \"-config-list\", \"RUNAS\",\n \"-config-list\", \"RuNaS\"};\n std::vector<Operation> operations = GivenParsedParameters(DIM(argv), argv);\n // should return three operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), operations.size() );\n for (std::vector<Operation>::const_iterator iter = operations.begin();\n iter != operations.end();\n ++iter)\n {\n CPPUNIT_ASSERT( iter->m_eType == Operation::eOpType_Config_List);\n }\n }\n\n /**\n The cmdparser should not alter the case of the parameters for \n provider configuration. It is up to the speciffic provider\n to descide if the parameter should be case sensitive or not.\n */\n void testProviderParametersPreservesCase()\n {\n PCHAR argv[] = {\"-config-set\", \"runas\", \"SomeParameter=/some/dir/\",\n \"-config-set\", \"runas\", \"someparameter=/Some/Dir/\"};\n std::vector<Operation> operations = GivenParsedParameters(DIM(argv), argv);\n // should return two operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_strName == L\"SomeParameter\" );\n CPPUNIT_ASSERT( operations[0].m_strValue == L\"/some/dir/\" );\n CPPUNIT_ASSERT( operations[1].m_strName == L\"someparameter\" );\n CPPUNIT_ASSERT( operations[1].m_strValue == L\"/Some/Dir/\" );\n }\n\n#endif\n\n void testStartStop()\n {\n PCHAR argv[] = {\"-start\", \"all\"};\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return only one operation\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(1), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Svc_Start);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_All);\n\n PCHAR argv2[] = {\"-stop\", \"-start\" };\n \n operations = GivenParsedParameters(DIM(argv2), argv2);\n // should return two operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Svc_Stop);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Default);\n CPPUNIT_ASSERT( operations[1].m_eType == Operation::eOpType_Svc_Start);\n CPPUNIT_ASSERT( operations[1].m_eComponent == Operation::eCompType_Default);\n }\n\n void testStatus()\n {\n PCHAR argv[] = {\"-status\", \"-status\", \"all\" };\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return three operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Svc_Status);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Default);\n CPPUNIT_ASSERT( operations[1].m_eType == Operation::eOpType_Svc_Status);\n CPPUNIT_ASSERT( operations[1].m_eComponent == Operation::eCompType_All);\n }\n\n void testProviderService()\n {\n PCHAR argv[] = {\"-status\", \"provider\", \"-restart\", \"provider\", \"-start\", \"provider\", \"-stop\", \"provider\"};\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return three operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(4), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Svc_Status);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Provider);\n CPPUNIT_ASSERT( operations[1].m_eType == Operation::eOpType_Svc_Restart);\n CPPUNIT_ASSERT( operations[1].m_eComponent == Operation::eCompType_Provider);\n CPPUNIT_ASSERT( operations[2].m_eType == Operation::eOpType_Svc_Start);\n CPPUNIT_ASSERT( operations[2].m_eComponent == Operation::eCompType_Provider);\n CPPUNIT_ASSERT( operations[3].m_eType == Operation::eOpType_Svc_Stop);\n CPPUNIT_ASSERT( operations[3].m_eComponent == Operation::eCompType_Provider);\n }\n\n void testShowVersion()\n {\n PCHAR argv[] = {\"-version\", \"-v\" };\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return two operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_eType == Operation::eOpType_Show_Version);\n CPPUNIT_ASSERT( operations[0].m_eComponent == Operation::eCompType_Default);\n CPPUNIT_ASSERT( operations[1].m_eType == Operation::eOpType_Show_Version);\n CPPUNIT_ASSERT( operations[1].m_eComponent == Operation::eCompType_Default);\n }\n\n /**\n Tests that the \"-*\" arguemnts like -version and -start are case insensitive.\n */\n void testArgumentIsCaseInsensitive()\n {\n PCHAR argv[] = {\"-VERSION\", \"-V\", \"-version\", \"-v\", \"-VerSIon\" };\n\n std::vector< Operation > operations = GivenParsedParameters(DIM(argv), argv);\n // should return five operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(5), operations.size() );\n for (std::vector<Operation>::const_iterator iter = operations.begin();\n iter != operations.end();\n ++iter)\n {\n CPPUNIT_ASSERT( iter->m_eType == Operation::eOpType_Show_Version);\n }\n }\n\n /**\n Tests that service names (cimom, ...) for service control\n are case insensitive.\n */\n void testServiceIsCaseInsensitive()\n {\n PCHAR argv[] = {\"-start\", \"cimom\", \"-start\", \"CIMOM\", \"-start\", \"CiMoM\"};\n\n std::vector<Operation> operations = GivenParsedParameters(DIM(argv), argv);\n // should return three operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), operations.size() );\n for (std::vector<Operation>::const_iterator iter = operations.begin();\n iter != operations.end();\n ++iter)\n {\n CPPUNIT_ASSERT( iter->m_eComponent == Operation::eCompType_CIMom);\n }\n }\n\n /**\n The log level parameters should be case insensitive.\n */\n void testGenericLogLevelIsCaseInsensitive()\n {\n PCHAR argv[] = {\"-log-set\", \"all\", \"verbose\",\n \"-log-set\", \"all\", \"VERBOSE\",\n \"-log-set\", \"all\", \"VeRbOsE\"};\n\n std::vector<Operation> operations = GivenParsedParameters(DIM(argv), argv);\n // should return three operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(3), operations.size() );\n for (std::vector<Operation>::const_iterator iter = operations.begin();\n iter != operations.end();\n ++iter)\n {\n CPPUNIT_ASSERT( iter->m_eLogLevel == SCX_AdminLogAPI::eLogLevel_Verbose );\n }\n }\n\n /**\n The cmdparser should not alter the case of the parameters for \n log set provider configuration. It is up to the speciffic configurator\n to descide if the parameter should be case sensitive or not.\n */\n void testLogSetProviderArgumentPreservesCase()\n {\n PCHAR argv[] = {\"-log-set\", \"provider\", \"stdout:some.module=info\",\n \"-log-set\", \"provider\", \"STDOUT:sOmE.MoDuLe=INFO\"};\n std::vector<Operation> operations = GivenParsedParameters(DIM(argv), argv);\n // should return two operations\n CPPUNIT_ASSERT_EQUAL( static_cast<size_t>(2), operations.size() );\n CPPUNIT_ASSERT( operations[0].m_strName == L\"stdout:some.module\" );\n CPPUNIT_ASSERT( operations[0].m_strValue == L\"info\" );\n CPPUNIT_ASSERT( operations[1].m_strName == L\"STDOUT:sOmE.MoDuLe\" );\n CPPUNIT_ASSERT( operations[1].m_strValue == L\"INFO\" );\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( CmdParserTest );\n\n" }, { "alpha_fraction": 0.5976803302764893, "alphanum_fraction": 0.6064402461051941, "avg_line_length": 38.06666564941406, "blob_id": "73c62ca80753cd205ff96fe4f92e04422d771b3d", "content_id": "5a69634d87e9d06f2d1462321e417e1742ea6a3c", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 20434, "license_type": "permissive", "max_line_length": 122, "num_lines": 510, "path": "/test/code/providers/appserver_provider/tomcatappserverinstance_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\r\n Copyright (c) Microsoft Corporation. All rights reserved.\r\n\r\n Created date 2011-05-18\r\n\r\n tomcat appserver data colletion test class.\r\n\r\n*/\r\n/*----------------------------------------------------------------------------*/\r\n#include <scxcorelib/scxcmn.h>\r\n#include <scxcorelib/stringaid.h>\r\n#include <scxcorelib/scxfilesystem.h>\r\n#include <testutils/scxunit.h>\r\n#include <scxcorelib/scxprocess.h>\r\n\r\n#include <tomcatappserverinstance.h>\r\n\r\n#include <cppunit/extensions/HelperMacros.h>\r\n\r\nusing namespace SCXCoreLib;\r\nusing namespace SCXSystemLib;\r\nusing namespace std;\r\n\r\n// Test dependencies used to get the XML content from string constants instead of from files\r\n// Also has the ability to control some aspects of the XML to supply, to simulate different problems\r\nclass TomcatAppServerInstanceTestPALDependencies : public TomcatAppServerInstancePALDependencies\r\n{\r\npublic:\r\n\r\n TomcatAppServerInstanceTestPALDependencies() : \r\n m_versionFilename(L\"\"), m_xmlServerFilename(L\"\"), m_noVersionFile(false), m_noVersion(false), \r\n m_noServerFile(false), m_emptyVersionFile(false), m_emptyServerFile(false), m_badXmlServerFile(false),\r\n m_NoProtocol(false), m_IncludeHTTPS(true), m_includeVersionScript(false)\r\n {}\r\n\t\r\n\t// Should the version script file be used when trying to determine version\r\n\tvoid SetIncludeVersionScript(bool includeVersionScript)\r\n\t{\r\n\t\tm_includeVersionScript = includeVersionScript;\r\n\t}\r\n\r\n // Should the we throw an exception when opening the version file\r\n void SetNoVersionFile(bool noVersionFile)\r\n {\r\n m_noVersionFile = noVersionFile;\r\n }\r\n\r\n // Should the version file contain the version string\r\n void SetNoVersion(bool noVersion)\r\n {\r\n m_noVersion = noVersion;\r\n }\r\n\r\n // Should the we throw an exception when opening the server file\r\n void SetNoServerFile(bool noServerFile)\r\n {\r\n m_noServerFile = noServerFile;\r\n }\r\n\r\n // Should the we return an empty string for the content of the version file\r\n void SetEmptyVersionFile(bool emptyVersionFile)\r\n {\r\n m_emptyVersionFile = emptyVersionFile;\r\n }\r\n\r\n // Should the we return an empty string for the content of the server file\r\n void SetEmptyServerFile(bool emptyServerFile)\r\n {\r\n m_emptyServerFile = emptyServerFile;\r\n }\r\n\r\n // Should the we return invalid XML for the content of the server file\r\n void SetBadXmlServerFile(bool badXmlServerFile)\r\n {\r\n m_badXmlServerFile = badXmlServerFile;\r\n }\r\n\r\n // Should the Connector's contain a protocol attribute\r\n void SetNoProtocol(bool noProtocol)\r\n {\r\n m_NoProtocol = noProtocol;\r\n }\r\n\r\n // Should the Service contain a HTTPS connector\r\n void SetIncludeHTTPS(bool includeHTTPS)\r\n {\r\n m_IncludeHTTPS = includeHTTPS;\r\n }\r\n\r\n virtual SCXHandle<std::istream> OpenVersionFile(wstring filename)\r\n {\r\n m_versionFilename = filename;\r\n\r\n SCXHandle<stringstream> filecontent( new stringstream );\r\n\r\n if (m_noVersionFile)\r\n {\r\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\r\n }\r\n\r\n if (m_emptyVersionFile)\r\n {\r\n return filecontent;\r\n }\r\n\r\n *filecontent << \"================================================================================\" << endl;\r\n *filecontent << \" Licensed to the Apache Software Foundation (ASF) under one or more\" << endl;\r\n *filecontent << \" contributor license agreements. See the NOTICE file distributed with\" << endl;\r\n *filecontent << \" this work for additional information regarding copyright ownership.\" << endl;\r\n *filecontent << \" The ASF licenses this file to You under the Apache License, Version 2.0\" << endl;\r\n *filecontent << \" (the \\\"License\\\"); you may not use this file except in compliance with\" << endl;\r\n *filecontent << \" the License. You may obtain a copy of the License at\" << endl;\r\n *filecontent << \"\" << endl;\r\n *filecontent << \" http://www.apache.org/licenses/LICENSE-2.0\" << endl;\r\n *filecontent << \"\" << endl;\r\n *filecontent << \" Unless required by applicable law or agreed to in writing, software\" << endl;\r\n *filecontent << \" distributed under the License is distributed on an \\\"AS IS\\\" BASIS,\" << endl;\r\n *filecontent << \" WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\" << endl;\r\n *filecontent << \" See the License for the specific language governing permissions and\" << endl;\r\n *filecontent << \" limitations under the License.\" << endl;\r\n *filecontent << \"================================================================================\" << endl;\r\n *filecontent << \"\" << endl;\r\n *filecontent << \" $Id: RELEASE-NOTES 786654 2009-06-19 20:25:01Z markt $\" << endl;\r\n *filecontent << \"\" << endl;\r\n *filecontent << \"\" << endl;\r\n\r\n if (!m_noVersion)\r\n {\r\n *filecontent << \" Apache Tomcat Version 6.0.29 \\r\" << endl;\r\n }\r\n\r\n *filecontent << \" Release Notes\" << endl;\r\n *filecontent << \"\" << endl;\r\n *filecontent << \"\" << endl;\r\n *filecontent << \"=============================\" << endl;\r\n *filecontent << \"KNOWN ISSUES IN THIS RELEASE:\" << endl;\r\n *filecontent << \"=============================\" << endl;\r\n *filecontent << \"\" << endl;\r\n *filecontent << \"* Dependency Changes\" << endl;\r\n *filecontent << \"* JNI Based Applications\" << endl;\r\n *filecontent << \"* Bundled APIs\" << endl;\r\n *filecontent << \"* Web application reloading and static fields in shared libraries\" << endl;\r\n *filecontent << \"* Tomcat on Linux\" << endl;\r\n *filecontent << \"* Enabling SSI and CGI Support\" << endl;\r\n\r\n return filecontent;\r\n }\r\n\r\n virtual SCXHandle<std::istream> OpenXmlServerFile(wstring filename)\r\n {\r\n m_xmlServerFilename = filename;\r\n\r\n SCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n if (m_noServerFile)\r\n {\r\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\r\n }\r\n\r\n if (m_emptyServerFile)\r\n {\r\n return xmlcontent;\r\n }\r\n\r\n *xmlcontent << \"<?xml version='1.0' encoding='utf-8'?>\" << endl;\r\n *xmlcontent << \"<Server port=\\\"8005\\\" shutdown=\\\"SHUTDOWN\\\">\" << endl;\r\n *xmlcontent << \" <Listener className=\\\"org.apache.catalina.core.JreMemoryLeakPreventionListener\\\" />\" << endl;\r\n *xmlcontent << \" <Listener className=\\\"org.apache.catalina.mbeans.GlobalResourcesLifecycleListener\\\" />\" << endl;\r\n *xmlcontent << \" <Service name=\\\"Catalina\\\">\" << endl;\r\n *xmlcontent << \" <Connector port=\\\"8011\\\" protocol=\\\"MyProtocol\\\" redirectPort=\\\"8443\\\" />\" << endl;\r\n *xmlcontent << \" <Connector port=\\\"8080\\\" \"<< endl;\r\n if(!m_NoProtocol)\r\n {\r\n *xmlcontent << \" protocol=\\\"HTTP/1.1\\\" \" << endl;\r\n }\r\n *xmlcontent << \" connectionTimeout=\\\"20000\\\" \" << endl;\r\n *xmlcontent << \" redirectPort=\\\"8443\\\" />\" << endl;\r\n\r\n if(m_IncludeHTTPS)\r\n {\r\n *xmlcontent << \" <Connector port=\\\"8443\\\" SSLEnabled=\\\"true\\\"\" << endl;\r\n if(!m_NoProtocol)\r\n {\r\n *xmlcontent << \" protocol=\\\"HTTP/1.1\\\" \" << endl;\r\n }\r\n *xmlcontent << \" maxThreads=\\\"150\\\" scheme=\\\"https\\\" secure=\\\"true\\\"\" << endl;\r\n *xmlcontent << \" clientAuth=\\\"false\\\" sslProtocol=\\\"TLS\\\" />\" << endl;\r\n }\r\n\r\n *xmlcontent << \" <Connector port=\\\"8009\\\" protocol=\\\"AJP/1.3\\\" redirectPort=\\\"8443\\\" />\" << endl;\r\n *xmlcontent << \" <Engine name=\\\"Catalina\\\" defaultHost=\\\"localhost\\\">\" << endl;\r\n *xmlcontent << \" <Realm className=\\\"org.apache.catalina.realm.UserDatabaseRealm\\\"\" << endl;\r\n *xmlcontent << \" resourceName=\\\"UserDatabase\\\"/>\" << endl;\r\n *xmlcontent << \" <Host name=\\\"localhost\\\" appBase=\\\"webapps\\\"\" << endl;\r\n *xmlcontent << \" unpackWARs=\\\"true\\\" autoDeploy=\\\"true\\\"\" << endl;\r\n *xmlcontent << \" xmlValidation=\\\"false\\\" xmlNamespaceAware=\\\"false\\\">\" << endl;\r\n *xmlcontent << \" </Host>\" << endl;\r\n *xmlcontent << \" </Engine>\" << endl;\r\n *xmlcontent << \" </Service>\" << endl;\r\n \r\n if (!m_badXmlServerFile)\r\n {\r\n *xmlcontent << \"</Server>\" << endl;\r\n }\r\n\r\n return xmlcontent;\r\n }\r\n\r\n\tvirtual wstring GetVersionScriptCommand(SCXCoreLib::SCXFilePath filepath)\r\n {\r\n wstring cli;\r\n if(m_includeVersionScript)\r\n {\r\n cli = L\"./testfiles/TomcatVersionCheck.sh\";\r\n }\r\n return cli;\r\n }\r\n\r\n wstring m_versionFilename;\r\n wstring m_xmlServerFilename;\r\n bool m_noVersionFile;\r\n bool m_noVersion;\r\n bool m_noServerFile;\r\n bool m_emptyVersionFile;\r\n bool m_emptyServerFile;\r\n bool m_badXmlServerFile;\r\n bool m_NoProtocol;\r\n bool m_IncludeHTTPS;\r\n\tbool m_includeVersionScript;\r\n};\r\n\r\nclass TomcatAppServerInstance_Test : public CPPUNIT_NS::TestFixture\r\n{\r\n CPPUNIT_TEST_SUITE( TomcatAppServerInstance_Test );\r\n\r\n CPPUNIT_TEST( testAllGood );\r\n CPPUNIT_TEST( testNoVersion );\r\n CPPUNIT_TEST( testNoServerFile );\r\n CPPUNIT_TEST( testNoVersionFile );\r\n CPPUNIT_TEST( testEmptyServerFile );\r\n CPPUNIT_TEST( testEmptyVersionFile );\r\n CPPUNIT_TEST( testBadXmlServerFile );\r\n CPPUNIT_TEST( testAllGoodTomcat5 );\r\n CPPUNIT_TEST( testAllGoodNoHTTPS );\r\n\tCPPUNIT_TEST( testVersionScript );\r\n\r\n CPPUNIT_TEST_SUITE_END();\r\n\r\n public:\r\n\r\n void setUp(void)\r\n {\r\n }\r\n\r\n void tearDown(void)\r\n {\r\n }\r\n\r\n\t// Test to make sure we can retrieve version from version.sh script\r\n\tvoid testVersionScript()\r\n\t{\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n \r\n\t\tdeps->SetNoVersionFile(true);\r\n\t\tdeps->SetIncludeVersionScript(true);\r\n\r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT_EQUAL(L\"id/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL(L\"id/\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"Tomcat\", asInstance->GetType());\r\n\r\n CPPUNIT_ASSERT_EQUAL(L\"8.0.9.0\", asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"8\", asInstance->GetMajorVersion());\r\n\r\n CPPUNIT_ASSERT_EQUAL(L\"8080\", asInstance->GetHttpPort());\r\n CPPUNIT_ASSERT_EQUAL(L\"8443\", asInstance->GetHttpsPort());\r\n\r\n\t}\r\n\r\n // Test with XML not containing the HTTPBinding property, but which do contain the HTTP section\r\n void testAllGood()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n \r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"6.0.29\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"6\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n // Test with XML not containing the section we get the version from \r\n void testNoVersion()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetNoVersion(true);\r\n \r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n // Test with code that throw exception when we try to open the ports file\r\n void testNoServerFile()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetNoServerFile(true);\r\n\r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"6.0.29\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"6\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n // Test with code that throw exception when we try to open the version file\r\n void testNoVersionFile()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetNoVersionFile(true);\r\n\r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n // Test with code that returns an empty string from the ports file\r\n void testEmptyServerFile()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetEmptyServerFile(true);\r\n\r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"6.0.29\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"6\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n // Test with code that returns an empty string from the version file\r\n void testEmptyVersionFile()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetEmptyVersionFile(true);\r\n\r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n // Test with code that returns invalid XML from the ports file\r\n void testBadXmlServerFile()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetBadXmlServerFile(true);\r\n\r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id\", L\"home\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"6.0.29\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"6\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n // Test with XML not containing the protocol attribute for the Connector\r\n // this is the default Tomcat 5 configuration\r\n void testAllGoodTomcat5()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetNoProtocol(true);\r\n\r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"6.0.29\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"6\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n // Test with XML not containing the secure protocol attribute for the Connector\r\n // this is the default Tomcat setting i.e. no HTTPS configured\r\n void testAllGoodNoHTTPS()\r\n {\r\n SCXHandle<TomcatAppServerInstanceTestPALDependencies> deps(new TomcatAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetIncludeHTTPS(false);\r\n \r\n SCXHandle<TomcatAppServerInstance> asInstance( new TomcatAppServerInstance(L\"id/\", L\"home/\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"Tomcat\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"6.0.29\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"6\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_versionFilename == L\"home/RELEASE-NOTES\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/conf/server.xml\");\r\n }\r\n\r\n};\r\n\r\nCPPUNIT_TEST_SUITE_REGISTRATION( TomcatAppServerInstance_Test );\r\n" }, { "alpha_fraction": 0.4749661684036255, "alphanum_fraction": 0.4898511469364166, "avg_line_length": 40.05555725097656, "blob_id": "98e8eb37cecc53c33f26faca2d563348ac636596", "content_id": "6796c3dedf813e33215f4cbad0cdc7aa431f1a1e", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 739, "license_type": "permissive", "max_line_length": 81, "num_lines": 18, "path": "/build/Makefile.gcc4", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#\n# Settings for all POSIX platforms. Each can be overridden in a platform-\n# specific file (Makefile.pf.<platform>, leaving this file to contain defaults.\n#\n#--------------------------------------------------------------------------------\n\ninclude $(SCX_BRD)/build/Makefile.gcc3\nCXX_WARN_STRICT_FLAGS+=-Wextra\nCXX_WARN_FLAGS+=-Wstrict-null-sentinel -Wmissing-include-dirs -Winit-self\n\nifeq ($(PF_DISTRO)$(PF_MAJOR),SUSE11)\n CXX_WARN_FLAGS+=-Wno-ignored-qualifiers \nendif\n" }, { "alpha_fraction": 0.6191064119338989, "alphanum_fraction": 0.651709258556366, "avg_line_length": 51.678863525390625, "blob_id": "a682903e9900b10b68abdf99d64bb951fd25aa5a", "content_id": "844852997ab8cde3213be5a7d30d8f91c3ed072d", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 25918, "license_type": "permissive", "max_line_length": 271, "num_lines": 492, "path": "/test/code/providers/appserver_provider/websphereappserverinstance_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n Created date 2011-05-18\n\n websphere appserver data colletion test class.\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfilesystem.h>\n#include <testutils/scxunit.h>\n\n#include <websphereappserverinstance.h>\n\n#include <cppunit/extensions/HelperMacros.h>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\nusing namespace std;\n\n// Test dependencies used to get the XML content from string constants instead of from files\n// Also has the ability to control some aspects of the XML to supply, to simulate different problems\nclass WebSphereAppServerInstanceTestPALDependencies : public WebSphereAppServerInstancePALDependencies\n{\npublic:\n\n WebSphereAppServerInstanceTestPALDependencies() : \n m_xmlServerFilename(L\"\"), m_noServerFile(false), m_emptyServerFile(false), m_badXmlServerFile(false),\n m_xmlVersionFilename(L\"\"), m_noVersionFile(false), m_emptyVersionFile(false), m_badXmlVersionFile(false),m_version(7)\n {}\n\n // Should the we throw an exception when opening the server file\n void SetNoServerFile(bool noServerFile)\n {\n m_noServerFile = noServerFile;\n }\n\n // Should the we return an empty string for the content of the server file\n void SetEmptyServerFile(bool emptyServerFile)\n {\n m_emptyServerFile = emptyServerFile;\n }\n\n // Should the we return invalid XML for the content of the server file\n void SetBadXmlServerFile(bool badXmlServerFile)\n {\n m_badXmlServerFile = badXmlServerFile;\n }\n\n // Should the we throw an exception when opening the version file\n void SetNoVersionFile(bool noVersionFile)\n {\n m_noVersionFile = noVersionFile;\n }\n\n // Should the we return an empty string for the content of the version file\n void SetEmptyVersionFile(bool emptyVersionFile)\n {\n m_emptyVersionFile = emptyVersionFile;\n }\n \n // If we need specific version - besides 7 - what version file to return\n void SetVersion(int version)\n {\n m_version = version;\n }\n\n // Should the we return invalid XML for the content of the version file\n void SetBadXmlVersionFile(bool badXmlVersionFile)\n {\n m_badXmlVersionFile = badXmlVersionFile;\n }\n\n virtual SCXHandle<std::istream> OpenXmlVersionFile(const wstring& filename)\n {\n m_xmlVersionFilename = filename;\n\n SCXHandle<stringstream> xmlcontent( new stringstream );\n\n if (m_noVersionFile)\n {\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\n }\n\n if (m_emptyVersionFile)\n {\n return xmlcontent;\n }\n\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\n *xmlcontent << \"<profile>\" << endl;\n *xmlcontent << \" <id>default</id>\" << endl;\n *xmlcontent << \" <version>\" << m_version << \".0.0.0</version>\" << endl;\n\n *xmlcontent << \" <build-info date=\\\"8/31/08\\\" level=\\\"r0835.03\\\"/>\" << endl;\n \n if (!m_badXmlVersionFile)\n {\n *xmlcontent << \"</profile>\" << endl;\n }\n\n return xmlcontent;\n }\n\n virtual SCXHandle<std::istream> OpenXmlServerFile(const wstring& filename)\n {\n m_xmlServerFilename = filename;\n\n SCXHandle<stringstream> xmlcontent( new stringstream );\n\n if (m_noServerFile)\n {\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\n }\n\n if (m_emptyServerFile)\n {\n return xmlcontent;\n }\n\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\n *xmlcontent << \" <serverindex:ServerIndex xmi:version=\\\"2.0\\\" xmlns:xmi=\\\"http://www.omg.org/XMI\\\" xmlns:serverindex=\\\"http://www.ibm.com/websphere/appserver/schemas/5.0/serverindex.xmi\\\" xmi:id=\\\"ServerIndex_1\\\" hostName=\\\"SCXOMD-WS7-07.SCX.com\\\">\" << endl;\n *xmlcontent << \" <serverEntries xmi:id=\\\"ServerEntry_1183122129640\\\" serverName=\\\"server1\\\" serverType=\\\"APPLICATION_SERVER\\\">\" << endl;\n *xmlcontent << \" <deployedApplications>WebSphereWSDM.ear/deployments/WebSphereWSDM</deployedApplications>\" << endl;\n *xmlcontent << \" <deployedApplications>isclite.ear/deployments/isclite</deployedApplications>\" << endl;\n *xmlcontent << \" <deployedApplications>DefaultApplication.ear/deployments/DefaultApplication</deployedApplications>\" << endl;\n *xmlcontent << \" <deployedApplications>ivtApp.ear/deployments/ivtApp</deployedApplications>\" << endl;\n *xmlcontent << \" <deployedApplications>query.ear/deployments/query</deployedApplications>\" << endl;\n *xmlcontent << \" <deployedApplications>ibmasyncrsp.ear/deployments/ibmasyncrsp</deployedApplications>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129640\\\" endPointName=\\\"BOOTSTRAP_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129640\\\" host=\\\"SCXOMD-WS7-07.SCX.com\\\" port=\\\"2809\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129641\\\" endPointName=\\\"SOAP_CONNECTOR_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129641\\\" host=\\\"SCXOMD-WS7-07.SCX.com\\\" port=\\\"8880\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129642\\\" endPointName=\\\"ORB_LISTENER_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129642\\\" host=\\\"SCXOMD-WS7-07.SCX.com\\\" port=\\\"9100\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129643\\\" endPointName=\\\"SAS_SSL_SERVERAUTH_LISTENER_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129643\\\" host=\\\"SCXOMD-WS7-07.SCX.com\\\" port=\\\"9401\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129644\\\" endPointName=\\\"CSIV2_SSL_SERVERAUTH_LISTENER_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129644\\\" host=\\\"SCXOMD-WS7-07.SCX.com\\\" port=\\\"9403\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129645\\\" endPointName=\\\"CSIV2_SSL_MUTUALAUTH_LISTENER_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129645\\\" host=\\\"SCXOMD-WS7-07.SCX.com\\\" port=\\\"9402\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129646\\\" endPointName=\\\"WC_adminhost\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129646\\\" host=\\\"*\\\" port=\\\"9060\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129647\\\" endPointName=\\\"WC_defaulthost\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129647\\\" host=\\\"*\\\" port=\\\"9080\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129648\\\" endPointName=\\\"DCS_UNICAST_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129648\\\" host=\\\"*\\\" port=\\\"9353\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129649\\\" endPointName=\\\"WC_adminhost_secure\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129649\\\" host=\\\"*\\\" port=\\\"9043\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129650\\\" endPointName=\\\"WC_defaulthost_secure\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129650\\\" host=\\\"*\\\" port=\\\"9443\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129651\\\" endPointName=\\\"SIP_DEFAULTHOST\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129651\\\" host=\\\"*\\\" port=\\\"5060\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129652\\\" endPointName=\\\"SIP_DEFAULTHOST_SECURE\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129652\\\" host=\\\"*\\\" port=\\\"5061\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129653\\\" endPointName=\\\"SIB_ENDPOINT_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1294703843065\\\" host=\\\"*\\\" port=\\\"7276\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129654\\\" endPointName=\\\"SIB_ENDPOINT_SECURE_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1294703843068\\\" host=\\\"*\\\" port=\\\"7286\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129655\\\" endPointName=\\\"SIB_MQ_ENDPOINT_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1294703843072\\\" host=\\\"*\\\" port=\\\"5558\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129656\\\" endPointName=\\\"SIB_MQ_ENDPOINT_SECURE_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1294703843077\\\" host=\\\"*\\\" port=\\\"5578\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1183122129657\\\" endPointName=\\\"IPC_CONNECTOR_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1183122129657\\\" host=\\\"${LOCALHOST_NAME}\\\" port=\\\"9633\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" </serverEntries>\" << endl;\n *xmlcontent << \" <serverEntries xmi:id=\\\"ServerEntry_1313615896936\\\" serverName=\\\"WebServer1\\\" serverType=\\\"WEB_SERVER\\\">\" << endl;\n *xmlcontent << \" <deployedApplications>query.ear/deployments/query</deployedApplications>\" << endl;\n *xmlcontent << \" <deployedApplications>ivtApp.ear/deployments/ivtApp</deployedApplications>\" << endl;\n *xmlcontent << \" <deployedApplications>DefaultApplication.ear/deployments/DefaultApplication</deployedApplications>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1313615896936\\\" endPointName=\\\"WEBSERVER_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1313615896936\\\" host=\\\"SCXOMD-WS7-07.SCX.com\\\" port=\\\"80\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" <specialEndpoints xmi:id=\\\"NamedEndPoint_1313615896937\\\" endPointName=\\\"WEBSERVER_ADMIN_ADDRESS\\\">\" << endl;\n *xmlcontent << \" <endPoint xmi:id=\\\"EndPoint_1313615896937\\\" host=\\\"SCXOMD-WS7-07.SCX.com\\\" port=\\\"8008\\\"/>\" << endl;\n *xmlcontent << \" </specialEndpoints>\" << endl;\n *xmlcontent << \" </serverEntries>\" << endl;\n \n if (!m_badXmlServerFile)\n {\n *xmlcontent << \"</serverindex:ServerIndex>\" << endl;\n }\n\n return xmlcontent;\n }\n\n wstring m_xmlServerFilename;\n bool m_noServerFile;\n bool m_emptyServerFile;\n bool m_badXmlServerFile;\n wstring m_xmlVersionFilename;\n bool m_noVersionFile;\n bool m_emptyVersionFile;\n bool m_badXmlVersionFile;\n int m_version;\n};\n\nclass WebSphereAppServerInstance_Test : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( WebSphereAppServerInstance_Test );\n\n CPPUNIT_TEST( testAllGood );\n CPPUNIT_TEST( testAllGoodNonDefaultProfiles );\n CPPUNIT_TEST( testNoServerFile );\n CPPUNIT_TEST( testNoVersionFile );\n CPPUNIT_TEST( testEmptyServerFile );\n CPPUNIT_TEST( testEmptyVersionFile );\n CPPUNIT_TEST( testBadXmlServerFile );\n CPPUNIT_TEST( testBadXmlVersionFile );\n CPPUNIT_TEST( testRemovingNetworkDeploymentInstallation );\n\n CPPUNIT_TEST_SUITE_END();\n\n public:\n\n void setUp(void)\n {\n }\n\n void tearDown(void)\n {\n }\n\n // Test with XML not containing the HTTPBinding property, but which do contain the HTTP section\n void testAllGood()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n \n SCXHandle<WebSphereAppServerInstance> asInstance( new WebSphereAppServerInstance(L\"home\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps) );\n\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"profile-cell-node-server1\");\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"home/\");\n CPPUNIT_ASSERT(asInstance->GetProfile() == L\"profile\");\n CPPUNIT_ASSERT(asInstance->GetCell() == L\"cell\");\n CPPUNIT_ASSERT(asInstance->GetNode() == L\"node\");\n CPPUNIT_ASSERT(asInstance->GetServer() == L\"server1\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"WebSphere\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"7.0.0.0\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"7\");\n\n CPPUNIT_ASSERT_EQUAL(\"9080\", StrToMultibyte(asInstance->GetHttpPort()));\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"9443\");\n\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"home/config/cells/cell/nodes/node/serverindex.xml\");\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"home/properties/version/profile.version\");\n }\n\n // Test with non default profiles path for WebSphere 6.1 and WebSphere 7.0\n void testAllGoodNonDefaultProfiles()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n \n SCXHandle<WebSphereAppServerInstance> asInstance( new WebSphereAppServerInstance(L\"/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps) );\n\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"profile-cell-node-server1\");\n CPPUNIT_ASSERT_EQUAL( \"/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/\",StrToMultibyte(asInstance->GetDiskPath()));\n CPPUNIT_ASSERT(asInstance->GetProfile() == L\"profile\");\n CPPUNIT_ASSERT(asInstance->GetCell() == L\"cell\");\n CPPUNIT_ASSERT(asInstance->GetNode() == L\"node\");\n CPPUNIT_ASSERT(asInstance->GetServer() == L\"server1\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"WebSphere\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"7.0.0.0\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"7\");\n\n CPPUNIT_ASSERT_EQUAL(\"9080\", StrToMultibyte(asInstance->GetHttpPort()));\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"9443\");\n\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/config/cells/cell/nodes/node/serverindex.xml\");\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/properties/version/profile.version\");\n }\n\n\n // Test with code that throw exception when we try to open the ports file\n void testNoServerFile()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n \n deps->SetNoServerFile(true);\n\n SCXHandle<WebSphereAppServerInstance> asInstance( new WebSphereAppServerInstance(L\"home\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps) );\n\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"profile-cell-node-server1\");\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"home/\");\n CPPUNIT_ASSERT(asInstance->GetProfile() == L\"profile\");\n CPPUNIT_ASSERT(asInstance->GetCell() == L\"cell\");\n CPPUNIT_ASSERT(asInstance->GetNode() == L\"node\");\n CPPUNIT_ASSERT(asInstance->GetServer() == L\"server1\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"WebSphere\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"7.0.0.0\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"7\");\n\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\n\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"home/config/cells/cell/nodes/node/serverindex.xml\");\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"home/properties/version/profile.version\");\n }\n\n // Test with code that throw exception when we try to open the version file\n void testNoVersionFile()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n \n deps->SetNoVersionFile(true);\n\n SCXHandle<WebSphereAppServerInstance> asInstance( new WebSphereAppServerInstance(L\"home\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps) );\n\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"profile-cell-node-server1\");\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"home/\");\n CPPUNIT_ASSERT(asInstance->GetProfile() == L\"profile\");\n CPPUNIT_ASSERT(asInstance->GetCell() == L\"cell\");\n CPPUNIT_ASSERT(asInstance->GetNode() == L\"node\");\n CPPUNIT_ASSERT(asInstance->GetServer() == L\"server1\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"WebSphere\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\n\n CPPUNIT_ASSERT_EQUAL(\"9080\", StrToMultibyte(asInstance->GetHttpPort()));\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"9443\");\n\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"home/config/cells/cell/nodes/node/serverindex.xml\");\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"home/properties/version/profile.version\");\n }\n\n // Test with code that returns an empty string from the ports file\n void testEmptyServerFile()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n \n deps->SetEmptyServerFile(true);\n\n SCXHandle<WebSphereAppServerInstance> asInstance( new WebSphereAppServerInstance(L\"home\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps) );\n\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"profile-cell-node-server1\");\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"home/\");\n CPPUNIT_ASSERT(asInstance->GetProfile() == L\"profile\");\n CPPUNIT_ASSERT(asInstance->GetCell() == L\"cell\");\n CPPUNIT_ASSERT(asInstance->GetNode() == L\"node\");\n CPPUNIT_ASSERT(asInstance->GetServer() == L\"server1\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"WebSphere\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"7.0.0.0\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"7\");\n\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\n\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"home/config/cells/cell/nodes/node/serverindex.xml\");\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"home/properties/version/profile.version\");\n }\n\n // Test with code that returns an empty string from the version file\n void testEmptyVersionFile()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n \n deps->SetEmptyVersionFile(true);\n\n SCXHandle<WebSphereAppServerInstance> asInstance( new WebSphereAppServerInstance(L\"home\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps) );\n\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"profile-cell-node-server1\");\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"home/\");\n CPPUNIT_ASSERT(asInstance->GetProfile() == L\"profile\");\n CPPUNIT_ASSERT(asInstance->GetCell() == L\"cell\");\n CPPUNIT_ASSERT(asInstance->GetNode() == L\"node\");\n CPPUNIT_ASSERT(asInstance->GetServer() == L\"server1\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"WebSphere\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\n\n CPPUNIT_ASSERT_EQUAL(\"9080\", StrToMultibyte(asInstance->GetHttpPort()));\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"9443\");\n\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"home/config/cells/cell/nodes/node/serverindex.xml\");\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"home/properties/version/profile.version\");\n }\n\n // Test with code that returns invalid XML from the ports file\n void testBadXmlServerFile()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n \n deps->SetBadXmlServerFile(true);\n\n SCXHandle<WebSphereAppServerInstance> asInstance( new WebSphereAppServerInstance(L\"home\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps) );\n\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"profile-cell-node-server1\");\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"home/\");\n CPPUNIT_ASSERT(asInstance->GetProfile() == L\"profile\");\n CPPUNIT_ASSERT(asInstance->GetCell() == L\"cell\");\n CPPUNIT_ASSERT(asInstance->GetNode() == L\"node\");\n CPPUNIT_ASSERT(asInstance->GetServer() == L\"server1\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"WebSphere\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"7.0.0.0\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"7\");\n\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\n\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"home/config/cells/cell/nodes/node/serverindex.xml\");\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"home/properties/version/profile.version\");\n }\n\n // Test with code that returns invalid XML from the version file\n void testBadXmlVersionFile()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n \n deps->SetBadXmlVersionFile(true);\n\n SCXHandle<WebSphereAppServerInstance> asInstance( new WebSphereAppServerInstance(L\"home\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps) );\n\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"profile-cell-node-server1\");\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"home/\");\n CPPUNIT_ASSERT(asInstance->GetProfile() == L\"profile\");\n CPPUNIT_ASSERT(asInstance->GetCell() == L\"cell\");\n CPPUNIT_ASSERT(asInstance->GetNode() == L\"node\");\n CPPUNIT_ASSERT(asInstance->GetServer() == L\"server1\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"WebSphere\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\n\n CPPUNIT_ASSERT_EQUAL(\"9080\", StrToMultibyte(asInstance->GetHttpPort()));\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"9443\");\n\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"home/config/cells/cell/nodes/node/serverindex.xml\");\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"home/properties/version/profile.version\");\n }\n\n // Test removing non existent WebSphere Application Server with greater logic than checking profile.version\n // This change is neccessary for WebSphere Network Deployment configurations\n void testRemovingNetworkDeploymentInstallation()\n {\n SCXHandle<WebSphereAppServerInstanceTestPALDependencies> deps(new WebSphereAppServerInstanceTestPALDependencies());\n\n // Set WebSphere version to 8\n deps->SetVersion(8);\n\n // Create good instance with proper server directory\n // Note: Makefile.tests, as part of setup, creates directory\n // structure under $(TARGET_DIR)/testfiles.\n SCXHandle<WebSphereAppServerInstance> asInstance(new WebSphereAppServerInstance(L\"testfiles/websphere_networkdeployment/profiles/profile1/servers/server1\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps));\n asInstance->Update();\n CPPUNIT_ASSERT_EQUAL(L\"8.0.0.0\", asInstance->GetVersion());\n \n // Create bad instance with incorrect server directory\n SCXHandle<WebSphereAppServerInstance> asInstance2(new WebSphereAppServerInstance(L\"../../test/code/shared/testutils/websphere_badnetworkdeployment/profiles/profile1/\", L\"cell\", L\"node\", L\"profile\", L\"server1\", deps));\n asInstance2->Update();\n CPPUNIT_ASSERT_EQUAL(L\"8.0.0.0\", asInstance2->GetVersion());\n\n CPPUNIT_ASSERT_EQUAL(true, asInstance->IsStillInstalled());\n CPPUNIT_ASSERT_EQUAL(false, asInstance2->IsStillInstalled());\n\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( WebSphereAppServerInstance_Test );\n" }, { "alpha_fraction": 0.5392781496047974, "alphanum_fraction": 0.549186110496521, "avg_line_length": 26.705883026123047, "blob_id": "3ef3207445e895a09626f577b6bcfdd8da646a69", "content_id": "882da3b344bc5fe116ee86e96383d2ab4bbe7a82", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4239, "license_type": "permissive", "max_line_length": 100, "num_lines": 153, "path": "/source/code/shared/tools/omi_preexec/omi_preexec.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief Operations Manager pre-execution program (used by OMI)\n\n \\date 06-20-2014\n\n\n \\note This code (originally developed by Microsoft and inserted into\n OpenPegasus) was lifted from Pegasus to put into OMI, then\n lifted from prior versions of OMI to put into this stand-alone\n program.\n*/\n\n#include <scxcorelib/strerror.h>\n\n#include <errno.h>\n#include <iostream>\n#include <pwd.h>\n#include <stdlib.h>\n#include <string.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <unistd.h>\n\nconst static bool g_bDebug = false;\n\nstatic int _createDir(\n std::string baseDir,\n uid_t uid,\n gid_t gid)\n{\n struct passwd pwbuf;\n char buf[1024];\n struct passwd* pw = NULL;\n\n#if defined(sun)\n if ((pw = getpwuid_r(uid, &pwbuf, buf, sizeof(buf))) == NULL)\n#else\n if (getpwuid_r(uid, &pwbuf, buf, sizeof(buf), &pw) != 0 || !pw)\n#endif\n {\n std::cerr << \"Error executing getpwuid_r: errno=\" << errno << std::endl;\n return errno;\n }\n\n // Try to create a new subdir from the user name\n std::string dirName = baseDir;\n dirName += pw->pw_name;\n\n if (mkdir(dirName.c_str(), 0700) == 0)\n {\n // Try to change ownership of the new subdir\n if (chown(dirName.c_str(), uid, gid) == 0)\n {\n if (g_bDebug)\n {\n std::cout << \"Created directory: \" << dirName.c_str() << std::endl;\n }\n }\n else\n {\n int saved_errno = errno;\n std::cerr << \"Failed to change owner for directory \" << dirName.c_str()\n << \", errno=\" << saved_errno\n << \" (\" << SCXCoreLib::strerror(saved_errno) << \")\" << std::endl;\n return saved_errno;\n }\n }\n else\n {\n // If creation of dir failed, only log if the failure was not that it \n // already existed\n if (errno != EEXIST)\n {\n int saved_errno = errno;\n std::cerr << \"Failed to create directory \" << dirName.c_str()\n << \", errno=\" << saved_errno \n << \" (\" << SCXCoreLib::strerror(saved_errno) << \")\" << std::endl;\n return saved_errno;\n }\n }\n\n return 0;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n main function.\n\n \\param argc size of \\a argv[]\n \\param argv array of string pointers from the command line.\n \\returns 0 on success, otherwise, 1 on error.\n\n Usage: omi_preexec full-path user-id group-id\n\n Specifically, we expect argc==4 with the following arguments set:\n\n argv[0]=<FULLPROGRAMPATH>\n argv[1]=<FULLPROGRAMPATH>\n argv[2]=<UID>\n argv[3]=<GID>\n\n Result Code\n \\n -1 an exception has occured\n \\n 0 success\n \\n >1 an error occured while executing the command.\n\n Specifically, this program is executed by OMI whenever a non-privileged user\n is executing a provider (just the first time for that UID/GID combination).\n However, we will be called once for that combination UID/GID each time the\n OMI server is started.\n\n This program will create subdirectories necessary for proper OM execution\n (primarily for log/state files).\n\n*/\n\nint main(int argc, char *argv[])\n{\n char *endptr;\n if (argc != 3)\n {\n std::cerr << \"Invalid number of parameters: \" << argc << std::endl;\n return 1;\n }\n\n int uid = (int) strtol( argv[1], &endptr, 10 );\n int gid = (int) strtol( argv[2], &endptr, 10 );\n\n // If spawning a non-root process, create subdir for scx log & persist \n // with new uid as owner, if not already existing, so that we have \n // somewhere that this subprocess have permission to write to.\n if (uid != 0)\n {\n int rc;\n\n if (0 != (rc = _createDir(\"/var/opt/microsoft/scx/lib/state/\", uid, gid)))\n {\n return rc;\n }\n\n if (0 != (rc = _createDir(\"/var/opt/microsoft/scx/log/\", uid, gid)))\n {\n return rc;\n }\n }\n\n return 0;\n}\n" }, { "alpha_fraction": 0.6044013500213623, "alphanum_fraction": 0.6078071594238281, "avg_line_length": 40.94505310058594, "blob_id": "dd32c817a6d819054f33456d9903822f42b95b56", "content_id": "c838ac8189ce2209fc2bc9de95427fc4e3b382f7", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3817, "license_type": "permissive", "max_line_length": 169, "num_lines": 91, "path": "/source/code/providers/support/appserver/appserverenumeration.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file appserverenumeration.h\n\n \\brief Enumeration of application servers\n\n \\date 11-05-18 12:00:00\n\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef APPSERVERENUMERATION_H\n#define APPSERVERENUMERATION_H\n\n#include <vector>\n\n#include <scxsystemlib/entityenumeration.h>\n#include <scxsystemlib/processenumeration.h>\n#include \"appserverinstance.h\"\n#include <scxcorelib/scxlog.h>\n\nnamespace SCXSystemLib\n{\n\n const static std::wstring PATH_SEPERATOR = L\":\";\n const static std::string WEBSPHERE_RUNTIME_CLASS = \"com.ibm.ws.runtime.WsServer\";\n const static std::wstring JBOSS_RUN_JAR = L\"/bin/run.jar\";\n /*----------------------------------------------------------------------------*/\n /**\n Class representing all external dependencies from the AppServer PAL.\n\n */\n class AppServerPALDependencies\n {\n public:\n virtual ~AppServerPALDependencies() {};\n virtual std::vector<SCXCoreLib::SCXHandle<ProcessInstance> > Find(const std::wstring& name);\n virtual bool GetParameters(SCXCoreLib::SCXHandle<ProcessInstance> inst, std::vector<std::string>& params);\n virtual void GetWeblogicInstances(vector<wstring> weblogicProcesses, vector<SCXCoreLib::SCXHandle<AppServerInstance> >& newInst);\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Class that represents a colletion of application servers.\n\n PAL Holding collection of application servers.\n\n */\n class AppServerEnumeration : public EntityEnumeration<AppServerInstance>\n {\n public:\n explicit AppServerEnumeration(SCXCoreLib::SCXHandle<AppServerPALDependencies> = SCXCoreLib::SCXHandle<AppServerPALDependencies>(new AppServerPALDependencies()));\n virtual ~AppServerEnumeration();\n virtual void Init();\n virtual void Update(bool updateInstances=true);\n virtual void UpdateInstances();\n virtual void CleanUp();\n \n protected:\n /*\n * De-serialize instances from disk\n */\n virtual void ReadInstancesFromDisk();\n\n /*\n * Serialize instances to disk\n */\n virtual void WriteInstancesToDisk();\n\n private:\n SCXCoreLib::SCXHandle<AppServerPALDependencies> m_deps; //!< Collects external dependencies of this class.\n SCXCoreLib::SCXLogHandle m_log; //!< Log handle.\n bool CheckProcessCmdLineArgExists(std::vector<std::string>& params, const std::string& value);\n std::string ParseOutCommandLineArg(std::vector<std::string>& params, \n const std::string& key,\n const bool EqualsDelimited,\n const bool SpaceDelimited ) const;\n std::wstring GetJBossPathFromClassPath(const std::wstring& classpath) const;\n int GetArgNumber(vector<string>& params, const string& value); \n void CreateTomcatInstance(vector<SCXCoreLib::SCXHandle<AppServerInstance> > *ASInstances, vector<string> params);\n void CreateJBossInstance(vector<SCXCoreLib::SCXHandle<AppServerInstance> > *ASInstances, vector<string> params);\n std::wstring GetWeblogicHome(vector<string> params);\n string GetParentDirectory(const string& directoryPath,int levels=1);\n void CreateWebSphereInstance(vector<SCXCoreLib::SCXHandle<AppServerInstance> > *ASInstances, vector<string> params); \n };\n\n}\n\n#endif /* APPSERVERENUMERATION_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5255230665206909, "alphanum_fraction": 0.5288130640983582, "avg_line_length": 29.776899337768555, "blob_id": "cf9eb42e1108443c906c588fba4b27933980c287", "content_id": "7dc3c91ec3e9eb341ff4351408a86954478e0c18", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 19453, "license_type": "permissive", "max_line_length": 144, "num_lines": 632, "path": "/source/code/shared/tools/scx_admin/scx_admin.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief scx configuration tool for SCX.\n\n \\date 8/22/2008\n\n*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxlogpolicy.h>\n\n\n#include <iostream>\n\n#include \"admin_api.h\"\n#include \"buildversion.h\"\n#include \"cimconfigurator.h\"\n#include \"cmdparser.h\"\n#include \"logconfigurator.h\"\n#if !defined(SCX_STACK_ONLY)\n#include \"runasadminprovider.h\"\n#endif\n#include \"servicecontrol.h\"\n\nusing namespace SCX_Admin;\nusing namespace SCXCoreLib;\nusing namespace std;\n\n// Global Data\nstatic SCX_LogConfigurator g_oLogConfigurator; ///< scx core log configurator\nstatic SCX_CimConfigurator g_oCIMConfigurator; ///< open-pegasus configurator\nstatic bool g_bQuiet = false; ///< global option: quiet mode\n\nstatic void usage(const char * name, int exitValue);\nstatic void show_version();\nstatic void ListHandler( const char * name, const Operation& params );\nstatic void LogRotateHandler( const char * name, const Operation& params );\nstatic void LogResetHandler( const char * name, const Operation& params );\nstatic void LogSetHandler( const char * name, const Operation& params );\nstatic void LogProviderReset( const Operation& params );\nstatic void LogProviderSet( const Operation& params );\nstatic void LogProviderRemove( const Operation& params );\nstatic vector<SCX_AdminLogAPI*> GetLogConfigurators( Operation::enumComponentType eComponent );\n\n#if !defined(SCX_STACK_ONLY)\nstatic void ListConfig();\nstatic void SetConfig( const Operation& params );\nstatic void ResetConfig( const Operation& params );\n#endif\n\nstatic void SvcManagement( const Operation& params );\n\n/*----------------------------------------------------------------------------*/\n/**\n Log policy specific to scxadmin with its own config file name and default log file name\n*/\nclass SCXAdminLogPolicy : public SCXLogPolicy\n{\npublic:\n /**\n Virtual destructor.\n */\n virtual ~SCXAdminLogPolicy() {}\n\n /**\n Get the path of the log config file.\n \\returns the path of the log config file.\n */\n virtual SCXFilePath GetConfigFileName() const\n {\n#if defined(WIN32)\n return SCXFilePath(L\"C:\\\\scxadminlog.conf\");\n#elif defined(SCX_UNIX)\n return SCXFilePath(L\"/etc/opt/microsoft/scx/conf/scxadminlog.conf\");\n#endif\n }\n\n /**\n If no config is specified, then log output will be written\n to the file specified by this method.\n \\returns Path to the default log file.\n */\n virtual SCXFilePath GetDefaultLogFileName() const\n {\n#if defined(WIN32)\n return SCXFilePath(L\"C:\\\\scxadmin.log\");\n#elif defined(SCX_UNIX)\n return SCXFilePath(L\"/var/opt/microsoft/scx/log/scxadmin.log\");\n#endif\n }\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n Log policy factory for scxadmin.\n\n \\returns The log policy object.\n*/\nSCXCoreLib::SCXHandle<SCXCoreLib::SCXLogPolicy> CustomLogPolicyFactory()\n{\n return SCXHandle<SCXLogPolicy>(new SCXAdminLogPolicy());\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n scx_admin(main) function.\n\n \\param argc size of \\a argv[]\n \\param argv array of string pointers from the command line.\n \\returns 0 on success, otherwise, 1 on error.\n\n Usage: \n Result Code\n \\n 0 success\n \\n >1 an error occured while executing the command.\n\n*/\nint scx_admin(int argc, const char *argv[])\n{\n bool bOverrideStatus = false;\n\n // If no arguments, show usage help.\n if(1 == argc)\n {\n usage(argv[0], 0);\n }\n\n std::vector< Operation > operations;\n std::wstring error_msg;\n\n // should be ok to parse \n if ( !ParseAllParameters( argc-1, argv+1, operations, error_msg ) ){\n wcout << error_msg << L\"\\n\";\n usage(argv[0], 1);\n }\n\n for ( unsigned int i = 0; i < operations.size(); i++ ){\n switch ( operations[i].m_eType ) {\n default:\n case Operation::eOpType_Unknown:\n wcout << L\"not supported yet...\\n\";\n return 1;\n\n case Operation::eOpType_Svc_Restart:\n case Operation::eOpType_Svc_Start:\n case Operation::eOpType_Svc_Stop:\n SvcManagement( operations[i] );\n break;\n\n case Operation::eOpType_Svc_Status:\n SvcManagement( operations[i] );\n bOverrideStatus = true;\n break;\n\n#if !defined(SCX_STACK_ONLY)\n\n case Operation::eOpType_Config_List:\n ListConfig();\n break;\n \n case Operation::eOpType_Config_Set:\n SetConfig( operations[i] );\n break;\n \n case Operation::eOpType_Config_Reset:\n ResetConfig( operations[i] );\n break;\n\n#endif\n \n case Operation::eOpType_Log_Prov_Reset:\n LogProviderReset( operations[i] );\n break;\n case Operation::eOpType_Log_Prov_Set:\n LogProviderSet( operations[i] );\n break;\n case Operation::eOpType_Log_Prov_Remove:\n LogProviderRemove( operations[i] );\n break;\n \n case Operation::eOpType_Global_Usage:\n usage(argv[0], 0);\n break;\n \n case Operation::eOpType_GlobalOption_Quiet:\n g_bQuiet = true;\n break;\n \n case Operation::eOpType_Log_List:\n ListHandler(argv[0], operations[i] );\n break;\n \n case Operation::eOpType_Log_Rotate:\n LogRotateHandler(argv[0], operations[i] );\n break;\n \n case Operation::eOpType_Log_Reset:\n LogResetHandler(argv[0], operations[i] );\n break;\n \n case Operation::eOpType_Log_Set:\n LogSetHandler(argv[0], operations[i] );\n break;\n\n case Operation::eOpType_Show_Version:\n show_version();\n break;\n }\n }\n\n // If we're supposed to override status with state if cimom, do so\n if (bOverrideStatus)\n {\n static SCX_CimomServiceControl s_CIM;\n return (0 == s_CIM.CountProcessesAlive());\n }\n\n return 0;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Output a usage message.\n \n \\param name Application name (derived from argv[0]).\n \\param exitValue Value to return after writing the usage message.\n \\return Does not return.\n*/\nstatic void usage(char const * const name, int exitValue)\n{\n (void) name;\n\n /*\n * We can't dump 'name' anymore since it will contain a . since it's now hidden\n * (scxadmin is now staged as hidden since we have a helper script to launch it)\n */\n\n if ( !g_bQuiet) wcout << L\"Usage: scxadmin\" << L\"\\n\" <<\n \"Generic options (for all commands)\\n\" <<\n \" [-quiet]\\tSet quiet mode (no output)\\n\" <<\n \"\\n\" <<\n \"\\tGeneral Options\\n\" <<\n \"scxadmin -version\\n\" <<\n \"\\n\" <<\n \"\\tService Management\\n\" <<\n \"scxadmin {-start|-stop|-restart|-status} [all|cimom|provider]\\n\" <<\n \"\\n\" <<\n#if !defined(SCX_STACK_ONLY)\n \"\\tProviders Management\\n\" <<\n \"scxadmin -config-list {RunAs} \\n\" <<\n \"scxadmin -config-set {RunAs} {CWD=<directory>|ChRootPath=<directory>|AllowRoot={true|false}}\\n\" <<\n \"scxadmin -config-reset {RunAs} [CWD|ChRootPath|AllowRoot]\\n\" <<\n \"\\n\" <<\n#endif\n \"\\tLog Configuration Management\\n\" <<\n \"scxadmin {-log-list|-log-rotate|-log-reset} [all|cimom|provider]\\n\" <<\n \"scxadmin -log-set [all|cimom|provider] {verbose|intermediate|errors}\\n\" <<\n \"scxadmin -log-set provider {{FILE:<path>|STDOUT}:<module-id>={SUPPRESS|ERROR|WARNING|INFO|TRACE|HYSTERICAL}}\\n\" <<\n \"scxadmin {-log-reset|-log-remove} provider [{FILE:<path>|STDOUT}]\\n\" <<\n \"\\n\";\n\n exit(exitValue);\n} \n\n/*----------------------------------------------------------------------------*/\n/**\n Output the version string\n*/\nstatic void show_version()\n{\n if ( !g_bQuiet)\n {\n wcout << L\"Version: \" << SCX_BUILDVERSION_MAJOR << L\".\" << SCX_BUILDVERSION_MINOR\n << L\".\" << SCX_BUILDVERSION_PATCH << L\"-\" << SCX_BUILDVERSION_BUILDNR\n << L\" (\" << SCX_BUILDVERSION_STATUS << L\" - \" << SCX_BUILDVERSION_DATE << \"L)\\n\";\n }\n\n return;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-log-list\" operation\n \\param params - current operation with detailed parameters\n*/ \nstatic void ListHandler( const char * , const Operation& params )\n{\n vector<SCX_AdminLogAPI*> logConfigs = GetLogConfigurators( params.m_eComponent );\n std::wostringstream buf;\n \n // print all entries\n for ( unsigned int i = 0; i < logConfigs.size(); i++ ){\n try {\n if ( !logConfigs[i]->Print( buf ) && logConfigs.size() == 1 ){\n if ( !g_bQuiet) wcout << L\"operation is not supported\\n\";\n exit(1);\n }\n } catch ( SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n buf << L\"\\n\";\n }\n\n if ( !g_bQuiet) wcout << buf.str() << L\"\\n\";\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-log-rotate\" operation\n \\param params - current operation with detailed parameters\n*/ \nstatic void LogRotateHandler( const char * , const Operation& params )\n{\n vector<SCX_AdminLogAPI*> logConfigs = GetLogConfigurators( params.m_eComponent );\n \n // print all/selected entries\n for ( unsigned int i = 0; i < logConfigs.size(); i++ ){\n try {\n if ( !logConfigs[i]->LogRotate() && logConfigs.size() == 1 ){\n if ( !g_bQuiet) wcout << L\"operation is not supported\\n\";\n exit(1);\n }\n } catch (SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-log-reset\" operation\n \\param params - current operation with detailed parameters\n*/ \nstatic void LogResetHandler( const char * , const Operation& params )\n{\n vector<SCX_AdminLogAPI*> logConfigs = GetLogConfigurators( params.m_eComponent );\n \n // reset log-level for all/selected entries\n for ( unsigned int i = 0; i < logConfigs.size(); i++ ){\n try {\n if ( !logConfigs[i]->Reset() && logConfigs.size() == 1 ){\n if ( !g_bQuiet) wcout << L\"operation is not supported\\n\";\n exit(1);\n }\n } catch (SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-log-set\" operation\n \\param params - current operation with detailed parameters\n*/ \nstatic void LogSetHandler( const char * , const Operation& params )\n{\n vector<SCX_AdminLogAPI*> logConfigs = GetLogConfigurators( params.m_eComponent );\n \n // set log-level for all/selected entries\n for ( unsigned int i = 0; i < logConfigs.size(); i++ ){\n try {\n if ( !logConfigs[i]->Set(params.m_eLogLevel) && logConfigs.size() == 1 ){\n if ( !g_bQuiet) wcout << L\"operation is not supported\\n\";\n exit(1);\n }\n } catch (SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-log-reset provider\" operation (provider specific)\n \\param params - current operation with detailed parameters\n*/ \nstatic void LogProviderReset( const Operation& params )\n{\n try {\n g_oLogConfigurator.Reset(params.m_strName);\n } catch (SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-log-set provider\" operation (provider specific)\n \\param params - current operation with detailed parameters\n*/ \nstatic void LogProviderSet( const Operation& params )\n{\n try {\n g_oLogConfigurator.Set(params.m_strName, params.m_strValue);\n } catch (SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n \n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-log-remove provider\" operation (provider specific)\n \\param params - current operation with detailed parameters\n*/ \nstatic void LogProviderRemove( const Operation& params )\n{\n try {\n g_oLogConfigurator.Remove(params.m_strName);\n } catch (SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n helper function that returns array of logs based on the scope of operation\n \\param eComponent - required component\n \\returns array of log configurator\n \n*/ \nstatic vector<SCX_AdminLogAPI*> GetLogConfigurators( Operation::enumComponentType eComponent )\n{\n vector<SCX_AdminLogAPI*> res;\n\n switch ( eComponent ){\n case Operation::eCompType_All:\n case Operation::eCompType_Default:\n res.push_back( &g_oCIMConfigurator );\n res.push_back( &g_oLogConfigurator );\n break;\n\n case Operation::eCompType_CIMom:\n res.push_back( &g_oCIMConfigurator );\n break;\n \n case Operation::eCompType_Provider:\n res.push_back( &g_oLogConfigurator );\n break;\n\n case Operation::eCompType_Unknown:\n break;\n \n }\n\n return res;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n helper function that returns array of service managers based on the scope of operation\n \\param eComponent - required component\n \\param eOperation - performed operation\n \\returns array of services\n \n*/ \nstatic vector<SCX_AdminServiceManagementAPI*> GetSvcManagers( Operation::enumComponentType eComponent, Operation::enumOperationType eOperation )\n{\n vector<SCX_AdminServiceManagementAPI*> res;\n static SCX_CimomServiceControl s_CIM;\n static SCX_ProviderServiceControl s_Provider;\n\n switch ( eComponent ){\n case Operation::eCompType_All:\n case Operation::eCompType_Default:\n res.push_back( &s_CIM );\n if (eOperation == Operation::eOpType_Svc_Status) {\n res.push_back( &s_Provider );\n }\n break;\n\n case Operation::eCompType_CIMom:\n res.push_back( &s_CIM );\n break;\n \n case Operation::eCompType_Provider:\n res.push_back( &s_Provider );\n break;\n\n case Operation::eCompType_Unknown:\n break;\n \n }\n\n return res;\n}\n\n#if !defined(SCX_STACK_ONLY)\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-config-list\" operation\n*/ \nvoid ListConfig()\n{\n SCX_RunAsAdminProvider oCfg;\n\n std::wostringstream buf;\n \n try {\n if ( !oCfg.Print( buf ) ){\n if ( !g_bQuiet) wcout << L\"operation is not supported\\n\";\n exit(1);\n }\n } catch ( SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n buf << L\"\\n\";\n\n if ( !g_bQuiet) wcout << buf.str() << L\"\\n\";\n \n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-config-set\" operation\n \\param params - current operation with detailed parameters\n*/ \nstatic void SetConfig( const Operation& params )\n{\n SCX_RunAsAdminProvider oCfg;\n\n try {\n if ( !oCfg.Set( params.m_strName, params.m_strValue ) ){\n if ( !g_bQuiet) wcout << L\"operation is not supported\\n\";\n exit(1);\n }\n } catch ( SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n if ( !g_bQuiet) wcout << L\"Remember to restart cimom for changes to take effect\" << std::endl;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler \"-config-reset\" operation\n \\param params - current operation with detailed parameters\n*/ \nstatic void ResetConfig( const Operation& params )\n{\n SCX_RunAsAdminProvider oCfg;\n\n try {\n if ( !oCfg.Reset( params.m_strName ) ){\n if ( !g_bQuiet) wcout << L\"operation is not supported\\n\";\n exit(1);\n }\n } catch ( SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n exit(1);\n }\n if ( !g_bQuiet) wcout << L\"Remember to restart cimom for changes to take effect\" << std::endl;\n}\n\n#endif\n\n/*----------------------------------------------------------------------------*/\n/**\n Handler for service management operations:\n -status, -start, -stop, -restart\n \\param params - current operation with detailed parameters\n*/ \nstatic void SvcManagement( const Operation& params )\n{\n vector<SCX_AdminServiceManagementAPI*> mgrs = GetSvcManagers( params.m_eComponent, params.m_eType );\n\n // print all/selected entries\n for ( unsigned int i = 0; i < mgrs .size(); i++ ){\n try {\n bool bRes = false;\n std::wstring buf;\n\n switch ( (int)params.m_eType ){\n case Operation::eOpType_Svc_Restart:\n bRes = mgrs[i]->Restart( buf );\n break;\n case Operation::eOpType_Svc_Start:\n bRes = mgrs[i]->Start( buf );\n break;\n case Operation::eOpType_Svc_Stop:\n bRes = mgrs[i]->Stop( buf );\n break;\n case Operation::eOpType_Svc_Status:\n bRes = mgrs[i]->Status( buf );\n break;\n }\n\n if ( !bRes&& mgrs.size() == 1 ){\n if ( !g_bQuiet) wcout << L\"operation is not supported\\n\";\n exit(1);\n }\n \n if ( !g_bQuiet) \n wcout << buf << L\"\\n\";\n \n } catch (SCXException& e ) {\n if ( !g_bQuiet) wcout << e.What() << L\"\\n\";\n // It's hard to get the \"real\" return code, so just return generic error\n exit(1);\n }\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n main function of the tool\n \\param argc size of \\a argv[]\n \\param argv array of string pointers from the command line.\n \\returns 0 on success, otherwise, 1 on error.\n*/ \nint main(int argc, const char *argv[])\n{\n return scx_admin(argc, argv );\n}\n\n\n" }, { "alpha_fraction": 0.4950321316719055, "alphanum_fraction": 0.5032144784927368, "avg_line_length": 27.516666412353516, "blob_id": "b2a3f042b37e95399c33576b55ce9e790b471e8a", "content_id": "669a76b59a48579f86c5b1554179695bb4edcc53", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1711, "license_type": "permissive", "max_line_length": 88, "num_lines": 60, "path": "/test/code/shared/testutils/testrunnerlogpolicy.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n \n*/\n/**\n \\file \n\n \\brief Contains log policy of the testrunner.\n\n \\date 2008-08-06 16:30:27\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxlogpolicy.h>\n\n/*----------------------------------------------------------------------------*/\n/**\n Defines the testrunner log policy.\n*/\nclass TestrunnerLogPolicy : public SCXCoreLib::SCXLogPolicy\n{\npublic:\n /**\n Virtual destructor.\n */\n virtual ~TestrunnerLogPolicy() {}\n\n /**\n Get the path of the log config file.\n \\returns the path of the log config file.\n */\n virtual SCXCoreLib::SCXFilePath GetConfigFileName() const\n {\n return SCXCoreLib::SCXFilePath(L\"./scxlog.conf\");\n }\n\n /**\n If no config is specified, then log output will be written\n to the file specified by this method.\n \\returns Path to the default log file.\n */\n virtual SCXCoreLib::SCXFilePath GetDefaultLogFileName() const\n {\n return SCXCoreLib::SCXFilePath(L\"./scxtestrunner.log\");\n }\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n This is the testrunner log policy factory. It will return the testrunner\n log policy.\n\n \\returns The default log policy object.\n*/\nSCXCoreLib::SCXHandle<SCXCoreLib::SCXLogPolicy> CustomLogPolicyFactory()\n{\n return SCXCoreLib::SCXHandle<SCXCoreLib::SCXLogPolicy>( new TestrunnerLogPolicy() );\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6005502343177795, "alphanum_fraction": 0.6051356196403503, "avg_line_length": 32.47368240356445, "blob_id": "e1a44d6f2e666fb551d262448ff0dc952a065306", "content_id": "0ec38113939fea39bd76a21bb1ecc20a1680a1b7", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7633, "license_type": "permissive", "max_line_length": 120, "num_lines": 228, "path": "/source/code/shared/tools/scx_ssl_config/scxsslcert.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n \n \\brief Defines the openSSL certificate generation class\n \n \\date 1-29-2008\n \n Wraps the openSSL certificate generation functions for use with the SCX\n installation tools.\n \n*/\n\n#ifndef SCXSSLCERT_H\n#define SCXSSLCERT_H\n\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxexception.h>\n#include <iosfwd>\n#include <openssl/x509.h>\n#include <iostream>\n#include <sstream>\n#include <set>\n/*----------------------------------------------------------------------------*/\n/**\n Generic exception for SSL Certificate errors.\n \n*/ \nclass SCXSSLException : public SCXCoreLib::SCXException {\n public:\n /*----------------------------------------------------------------------------*/\n /**\n Ctor\n \\param[in] reason Cause of the exception.\n \\param[in] l Source code location object\n */\n SCXSSLException(std::wstring reason,\n const SCXCoreLib::SCXCodeLocation& l) :\n SCXException(l),\n m_Reason(reason)\n { };\n\n std::wstring What() const;\n\n protected:\n //! The source code name of the violating pointer\n std::wstring m_Reason;\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n openSSL certificate provides a wrapper class for the openSSL certificate\n generation functons.\n \n \\author Carl Nicol\n \\date 1-31-2008\n\n SCXSSLCertificate wraps the openSSL API calls used to generate certificates.\n\n \\note Data is stored using wstring, however, the openSSL API calls use C-strings\n so all data is translated to a C-string before it is actually used.\n\n*/\nclass SCXSSLCertificate\n{\n private:\n /// The type of encoding used to produce the key.\n enum KeyType {\n eKeyTypeNone = 0, ///< No encoding type specified.\n eKeyTypeRSA = 1, ///< RSA encoding\n eKeyTypeDSA = 2, ///< DSA encoding\n eKeyTypeDH = 3, ///< DH encoding\n eKeyTypeEC = 4, ///< EC encoding\n eKeyTypeMax = 5 ///< Above range of encoding enums.\n };\n\n /// The certificate file format type\n enum FormatType {\n eFormatTypeNone = 0, ///< No certificate format specified.\n eFormatTypeASN1 = 1, ///< ASN1 formatted certificate.\n eFormatTypePEM = 3, ///< PEM formatted certificate\n eFormatTypeMax = 4 ///< Above range of format types.\n };\n\n int m_startDays; ///< Days to offset valid start time with;\n int m_endDays; ///< Days to offset valid end time with;\n int m_bits; ///< Number of bits in key\n bool m_clientCert; ///< Certificate to be used for client authentication\n\nprotected:\n SCXCoreLib::SCXFilePath m_KeyPath; ///< Path to key file;\n SCXCoreLib::SCXFilePath m_CertPath; ///< Path to certificate;\n std::wstring m_hostname; ///< Hostname\n std::wstring m_domainname; ///< Domainname\n\npublic:\n SCXSSLCertificate(SCXCoreLib::SCXFilePath keyPath, SCXCoreLib::SCXFilePath certPath,\n int startDays, int endDays, const std::wstring & hostname,\n const std::wstring & domainname, int bits, bool clientCert = false);\n \n virtual ~SCXSSLCertificate();\n\n void LoadRndNumber();\n void SaveRndNumber();\n void Generate();\n\nprotected:\n size_t LoadRandomFromFile(const char* file, size_t num);\n\nprivate:\n /// Do not allow copy. Intentionally left unimplemented.\n SCXSSLCertificate( const SCXSSLCertificate & rhs );\n /// Do not allow copy. Intentionally left unimplemented.\n SCXSSLCertificate & operator=( const SCXSSLCertificate & rhs );\n\n void DoGenerate();\n void SetX509Properties(X509_REQ *req, EVP_PKEY *pkey);\n virtual size_t LoadRandomFromDevRandom(size_t randomNeeded);\n virtual size_t LoadRandomFromDevUrandom(size_t randomNeeded);\n virtual size_t LoadRandomFromUserFile();\n virtual void DisplaySeedWarning(size_t goodRandomNeeded);\n\n friend class ScxSSLCertTest;\n};\n\n// Comparator for SuffixSortedFileSet\nstruct IntegerSuffixComparator\n{\n bool operator()(const SCXCoreLib::SCXFilePath * pa, const SCXCoreLib::SCXFilePath * pb) const;\n static bool IsGoodFileName(const SCXCoreLib::SCXFilePath& path);\n};\n\n// Set sorted on integer file name suffix, e.g. libcidn.so.<N> .\ntypedef std::set<const SCXCoreLib::SCXFilePath *, IntegerSuffixComparator> SuffixSortedFileSet;\n\n/**\n SCXSSLCertificateLocalDomain is a wrapper to SCXSSLCertificate that provides \n conversion of localized domain names. \n*/\n\ntypedef int(*IDNFuncPtr)(const char *, char **, int) ;\n\nclass SCXSSLCertificateLocalizedDomain : public SCXSSLCertificate\n{\npublic:\n SCXSSLCertificateLocalizedDomain(SCXCoreLib::SCXFilePath keyPath, SCXCoreLib::SCXFilePath certPath,\n int startDays, int endDays, const std::wstring & hostname,\n const std::wstring & domainname_raw, int bits, bool clientCert = false);\n\n using SCXSSLCertificate::Generate; \n void Generate(std::ostringstream& verbage);\n\nprivate:\n static void * GetLibIDN(void);\n static void CloseLibIDN(void * hLib);\n static void * GetLibIDNByDirectory(const char * sDir);\n static IDNFuncPtr GetIDNAToASCII(void * hLib);\n static void CleanupErrorOutput(const char * sErr, std::ostringstream& verbage);\n\nprivate:\n /**\n Helper class to ensure that IDN library is closed properly regardless of exceptions\n */\n class AutoClose \n {\n public:\n /*\n AutoClose constructor\n \\param[in] hLib Library handle to close\n */\n AutoClose(void * hLib) : m_hLib(hLib) {}\n ~AutoClose();\n\n private:\n void * m_hLib; //!< Library handle\n };\n\nprivate:\n std::wstring m_domainname_raw;\n\n friend class ScxSSLCertTest;\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n Specific errno exception for username related errors (see SCXErrnoException).\n*/\nclass SCXErrnoUserNameException : public SCXCoreLib::SCXErrnoException\n{\npublic:\n /*----------------------------------------------------------------------------*/\n /**\n Ctor\n \\param[in] fkncall Function call for user-related operation\n \\param[in] user username parameter causing internal error\n \\param[in] errno_ System error code with local interpretation\n \\param[in] l Source code location object\n */\n\n SCXErrnoUserNameException(std::wstring fkncall, std::wstring user, int errno_, const SCXCoreLib::SCXCodeLocation& l)\n : SCXErrnoException(fkncall, errno_, l), m_fkncall(fkncall), m_user(user)\n { };\n\n std::wstring What() const {\n std::wostringstream txt;\n txt << L\"Calling \" << m_fkncall << \"() with user name parameter\\\"\" << m_user\n << \"\\\", returned an error with errno = \" << m_errno << L\" (\" << m_errtext.c_str() << L\")\";\n return txt.str();\n }\n\n /** Returns function call for the user operation falure\n \\returns user-operation in std::wstring encoding\n */\n std::wstring GetFnkcall() const { return m_fkncall; }\n\n std::wstring GetUser() const { return m_user; }\nprotected:\n //! Text of user-related function call\n std::wstring m_fkncall;\n std::wstring m_user;\n};\n\n\n#endif /* SCXSSLCERT_H */\n\n/*--------------------------E-N-D---O-F---F-I-L-E----------------------------*/\n\n" }, { "alpha_fraction": 0.6888889074325562, "alphanum_fraction": 0.6888889074325562, "avg_line_length": 34.130435943603516, "blob_id": "0026208d67f8713809bbde193476b4414caa4698", "content_id": "53a7b50e5b466843c7f1d9c78ce9f5a7eda17ca6", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 810, "license_type": "permissive", "max_line_length": 76, "num_lines": 23, "path": "/test/code/shared/tools/scx_prune_repository/commandlineparser_test.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "import unittest\nimport sys\nsys.path.append('../../../../source/code/tools/scx_prune_repository')\nfrom commandlineparser import CommandLineParser\n\nclass CommandLineParserTestCase(unittest.TestCase):\n def setUp(self):\n pass\n\n def tearDown(self):\n pass\n\n def testOptParserHasCimSchemaDir(self):\n sys.argv.append(\"--cim_schema_dir=/some/directory\")\n cmdLineParser = CommandLineParser()\n self.assert_(cmdLineParser.has_option('--cim_schema_dir'))\n self.assertEqual(cmdLineParser.getCIMSchemaDir(), '/some/directory')\n\n def testOneArgument(self):\n sys.argv.append(\"--cim_schema_dir=/some/directory\")\n sys.argv.append('myFile.mof')\n cmdLineParser = CommandLineParser()\n self.assertEqual(cmdLineParser.getArguments(), ['myFile.mof'])\n\n\n" }, { "alpha_fraction": 0.6052327156066895, "alphanum_fraction": 0.6144878268241882, "avg_line_length": 32.34124755859375, "blob_id": "aace929db6a180fc218777bd03704d613df2ab9d", "content_id": "5e5f3da703364d526de339d6dd50f712d0225e4c", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11237, "license_type": "permissive", "max_line_length": 119, "num_lines": 337, "path": "/test/code/shared/testutils/testrunner.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n */\n#define IMPLEMENT_SCXUNIT_WARNING\n#define IMPLEMENT_SCXTestRunner\n#include <testutils/scxunit.h>\n#include <cppunit/XmlOutputter.h>\n#include <cppunit/TextOutputter.h>\n#include <cppunit/Exception.h>\n#include <cppunit/CompilerOutputter.h>\n#include <cppunit/extensions/TestFactoryRegistry.h>\n#include <cppunit/TestResult.h>\n#include <cppunit/Test.h>\n#include <cppunit/ui/text/TestRunner.h>\n#include <cppunit/TestResultCollector.h>\n#include <cppunit/TestRunner.h>\n#include <cppunit/BriefTestProgressListener.h>\n#include <cppunit/TextTestProgressListener.h>\n#include <scxcorelib/scxcmn.h> \n#include <testutils/scxassert_cppunit.h>\n#include <scxcorelib/stringaid.h>\n#include <fstream>\n\n#if !defined(WIN32)\n#include <signal.h>\n#include <sys/time.h>\n#endif\n\n//#include \"../common_lib/util/log/scxlogbackendsimple.h\"\n\nusing namespace std;\n\n#ifdef WIN32\nconst char cPathDelim = '\\\\';\n#else\nconst char cPathDelim = '/';\n#endif\n\n//! There was unexpected assertion failure in a test case\nclass SCXUnexpectedAssertionFailureException : public CPPUNIT_NS::Exception\n{\npublic:\n SCXUnexpectedAssertionFailureException(const std::string &testName)\n : Exception(CPPUNIT_NS::Message(\"Unexpected assertion failure\", testName)) { }\n\n};\n\n//! Monitors test case run times.\nclass TimerListener : public CPPUNIT_NS::BriefTestProgressListener\n{\nprivate:\n#if defined(WIN32)\n typedef _SYSTEMTIME TimerListnerTimestamp;\n#else\n typedef timeval TimerListnerTimestamp;\n#endif\n\n void GetTimestamp(TimerListnerTimestamp* ts)\n {\n#if defined(WIN32)\n GetSystemTime(ts);\n#else\n gettimeofday(ts, NULL);\n#endif\n }\n\n long GetTimeDiff(TimerListnerTimestamp* start, TimerListnerTimestamp* stop)\n {\n#if defined(WIN32)\n // real time difference not really intesresting so using approximate:\n return (stop->wYear - start->wYear) * 365 * 24 * 60 * 60 * 1000\n + (stop->wMonth - start->wMonth) * 30 * 24 * 60 * 60 * 1000\n + (stop->wDay - start->wDay) * 24 * 60 * 60 * 1000\n + (stop->wHour - start->wHour) * 60 * 60 * 1000\n + (stop->wMinute - start->wMinute) * 60 * 1000\n + (stop->wSecond - start->wSecond) * 1000\n + (stop->wMilliseconds - start->wMilliseconds);\n#else\n return (stop->tv_sec - start->tv_sec) * 1000\n + (stop->tv_usec - start->tv_usec) / 1000;\n#endif\n }\npublic:\n TimerListener()\n : CPPUNIT_NS::BriefTestProgressListener()\n , m_slowLimit(-1)\n { }\n\n void SetSlowLimit(long v) { m_slowLimit = v; }\n\n std::string ReportSlow()\n {\n std::string s(\"\");\n for (std::vector<std::string>::iterator it = m_report.begin(); it != m_report.end(); it++) {\n s += *it;\n s += \"\\n\";\n }\n return s;\n }\n\n size_t GetSlowCount()\n {\n return m_report.size();\n }\n\n virtual void startTest( CPPUNIT_NS::Test*)\n {\n GetTimestamp(&m_startTime);\n }\n\n virtual void endTest( CPPUNIT_NS::Test *test)\n {\n TimerListnerTimestamp stopTime;\n GetTimestamp(&stopTime);\n long diff = GetTimeDiff(&m_startTime, &stopTime);\n if (m_slowLimit >= 0 && diff >= m_slowLimit) {\n char buf[1024*10];\n sprintf(buf, \"%8.3fs %s\", static_cast<float>(diff) / 1000.0F, test->getName().c_str());\n m_report.push_back(buf);\n }\n }\n\nprivate:\n TimerListnerTimestamp m_startTime; //!< Tracks starting time for tests.\n long m_slowLimit; //!< The slow limit.\n std::vector<std::string> m_report; //!< Holds report for slow tests.\n};\n \n\n\n//! Monitors test cases for unexpected assertions.\nclass MyTestListener : public CPPUNIT_NS::BriefTestProgressListener\n{\npublic:\n virtual void startTest( CPPUNIT_NS::Test *test)\n {\n SCXCoreLib::SCXAssertCounter::Reset(); \n BriefTestProgressListener::startTest(test);\n }\n\n virtual void endTest( CPPUNIT_NS::Test *test)\n {\n if (SCXCoreLib::SCXAssertCounter::GetFailedAsserts() > 0)\n { \n m_eventManager->addFailure(test, new SCXUnexpectedAssertionFailureException(\n test->getName() + \"; \" + SCXCoreLib::StrToMultibyte(SCXCoreLib::SCXAssertCounter::GetLastMessage()) ));\n }\n BriefTestProgressListener::endTest(test);\n }\n\n virtual void startTestRun(CPPUNIT_NS::Test *, CPPUNIT_NS::TestResult *eventManager) \n {\n m_eventManager = eventManager;\n }\n\n virtual void endTestRun(CPPUNIT_NS::Test *, CPPUNIT_NS::TestResult *) \n {\n m_eventManager = 0;\n }\n\nprivate:\n CPPUNIT_NS::TestResult * m_eventManager; //!< Collects the result of running each test case\n};\n\nint main (int argc, char** argv)\n{\n#if defined(_DEBUG) && defined(WIN32)\n // enable memory leak reporting in run-time library\n int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);\n tmpDbgFlag |= _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF;\n _CrtSetDbgFlag(tmpDbgFlag);\n _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );\n _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );\n#endif\n\n\n string outDir;\n long slowLimit = -1;\n bool bNamesSpecified = false;\n bool bAttrsSpecified = false;\n\n for ( int i = 1; i < argc; i++ ){\n \n if (!strncmp(argv[i], \"-logdir=\", strlen(\"-logdir=\")))\n {\n outDir = argv[i]+ strlen(\"-logdir=\");\n if (outDir[outDir.length()] != cPathDelim)\n {\n outDir += cPathDelim;\n }\n }\n else if (!strncmp(argv[i], \"-scxlogdir=\", strlen(\"-scxlogdir=\")))\n {\n string scxoutDir = argv[i]+ strlen(\"-scxlogdir=\");\n if (scxoutDir[scxoutDir.length()] != cPathDelim)\n {\n scxoutDir += cPathDelim;\n }\n/* SCXCoreLib::SCXLogBackendSimple::s_configFileName = scxoutDir + \"scxlog.conf\";\n SCXCoreLib::SCXLogBackendSimple::s_logFileName = SCXCoreLib::StrFromMultibyte(scxoutDir + \"scx.log\");*/\n }\n else if (0 == strncmp(argv[i], \"-test=\", strlen(\"-test=\")))\n {\n string testName = argv[i]+ strlen(\"-test=\");\n SCXTestRunner::s_Instance.SetTestNameFilter(testName);\n\n // Qualifier -test overrides environment variable\n bNamesSpecified = true;\n }\n else if (0 == strncmp(argv[i], \"-attr=\", strlen(\"-attr=\")))\n {\n string attr = argv[i]+ strlen(\"-attr=\");\n SCXTestRunner::s_Instance.SetTestAttributeFilter(attr);\n\n // Qualifier -attr overrides environment variable\n bAttrsSpecified = true;\n }\n else if (0 == strncmp(argv[i], \"-slow=\", strlen(\"-slow=\")))\n {\n slowLimit = atol(argv[i]+ strlen(\"-slow=\"));\n }\n else\n {\n cout << \"Illegal switch. Possible switches:\" << endl;\n cout << \" -logdir=<dir>\" << endl;\n cout << \" -scxoutDir=<dir>\" << endl;\n cout << \" -test=<name> Only run tests containg the string <name>.\" << endl;\n cout << \" -attr=<attribute> Only run tests with given attribute.\" << endl;\n cout << \" -slow=<limit> Report tests slower than limit in microseconds.\" << endl;\n cout << endl;\n cout << \"Test/attribute names may be prepended with '-' to exclude them (-attr=-slow)\" << endl;\n cout << endl;\n cout << \"Environment variables that may be used:\" << endl;\n cout << \" SCX_TESTRUN_ATTRS: Test attribte filter if -attr= qualifier is not specified\" << endl;\n cout << \" SCX_TESTRUN_NAMES: Test name filter if -test= qualifier is not specified\" << endl;\n cout << endl;\n return 1;\n }\n }\n \n if (! bNamesSpecified) {\n const char *cTestNames = getenv(\"SCX_TESTRUN_NAMES\");\n\n if (NULL != cTestNames) {\n string sTestNames = cTestNames;\n cout << \"Limiting tests to: \" << sTestNames << endl;\n\n SCXTestRunner::s_Instance.SetTestNameFilter(sTestNames);\n }\n }\n\n if (! bAttrsSpecified) {\n const char *cTestAttrs = getenv(\"SCX_TESTRUN_ATTRS\");\n\n if (NULL != cTestAttrs) {\n string sTestAttrs = cTestAttrs;\n cout << \"Limiting attributes to: \" << sTestAttrs << endl;\n\n SCXTestRunner::s_Instance.SetTestAttributeFilter(sTestAttrs);\n }\n }\n\n#if !defined(WIN32)\n // We need to raise the SIGUSR1 to ALL testrunner processes in one test \n // (see processpal_test.cpp) and the default behaviour, which is to \n // terminate the recipient, was not satisfactory.\n signal(SIGUSR1, SIG_IGN);\n#endif\n\n // Create the event manager and test controller\n CPPUNIT_NS::TestResult controller;\n\n // register listener for collecting the test-results\n CPPUNIT_NS::TestResultCollector collectedresults;\n controller.addListener(&collectedresults);\n\n // Add a listener that print what tests are run to the output interactively\n MyTestListener progress;\n controller.addListener( &progress );\n\n TimerListener timer;\n timer.SetSlowLimit(slowLimit);\n controller.addListener( &timer );\n\n // insert test-suite at test-runner by registry\n // NOTE: you should NOT delete this pointer.\n SCXTestRunner* testrunnerInstance = &SCXTestRunner::s_Instance;\n\n // Use the factory mechanism to register all tests\n testrunnerInstance->addTest (CPPUNIT_NS :: TestFactoryRegistry :: getRegistry ().makeTest ());\n // Run! \n testrunnerInstance->run(controller); \n\n std::cout << std::endl << \"---- All tests run ----\" << std::endl << std::endl;\n\n // output slow tests:\n if (timer.GetSlowCount() > 0) {\n std::cout << \"SLOW TESTS (\" << timer.GetSlowCount() << \"):\" << std::endl << timer.ReportSlow() << std::endl;\n }\n\n // output warnings to stdout\n for (std::wstring warning = SCXCoreLib::SCXUnitWarning::PopWarning(); \n L\"\" != warning; \n warning = SCXCoreLib::SCXUnitWarning::PopWarning())\n {\n std::wcout << L\"WARNING: \" << warning << std::endl;\n }\n\n // output results in compiler-format\n// CPPUNIT_NS :: CompilerOutputter compilerOutputter (&collectedresults, std::cerr);\n// compilerOutputter.write();\n\n // Format in plain text to stdout\n CPPUNIT_NS::TextOutputter stdoutTextOutputter( &collectedresults, std::cout ); \n stdoutTextOutputter.write();\n\n // Format in plain text to file\n string logFileName;\n logFileName = outDir+\"cppunit_result.log\";\n ofstream myTextStream(logFileName.c_str());\n CPPUNIT_NS::TextOutputter textOutputter( &collectedresults, myTextStream ); \n textOutputter.write();\n myTextStream.close();\n\n // Format as XML\n string xmlFileName;\n xmlFileName = outDir + \"cppunit_result.xml\";\n ofstream myStream(xmlFileName.c_str());\n CPPUNIT_NS::XmlOutputter xmlOutputter( &collectedresults, myStream );\n xmlOutputter.setStyleSheet(\"report.xsl\");\n xmlOutputter.write();\n myStream.close();\n\n // return 0 if tests were successful\n return collectedresults.wasSuccessful () ? 0 : 1;\n}\n\n" }, { "alpha_fraction": 0.5954616665840149, "alphanum_fraction": 0.5982785820960999, "avg_line_length": 32.98936080932617, "blob_id": "4ae60d7918ffa15e5ae1fbce38d13039d31384a2", "content_id": "687a65dd073586437504cda9497492ffbfcf15f9", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6390, "license_type": "permissive", "max_line_length": 100, "num_lines": 188, "path": "/source/code/shared/tools/scx_admin/admin_api.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief scx admin config API for SCX.\n\n \\date 8/27/2008\n\n*/\n#ifndef _ADMIN_API_H\n#define _ADMIN_API_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n\n#include <iostream>\n\nusing namespace SCXCoreLib;\n/*----------------------------------------------------------------------------*/\n/**\n Admin utility implementation exception for all Errors\n\n Provide human-readable description of the error and notifies\n that operation is \"supported-in-general\" but cannot be completed at this time\n \n*/ \nclass SCXAdminException : public SCXException {\npublic: \n /*----------------------------------------------------------------------------*/\n /**\n Ctor\n \\param[in] description Description of the internal error\n \\param[in] l Source code location object\n\n */\n SCXAdminException(std::wstring description, \n const SCXCodeLocation& l) : SCXException(l),\n m_strDescription(description)\n {}\n\n /** (overload)\n Format details of violation\n \n */\n std::wstring What() const { return m_strDescription;}\n\nprotected:\n //! Description of internal error\n std::wstring m_strDescription;\n}; \n\n\n/*----------------------------------------------------------------------------*/\n/**\n API to Log-Configuration modules\n\n Allows to manipulate log configurations for different components in unified way.\n As a generic rule, all functions return \"true\" for successful operation,\n \"false\" for unsupported funcitons and throw \"SCXAdminException\" exception \n for failed operations\n \n*/ \nclass SCX_AdminLogAPI {\npublic:\n //! log level for generic configuration\n enum LogLevelEnum{ \n eLogLevel_Verbose,\n eLogLevel_Intermediate,\n eLogLevel_Errors\n };\n\n /** Virtual destructor needed */\n virtual ~SCX_AdminLogAPI() {}\n\n \n /** Instructs component to rotate the log (close/re-open log files).\n \\returns \"true\" if success, \"false\" if not supported\n */\n virtual bool LogRotate() = 0;\n \n /** Prints current log configuration of the component into provided stream\n \\param[in] buf stream for configuration writing\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Print(std::wostringstream& buf) const = 0;\n \n /** Resets configuration of the component to the default level (installation-time)\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Reset() = 0;\n \n /** Changes configuration of the component to the provided level\n \\param[in] level new configuration level\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Set(LogLevelEnum level) = 0;\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n API to Provider-Configuration \n\n Allows to manipulate configuration options for different providers in unified way.\n As a generic rule, all functions return \"true\" for successful operation,\n \"false\" for unsupported funcitons and throw \"SCXAdminException\" exception \n for failed operations\n \n*/ \nclass SCX_AdminProviderConfigAPI {\npublic:\n /** Virtual destructor needed */\n virtual ~SCX_AdminProviderConfigAPI(){}\n\n /** Prints current log configuration of the component into provided stream\n \\param[in] buf stream for configuration writing\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Print(std::wostringstream& buf) const = 0;\n \n /** Resets configuration of the component to the default level (installation-time)\n \\param[in] name property name for resetting\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Reset( const std::wstring& name ) = 0;\n \n /** Changes configuration of the component with provided name/value pair\n \\param[in] name property name for setting\n \\param[in] value new value\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Set(const std::wstring& name, const std::wstring& value) = 0;\n \n};\n\n\n/*----------------------------------------------------------------------------*/\n/**\n API to Service management (specific to one service) \n\n Allows to perform \"start/stop/status\" operations for given service\n \n*/ \nclass SCX_AdminServiceManagementAPI {\npublic:\n /** Virtual destructor needed */\n virtual ~SCX_AdminServiceManagementAPI(){}\n\n /** Starts the service\n \\param[out] info string that explains details like \"started\" \n or \"is already running\" in case of success\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Start( std::wstring& info ) const = 0;\n \n /** Stop the service\n \\param[out] info string that explains details like \"stopped\" \n or \"was not running\" in case of success\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Stop( std::wstring& info ) const = 0;\n \n /** Restart the service (stop/start sequence)\n \\param[out] info string that explains details like \"stopped\" \n or \"was not running\" in case of success\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Restart( std::wstring& info ) const = 0;\n\n /** Returns status of the service\n \\param[out] info string that provides status\n \\returns \"true\" if success, \"false\" if not supported\n \\throws SCXAdminException on failure\n */\n virtual bool Status( std::wstring& info ) const = 0;\n};\n\n#endif /* _ADMIN_API_H */\n" }, { "alpha_fraction": 0.7159090638160706, "alphanum_fraction": 0.7215909361839294, "avg_line_length": 28.33333396911621, "blob_id": "f0b06f3c964b296009ad382f67bfd23ab22e261e", "content_id": "0bc52004ed08a156571ead64eae19ed875cd1b9d", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 176, "license_type": "permissive", "max_line_length": 60, "num_lines": 6, "path": "/build/pbuild", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Convenience script to easily call pbuild\n\nexec python `dirname $0`/../test/util/pbuild/pbuild.py \"$@\"\n" }, { "alpha_fraction": 0.5934123396873474, "alphanum_fraction": 0.5957484245300293, "avg_line_length": 35.66595458984375, "blob_id": "365b13a6e40b2a94a031c0f168cbfff96f028909", "content_id": "4ca4b961607a4400652a54ce03c640865df136ba", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17123, "license_type": "permissive", "max_line_length": 142, "num_lines": 467, "path": "/test/code/shared/tools/scx_admin/logconfigurator_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for wsman configurator functionality which is part of the scx_admin tool\n\n \\date 2008-08-28 13:48\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <logconfigurator.h> \n#include <testutils/scxunit.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n\n#include <testutils/scxtestutils.h>\n\n// using namespace SCXCore;\n// using namespace SCXCoreLib;\n// using namespace SCXSystemLib;\n\nclass LogConfigTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( LogConfigTest );\n CPPUNIT_TEST( testLogRotate );\n CPPUNIT_TEST( testNoConfFile );\n CPPUNIT_TEST( testExistingConfFile );\n CPPUNIT_TEST( testCreatingConfFile );\n CPPUNIT_TEST( testResetLogConf );\n CPPUNIT_TEST( testProvSetThresholdForStdOut );\n CPPUNIT_TEST( testProvSetThresholdForTwoBackends );\n CPPUNIT_TEST( testSetInvalidSeverityThrows );\n CPPUNIT_TEST( testProvResetLogConf );\n CPPUNIT_TEST( testProvRemoveLogfile );\n CPPUNIT_TEST( testProviderLogBackendNameIsCaseInsensitive );\n CPPUNIT_TEST( testProviderLogFilePathIsCaseSensitive );\n CPPUNIT_TEST( testProviderLogModuleIdIsCaseSensitive );\n CPPUNIT_TEST( testProviderLogSeverityIsCaseInsensitive );\n SCXUNIT_TEST_ATTRIBUTE(testLogRotate, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n\n /*\n * This is what we try to parse:\nFILE (\nPATH: /VAR/Opt/Microsoft/scx/log/scx.log\nMODULE: INFO\nMODULE: module ERROR\n)\n\nFILE (\nPATH: /var/opt/microsoft/scx/log/scx.log\nMODULE: INFO\nMODULE: module TRACE\n)\n\nSTDOUT (\nMODULE: INFO\nMODULE: module INFO\n)\n */\n std::wstring GetLogLevel(const SCXFilePath& cfgfile,\n const std::wstring& backendName,\n const std::wstring& fileBackendPath,\n const std::wstring& module)\n {\n std::vector<std::wstring> lines;\n SCXStream::NLFs nlfs;\n SCXFile::ReadAllLinesAsUTF8(cfgfile, lines, nlfs);\n \n for (std::vector<std::wstring>::const_iterator iter = lines.begin();\n iter != lines.end();\n ++iter)\n {\n if (StrAppend(backendName, L\" (\") == *iter)\n {\n if (L\"FILE\" == backendName)\n {\n ++iter;\n if (iter != lines.end() && std::wstring(L\"PATH: \").append(fileBackendPath) != *iter)\n {\n continue;\n }\n }\n while (iter != lines.end() && L\")\" != *iter)\n {\n std::vector<std::wstring> tokens;\n StrTokenize(*iter, tokens);\n if (tokens.size() == 3 && tokens[0] == L\"MODULE:\" && tokens[1] == module)\n {\n return tokens[2];\n }\n else if (tokens.size() == 2 && tokens[0] == L\"MODULE:\" && module == L\"\")\n {\n return tokens[1];\n }\n ++iter;\n }\n }\n }\n return L\"\";\n }\n\n /**\n Return the content of the file as a string.\n */\n std::string GetFileContent(const SCXFilePath& cfgfile)\n {\n std::string str;\n str.resize( 1024 * 256 ); // should be enough\n size_t size = SCXFile::ReadAvailableBytes( cfgfile, &str[0], str.size() );\n str.resize( size );\n return str;\n }\n\n \npublic:\n void setUp(void)\n {\n /* This method will be called once before each test function. */\n }\n\n void tearDown(void)\n {\n /* This method will be called once after each test function. */\n }\n\n bool MeetsPrerequisites(std::wstring testName)\n {\n /* Privileges needed for this platform */\n if (0 == geteuid())\n {\n return true;\n }\n\n std::wstring warnText;\n\n warnText = L\"Platform needs privileges to run \" + testName + L\" test\";\n\n SCXUNIT_WARNING(warnText);\n return false;\n }\n\n void testLogRotate(void)\n {\n SCX_LogConfigurator subject;\n\n if (MeetsPrerequisites(L\"testLogRotate\"))\n {\n // LogRotate isn't supported by OpenWSMan\n CPPUNIT_ASSERT_MESSAGE(\"Unexpected return value from method LogRotate()\", \n subject.LogRotate() == true);\n }\n }\n\n // \n // check if default one\n void testNoConfFile()\n {\n // This file should not exist.\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n\n SCX_LogConfigurator subject(cfgfile);\n\n std::wostringstream buf;\n subject.Print( buf );\n std::wstring str = buf.str();\n\n // should be some \"FILE\" default configuration\n CPPUNIT_ASSERT( str.size() > 0 );\n CPPUNIT_ASSERT( str.find(L\"FILE\") != str.npos );\n }\n\n\n // reading the exisitng one \n void testExistingConfFile()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n\n // Create a simple example file\n std::vector<std::wstring> lines;\n lines.push_back(L\"FILE (\");\n lines.push_back(L\"PATH: /var/log-1\");\n lines.push_back(L\")\");\n lines.push_back(L\"\"); // Must be here, or else the last newline will be omitted.\n SCXFile::WriteAllLinesAsUTF8(cfgfile, lines, std::ios_base::out);\n \n SCX_LogConfigurator subject(cfgfile);\n\n std::wostringstream buf;\n subject.Print( buf );\n \n std::wstring str = buf.str();\n\n // should be some \"FILE\" default configuration\n CPPUNIT_ASSERT( str.size() > 0 ); \n CPPUNIT_ASSERT( str.find(L\"FILE\") != str.npos );\n CPPUNIT_ASSERT( str.find(L\"/var/log-1\") != str.npos );\n CPPUNIT_ASSERT( str.find(L\"INFO\") != str.npos ); // The only severity will be default INFO\n }\n \n // set \"verbose\" - should create a file\n void testCreatingConfFile()\n {\n // This file should not exist.\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n\n SCX_LogConfigurator subject(cfgfile);\n\n CPPUNIT_ASSERT( subject.Set( SCX_AdminLogAPI::eLogLevel_Verbose ) );\n CPPUNIT_ASSERT( SCXFile::Exists(cfgfile) ); // Should be created\n }\n\n // generic reset\n void testResetLogConf()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n\n // Create a simple example file\n std::vector<std::wstring> lines;\n lines.push_back(L\"FILE (\");\n lines.push_back(L\"PATH: /var/log-1\");\n lines.push_back(L\"MODULE: TRACE\");\n lines.push_back(L\"MODULE: scxtest.core.common.pal WARNING\");\n lines.push_back(L\"MODULE: scxtest.core.common.pal.system.common HYSTERICAL\");\n lines.push_back(L\"MODULE: scxtest.core.common.pal.system.common.entityenumeration INFO\");\n lines.push_back(L\")\");\n lines.push_back(L\"\"); // Must be here, or else the last newline will be omitted.\n SCXFile::WriteAllLinesAsUTF8(cfgfile, lines, std::ios_base::out);\n\n {\n SCX_LogConfigurator subject(cfgfile);\n CPPUNIT_ASSERT (subject.Reset() );\n }\n\n std::string str = GetFileContent(cfgfile);\n\n CPPUNIT_ASSERT( str.find(\"HYSTERICAL\") == str.npos ); // Should be gone\n CPPUNIT_ASSERT( str.find(\"scxtest.core.common.pal\") == str.npos ); // should be gone\n CPPUNIT_ASSERT( str.find(\"FILE\") != str.npos ); // should still be there\n CPPUNIT_ASSERT( str.find(\"/var/log-1\") != str.npos ); // should still be there\n }\n \n // provider set\n void testProvSetThresholdForStdOut()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n\n SCX_LogConfigurator subject(cfgfile);\n\n // set several entries: should create a new file with specific entries:\n subject.Set( L\"STDOUT\", L\"TRACE\" );\n subject.Set( L\"STDOUT:scxtest.core.common.pal.system.common.entityenumeration\", L\"INFO\" );\n\n std::string str = GetFileContent(cfgfile);\n\n // we should not see these entries\n CPPUNIT_ASSERT( str.find(\"HYSTERICAL\") == str.npos );\n CPPUNIT_ASSERT( str.find(\"FILE\") == str.npos );\n CPPUNIT_ASSERT( str.find(\"/var\") == str.npos );\n\n // but should see these:\n CPPUNIT_ASSERT( L\"TRACE\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"\") );\n CPPUNIT_ASSERT( L\"INFO\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"scxtest.core.common.pal.system.common.entityenumeration\") );\n }\n\n // provider set\n void testProvSetThresholdForTwoBackends()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n\n SCX_LogConfigurator subject(cfgfile);\n\n // Positive test to set lower case entry: should create a new file with specific entries (upper case):\n subject.Set( L\"STDOUT\", L\"trace\" );\n subject.Set( L\"STDOUT:scxtest.core.common.pal.system.common.entityenumeration\", L\"info\" );\n subject.Set( L\"FILE:/myvar/opt/microsoft/scx/log/scx.log:scxtest.core.common.pal.system.common.entityenumeration\", L\"info\" );\n\n std::string str = GetFileContent(cfgfile);\n\n // we should not see these entries\n CPPUNIT_ASSERT( str.find(\"HYSTERICAL\") == str.npos );\n CPPUNIT_ASSERT( str.find(\"/var\") == str.npos );\n\n // but should see these:\n CPPUNIT_ASSERT( L\"TRACE\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"\") );\n CPPUNIT_ASSERT( L\"INFO\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"scxtest.core.common.pal.system.common.entityenumeration\") );\n CPPUNIT_ASSERT( L\"INFO\" == GetLogLevel(cfgfile, \n L\"FILE\", L\"/myvar/opt/microsoft/scx/log/scx.log\",\n L\"scxtest.core.common.pal.system.common.entityenumeration\") );\n }\n\n // Negative test to set invalid entry: should throw an exception\n void testSetInvalidSeverityThrows()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n SCX_LogConfigurator invTest(cfgfile);\n\n invTest.Set( L\"STDOUT\", L\"trace\" );\n\n CPPUNIT_ASSERT_THROW_MESSAGE( \"invalid severity string: anything1\",\n invTest.Set( L\"STDOUT:scxtest.core.common.pal.system.common.entityenumeration\", L\"anything\" ),\n SCXAdminException );\n\n CPPUNIT_ASSERT_THROW_MESSAGE( \"invalid severity string: anything2\",\n invTest.Set( L\"FILE:/myvar/opt/microsoft/scx/log/scx.log:scxtest.core.common.pal.system.common.entityenumeration\", L\"anything2\" ),\n SCXAdminException );\n }\n\n // provider set\n void testProvResetLogConf()\n {\n // create a file\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n\n {\n SCX_LogConfigurator subject(cfgfile);\n\n subject.Set( L\"STDOUT\", L\"trace\" );\n subject.Set( L\"STDOUT:scxtest.core.common.pal.system.common.entityenumeration\", L\"info\" );\n subject.Set( L\"FILE:/myvar/opt/microsoft/scx/log/scx.log:scxtest.core.common.pal.system.common.entityenumeration\", L\"info\" );\n }\n \n SCX_LogConfigurator subject(cfgfile);\n\n subject.Reset( L\"STDOUT\" );\n subject.Reset( L\"FILE:/myvar/opt/microsoft/scx/log/scx.log\" );\n\n CPPUNIT_ASSERT_THROW_MESSAGE( \"exception is expected since entry does not exist\",\n subject.Reset( L\"FILE:/var/opt/microsoft/scx/log/scx.log\" ),\n SCXAdminException );\n \n std::string str = GetFileContent(cfgfile);\n\n // we should not see these entries\n CPPUNIT_ASSERT( str.find(\"HYSTERICAL\") == str.npos );\n CPPUNIT_ASSERT( str.find(\"/var\") == str.npos );\n CPPUNIT_ASSERT( str.find(\"MODULE: scxtest.core.common.pal.system.common.entityenumeration INFO\") == str.npos );\n\n // but should see these:\n CPPUNIT_ASSERT( str.find(\"STDOUT\") != str.npos );\n CPPUNIT_ASSERT( str.find(\"FILE\") != str.npos );\n CPPUNIT_ASSERT( str.find(\"PATH: /myvar/opt/microsoft/scx/log/scx.log\") != str.npos );\n }\n\n // provider set\n void testProvRemoveLogfile()\n {\n // create a file\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"./testfiles/log.conf\"));\n\n {\n SCX_LogConfigurator subject(cfgfile);\n\n subject.Set( L\"STDOUT\", L\"trace\" );\n subject.Set( L\"STDOUT:scxtest.core.common.pal.system.common.entityenumeration\", L\"info\" );\n subject.Set( L\"FILE:/myvar/opt/microsoft/scx/log/scx.log:scxtest.core.common.pal.system.common.entityenumeration\", L\"info\" );\n }\n \n SCX_LogConfigurator subject(cfgfile);\n\n subject.Remove( L\"STDOUT\" );\n\n CPPUNIT_ASSERT_THROW_MESSAGE( \"exception is expected since entry does not exist\",\n subject.Remove( L\"FILE:/var/opt/microsoft/scx/log/scx.log\" ),\n SCXAdminException );\n\n std::string str = GetFileContent(cfgfile);\n\n // we should not see these entries\n CPPUNIT_ASSERT( str.find(\"HYSTERICAL\") == str.npos );\n CPPUNIT_ASSERT( str.find(\"/var\") == str.npos );\n CPPUNIT_ASSERT( str.find(\"STDOUT\") == str.npos );\n\n // but should see these:\n CPPUNIT_ASSERT( str.find(\"FILE\") != str.npos );\n CPPUNIT_ASSERT( str.find(\"PATH: /myvar/opt/microsoft/scx/log/scx.log\") != str.npos );\n CPPUNIT_ASSERT( str.find(\"MODULE: scxtest.core.common.pal.system.common.entityenumeration INFO\") != str.npos );\n }\n\n /**\n The log backend name (FILE or STDOUT) in provider log configuration should be \n case insensitive.\n */ \n void testProviderLogBackendNameIsCaseInsensitive()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"log.conf\"));\n cfgfile.SetDirectory(L\"./testfiles/\");\n\n SCX_LogConfigurator subject(cfgfile);\n\n subject.Set( L\"STDOUT:module\", L\"TRACE\" );\n subject.Set( L\"stdout:module\", L\"INFO\" );\n\n subject.Set( L\"FILE:/var/opt/microsoft/scx/log/scx.log:module\", L\"TRACE\" );\n subject.Set( L\"file:/var/opt/microsoft/scx/log/scx.log:module\", L\"ERROR\" );\n\n CPPUNIT_ASSERT( L\"INFO\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"module\") );\n CPPUNIT_ASSERT( L\"ERROR\" == GetLogLevel(cfgfile, L\"FILE\", L\"/var/opt/microsoft/scx/log/scx.log\", L\"module\") );\n }\n\n /**\n The log file backend path in provider log configuration should be \n case sensitive.\n */ \n void testProviderLogFilePathIsCaseSensitive()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"log.conf\"));\n cfgfile.SetDirectory(L\"./testfiles/\");\n\n SCX_LogConfigurator subject(cfgfile);\n\n subject.Set( L\"FILE:/var/opt/microsoft/scx/log/scx.log:module\", L\"TRACE\" );\n subject.Set( L\"FILE:/VAR/Opt/Microsoft/scx/log/scx.log:module\", L\"ERROR\" );\n\n CPPUNIT_ASSERT( L\"TRACE\" == GetLogLevel(cfgfile, L\"FILE\", L\"/var/opt/microsoft/scx/log/scx.log\", L\"module\") );\n CPPUNIT_ASSERT( L\"ERROR\" == GetLogLevel(cfgfile, L\"FILE\", L\"/VAR/Opt/Microsoft/scx/log/scx.log\", L\"module\") );\n }\n\n /**\n The module id in provider log configuration should be \n case sensitive.\n */ \n void testProviderLogModuleIdIsCaseSensitive()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"log.conf\"));\n cfgfile.SetDirectory(L\"./testfiles/\");\n\n SCX_LogConfigurator subject(cfgfile);\n\n subject.Set( L\"STDOUT:module\", L\"TRACE\" );\n subject.Set( L\"STDOUT:MODULE\", L\"INFO\" );\n subject.Set( L\"STDOUT:MoDuLe\", L\"ERROR\" );\n\n CPPUNIT_ASSERT( L\"TRACE\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"module\") );\n CPPUNIT_ASSERT( L\"INFO\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"MODULE\") );\n CPPUNIT_ASSERT( L\"ERROR\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"MoDuLe\") );\n }\n\n /**\n The severity threshold in provider log configuration should be \n case insensitive.\n */ \n void testProviderLogSeverityIsCaseInsensitive()\n {\n SelfDeletingFilePath cfgfile(SCXFileSystem::DecodePath(\"log.conf\"));\n cfgfile.SetDirectory(L\"./testfiles/\");\n\n SCX_LogConfigurator subject(cfgfile);\n\n subject.Set( L\"STDOUT:module\", L\"trace\" );\n subject.Set( L\"STDOUT:MODULE\", L\"TrAcE\" );\n subject.Set( L\"STDOUT:MoDuLe\", L\"TRACE\" );\n\n CPPUNIT_ASSERT( L\"TRACE\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"module\") );\n CPPUNIT_ASSERT( L\"TRACE\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"MODULE\") );\n CPPUNIT_ASSERT( L\"TRACE\" == GetLogLevel(cfgfile, L\"STDOUT\", L\"\", L\"MoDuLe\") );\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( LogConfigTest );\n" }, { "alpha_fraction": 0.4658283293247223, "alphanum_fraction": 0.4729360342025757, "avg_line_length": 30, "blob_id": "a58bf2c4b0ca39ea5b1710ead667e81170aeed17", "content_id": "cbfbb525f77bd7ac19c7672918403c310ffde070", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1829, "license_type": "permissive", "max_line_length": 102, "num_lines": 59, "path": "/source/code/providers/support/logfileprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n \n*/\n/**\n \\file logfileprovider.h\n \n \\brief LogFile provider header file\n \n \\date 2008-0-08 09:35:36\n \n*/\n/*----------------------------------------------------------------------------*/\n#ifndef LOGFILEPROVIDER_H\n#define LOGFILEPROVIDER_H\n\n#include \"logfileutils.h\"\n\nnamespace SCXCore\n{\n /*----------------------------------------------------------------------------*/\n /**\n LogFile provider\n */\n class LogFileProvider\n {\n public:\n LogFileProvider();\n LogFileProvider(SCXCoreLib::SCXHandle<LogFileReader> pReader);\n ~LogFileProvider();\n\n const std::wstring DumpString() const;\n void Load();\n void Unload();\n\n SCXCoreLib::SCXLogHandle& GetLogHandle();\n\n bool InvokeLogFileReader(const std::wstring& filename,\n const std::wstring& qid,\n const std::vector<SCXCoreLib::SCXRegexWithIndex>& regexps,\n bool fPerformElevation,\n std::vector<std::wstring>& matchedLines);\n\n int InvokeResetStateFile(const std::wstring& filename,\n const std::wstring& qid,\n int resetOnRead,\n bool fPerformElevation);\n\n private:\n SCXCoreLib::SCXHandle<LogFileReader> m_pLogFileReader;\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n };\n\n extern LogFileProvider g_LogFileProvider;\n}\n\n#endif /* LOGFILEPROVIDER_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5586459636688232, "alphanum_fraction": 0.5635449886322021, "avg_line_length": 39.407405853271484, "blob_id": "39b868a98a549d2e7bd816d8c1e650d02e04e491", "content_id": "737a7004bbd6b65bdbf183bff31a9dc5d6518f21", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 31639, "license_type": "permissive", "max_line_length": 186, "num_lines": 783, "path": "/source/code/providers/support/appserver/appserverenumeration.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file appserverenumeration.cpp\n\n \\brief Enumeration of Application Server\n\n \\date 11-05-18 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/scxregex.h>\n\n#include <scxcorelib/scxcondition.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfilepath.h>\n\n#include <scxsystemlib/processenumeration.h>\n#include <scxsystemlib/processinstance.h>\n\n#include \"appserverenumeration.h\"\n#include \"jbossappserverinstance.h\"\n#include \"tomcatappserverinstance.h\"\n#include \"weblogicappserverenumeration.h\"\n#include \"websphereappserverinstance.h\"\n#include \"manipulateappserverinstances.h\"\n#include \"persistappserverinstances.h\"\n\n#include <string>\n#include <vector>\n\nusing namespace std;\nusing namespace SCXCoreLib;\n \nnamespace SCXSystemLib\n{\n /**\n Returns a vector containing all running processes with the name matching the criteria.\n */\n vector<SCXHandle<ProcessInstance> > AppServerPALDependencies::Find(const wstring& name)\n {\n SCXHandle<ProcessEnumeration> enumProc = SCXHandle<ProcessEnumeration>(new ProcessEnumeration());\n enumProc->SampleData();\n return enumProc->Find(name);\n }\n \n /**\n Populates the params with the process parameters.\n */\n bool AppServerPALDependencies::GetParameters(SCXHandle<ProcessInstance> inst, vector<string>& params)\n {\n return inst->GetParameters(params);\n }\n\n /**\n Populates the newInst with the newly created Weblogic AppServerInstances.\n \n \\param[in] weblogicProcesses Vector containing the home peth of all running Weblogic processes.\n \\param[out] newInst Vector containing newly created AppServerInstances.\n */\n void AppServerPALDependencies::GetWeblogicInstances(vector<wstring> weblogicProcesses, vector<SCXHandle<AppServerInstance> >& newInst)\n {\n WebLogicAppServerEnumeration weblogicEnum(\n SCXCoreLib::SCXHandle<IWebLogicFileReader> (new WebLogicFileReader()));\n \n weblogicEnum.GetInstances(weblogicProcesses,newInst);\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Default constructor\n\n \\param[in] deps Dependencies for the AppServer Enumeration.\n */\n AppServerEnumeration::AppServerEnumeration(SCXCoreLib::SCXHandle<AppServerPALDependencies> deps) :\n EntityEnumeration<AppServerInstance>(),\n m_deps(deps)\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.common.pal.system.appserver.appserverenumeration\");\n\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration default constructor\");\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Destructor\n\n */\n AppServerEnumeration::~AppServerEnumeration()\n {\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration destructor\");\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Create AppServer instances\n\n */\n void AppServerEnumeration::Init()\n {\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration Init()\");\n ReadInstancesFromDisk();\n Update(false);\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Deserialize Instances from disk\n\n */\n void AppServerEnumeration::ReadInstancesFromDisk()\n {\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration ReadInstancesFromDisk()\");\n\n SCXHandle<PersistAppServerInstances> cache( \n new PersistAppServerInstances() );\n vector<SCXHandle<AppServerInstance> > readInstances;\n cache->ReadFromDisk(readInstances);\n\n for (EntityIterator i = readInstances.begin();\n readInstances.end() != i;\n ++i)\n {\n SCX_LOGTRACE(m_log, L\"adding an instance from cache read\");\n AddInstance(*i);\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get JBoss parameters and from the commandline and create an AppServerInstance\n\n */\n void AppServerEnumeration::CreateJBossInstance(vector<SCXCoreLib::SCXHandle<AppServerInstance> > *ASInstances, vector<string> params)\n {\n bool gotInstPath=false;\n wstring instDir;\n string config;\n string configFromDashC;\n string configFromJBossProperty;\n string configFromJBossDomainProperty;\n string configFromJBossStandaloneProperty;\n string ports;\n wstring deployment = L\"\";\n \n // We have a 'JBoss' instance, now get the base directory from the 'classpath' commandline argument\n string arg = ParseOutCommandLineArg(params, \"-classpath\",true,true);\n if ( arg.length() > 0 )\n {\n instDir = GetJBossPathFromClassPath(StrFromUTF8(arg));\n if(instDir.length() > 0)\n {\n gotInstPath=true;\n }\n }\n \n // If we still do not have a JBoss instance check if JBoss AS 7 / Wildfly 8 Server\n // This property exists for both Standalone versions and Domain versions of JBoss/Wildfly\n if(!gotInstPath)\n {\n string arg2 = ParseOutCommandLineArg(params,\"-Djboss.home.dir\",true,true);\n instDir = StrFromUTF8(arg2);\n if(instDir.length() > 0)\n {\n gotInstPath = true;\n }\n }\n configFromDashC = ParseOutCommandLineArg(params, \"-c\",false,true);\n configFromJBossProperty = ParseOutCommandLineArg(params, \"-Djboss.server.name\",true,false);\n \n // These properties are specific for JBoss 7 and Wildfly\n // The Logging property is optional when running in domain mode, thus the server data directory is used\n configFromJBossDomainProperty = ParseOutCommandLineArg(params, \"-Djboss.server.data.dir\", true, false);\n configFromJBossStandaloneProperty = ParseOutCommandLineArg(params, \"-Dlogging.configuration\",true,false);\n \n // Give priority to JBoss 7 and wildfly as they can have non default config.\n // If config from -c is checked first It would lead to incorrect install path for JBoss 7 and wildfly.\n if ( configFromJBossDomainProperty.length() != 0 )\n {\n // Sample domain value: /root/wildfly-8.1.0.CR2/domain/servers/server-one/data\n config = configFromJBossDomainProperty;\n }\n else if ( configFromJBossStandaloneProperty.length() != 0 )\n {\n // Sample standalone value: /root/wildfly-8.1.0.CR2/standalone/configuration/logging.properties\n\n /* Following is the preference for getting configuration directory:\n jboss.server.config.dir\n jboss.server.base.dir + /configuration\n jboss.home.dir + /standalone/configuration \n */\n string confDir = ParseOutCommandLineArg(params, \"-Djboss.server.config.dir\",true,false);\n string baseDir = ParseOutCommandLineArg(params, \"-Djboss.server.base.dir\",true,false);\n string homeDir = ParseOutCommandLineArg(params, \"-Djboss.home.dir\",true,false);\n\n if(confDir.size() > 0)\n {\n confDir.append(\"/\");\n config = confDir;\n }\n else if(baseDir.size() > 0)\n {\n baseDir.append(\"/configuration/\");\n config = baseDir;\n }\n else\n {\n homeDir.append(\"/standalone/configuration/\");\n config = homeDir;\n }\n // JBoss standalone can have non default config file (standalone-full.xml, standalone-ha.xml etc.)\n // If -c argument is also present then ports should be read from that file\n if ( configFromDashC.length() != 0 )\n {\n // -c gives relative path of config file wrt configuration directory. \n config.append(configFromDashC);\n }\n ports = ParseOutCommandLineArg(params, \"-Djboss.socket.binding.port-offset\",true,false); \n deployment = L\"standalone\";\n }\n else if ( configFromDashC.length() != 0 )\n {\n config = configFromDashC;\n }\n else if ( configFromJBossProperty.length() != 0 )\n {\n config = configFromJBossProperty;\n }\n else\n {\n config = \"default\";\n }\n \n if(ports.empty())\n {\n ports = ParseOutCommandLineArg(params, \"-Djboss.service.binding.set\",true,false);\n }\n \n if(gotInstPath)\n {\n SCXCoreLib::SCXHandle<JBossAppServerInstancePALDependencies> deps = SCXCoreLib::SCXHandle<JBossAppServerInstancePALDependencies>(new JBossAppServerInstancePALDependencies());\n SCXCoreLib::SCXHandle<JBossAppServerInstance> inst ( \n new JBossAppServerInstance(instDir,StrFromUTF8(config),StrFromUTF8(ports),deps,deployment) );\n inst->Update();\n\n SCX_LOGTRACE(m_log, L\"Found a running app server process\");\n inst->SetIsRunning(true);\n ASInstances->push_back(inst);\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get Tomcat parameters from the commandline and create an AppServerInstance\n\n */\n void AppServerEnumeration::CreateTomcatInstance(vector<SCXCoreLib::SCXHandle<AppServerInstance> > *ASInstances, vector<string> params)\n {\n bool gotInstPath=false;\n string instDir;\n string config;\n \n instDir = ParseOutCommandLineArg(params, \"-Dcatalina.home\",true,true);\n if ( !instDir.empty() )\n {\n gotInstPath=true;\n }\n\n // We have a 'Tomcat' instance, now get the base directory from the '-Dcatalina.home' commandline argument\n config = ParseOutCommandLineArg(params, \"-Dcatalina.base\",true,true);\n if ( config.empty() )\n {\n config = instDir;\n }\n \n if(gotInstPath)\n {\n SCXCoreLib::SCXHandle<TomcatAppServerInstance> inst ( \n new TomcatAppServerInstance(StrFromUTF8(config), StrFromUTF8(instDir)) );\n inst->Update();\n \n SCX_LOGTRACE(m_log, L\"Found a running instance of Tomcat\");\n inst->SetIsRunning(true);\n ASInstances->push_back(inst);\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get WebSphere parameters from the commandline and create an AppServerInstance\n \n The commandline has the \"-Dserver.root\" key which contains the disk path to the instance\n The WebSphere startup script runs websphere with the following arguments after the \"com.ibm.ws.runtime.WsServer\" class\n \"%CONFIG_ROOT%\" \"%WAS_CELL%\" \"%WAS_NODE%\" %* %WORKSPACE_ROOT_PROP%\n \n */\n void AppServerEnumeration::CreateWebSphereInstance(vector<SCXCoreLib::SCXHandle<AppServerInstance> > *ASInstances, vector<string> params)\n {\n int argNumberForRuntimeClass;\n string configRoot;\n string instDir;\n string wasCell;\n string wasNode;\n string wasServer;\n wstring wasProfile;\n bool gotInstPath = false;\n bool gotParams = false;\n\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration::CreateWebSphereInstance enter\");\n\n argNumberForRuntimeClass = GetArgNumber(params, WEBSPHERE_RUNTIME_CLASS);\n SCX_LOGTRACE(m_log, StrAppend(L\"AppServerEnumeration::CreateWebSphereInstance argNumberForRuntimeClass: \", argNumberForRuntimeClass)); \n\n if(argNumberForRuntimeClass >= 0)\n {\n // parse out the \"%CONFIG_ROOT%\" \"%WAS_CELL%\" \"%WAS_NODE%\" %* %WORKSPACE_ROOT_PROP%\n // The +5 is for the 4 arguments and and extra 1 for the zero based offset of the \n // argNumberForRuntimeClass.\n if(params.size() >= (unsigned int)argNumberForRuntimeClass+5)\n {\n configRoot = params[argNumberForRuntimeClass+1];\n wasCell = params[argNumberForRuntimeClass+2];\n wasNode = params[argNumberForRuntimeClass+3];\n wasServer = params[argNumberForRuntimeClass+4];\n gotParams = true;\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration::CreateWebSphereInstance gotParams\");\n }\n }\n // If there are multiple servers per profile use -Dosgi.configuration.area instead of -Dserver.root\n // This will maintain unique disk paths for multiple servers within a single profile\n instDir = ParseOutCommandLineArg(params, \"-Dosgi.configuration.area\",true,true);\n SCXRegex re(L\"(.*)/(.*)/(.*)/(.*)/(.*)\");\n vector<wstring> v_profileDiskPath;\n \n // Run Regex Matching to ensure minimum directory structure is present\n // Check directory structure to ensure no match for single server profile configuration\n // Example of single server profile configuration \"-Dosgi.configuration.area = /usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/configuration\"\n if ( !instDir.empty() \n && re.ReturnMatch(StrFromUTF8(instDir),v_profileDiskPath, 0)\n && v_profileDiskPath[3].compare(L\"servers\") == 0)\n {\n // From previous regex, if disk path matched minimum directory structure and is not a single server profile\n // the vector v_profileDiskPath will be populated with the following\n // \n // Example of serverDiskPath ../usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/servers/<server name>/configuration\n //\n // v_profileDiskPath[1] will include disk path until profile name <../../../../profiles>\n // v_profileDiskPath[2] will include profile name <AppSrv01>\n // v_profileDiskPath[3] will include the text \"servers\"\n // v_profileDiskPath[4] will include server name <server name>\n instDir =StrToUTF8( v_profileDiskPath[1].append(L\"/\").append(v_profileDiskPath[2]).append(L\"/\").append(v_profileDiskPath[3]).append(L\"/\").append(v_profileDiskPath[4])); \n wasProfile=v_profileDiskPath[2];\n gotInstPath=true;\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration::CreateWebSphereInstance gotInstPath\");\n } \n else\n {\n // If -Dosgi.configuration.area is empty or only one server under profile \n // then default to -Dserver.root\n instDir = ParseOutCommandLineArg(params, \"-Dserver.root\", true, true);\n if ( !instDir.empty() )\n {\n SCXFilePath sf(StrFromUTF8(instDir));\n wasProfile = sf.GetFilename();\n gotInstPath=true;\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration::CreateWebSphereInstance gotInstPath\");\n }\n }\n if(gotInstPath && gotParams)\n {\n SCXCoreLib::SCXHandle<WebSphereAppServerInstance> inst ( \n new WebSphereAppServerInstance(StrFromUTF8(instDir),StrFromUTF8(wasCell),StrFromUTF8(wasNode),wasProfile,StrFromUTF8(wasServer)) );\n inst->Update();\n \n SCX_LOGTRACE(m_log, L\"Found a running instance of WebSphere\");\n inst->SetIsRunning(true);\n ASInstances->push_back(inst);\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get Weblogic parameters from the commandline and find the base directory\n -Dweblogic.Name=AdminServer \n -Dplatform.home=/opt/Oracle/Middleware/wlserver_10.3\n -Dwls.home=/opt/Oracle/Middleware/wlserver_10.3/server \n -Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server \n */\n wstring AppServerEnumeration::GetWeblogicHome(vector<string> params)\n {\n string wlPlatformHome;\n string wlPlatformHome12c;\n\t\tstring wlPlatformHome12c3;\n wstring PlatformHome;\n \n wlPlatformHome = ParseOutCommandLineArg(params, \"-Dplatform.home\",true,true);\n wlPlatformHome12c = ParseOutCommandLineArg(params, \"-Dbea.home\", true, true);\n\t\t// With WebLogic 12.1.2 and 12.1.3 Oracle has removed -Dbea.home, -Dplatform.home, and -Dweblogic.system.BootIdentityFile\n\t\twlPlatformHome12c3 = ParseOutCommandLineArg(params, \"-Dweblogic.home\", true, true);\n\n if ( !wlPlatformHome.empty() )\n {\n // Commandline entry for \"-Dplatform.home\" looks like this\n // \"-Dplatform.home=/opt/Oracle/Middleware/wlserver_10.3\"\n // remove the \"wlserver_10.3\" portion to return the platform\n // home directory.\n // There is the possibility that the wlPlatformHome ends with a\n // trailing '/', we need to strip it off.\n PlatformHome = StrFromUTF8(GetParentDirectory(wlPlatformHome));\n SCX_LOGTRACE(m_log, L\"Found a running instance of Weblogic with -Dplatform.home\");\n }\n else if( !wlPlatformHome12c.empty() )\n {\n // Commandline entry for \"-Dbea.home\" looks like this\n // \"-Dbea.home=/root/Oracle/Middleware\"\n PlatformHome = StrFromUTF8(wlPlatformHome12c);\n SCX_LOGTRACE(m_log, L\"Found a running instance of Weblogic with -Dbea.home\");\n }\n\t\telse if( !wlPlatformHome12c3.empty() )\n\t\t{\n\t\t\t// CommandLie entry for \"-Dweblogic.home\" looks like this\n\t\t\t// \"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\"\n\t\t\tPlatformHome = StrFromUTF8(GetParentDirectory(GetParentDirectory(wlPlatformHome12c3)));\n\t\t\tSCX_LOGTRACE(m_log, L\"Found a running instance of WebLogic with -Dweblogic.home\");\n\t\t}\n else\n {\n // -Dweblogic.system.BootIdentityFile=/opt/Oracle/Middleware/user_projects/domains/base_domain/servers/Managed1/data/nodemanager/boot.properties \n string wlBootId = ParseOutCommandLineArg(params, \"-Dweblogic.system.BootIdentityFile\",true,true);\n if ( !wlBootId.empty() )\n {\n PlatformHome = StrFromUTF8(GetParentDirectory(wlBootId,8)); // remove '/user_projects/domains/base_domain/servers/Managed1/data/nodemanager/boot.properties' \n }\n else\n {\n SCX_LOGTRACE(m_log, L\"Weblogic process does not contain the 'platform.home', 'weblogic.home', or 'weblogic.system.BootIdentityFile' commandline argument.\");\n }\n }\n return PlatformHome;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Update all AppServer data\n\n */\n void AppServerEnumeration::Update(bool /*updateInstances*/)\n {\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration Update()\");\n vector<SCXCoreLib::SCXHandle<AppServerInstance> > ASInstances;\n bool gotWeblogicProcesses = false;\n vector<wstring> weblogicProcesses;\n\n // Find all Java processes running\n vector<SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> > procList = m_deps->Find(L\"java\");\n for (vector<SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> >::iterator it = procList.begin(); it != procList.end(); it++)\n {\n vector<string> params;\n\n if (m_deps->GetParameters((*it),params)) \n {\n // Log \"Found java process, Parameters: Size=x, Contents: y\"\n if (eTrace == m_log.GetSeverityThreshold())\n {\n std::wostringstream txt;\n txt << L\"AppServerEnumeration Update(): Found java process, Parameters: Size=\" << params.size();\n if (params.size() > 0)\n {\n txt << L\", Contents:\";\n\n int count = 0;\n for (vector<string>::iterator itp = params.begin(); itp != params.end(); ++itp)\n {\n txt << L\" \" << ++count << L\":\\\"\" << StrFromUTF8(*itp) << L\"\\\"\";\n }\n }\n\n SCX_LOGTRACE(m_log, txt.str());\n }\n\n // Loop through each 'java' process and check for 'JBoss' argument on the commandline\n if(CheckProcessCmdLineArgExists(params,\"org.jboss.Main\") ||\n CheckProcessCmdLineArgExists(params,\"org.jboss.as.standalone\") ||\n CheckProcessCmdLineArgExists(params,\"org.jboss.as.server\"))\n {\n CreateJBossInstance(&ASInstances, params);\n }\n // Loop through each 'java' process and check for Tomcat i.e. 'Catalina' argument on the commandline\n if(CheckProcessCmdLineArgExists(params,\"org.apache.catalina.startup.Bootstrap\"))\n {\n CreateTomcatInstance(&ASInstances, params);\n }\n \n // Loop through each 'java' process and check for Weblogic i.e. 'weblogic.Server' argument on the commandline\n if(CheckProcessCmdLineArgExists(params,\"weblogic.Server\"))\n {\n wstring wlHome = GetWeblogicHome(params);\n if(!wlHome.empty())\n {\n weblogicProcesses.push_back(wlHome);\n gotWeblogicProcesses = true;\n }\n }\n\n // Loop through each 'java' process and check for WebSphere i.e. \n // com.ibm.ws.bootstrap.WSLauncher com.ibm.ws.runtime.WsServer argument on the commandline\n if(CheckProcessCmdLineArgExists(params,\"com.ibm.ws.bootstrap.WSLauncher\") &&\n CheckProcessCmdLineArgExists(params,WEBSPHERE_RUNTIME_CLASS))\n {\n CreateWebSphereInstance(&ASInstances, params);\n }\n }\n }\n\n // Get the list of Weblogic Instances and add them to the enumerator\n if(gotWeblogicProcesses)\n {\n vector<SCXHandle<AppServerInstance> > newInst;\n m_deps->GetWeblogicInstances(weblogicProcesses, newInst);\n\n for (\n vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = newInst.begin(); \n it != newInst.end();\n ++it)\n {\n SCX_LOGTRACE(m_log, L\"Adding a Weblogic instance\");\n ASInstances.push_back(*it);\n }\n }\n\n //Get the current instances and place them in a vector\n vector<SCXCoreLib::SCXHandle<AppServerInstance> > knownInstances;\n for (EntityIterator iter = Begin(); iter != End(); ++iter) \n {\n knownInstances.push_back(*iter);\n }\n\n SCX_LOGTRACE(m_log, L\"Merging previously known instances with current running processes\");\n SCX_LOGTRACE(m_log,\n StrAppend(L\"size of previously known instances: \",\n knownInstances.size()));\n SCX_LOGTRACE(m_log,\n StrAppend(L\"size of running processes : \", ASInstances.size()));\n\n ManipulateAppServerInstances::UpdateInstancesWithRunningProcesses(knownInstances, ASInstances);\n\n SCX_LOGTRACE(m_log,\n StrAppend(L\"size of merged list : \",\n knownInstances.size()));\n \n SCX_LOGTRACE(m_log, L\"delete all instances\");\n RemoveInstances() ;\n for (vector<SCXHandle<AppServerInstance> >::iterator it = knownInstances.begin(); \n it != knownInstances.end(); \n ++it)\n {\n SCX_LOGTRACE(m_log, L\"adding an instance from processes\");\n AddInstance(*it);\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Wrapper to EntityEnumeration's UpdateInstances()\n\n */\n void AppServerEnumeration::UpdateInstances()\n {\n EntityEnumeration<AppServerInstance>::UpdateInstances();\n }\n \n /*----------------------------------------------------------------------------*/\n /**\n Serialize Instances to disk\n\n */\n void AppServerEnumeration::WriteInstancesToDisk()\n {\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration WriteInstancesToDisk()\");\n\n SCXHandle<PersistAppServerInstances> cache( \n new PersistAppServerInstances() );\n vector<SCXHandle<AppServerInstance> > instancesToWrite;\n instancesToWrite.insert(instancesToWrite.end(), Begin(), End() );\n cache->EraseFromDisk();\n cache->WriteToDisk(instancesToWrite);\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Cleanup\n\n */\n void AppServerEnumeration::CleanUp()\n {\n SCX_LOGTRACE(m_log, L\"AppServerEnumeration CleanUp()\");\n WriteInstancesToDisk();\n }\n\n /*----------------------------------------------------------------------------\n * Check the process command line arguments looking \n * for a specific entry.\n *\n * \\param params List of commandline arguments\n * \\param value argument value to look for\n * \\returns true if the argument is found otherwise false\n */\n bool AppServerEnumeration::CheckProcessCmdLineArgExists(vector<string>& params, const string& value)\n {\n vector<string>::iterator pos;\n bool retval = false;\n\n for(pos = params.begin(); pos != params.end(); ++pos) \n {\n if(value == *pos)\n {\n retval = true;\n break;\n }\n }\n return retval;\n }\n \n /*----------------------------------------------------------------------------\n * Check the process command line arguments looking \n * for a specific entry and return the argument number of the entry.\n *\n * \\param params List of commandline arguments\n * \\param value argument value to look for\n * \\returns the argument number of the matching argument\n */\n int AppServerEnumeration::GetArgNumber(vector<string>& params, const string& value)\n {\n vector<string>::iterator pos;\n int retval = -1;\n bool found = false;\n\n for(pos = params.begin(); (pos != params.end() )&&(!found); ++pos) \n {\n retval++;\n if(value == *pos)\n {\n found = true;\n }\n }\n return !found?-1:retval;\n }\n \n /*----------------------------------------------------------------------------\n * Remove the last folder entry from the input folder\n *\n * \\param directoryPath Directory path\n * \\param levels number of directories to fall back\n * \\returns the parent directory\n */\n string AppServerEnumeration::GetParentDirectory(const string& directoryPath,int levels)\n {\n string thePath;\n size_t pos;\n\n\n if( '/' == directoryPath[directoryPath.length()-1] )\n {\n thePath = directoryPath.substr(directoryPath.length()-1);\n }\n else\n {\n thePath = directoryPath;\n }\n\n for(int i=0;i<levels;i++)\n {\n pos = thePath.find_last_of(\"/\");\n thePath = thePath.substr(0,pos);\n }\n\n return thePath;\n }\n \n /*----------------------------------------------------------------------------\n * Parse the commandline arguments looking for a specific \"key\"\n * when the \"key\" is found the associated value is returned.\n * The commandline arguments have different formats\n * arg0 -D abc;def (\"-D\" is the key and \"abc;def\" is the associated value)\n * arg0 name=bill (\"name\" is the key and \"bill\" is the value)\n *\n * \\param params List of commandline arguments\n * \\param key The \"key\" whose associated value must be retrieved\n * \\param EqualsDelimited Must the \"key\" be seperated from the \"value\" by an '=' sign\n * \\param SpaceDelimited Must the \"key\" be seperated from the \"value\" by a space\n * \\returns the associated value for the \"key\" or an empty string if not found.\n */\n string AppServerEnumeration::ParseOutCommandLineArg(vector<string>& params, \n const string& key,\n const bool EqualsDelimited,\n const bool SpaceDelimited ) const\n {\n vector<string>::iterator pos;\n const string emptyString = \"\"; \n string result = emptyString;\n bool returnTheNextArgAsValue = false;\n \n for(pos = params.begin(); pos != params.end(); ++pos) \n {\n string arg = static_cast<string>(*pos);\n \n if(returnTheNextArgAsValue)\n {\n result = arg;\n break;\n }\n \n if((key == arg) && SpaceDelimited)\n {\n /* \n * Some parameters are in the form key=value while some are \"key value\" \n * If the parameter length is the same size as the key then the value is \n * in the next arg.\n */\n returnTheNextArgAsValue = true;\n }\n else\n {\n /*\n * The following 2 scenarios still apply\n * key=value\n * key value - (this is done if the arg specified is a single arg \"key value\"\n */\n if(arg.length() > key.length()+1) \n {\n if(arg.substr(0,key.length()) == key)\n {\n if((EqualsDelimited && (arg[key.length()] == '=')) ||\n (SpaceDelimited && (arg[key.length()] == ' ')) )\n {\n result = arg.substr(key.length()+1);\n break;\n }\n }\n }\n }\n }\n return result;\n }\n\n \n /*----------------------------------------------------------------------------\n * Parse a given classpath string and find the item that ends with \n * \"/bin/run.jar\" the classpath item would typically be\n * \"/opt/JBoss-4.2.1/bin/run.jar\" and the return value should be \n * \"/opt/JBoss-4.2.1\". \n *\n * \\param classpath The entire classpath for an application serve\n * \\returns the application server base directory.\n */\n wstring AppServerEnumeration::GetJBossPathFromClassPath(const wstring& classpath) const\n {\n const wstring emptyString = L\"\"; \n wstring result = emptyString; \n vector<wstring> parts;\n vector<wstring>::iterator part;\n\n /* Search through the string checking each path element for '/bin/run.jar' */\n StrTokenize(classpath, parts, PATH_SEPERATOR);\n\n for(part = parts.begin(); part != parts.end(); ++part) \n {\n size_t pos = part->find(JBOSS_RUN_JAR);\n if(pos!=wstring::npos)\n {\n result = part->substr(0,pos+1); //include the trailing '/'\n break;\n }\n } \n return result;\n } \n}\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5851725339889526, "alphanum_fraction": 0.5881255865097046, "avg_line_length": 33.042327880859375, "blob_id": "83d001398e8b0eee403879a7ef4b5621ee753401", "content_id": "d7ea1e5a5277eff9296173420c7c02d9d18f8205", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6434, "license_type": "permissive", "max_line_length": 145, "num_lines": 189, "path": "/source/code/shared/tools/scx_admin/runasadminprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief runas configuration tool for SCX.\n\n \\date 2008-08-28 17:13:43\n\n*/\n\n#include \"runasadminprovider.h\"\n#include <scxcorelib/scxstream.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/stringaid.h>\n\n/*----------------------------------------------------------------------------*/\n/**\n Default Constructor for SCX_RunAsAdminProvider class\n*/\nSCX_RunAsAdminProvider::SCX_RunAsAdminProvider() :\n m_Configurator( \n SCXCoreLib::SCXHandle<SCXCore::ConfigurationParser>(new SCXCore::ConfigurationFileParser(L\"/etc/opt/microsoft/scx/conf/scxrunas.conf\")),\n SCXCoreLib::SCXHandle<SCXCore::ConfigurationWriter>(new SCXCore::ConfigurationFileWriter(L\"/etc/opt/microsoft/scx/conf/scxrunas.conf\"))),\n m_AllowRootDefault(true)\n{\n m_Configurator.Parse();\n\n#if defined(hpux)\n m_AllowRootDefault = GetSSHDConfPermitRootSetting(L\"/opt/ssh/etc/sshd_config\");\n#elif defined(macos)\n m_AllowRootDefault = GetSSHDConfPermitRootSetting(L\"/etc/sshd_config\");\n#elif defined(sun)\n# if (PF_MAJOR == 5) && (PF_MINOR == 8)\n m_AllowRootDefault = GetSSHDConfPermitRootSetting(L\"/usr/local/etc/sshd_config\");\n# else\n m_AllowRootDefault = GetSSHDConfPermitRootSetting(L\"/etc/ssh/sshd_config\");\n# endif\n#else\n m_AllowRootDefault = GetSSHDConfPermitRootSetting(L\"/etc/ssh/sshd_config\");\n#endif\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Constructor for SCX_RunAsAdminProvider class\n*/\nSCX_RunAsAdminProvider::SCX_RunAsAdminProvider( SCXCoreLib::SCXHandle<SCXCore::ConfigurationParser> parser,\n SCXCoreLib::SCXHandle<SCXCore::ConfigurationWriter> writer,\n const SCXCoreLib::SCXFilePath& sshdConfPath) :\n m_Configurator( parser, writer ),\n m_AllowRootDefault(true)\n{\n m_Configurator.Parse();\n m_AllowRootDefault = GetSSHDConfPermitRootSetting(sshdConfPath);\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Destructor for SCX_RunAsConfigurator class\n*/\nSCX_RunAsAdminProvider::~SCX_RunAsAdminProvider()\n{\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Prints current log configuration of the component into provided stream\n \\param[in] buf stream for configuration writing\n \\returns \"true\" if success, \"false\" if not supported\n throws \"SCXAdminException\" exception if failed\n*/\nbool SCX_RunAsAdminProvider::Print(std::wostringstream& buf) const\n{\n buf << L\"CWD = \" << m_Configurator.GetCWD().Get() << std::endl\n << L\"ChRootPath = \" << m_Configurator.GetChRootPath().Get() << std::endl\n << L\"AllowRoot = \" << (m_Configurator.GetAllowRoot() == true ? L\"true\" : L\"false\") << std::endl;\n \n return true;\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Resets configuration of the component to the default level (installation-time)\n \\param[in] name property name for resetting\n \\returns \"true\" if success, \"false\" if not supported\n throws \"SCXAdminException\" exception if failed\n*/\nbool SCX_RunAsAdminProvider::Reset( const std::wstring& name )\n{\n std::wstring lowerName = SCXCoreLib::StrToLower(name);\n if (L\"allowroot\" == lowerName)\n {\n m_Configurator.SetAllowRoot(m_AllowRootDefault);\n m_Configurator.Write();\n return true;\n }\n else if (L\"chrootpath\" == lowerName)\n {\n m_Configurator.ResetChRootPath();\n m_Configurator.Write();\n return true;\n }\n else if (L\"cwd\" == lowerName)\n {\n m_Configurator.ResetCWD();\n m_Configurator.Write();\n return true;\n }\n else if (L\"\" == name)\n {\n m_Configurator.SetAllowRoot(m_AllowRootDefault);\n m_Configurator.ResetChRootPath();\n m_Configurator.ResetCWD();\n m_Configurator.Write();\n return true;\n }\n\n throw SCXAdminException(L\"unknown property name \" + name, SCXSRCLOCATION);\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Changes configuration of the component with provided name/value pair\n \\param[in] name property name for setting\n \\param[in] value new value\n \\returns \"true\" if success, \"false\" if not supported\n throws \"SCXAdminException\" exception if failed\n*/\nbool SCX_RunAsAdminProvider::Set(const std::wstring& name, const std::wstring& value)\n{\n std::wstring lowerName = SCXCoreLib::StrToLower(name);\n std::wstring lowerValue = SCXCoreLib::StrToLower(value);\n if (L\"allowroot\" == lowerName)\n {\n if (L\"true\" == lowerValue ||\n L\"false\" == lowerValue)\n { \n m_Configurator.SetAllowRoot(L\"true\" == lowerValue);\n m_Configurator.Write();\n return true;\n }\n }\n else if (L\"chrootpath\" == lowerName)\n {\n m_Configurator.SetChRootPath(value);\n m_Configurator.Write();\n return true;\n }\n else if (L\"cwd\" == lowerName)\n {\n m_Configurator.SetCWD(value);\n m_Configurator.Write();\n return true;\n }\n throw SCXAdminException(L\"unknown property name \" + name + L\" or invalid value \" + value, SCXSRCLOCATION);\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Parses the supplied sshd_config file for the setting of \"PermitRoot\" and\n returns the value.\n \\param[in] sshdConfPath path to sshd_config file\n \\returns false if PermitRoot is set to no.\n*/\nbool SCX_RunAsAdminProvider::GetSSHDConfPermitRootSetting(const SCXCoreLib::SCXFilePath& sshdConfPath) const\n{\n SCXCoreLib::SCXStream::NLFs nlfs;\n std::vector<std::wstring> lines;\n SCXCoreLib::SCXFile::ReadAllLines(sshdConfPath, lines, nlfs);\n\n const std::wstring delimiters(L\" \\t\");\n for (std::vector<std::wstring>::const_iterator iter = lines.begin();\n iter != lines.end();\n ++iter)\n {\n std::vector<std::wstring> tokens;\n SCXCoreLib::StrTokenize(*iter, tokens, delimiters);\n if (tokens.size() == 2 && tokens[0] == L\"PermitRootLogin\" && tokens[1] == L\"no\")\n {\n return false;\n }\n }\n return true;\n}\n" }, { "alpha_fraction": 0.580551266670227, "alphanum_fraction": 0.5880105495452881, "avg_line_length": 35.04262161254883, "blob_id": "3b8eb6cbef2ab28375091518d6062dc4ae49dcd4", "content_id": "002b6549d7e91f2b4d29e9b41539503b44dcb7ef", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10993, "license_type": "permissive", "max_line_length": 106, "num_lines": 305, "path": "/test/code/providers/appserver_provider/appserverinstance_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n Created date 2011-05-18\n\n appserver data colletion test class.\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <testutils/scxunit.h>\n\n#include <appserverinstance.h>\n\n#include <cppunit/extensions/HelperMacros.h>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\nusing namespace std;\n\n\nclass AppServerInstance_Test : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( AppServerInstance_Test );\n\n CPPUNIT_TEST( testAllMembers );\n CPPUNIT_TEST( testSetIsDeepMonitoredHTTP );\n CPPUNIT_TEST( testSetIsDeepMonitoredHTTPS );\n CPPUNIT_TEST( testSetIsDeepMonitored );\n CPPUNIT_TEST( testSetIsRunning );\n CPPUNIT_TEST( testOperatorEqualsTrue );\n CPPUNIT_TEST( testOperatorEqualsFalseOnDiskPath );\n CPPUNIT_TEST( testOperatorEqualsFalseOnHttpPort );\n CPPUNIT_TEST( testOperatorEqualsFalseOnHttpsPort );\n CPPUNIT_TEST( testOperatorEqualsFalseOnIsDeepMonitored );\n CPPUNIT_TEST( testOperatorEqualsFalseOnIsRunning );\n CPPUNIT_TEST( testOperatorEqualsFalseOnType );\n CPPUNIT_TEST( testOperatorEqualsFalseOnVersion );\n CPPUNIT_TEST( testExtractMajorVersion );\n CPPUNIT_TEST_SUITE_END();\n\n public:\n\n void setUp(void)\n {\n }\n\n void tearDown(void)\n {\n }\n\n void testAllMembers()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> asInstance( new AppServerInstance(L\"id\", L\"type\") );\n\n // This call shouldn't do anything\n asInstance->Update();\n\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id\");\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id\");\n CPPUNIT_ASSERT(asInstance->GetType() == L\"type\");\n CPPUNIT_ASSERT(asInstance->GetIsDeepMonitored() == false);\n CPPUNIT_ASSERT(asInstance->GetIsRunning() == true);\n }\n\n void testSetIsDeepMonitoredHTTP()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> asInstance( new AppServerInstance(L\"id\", L\"type\") );\n\n asInstance->SetHttpPort(L\"8080\");\n CPPUNIT_ASSERT(asInstance->GetIsDeepMonitored() == false);\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\n\n asInstance->SetIsDeepMonitored(true, L\"HTTP\");\n\n CPPUNIT_ASSERT(asInstance->GetIsDeepMonitored() == true);\n CPPUNIT_ASSERT(asInstance->GetPort() == L\"8080\");\n CPPUNIT_ASSERT(asInstance->GetProtocol() == L\"HTTP\");\n }\n\n void testSetIsDeepMonitoredHTTPS()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> asInstance( new AppServerInstance(L\"id\", L\"type\") );\n\n asInstance->SetHttpsPort(L\"8443\");\n CPPUNIT_ASSERT(asInstance->GetIsDeepMonitored() == false);\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\n\n asInstance->SetIsDeepMonitored(true, L\"HTTPS\");\n\n CPPUNIT_ASSERT(asInstance->GetIsDeepMonitored() == true);\n CPPUNIT_ASSERT(asInstance->GetPort() == L\"8443\");\n CPPUNIT_ASSERT(asInstance->GetProtocol() == L\"HTTPS\");\n }\n\n void testSetIsDeepMonitored()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> asInstance( new AppServerInstance(L\"id\", L\"type\") );\n\n asInstance->SetHttpPort(L\"8080\");\n CPPUNIT_ASSERT(asInstance->GetIsDeepMonitored() == false);\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\n\n asInstance->SetIsDeepMonitored(true, L\"ABCD\");\n\n CPPUNIT_ASSERT(asInstance->GetIsDeepMonitored() == true);\n CPPUNIT_ASSERT(asInstance->GetPort() == L\"8080\");\n CPPUNIT_ASSERT(asInstance->GetProtocol() == L\"HTTP\");\n }\n\n void testSetIsRunning()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> asInstance( new AppServerInstance(L\"id\", L\"type\") );\n\n CPPUNIT_ASSERT(asInstance->GetIsRunning() == true);\n\n asInstance->SetIsRunning(false);\n\n CPPUNIT_ASSERT(asInstance->GetIsRunning() == false);\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Verify Operator== works for two identical objects\n */\n\n void testOperatorEqualsTrue()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> cutting( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n SCXCoreLib::SCXHandle<AppServerInstance> shipping( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n\n // Verify that equal works for itself\n CPPUNIT_ASSERT_MESSAGE(\"AppServerInstance should equal itself\", \n *cutting == *cutting);\n\n // Verify that equal works for two identical objects\n CPPUNIT_ASSERT_MESSAGE(\n \"AppServerInstance should equal an identical object\",\n *cutting == *shipping);\n CPPUNIT_ASSERT( *shipping == *cutting );\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Verify Operator==/Operator!= finds difference for different Disk Paths\n */\n void testOperatorEqualsFalseOnDiskPath()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> cutting( \n new AppServerInstance(L\"/opt/jboss1\", L\"type\") );\n SCXCoreLib::SCXHandle<AppServerInstance> shipping( \n new AppServerInstance(L\"/opt/jboss2\", L\"type\") );\n\n CPPUNIT_ASSERT_MESSAGE(\n \"AppServerInstance should not be equal for different DiskPaths\",\n *cutting != *shipping);\n CPPUNIT_ASSERT( *shipping != *cutting );\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Verify Operator==/Operator!= finds difference for different HTTP ports\n */\n void testOperatorEqualsFalseOnHttpPort()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> cutting( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n SCXCoreLib::SCXHandle<AppServerInstance> shipping( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n\n cutting->SetHttpPort(L\"8080\");\n shipping->SetHttpPort(L\"8081\");\n\n CPPUNIT_ASSERT_MESSAGE(\n \"AppServerInstance should not be equal for different HttpPorts\",\n *cutting != *shipping);\n CPPUNIT_ASSERT( *shipping != *cutting );\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Verify Operator==/Operator!= finds difference for different HTTPS ports\n */\n void testOperatorEqualsFalseOnHttpsPort()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> cutting( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n SCXCoreLib::SCXHandle<AppServerInstance> shipping( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n\n cutting->SetHttpsPort(L\"8443\");\n shipping->SetHttpsPort(L\"8444\");\n\n CPPUNIT_ASSERT_MESSAGE(\n \"AppServerInstance should not be equal for different HttpsPorts\",\n *cutting != *shipping);\n CPPUNIT_ASSERT( *shipping != *cutting );\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Verify Operator==/Operator!= finds difference for IsDeepMonitored\n */\n void testOperatorEqualsFalseOnIsDeepMonitored()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> cutting( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n SCXCoreLib::SCXHandle<AppServerInstance> shipping( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n\n cutting->SetIsDeepMonitored(true, L\"HTTP\");\n shipping->SetIsDeepMonitored(false, L\"HTTP\");\n\n CPPUNIT_ASSERT_MESSAGE(\n \"AppServerInstance should not be equal for differences in deep monitoring\",\n *cutting != *shipping);\n CPPUNIT_ASSERT( *shipping != *cutting );\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Verify Operator==/Operator!= finds difference for IsRunning\n */\n void testOperatorEqualsFalseOnIsRunning()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> cutting( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n SCXCoreLib::SCXHandle<AppServerInstance> shipping( \n new AppServerInstance(L\"/opt/jboss\", L\"type\") );\n\n cutting->SetIsRunning(true);\n shipping->SetIsRunning(false);\n\n CPPUNIT_ASSERT_MESSAGE(\n \"AppServerInstance should not be equal if one is running and the other is not\",\n *cutting != *shipping);\n CPPUNIT_ASSERT( *shipping != *cutting );\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Verify Operator==/Operator!= finds difference for different Type\n */\n void testOperatorEqualsFalseOnType()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> cutting( \n new AppServerInstance(L\"/opt/jboss\", L\"TOMCAT\") );\n SCXCoreLib::SCXHandle<AppServerInstance> shipping( \n new AppServerInstance(L\"/opt/jboss\", L\"JBOSS\") );\n\n CPPUNIT_ASSERT_MESSAGE(\n \"AppServerInstance should not be equal for different App Server types\",\n *cutting != *shipping);\n CPPUNIT_ASSERT( *shipping != *cutting );\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Verify Operator==/Operator!= finds difference for different Version\n */\n void testOperatorEqualsFalseOnVersion()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> cutting( \n new AppServerInstance(L\"/opt/jboss\", L\"JBOSS\") );\n SCXCoreLib::SCXHandle<AppServerInstance> shipping( \n new AppServerInstance(L\"/opt/jboss\", L\"JBOSS\") );\n\n cutting->SetVersion(L\"5.1.0-GA\");\n shipping->SetVersion(L\"4.2.0\");\n\n CPPUNIT_ASSERT_MESSAGE(\n \"AppServerInstance should not be equal for different App Server versions\",\n *cutting != *shipping);\n CPPUNIT_ASSERT( *shipping != *cutting );\n }\n\n /*-------------------------------------------------------------------*/\n /**\n Test the extraction of the major version from the version number\n */\n void testExtractMajorVersion()\n {\n SCXCoreLib::SCXHandle<AppServerInstance> asinst( new AppServerInstance(L\"/opt/jboss\", L\"JBOSS\") );\n\n asinst->SetVersion(L\"5.1.0-GA\");\n CPPUNIT_ASSERT(asinst->GetMajorVersion() == L\"5\");\n\n asinst->SetVersion(L\"4.2.0\");\n CPPUNIT_ASSERT(asinst->GetMajorVersion() == L\"4\");\n\n asinst->SetVersion(L\"10.3.2\");\n CPPUNIT_ASSERT(asinst->GetMajorVersion() == L\"10\");\n }\n\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( AppServerInstance_Test );\n" }, { "alpha_fraction": 0.6079581379890442, "alphanum_fraction": 0.6135066747665405, "avg_line_length": 41.3355712890625, "blob_id": "528fac5ad649683ab71f5676c3855709ece3dd4e", "content_id": "dedca274278655ed2538e14056ba74992806f8b1", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6308, "license_type": "permissive", "max_line_length": 114, "num_lines": 149, "path": "/test/code/providers/memory_provider/memoryprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n Created date 2007-07-04 10:08:57\n\n Memory provider test class.\n\n Only tests the functionality of the provider class.\n The actual data gathering is tested by a separate class.\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n\n#include \"startuplog.h\"\n#include \"memoryprovider.h\"\n#include \"SCX_Agent.h\"\n#include \"SCX_Agent_Class_Provider.h\"\n#include \"SCX_MemoryStatisticalInformation_Class_Provider.h\"\n\nusing namespace SCXCore;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nclass MemoryProvider_Test : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( MemoryProvider_Test );\n CPPUNIT_TEST( callDumpStringForCoverage );\n CPPUNIT_TEST( TestEnumerateInstancesKeysOnly );\n CPPUNIT_TEST( TestEnumerateInstances );\n CPPUNIT_TEST( TestVerifyKeyCompletePartial );\n CPPUNIT_TEST( TestGetInstance );\n\n SCXUNIT_TEST_ATTRIBUTE(callDumpStringForCoverage, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestEnumerateInstancesKeysOnly, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestEnumerateInstances, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartial, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestGetInstance, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector<std::wstring> m_keyNames;\n\npublic:\n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_MemoryStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n m_keyNames.push_back(L\"Name\");\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_MemoryStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void callDumpStringForCoverage()\n {\n CPPUNIT_ASSERT(g_MemoryProvider.DumpString().find(L\"MemoryProvider\") != std::wstring::npos);\n }\n\n void TestEnumerateInstancesKeysOnly()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_MemoryStatisticalInformation_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(L\"Memory\", context[0].GetKey(L\"Name\", CALL_LOCATION(errMsg)));\n }\n\n void TestEnumerateInstances()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_MemoryStatisticalInformation_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartial()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_MemoryStatisticalInformation_Class_Provider,\n mi::SCX_MemoryStatisticalInformation_Class>(m_keyNames, CALL_LOCATION(errMsg));\n }\n\n void TestGetInstance()\n {\n std::wstring errMsg;\n\n std::vector<std::wstring> keyValues;\n keyValues.push_back(L\"Memory\");\n TestableContext context;\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, (GetInstance<mi::SCX_MemoryStatisticalInformation_Class_Provider,\n mi::SCX_MemoryStatisticalInformation_Class>(m_keyNames, keyValues, context, CALL_LOCATION(errMsg))));\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void ValidateInstance(const TestableContext& context, std::wstring errMsg)\n {\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());// This provider has only one instance.\n const TestableInstance &instance = context[0];\n \n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, m_keyNames[0], instance.GetKeyName(0, CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Memory\", instance.GetKeyValue(0, CALL_LOCATION(errMsg)));\n\n std::wstring tmpExpectedProperties[] = {L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"IsAggregate\",\n L\"AvailableMemory\",\n L\"PercentAvailableMemory\",\n L\"UsedMemory\",\n L\"PercentUsedMemory\",\n L\"PagesPerSec\",\n L\"PagesReadPerSec\",\n L\"PagesWrittenPerSec\",\n L\"AvailableSwap\",\n L\"PercentAvailableSwap\",\n L\"UsedSwap\",\n L\"PercentUsedSwap\",\n L\"PercentUsedByCache\"};\n\n const size_t numprops = sizeof(tmpExpectedProperties) / sizeof(tmpExpectedProperties[0]);\n VerifyInstancePropertyNames(instance, tmpExpectedProperties, numprops, CALL_LOCATION(errMsg));\n\n // Test that the percentages add up to about 100%.\n TestableInstance::PropertyInfo info;\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, instance.FindProperty(L\"PercentAvailableMemory\", info));\n MI_Uint8 percentAvailableMemory = info.GetValue_MIUint8(CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, instance.FindProperty(L\"PercentUsedMemory\", info));\n MI_Uint8 percentUsedMemory = info.GetValue_MIUint8(CALL_LOCATION(errMsg));\n\n SCXUNIT_ASSERT_BETWEEN(static_cast<unsigned int>(percentAvailableMemory) + percentUsedMemory, 98, 102);\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( MemoryProvider_Test );\n" }, { "alpha_fraction": 0.5171703100204468, "alphanum_fraction": 0.521291196346283, "avg_line_length": 24.086206436157227, "blob_id": "42ced9410ff63493424e9efca1cb9de8e80050b1", "content_id": "9380a796872ce7cfd034efd78d47a7ab7ba78d3e", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1456, "license_type": "permissive", "max_line_length": 108, "num_lines": 58, "path": "/source/code/providers/support/memoryprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n * \n * */\n /**\n \\file memoryprovider.h\n\n \\brief Memory provider\n\n \\date 04-18-03\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef MEMORYPROVIDER_H\n#define MEMORYPROVIDER_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n#include <scxsystemlib/memoryenumeration.h>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXCore\n{\n class MemoryProvider\n {\n public:\n MemoryProvider() { };\n virtual ~MemoryProvider() { };\n void Load();\n void Unload();\n\n SCXCoreLib::SCXHandle<SCXSystemLib::MemoryEnumeration> GetMemoryEnumeration() const\n {\n return m_memEnum;\n }\n\n SCXLogHandle& GetLogHandle() { return m_log; }\n\n virtual const std::wstring DumpString() const\n {\n return L\"MemoryProvider\";\n }\n \n private:\n SCXCoreLib::SCXHandle<SCXSystemLib::MemoryEnumeration> m_memEnum;\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n };\n\n extern SCXCore::MemoryProvider g_MemoryProvider;\n}\n\n\n#endif /* MEMORYPROVIDER_H */\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n\n" }, { "alpha_fraction": 0.634102463722229, "alphanum_fraction": 0.6362001895904541, "avg_line_length": 40.45341491699219, "blob_id": "a791aa1df135e75e5deaadfa7857165bdfc2a3be", "content_id": "c7b5b19d4ad56157a9e148e9d724092e8139c921", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 6674, "license_type": "permissive", "max_line_length": 219, "num_lines": 161, "path": "/build/Makefile.providers", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*- \n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#--------------------------------------------------------------------------------\n\nPROVIDER_DIR := $(SCX_SRC_ROOT)/providers\nPROVIDER_SUPPORT_DIR := $(PROVIDER_DIR)/support\nAPPSERVER_SUPPORT_DIR := $(PROVIDER_DIR)/support/appserver\n\n#--------------------------------------------------------------------------------\n# Meta Provider\n\nSTATIC_METAPROVIDERLIB_SRCFILES = \\\n\t$(PROVIDER_DIR)/support/metaprovider.cpp \\\n\t$(PROVIDER_DIR)/SCX_Agent_Class_Provider.cpp\n\n#--------------------------------------------------------------------------------\n# AS Provider\n\nSTATIC_APPSERVERLIB_SRCFILES = \\\n\t$(APPSERVER_SUPPORT_DIR)/appserverenumeration.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/appserverinstance.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/appserverprovider.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/jbossappserverinstance.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/tomcatappserverinstance.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/weblogicappserverinstance.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/weblogicappserverenumeration.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/websphereappserverinstance.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/manipulateappserverinstances.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/persistappserverinstances.cpp \\\n\t$(APPSERVER_SUPPORT_DIR)/removenonexistentappserverinstances.cpp \\\n\t$(PROVIDER_DIR)/SCX_Application_Server_Class_Provider.cpp\n\n#--------------------------------------------------------------------------------\n# CPU Provider\n\nSTATIC_CPUPROVIDER_SRCFILES = \\\n\t$(PROVIDER_DIR)/SCX_ProcessorStatisticalInformation_Class_Provider.cpp \\\n\t$(PROVIDER_DIR)/SCX_RTProcessorStatisticalInformation_Class_Provider.cpp\n\n#--------------------------------------------------------------------------------\n# Disk Provider\n\nSTATIC_DISKPROVIDERLIB_SRCFILES = \\\n\t$(PROVIDER_DIR)/support/diskprovider.cpp \\\n\t$(PROVIDER_DIR)/support/filesystemprovider.cpp \\\n\t$(PROVIDER_DIR)/SCX_DiskDrive_Class_Provider.cpp \\\n\t$(PROVIDER_DIR)/SCX_DiskDriveStatisticalInformation_Class_Provider.cpp \\\n\t$(PROVIDER_DIR)/SCX_FileSystem_Class_Provider.cpp \\\n\t$(PROVIDER_DIR)/SCX_FileSystemStatisticalInformation_Class_Provider.cpp\n\n#--------------------------------------------------------------------------------\n# LogFile Provider\n\nSTATIC_LOGFILEPROVIDERLIB_SRCFILES = \\\n\t$(PROVIDER_DIR)/support/logfileutils.cpp \\\n\t$(PROVIDER_DIR)/support/logfileprovider.cpp \\\n\t$(PROVIDER_DIR)/SCX_LogFile_Class_Provider.cpp\n\n#--------------------------------------------------------------------------------\n# Memory Provider\n\nSTATIC_MEMORYPROVIDERLIB_SRCFILES = \\\n\t$(PROVIDER_DIR)/support/memoryprovider.cpp \\\n\t$(PROVIDER_DIR)/SCX_MemoryStatisticalInformation_Class_Provider.cpp\n\n#--------------------------------------------------------------------------------\n# Network Provider\n\nSTATIC_NETWORKPROVIDERLIB_SRCFILES = \\\n\t$(PROVIDER_DIR)/SCX_EthernetPortStatistics_Class_Provider.cpp \\\n\t$(PROVIDER_DIR)/SCX_IPProtocolEndpoint_Class_Provider.cpp \\\n\t$(PROVIDER_DIR)/SCX_LANEndpoint_Class_Provider.cpp \\\n\t$(PROVIDER_DIR)/support/networkprovider.cpp\n\n#--------------------------------------------------------------------------------\n# OS Provider\n\nSTATIC_OSPROVIDERLIB_SRCFILES = \\\n\t$(PROVIDER_SUPPORT_DIR)/scxrunasconfigurator.cpp \\\n\t$(PROVIDER_DIR)/support/osprovider.cpp \\\n\t$(PROVIDER_DIR)/support/runasprovider.cpp \\\n\t$(PROVIDER_DIR)/SCX_OperatingSystem_Class_Provider.cpp\n\n#--------------------------------------------------------------------------------\n# Process Provider\n\nSTATIC_PROCESSPROVIDERLIB_SRCFILES = \\\n $(PROVIDER_DIR)/support/processprovider.cpp \\\n\t$(PROVIDER_DIR)/SCX_UnixProcess_Class_Provider.cpp \\\n\t$(PROVIDER_DIR)/SCX_UnixProcessStatisticalInformation_Class_Provider.cpp\n\n#--------------------------------------------------------------------------------\n# Provider Library\n\nSTATIC_PROVIDERLIB_SRCFILES = \\\n\t$(PROVIDER_DIR)/schema.c \\\n\t$(PROVIDER_DIR)/stubs.cpp \\\n\t$(PROVIDER_DIR)/module.cpp \\\n\t$(PROVIDER_SUPPORT_DIR)/logpolicy.cpp \\\n\t$(PROVIDER_SUPPORT_DIR)/scxcimutils.cpp \\\n\t$(STATIC_METAPROVIDERLIB_SRCFILES) \\\n\t$(STATIC_APPSERVERLIB_SRCFILES) \\\n\t$(STATIC_CPUPROVIDER_SRCFILES) \\\n\t$(STATIC_DISKPROVIDERLIB_SRCFILES) \\\n\t$(STATIC_LOGFILEPROVIDERLIB_SRCFILES) \\\n\t$(STATIC_MEMORYPROVIDERLIB_SRCFILES) \\\n\t$(STATIC_NETWORKPROVIDERLIB_SRCFILES) \\\n\t$(STATIC_OSPROVIDERLIB_SRCFILES) \\\n\t$(STATIC_PROCESSPROVIDERLIB_SRCFILES)\n\n\n# The OMI source files won't compile with our very strict flags - ease up for them\n# (and, for HP, allow a mechanism to modify the flags)\n$(call src_to_obj,$(STATIC_PROVIDERLIB_SRCFILES)): CXX_WARN_STRICT_FLAGS=$(CXX_WARN_STRICT_FLAGS_PROVIDERS)\n$(call src_to_obj,$(STATIC_PROVIDERLIB_SRCFILES)): C_WARN_STRICT_FLAGS=$(CXX_WARN_STRICT_FLAGS_PROVIDERS)\n\nSTATIC_PROVIDERLIB_OBJFILES = $(call src_to_obj,$(STATIC_PROVIDERLIB_SRCFILES))\n\n# TODO: Not clear why the srcfiles need to be a dependency, but without it, build won't build after updating a source file\n$(INTERMEDIATE_DIR)/libomprovider.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_PROVIDERLIB_OBJFILES) $(STATIC_PROVIDERLIB_SRCFILES)\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $(STATIC_PROVIDERLIB_OBJFILES) # $^\n\n\nCLASSES = SCX_Agent \\\n\tSCX_Application_Server \\\n\tSCX_DiskDrive \\\n\tSCX_DiskDriveStatisticalInformation \\\n\tSCX_FileSystem \\\n\tSCX_FileSystemStatisticalInformation \\\n\tSCX_EthernetPortStatistics \\\n\tSCX_LANEndpoint \\\n\tSCX_IPProtocolEndpoint \\\n\tSCX_LogFile \\\n\tSCX_MemoryStatisticalInformation \\\n\tSCX_OperatingSystem \\\n\tSCX_ProcessorStatisticalInformation \\\n\tSCX_RTProcessorStatisticalInformation \\\n\tSCX_UnixProcess \\\n\tSCX_UnixProcessStatisticalInformation\n\nOMIGEN = $(TARGET_DIR)/omi/bin/omigen\n\n# .PHONY : schema_gen devel-deps\n# TODO - this target needs devel-deps to run first, but if it's included as a dependency, schema_gen won't run!\n# schema_gen : devel-deps\nschema_gen :\n\t# The omigen facility is unhappy if no ~/.omigenrc file exists, so create one for this run\n\ttouch ~/.omigenrc\n\tcd $(TARGET_DIR)/omi; $(OMIGEN) $(MOF_PATH)/scx.mof -d $(PROVIDER_DIR) $(CLASSES) --cpp -I $(SCXOMI_DIR)/share/omischema\n\trm ~/.omigenrc\n\n# Note: For omi_reg to work properly, run './configure --enable-local-omi'\nomi_reg :\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH):$(INTERMEDIATE_DIR)/omi/lib; cd $(INTERMEDIATE_DIR)/omi; bin/omireg --destdir=$(INTERMEDIATE_DIR)/omi -n root/scx -o @requestor@ $(INTERMEDIATE_DIR)/libSCXCoreProviderModule.so\n\n# bin/omiserver --destdir /home/jeffcof/dev/blue/opsmgr/target/Linux_REDHAT_6.1_x64_64_Debug/omi\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.6040909290313721, "alphanum_fraction": 0.6045454740524292, "avg_line_length": 32.769229888916016, "blob_id": "c1cd580614bf40af6e058fd33437e776f98664ba", "content_id": "664929ed59dbc87f1245cbc516c4ac80c14b0780", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2200, "license_type": "permissive", "max_line_length": 76, "num_lines": 65, "path": "/test/code/shared/tools/scx_prune_repository/dependencywalker_test.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "import unittest\nimport os\nimport shutil\nimport sys\nsys.path.append('../../../../source/code/tools/scx_prune_repository')\nfrom dependencywalker import DependencyWalker\nfrom moffilerepository import MofFileRepository\nfrom moffile import MofFile\n\nclass DependencyWalkerTestCase(unittest.TestCase):\n def setUp(self):\n try:\n os.mkdir('./repository')\n out = open('./repository/BaseClass.mof', 'w')\n out.write('class BaseClass {\\n')\n out.write('}')\n out.close()\n out = open('./repository/SubClass.mof', 'w')\n out.write('class SubClass : BaseClass {\\n')\n out.write('}')\n except OSError:\n pass\n \n def tearDown(self):\n try:\n shutil.rmtree('./repository', 1)\n os.remove('./TestFile.mof')\n except OSError:\n pass\n\n def testNoFiles(self):\n mofrepository = MofFileRepository('./repository')\n depLister = DependencyWalker(mofrepository, [])\n self.assertEqual(depLister.GetRequiredFiles(), [])\n\n def testMofFileWithNoDependentClasses(self):\n out = open('./TestFile.mof', 'w')\n out.write('class TestClass {\\n')\n out.write('}\\n')\n out.close()\n\n mofrepository = MofFileRepository('./repository')\n moffile = MofFile('./TestFile.mof')\n depLister = DependencyWalker(mofrepository, [moffile])\n self.assertEqual(depLister.GetRequiredFiles(), [])\n\n def testMofFileWithOneDependentClass(self):\n out = open('./TestFile.mof', 'w')\n out.write('class TestClass : BaseClass {\\n')\n out.write('}')\n out.close()\n\n mofrepository = MofFileRepository('./repository')\n moffile = MofFile('./TestFile.mof')\n depLister = DependencyWalker(mofrepository, [moffile])\n\n self.assertEqual(self.GetMofFileNames(depLister.GetRequiredFiles()),\n ['./repository/BaseClass.mof'])\n\n def GetMofFileNames(self, moffiles):\n filenames = []\n for moffile in moffiles:\n self.assert_(isinstance(moffile, MofFile))\n filenames.append(moffile.GetFileName())\n return filenames\n \n" }, { "alpha_fraction": 0.634088933467865, "alphanum_fraction": 0.6419354677200317, "avg_line_length": 32.834808349609375, "blob_id": "9c64ac3feb443341685b8dacc5e47be549b6e210", "content_id": "548b5ddd739e86c523d77ea8a7ab0c6b213522e8", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11470, "license_type": "permissive", "max_line_length": 148, "num_lines": 339, "path": "/source/code/providers/SCX_FileSystemStatisticalInformation_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_FileSystemStatisticalInformation_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-14-2013 11:09:45\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_FileSystemStatisticalInformation_Class_Provider.h\"\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxnameresolver.h>\n#include <scxcorelib/scxmath.h>\n#include \"support/filesystemprovider.h\"\n#include \"support/scxcimutils.h\"\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/scxpatternfinder.h>\n\n# define QLENGTH 1000\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_FileSystemStatisticalInformation_Class& inst,\n bool keysOnly,\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskInstance> diskinst)\n{\n diskinst->Update();\n\n // Populate the key values\n std::wstring name;\n if (diskinst->GetDiskName(name))\n {\n inst.Name_value(StrToMultibyte(name).c_str());\n }\n\n if (!keysOnly)\n {\n inst.Caption_value(\"File system information\");\n inst.Description_value(\"Performance statistics related to a logical unit of secondary storage\");\n\n scxulong data1;\n scxulong data2;\n scxulong data3;\n double ddata1;\n bool healthy;\n\n if (diskinst->GetHealthState(healthy))\n {\n inst.IsOnline_value(healthy);\n }\n\n inst.IsAggregate_value(diskinst->IsTotal());\n\n if (diskinst->GetIOPercentageTotal(data1))\n {\n inst.PercentBusyTime_value((unsigned char) data1);\n inst.PercentIdleTime_value((unsigned char) (100-data1));\n }\n\n if (diskinst->GetBytesPerSecondTotal(data1))\n {\n inst.BytesPerSecond_value(data1);\n }\n\n if (diskinst->GetBytesPerSecond(data1, data2))\n {\n inst.ReadBytesPerSecond_value(data1);\n inst.WriteBytesPerSecond_value(data2);\n }\n\n if (diskinst->GetTransfersPerSecond(data1))\n {\n inst.TransfersPerSecond_value(data1);\n }\n\n if (diskinst->GetReadsPerSecond(data1))\n {\n inst.ReadsPerSecond_value(data1);\n }\n\n if (diskinst->GetWritesPerSecond(data1))\n {\n inst.WritesPerSecond_value(data1);\n }\n\n if (diskinst->GetIOTimesTotal(ddata1))\n {\n inst.AverageTransferTime_value(ddata1);\n }\n\n if (diskinst->GetDiskSize(data1, data2, data3))\n {\n inst.FreeMegabytes_value(data2);\n inst.UsedMegabytes_value(data1);\n unsigned char freeSpace = 100;\n unsigned char usedSpace = 0;\n scxulong totalData = data1 + data2;\n if (0 < totalData)\n {\n freeSpace = (unsigned char) SCXCoreLib::GetPercentage(0, data2, 0, totalData);\n usedSpace = (unsigned char) SCXCoreLib::GetPercentage(0, data1, 0, totalData);\n }\n inst.PercentFreeSpace_value(freeSpace);\n inst.PercentUsedSpace_value(usedSpace);\n }\n\n // Report percentages for inodes even if inode data is not known\n {\n if (!diskinst->GetInodeUsage(data1, data2))\n {\n data1 = data2 = 0;\n }\n unsigned char freeInodes = 100;\n unsigned char usedInodes = 0;\n\n if (0 < data1+data2)\n {\n freeInodes = (unsigned char) SCXCoreLib::GetPercentage(0, data2, 0, data1);\n usedInodes = (unsigned char) SCXCoreLib::GetPercentage(0, data2, 0, data1, true);\n }\n\n inst.PercentFreeInodes_value(freeInodes);\n inst.PercentUsedInodes_value(usedInodes);\n }\n\n if (diskinst->GetDiskQueueLength(ddata1))\n {\n inst.AverageDiskQueueLength_value(ddata1);\n }\n }\n context.Post(inst);\n}\n\nSCX_FileSystemStatisticalInformation_Class_Provider::SCX_FileSystemStatisticalInformation_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_FileSystemStatisticalInformation_Class_Provider::~SCX_FileSystemStatisticalInformation_Class_Provider()\n{\n}\n\nvoid SCX_FileSystemStatisticalInformation_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n SCXCore::g_FileSystemProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_FileSystemProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_FileSystemStatisticalInformation_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystemStatisticalInformation_Class_Provider::Load\", SCXCore::g_FileSystemProvider.GetLogHandle() );\n}\n\nvoid SCX_FileSystemStatisticalInformation_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n SCXCore::g_FileSystemProvider.UnLoad();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystemStatisticalInformation_Class_Provider::Unload\", SCXCore::g_FileSystemProvider.GetLogHandle() );\n}\n\nvoid SCX_FileSystemStatisticalInformation_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_FileSystemProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"FileSystemStat EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n\n // Prepare File System Enumeration\n // (Note: Only do full update if we're not enumerating keys)\n\n wstring mountPoint=L\"\";\n size_t instancePos=(size_t)-1;\n\n if(filter) {\n char* exprStr[QLENGTH]={NULL};\n char* qtypeStr[QLENGTH]={NULL};\n\n const MI_Char** expr=(const MI_Char**)&exprStr;\n const MI_Char** qtype=(const MI_Char**)&qtypeStr;\n\n MI_Filter_GetExpression(filter, qtype, expr);\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"FileSystemStatisticalInformation Provider Filter Set with Expression: \",*expr));\n\n std::wstring filterQuery(SCXCoreLib::StrFromUTF8(*expr));\n\n SCXCoreLib::SCXPatternFinder::SCXPatternCookie s_patternID = 0, id=0;\n SCXCoreLib::SCXPatternFinder::SCXPatternMatch param;\n std::wstring s_pattern(L\"select * from SCX_FileSystemStatisticalInformation where Name=%name\");\n\n SCXCoreLib::SCXPatternFinder patterenfinder;\n patterenfinder.RegisterPattern(s_patternID, s_pattern);\n\n bool status=patterenfinder.Match(filterQuery, id, param);\n\n\n if ( status && param.end() != param.find(L\"name\") && id == s_patternID )\n {\n mountPoint=param.find(L\"name\")->second;\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"FileSystemStatisticalInformation Provider Enum Requested for mount point: \",mountPoint));\n }\n }\n\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskEnumeration> diskEnum = SCXCore::g_FileSystemProvider.getEnumstatisticalLogicalDisks();\n\n mountPoint != L\"\" && mountPoint != L\"_Total\"?diskEnum->UpdateSpecific(mountPoint, &instancePos):diskEnum->Update(!keysOnly); \n if (instancePos != (size_t)-1)\n {\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskInstance> diskInst = diskEnum->GetInstance(instancePos);\n SCX_FileSystemStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, keysOnly, diskInst);\n }\n else\n {\n for(size_t i = 0; i < diskEnum->Size(); i++)\n {\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskInstance> diskInst = diskEnum->GetInstance(i);\n SCX_FileSystemStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, keysOnly, diskInst);\n }\n\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskInstance> totalInst= diskEnum->GetTotalInstance();\n if (totalInst != NULL)\n {\n \t// There will always be one total instance\n \tSCX_FileSystemStatisticalInformation_Class inst;\n \tEnumerateOneInstance(context, inst, keysOnly, totalInst);\n }\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystemStatisticalInformation_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"FileSystemStat EnumerateInstances end\");\n}\n\nvoid SCX_FileSystemStatisticalInformation_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystemStatisticalInformation_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for DiskProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::DiskProvider::Lock\"));\n\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskEnumeration> diskEnum = SCXCore::g_FileSystemProvider.getEnumstatisticalLogicalDisks();\n diskEnum->Update(true);\n\n const std::string name = instanceName.Name_value().Str();\n\n if (name.size() == 0)\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n SCXHandle<SCXSystemLib::StatisticalLogicalDiskInstance> diskInst;\n diskInst = diskEnum->GetInstance(StrFromUTF8(name));\n\n if (diskInst == NULL)\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCX_FileSystemStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, false, diskInst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_FileSystemStatisticalInformation_Class_Provider::GetInstance\", \n SCXCore::g_FileSystemProvider.GetLogHandle() )\n}\n\nvoid SCX_FileSystemStatisticalInformation_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystemStatisticalInformation_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_FileSystemStatisticalInformation_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystemStatisticalInformation_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_FileSystemStatisticalInformation_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_FileSystemStatisticalInformation_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.5994030833244324, "alphanum_fraction": 0.6149892210960388, "avg_line_length": 30.736841201782227, "blob_id": "c1d0641e1427d4b6eaf06118f5c623636435bf8e", "content_id": "d85c1499553a64de3d2b6c65422e2945eaf03dae", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 6031, "license_type": "permissive", "max_line_length": 170, "num_lines": 190, "path": "/build/Makefile.pf.SunOS", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n# \n# Platform-specific overrides to the general POSIX platform file\n# \n#--------------------------------------------------------------------------------\n\n# Solaris 5.11 compiler is a little different ...\n\nifeq ($(PF_MAJOR),5)\nifeq ($(PF_MINOR),11)\n\nUSING_SOLARIS_11=1\n\nendif\nendif\n\n# Determine if we support -erroff=wbadlkginit ... (seems to be in SunStudio 5.13)\nWBADLKGINIT_SUPPORTED:=$(shell CC -V 2>&1 | grep 5.13 >/dev/null 2>&1 && echo \"1\" || echo \"0\")\n\n# Define flags. (These will be submitted to all commands that use the preprocesor)\nDEFINES += `pkg-config --cflags openssl` -DPF_MAJOR=$(PF_MAJOR) -DPF_MINOR=$(PF_MINOR) -D_LARGEFILE64_SOURCE=1\n\nifeq ($(SCX_STACK_ONLY), true)\n\tDEFINES += -DSCX_STACK_ONLY\nendif\n\n# Compiler flags that regulates warning levels\n# Suppresses warnings about extern \"C\":\nifeq ($(WBADLKGINIT_SUPPORTED),1)\nCXX_WARN_FLAGS=-errtags -erroff=badargtype2w,wbadinit,wnoretvalue,truncwarn,wbadlkginit -xwe +w\nelse\nCXX_WARN_FLAGS=-errtags -erroff=badargtype2w,wbadinit,wnoretvalue,truncwarn -xwe +w\nendif\n\n# CXX Compiler flags \nCXXFLAGS=$(DEFINES) $(CXX_WARN_FLAGS) -KPIC -mt -xspace -xtarget=generic -xarch=generic\nCFLAGS=$(DEFINES) $(CXX_WARN_FLAGS) -KPIC -mt -xspace -xtarget=generic -xarch=generic\n\n# On Solaris 11 (debug only), -features=no%split_init causes core dumps (due to\n# the fact that size optimization does not happen when the singleton is in a\n# separate dynamic library - as it is for Debug builds).\n#\n# For safety, include that flag in all cases EXCEPT for Solaris 11 (Debug)\n\nUSE_SOLARIS_SIZE_OPTIMIZATION=1\n\nifeq ($(BUILD_TYPE),Debug)\nifeq ($(USING_SOLARIS_11),1)\n\tUSE_SOLARIS_SIZE_OPTIMIZATION=0\nendif\nendif\n\nifeq ($(USE_SOLARIS_SIZE_OPTIMIZATION),1)\n\tCXXFLAGS += -features=no%split_init\n\tCFLAGS += -features=no%split_init\nendif\n\n# These flags are used for all link commands.\n# I.e. for executables, static libraries and for dynamic libraries.\nLDFLAGS_COMMON=-norunpath -lm -lpthread -mt -i\n\n# CXX Debug flags for debug builds\nifeq ($(BUILD_TYPE),Debug)\n\tCXXFLAGS += -g\n\tDEFINES += -D_DEBUG\n\tLDFLAGS_COMMON += -g\nifeq ($(ARCH),sparc)\n\tLDFLAGS_COMMON += -xcheck=%all\nendif\nelse\n\tCXXFLAGS += -g -xO1\n\tDEFINES += -DNDEBUG\n\tLDFLAGS_COMMON += -xldscope=hidden\nifeq ($(ARCH),sparc)\n\tLDFLAGS_COMMON += -xlinkopt=2\nendif\nendif\n\n# Linker flags\nLINK_OUTFLAG=-o $@\nLINK_STATLIB_OUTFLAG=-o $@\n\n#--------------------------------------------------------------------------------\n# Tools on this platform\n\n# Compiler for CPP files\nCXX=CC\n\n# Link command for executables\n# Link an executable \nLINK=CC -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR) -L$(SCXOMI_LIBS)\n\n# Link command for static libraries (archives)\nLINK_STATLIB=CC -xar -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR) $(LDFLAGS_COMMON)\n\n# Link a dynamic lib \nLINK_DYNLIB=CC -G -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR)\n\n# Include paths for POSIX platforms\nINCLUDES=-I$(SCX_SHARED_INCLUDE_DIR) -I$(INT_INCLUDE_DIR) -I$(SCXPAL_INT_INCLUDE_DIR) -I$(SCX_BRD) -I$(SCXPAL_DIR) -I$(SCX_SHARED_TST_EXT_INCLUDE_DIR) -I$(SCXOMI_INCLUDE)\nUNITTEST_EXTRA_INCLUDES=-I$(SCXPAL_TEST_ROOT)/include -I$(SCX_SHARED_SRC_ROOT)\n\n# No operation, i.e. suppressing a command\nNOOP=@echo Step suppressed \n\n# Command for making dependecies\nMKDEP=CC -xM1\n\n#--------------------------------------------------------------------------------\n# File type suffixes\n\nPF_OBJ_FILE_SUFFIX=o\nPF_STAT_LIB_FILE_SUFFIX=a\nPF_DYN_LIB_FILE_SUFFIX=so\nPF_EXE_FILE_SUFFIX=\nPF_KIT_FILE_SUFFIX=tar\n\n#--------------------------------------------------------------------------------\n# Paths\n#--------------------------------------------------------------------------------\n\n# Path to where the CPPUNIT libraries are checked in \nCPPUNIT_LIB_PATH=$(SCX_SHARED_TST_EXT_LIB_DIR)/solaris/$(ARCH)/cppunit\n\n#--------------------------------------------------------------------------------\n# Link switches for this platform, per target\n#--------------------------------------------------------------------------------\n\nLDFLAGS_DYNLIB = $(LDFLAGS_COMMON)\nLDFLAGS_EXECUTABLE = -lnsl -lrt $(LDFLAGS_COMMON)\n\n# The Core Provider Module links with these \nLDFLAGS_COREPROVIDERMODULE = $(LDFLAGS_DYNLIB) -lkstat -lsocket\n\n# The Test Provider Module links with these\nLDFLAGS_TESTPROVIDERMODULE = $(LDFLAGS_DYNLIB)\n\n# Test Provider specific link flags. Used to hide symbols\nTESTPROVIDERMODULE_EXTRA_LINKFLAGS=-M $(INTERMEDIATE_DIR)/testprovider.map\n\n# Transforms a list of symbols that should be exposed to the correct link flags\nget_ld_flags_for_retaining_symbols=$(addprefix -u, $(1))\n\n# The testrunner links with these\nLDFLAGS_TESTRUNNER = $(LDFLAGS_EXECUTABLE) -lkstat -lsocket\n\n# Run pkg-config to get ssl library switches for this platform\nSSL_LIBS = `pkg-config --libs openssl`\n\n#--------------------------------------------------------------------------------\n# InstallBuilder datafile determination\n#--------------------------------------------------------------------------------\n\nPF_DEPENDENT_DATAFILES = SunOS.data\nifeq ($(PF_ARCH), x86)\nPF_DEPENDENT_DATAFILES += SunOS_x86.data\nelse\nPF_DEPENDENT_DATAFILES += SunOS_SPARC.data\nendif\n\nifeq ($(PF_MINOR), 11)\nPF_DEPENDENT_DATAFILES += SunOS_5.11.data\n ifeq ($(PF_ARCH), x86)\nPF_DEPENDENT_DATAFILES += SunOS_x86_5.11.data\n else\nPF_DEPENDENT_DATAFILES += SunOS_SPARC_5.11.data\n endif\nendif\nifeq ($(PF_MINOR), 10)\nPF_DEPENDENT_DATAFILES += SunOS_5.10.data\n ifeq ($(PF_ARCH), x86)\nPF_DEPENDENT_DATAFILES += SunOS_x86_5.10.data\n else\nPF_DEPENDENT_DATAFILES += SunOS_SPARC_5.10.data\n endif\nendif\nifeq ($(PF_MINOR), 9)\nPF_DEPENDENT_DATAFILES += SunOS_5.9.data\n ifeq ($(PF_ARCH), x86)\nPF_DEPENDENT_DATAFILES += SunOS_x86_5.9.data\n else\nPF_DEPENDENT_DATAFILES += SunOS_SPARC_5.9.data\n endif\nendif\n\n#-------------------------------- End of File -----------------------------------\n\n" }, { "alpha_fraction": 0.6003671288490295, "alphanum_fraction": 0.6122259497642517, "avg_line_length": 40.055885314941406, "blob_id": "d7ae686130a59a465dfbd7cc8adbbe1b007da74b", "content_id": "c39195f90f26663bfe4b9808ca6f486ece19100e", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 48487, "license_type": "permissive", "max_line_length": 680, "num_lines": 1181, "path": "/test/code/providers/appserver_provider/weblogicappserverenumeration_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*---------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n */\n/**\n \\file weblogicappserverenumeration_test.h\n\n \\brief Tests for the logic of enumerating\n WebLogic application servers\n\n \\date 11-08-18 12:00:00\n\n */\n\n/*------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfilesystem.h>\n#include <scxcorelib/scxlog.h>\n#include <testutils/scxunit.h>\n\n#include <appserverconstants.h>\n#include <appserverinstance.h>\n#include <weblogicappserverenumeration.h>\n#include <weblogicappserverinstance.h>\n\n#include <cppunit/extensions/HelperMacros.h>\n\n#include <iostream>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\nusing namespace std;\n\nnamespace SCXUnitTests {\n\n const static size_t zeroSize = 0;\n const static size_t oneSize = 1;\n const static size_t twoSize = 2;\n const static size_t threeSize = 3;\n const static size_t fourSize = 4;\n\n const static wstring WEBLOGIC_MAJOR_VERSION_10 = L\"10\";\n const static wstring WEBLOGIC_MAJOR_VERSION_11 = L\"11\";\n\n const static wstring WEBLOGIC_VERSION_10 = L\"10.3.0.0\";\n const static wstring WEBLOGIC_VERSION_11 = L\"10.3.2.0\";\n\n const static wstring MOCK_WEBLOGIC_PROTOCOL = PROTOCOL_HTTPS;\n const static wstring MOCK_WEBLOGIC_ADMIN_HTTP_PORT = L\"7011\";\n const static wstring MOCK_WEBLOGIC_ADMIN_HTTPS_PORT = L\"7012\";\n const static wstring MOCK_WEBLOGIC_MANAGED_HTTP_PORT = L\"7013\";\n const static wstring MOCK_WEBLOGIC_MANAGED_HTTPS_PORT = L\"7513\";\n\n const static wstring WEBLOGIC_DEFAULT_INSTALLATION_PATH =\n L\"/opt/Oracle/WebLogic-11/Middleware/\";\n const static wstring WEBLOGIC_DEFAULT_DOMAIN_PATH =\n L\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain/\";\n const static wstring WEBLOGIC_DEFAULT_ADMIN_SERVER_PATH =\n L\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain/servers/AdminServer/\";\n const static wstring WEBLOGIC_DEFAULT_MANAGED_SERVER_PATH =\n L\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain/servers/new_ManagedServer_1/\";\n\n const static wstring WEBLOGIC_OTHER_INSTALLATION_PATH =\n L\"/opt/Oracle/WebLogic-11-testbed/Middleware/\";\n const static wstring WEBLOGIC_OTHER_DOMAIN_PATH =\n L\"/opt/Oracle/WebLogic-11-testbed/Middleware/user_projects/domains/base_domain/\";\n const static wstring WEBLOGIC_OTHER_ADMIN_SERVER_PATH =\n L\"/opt/Oracle/WebLogic-11-testbed/Middleware/user_projects/domains/base_domain/servers/AdminServer/\";\n const static wstring WEBLOGIC_OTHER_MANAGED_SERVER_PATH =\n L\"/opt/Oracle/WebLogic-11-testbed/Middleware/user_projects/domains/base_domain/servers/new_ManagedServer_1/\";\n\n\n/*\n * Unit Test mock implementation for a file reader that \n * has a both the domain-registry.xml file for WebLogic 11 \n * as well as a nodemanger.domains for WebLogic 10; however,\n * both files are empty\n */\nclass EmptyDomainFiles : public WebLogicFileReader\n{\npublic:\n EmptyDomainFiles() :\n WebLogicFileReader() \n {\n m_installationPath = WEBLOGIC_DEFAULT_INSTALLATION_PATH;\n };\n\n virtual ~EmptyDomainFiles() {};\n \nprotected:\n virtual bool DoesDomainRegistryXmlExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n\n virtual bool DoesNodemanagerDomainsExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n \n virtual bool DoesServerDirectoryExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n \n /*\n * This function should never be called because the domain files\n * do not exist.\n */\n virtual SCXHandle<istream> OpenConfigXml(const wstring&)\n {\n throw 404;\n }\n \n /*\n * Helper Method to Mock out the returned domain-registry.xml\n * for WebLogic 11g R1.\n * \n * <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n * <domain-registry xmlns=\"http://xmlns.oracle.com/weblogic/domain-registry\">\n * </domain-registry>\n * \n */\n virtual SCXHandle<istream> OpenDomainRegistryXml(const wstring&)\n {\n SCXHandle<stringstream> xmlcontent( new stringstream );\n\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\n *xmlcontent << \"<domain-registry xmlns=\\\"http://xmlns.oracle.com/weblogic/domain-registry\\\">\" << endl;\n *xmlcontent << \"</domain-registry>\" << endl;\n\n return xmlcontent;\n }\n \n /*\n * Helper Method to Mock out the returned nodemanager.domains\n * for WebLogic 10g R3. Note that the first domain appears in both\n * the domain-registry.xml as well as the older nodemanager.domains\n * file.\n * \n * #Domains and directories created by Configuration Wizard\n * #Tue Apr 12 15:23:12 PDT 2011\n * \n * Note: It is not clear if this can exist using the Oracle tools;\n * however, theoritcally a user code modify the files to look like\n * this (unclear if WebLogic would still run).\n */\n virtual SCXHandle<istream> OpenNodemanagerDomains(const wstring&)\n {\n SCXHandle<stringstream> content( new stringstream );\n\n *content << \"#Domains and directories created by Configuration Wizard\" << endl;\n *content << \"#Tue Apr 12 15:23:12 PDT 2011\" << endl;\n\n return content;\n }\n};\n\n/*\n * Unit Test mock implementation for a file reader that \n * has a missing domain-registry.xml file for WebLogic 11 \n * as well as a missing nodemanger.domains for WebLogic 10\n */\nclass MissingDomainFiles : public WebLogicFileReader\n{\npublic:\n MissingDomainFiles() :\n WebLogicFileReader() \n {\n m_installationPath = WEBLOGIC_DEFAULT_INSTALLATION_PATH;\n };\n\n virtual ~MissingDomainFiles() {};\n\nprotected:\n virtual bool DoesDomainRegistryXmlExist(const SCXFilePath& /*path*/)\n {\n return false;\n }\n \n virtual bool DoesNodemanagerDomainsExist(const SCXFilePath& /*path*/)\n {\n return false;\n }\n\n /*\n * This function should never be called because the domain files\n * do not exist.\n */\n virtual SCXHandle<istream> OpenConfigXml(const wstring&)\n {\n throw 404;\n }\n\n /*\n * Helper Method to Mock out the returned domain-registry.xml\n * for WebLogic 11g R1.\n * \n * This method should never get called because another method\n * for checking the file existence is hard-coded to false. To\n * be safe the function throws an exception.\n */\n virtual SCXHandle<istream> OpenDomainRegistryXml(const wstring&)\n {\n throw 404;\n }\n\n /*\n * Helper Method to Mock out the returned nodemanager.domains\n * for WebLogic 10g R3.\n */\n virtual SCXHandle<istream> OpenNodemanagerDomains(const wstring&)\n {\n throw 404;\n }\n};\n\n/*\n * Unit Test mock implementation for a file reader that has one\n * entry in the nodemanager.domains file. This in\n * turn points a simple installation that only has one Admin\n * Server and one managed server. The config.xml does not list\n * ports for HTTP or HTTPS for the Admin server - this implies\n * that the defaults are to be used. The Managed server does NOT\n * have SSL configured.\n */\nclass StandardWebLogic10 : public WebLogicFileReader\n{\n \npublic:\n StandardWebLogic10() :\n WebLogicFileReader() \n {\n m_installationPath = WEBLOGIC_DEFAULT_INSTALLATION_PATH;\n };\n \n virtual ~StandardWebLogic10() {};\n\nprotected:\n virtual bool DoesConfigXmlExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n\n virtual bool DoesDomainRegistryXmlExist(const SCXFilePath& /*path*/)\n {\n return false;\n }\n\n /*\n * For an 11g installation, this file exists, but is empty\n */\n virtual bool DoesNodemanagerDomainsExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n\n virtual bool DoesServerDirectoryExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n\n /*\n * Helper Method to Mock out the returned domain-registry.xml\n * for WebLogic 11g R1.\n * \n * <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n * <domain-registry xmlns=\"http://xmlns.oracle.com/weblogic/domain-registry\">\n * <domain location=\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain\"/>\n * </domain-registry>\n * \n */\n virtual SCXHandle<istream> OpenConfigXml(const wstring&)\n {\n SCXHandle<stringstream> xmlcontent( new stringstream );\n\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\n *xmlcontent << \"<domain xsi:schemaLocation=\\\"http://xmlns.oracle.com/weblogic/security/wls http://xmlns.oracle.com/weblogic/security/wls/1.0/wls.xsd http://xmlns.oracle.com/weblogic/domain http://xmlns.oracle.com/weblogic/1.0/domain.xsdhttp://xmlns.oracle.com/weblogic/security http://xmlns.oracle.com/weblogic/1.0/security.xsd http://xmlns.oracle.com/weblogic/security/xacml http://xmlns.oracle.com/weblogic/security/xacml/1.0/xacml.xsd\\\" xmlns=\\\"http://xmlns.oracle.com/weblogic/domain\\\" xmlns:sec=\\\"http://xmlns.oracle.com/weblogic/security\\\" xmlns:wls=\\\"http://xmlns.oracle.com/weblogic/security/wls\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">\" << endl;\n *xmlcontent << \" <name>base_domain</name>\" << endl;\n *xmlcontent << \" <domain-version>10.3.0.0</domain-version>\" << endl;\n *xmlcontent << \" <security-configuration xmlns:xacml=\\\"http://xmlns.oracle.com/weblogic/security/xacml\\\" xmlns:pas=\\\"http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator\\\">\" << endl;\n *xmlcontent << \" <name>base_domain</name>\" << endl;\n *xmlcontent << \" <realm>\" << endl;\n *xmlcontent << \" <sec:authentication-provider xsi:type=\\\"wls:default-authenticatorType\\\"/>\" << endl;\n *xmlcontent << \" <sec:authentication-provider xsi:type=\\\"wls:default-identity-asserterType\\\">\" << endl;\n *xmlcontent << \" <sec:active-type>AuthenticatedUser</sec:active-type>\" << endl;\n *xmlcontent << \" </sec:authentication-provider>\" << endl;\n *xmlcontent << \" <sec:role-mapper xsi:type=\\\"xacml:xacml-role-mapperType\\\"/>\" << endl;\n *xmlcontent << \" <sec:authorizer xsi:type=\\\"xacml:xacml-authorizerType\\\"/>\" << endl;\n *xmlcontent << \" <sec:adjudicator xsi:type=\\\"wls:default-adjudicatorType\\\"/>\" << endl;\n *xmlcontent << \" <sec:credential-mapper xsi:type=\\\"wls:default-credential-mapperType\\\"/>\" << endl;\n *xmlcontent << \" <sec:cert-path-provider xsi:type=\\\"wls:web-logic-cert-path-providerType\\\"/>\" << endl;\n *xmlcontent << \" <sec:cert-path-builder>WebLogicCertPathProvider</sec:cert-path-builder>\" << endl;\n *xmlcontent << \" <sec:name>myrealm</sec:name>\" << endl;\n *xmlcontent << \" <sec:password-validator xsi:type=\\\"pas:system-password-validatorType\\\">\" << endl;\n *xmlcontent << \" <sec:name>SystemPasswordValidator</sec:name>\" << endl;\n *xmlcontent << \" <pas:min-password-length>8</pas:min-password-length>\" << endl;\n *xmlcontent << \" <pas:min-numeric-or-special-characters>1</pas:min-numeric-or-special-characters>\" << endl;\n *xmlcontent << \" </sec:password-validator>\" << endl;\n *xmlcontent << \" </realm>\" << endl;\n *xmlcontent << \" <default-realm>myrealm</default-realm>\" << endl;\n *xmlcontent << \" <credential-encrypted></credential-encrypted>\" << endl;\n *xmlcontent << \" <node-manager-username>weblogic</node-manager-username>\" << endl;\n *xmlcontent << \" <node-manager-password-encrypted></node-manager-password-encrypted>\" << endl;\n *xmlcontent << \" </security-configuration>\" << endl;\n *xmlcontent << \" <server>\" << endl;\n *xmlcontent << \" <name>AdminServer</name>\" << endl;\n *xmlcontent << \" <ssl>\" << endl;\n *xmlcontent << \" <name>AdminServer</name>\" << endl;\n *xmlcontent << \" <enabled>true</enabled>\" << endl;\n *xmlcontent << \" </ssl>\" << endl;\n *xmlcontent << \" <machine>new_UnixMachine_1</machine>\" << endl;\n *xmlcontent << \" <listen-address/>\" << endl;\n *xmlcontent << \" </server>\" << endl;\n *xmlcontent << \" <server>\" << endl;\n *xmlcontent << \" <name>new_ManagedServer_1</name>\" << endl;\n *xmlcontent << \" <machine>new_UnixMachine_1</machine>\" << endl;\n *xmlcontent << \" <listen-port>7013</listen-port>\" << endl;\n *xmlcontent << \" <listen-address/>\" << endl;\n *xmlcontent << \" </server>\" << endl;\n *xmlcontent << \" <embedded-ldap>\" << endl;\n *xmlcontent << \" <name>base_domain</name>\" << endl;\n *xmlcontent << \" <credential-encrypted></credential-encrypted>\" << endl;\n *xmlcontent << \" </embedded-ldap>\" << endl;\n *xmlcontent << \" <configuration-version>10.3.0.0</configuration-version>\" << endl;\n *xmlcontent << \" <machine xsi:type=\\\"unix-machineType\\\">\" << endl;\n *xmlcontent << \" <name>new_UnixMachine_1</name>\" << endl;\n *xmlcontent << \" <node-manager>\" << endl;\n *xmlcontent << \" <name>new_UnixMachine_1</name>\" << endl;\n *xmlcontent << \" <listen-address>localhost</listen-address>\" << endl;\n *xmlcontent << \" <listen-port>5566</listen-port>\" << endl;\n *xmlcontent << \" </node-manager>\" << endl;\n *xmlcontent << \" </machine>\" << endl;\n *xmlcontent << \" <admin-server-name>AdminServer</admin-server-name>\" << endl;\n *xmlcontent << \"</domain>\" << endl;\n\n return xmlcontent;\n }\n\n /*\n * Helper Method to Mock out the returned domain-registry.xml.\n * This file does not exist on WebLogic 10, so the mock object\n * will throw an exception.\n */\n virtual SCXHandle<istream> OpenDomainRegistryXml(const wstring&)\n {\n throw 404;\n }\n\n /*\n * Helper Method to Mock out the returned nodemanager.domains\n * for WebLogic 10g R3. Note that the first domain appears in both\n * the domain-registry.xml as well as the older nodemanager.domains\n * file.\n * \n * #Domains and directories created by Configuration Wizard\n * #Tue Apr 12 15:23:12 PDT 2011\n * base_domain=/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain\n * \n */\n virtual SCXHandle<istream> OpenNodemanagerDomains(const wstring&)\n {\n SCXHandle<stringstream> content( new stringstream );\n\n *content << \"#Domains and directories created by Configuration Wizard\" << endl;\n *content << \"#Tue Apr 12 15:23:12 PDT 2011\" << endl;\n *content << \"base_domain=/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain\" << endl;\n\n return content;\n } \n};\n\n/*\n * Unit Test mock implementation for a file reader that has one\n * entry in the domain-registry.xml file for WebLogic 11. This in\n * turn points to a simple installation that only has one Admin\n * Server.\n * \n * In essense, this would be the case if a discovery were run on\n * a WebLogic that had just been installed. \n */\nclass StandardWebLogic11 : public WebLogicFileReader\n{\n \npublic:\n StandardWebLogic11() :\n WebLogicFileReader() \n {\n m_installationPath = WEBLOGIC_DEFAULT_INSTALLATION_PATH;\n };\n \n virtual ~StandardWebLogic11() {};\n\nprotected:\n virtual bool DoesConfigXmlExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n\n virtual bool DoesDomainRegistryXmlExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n\n /*\n * For an 11g installation, this file exists, but is empty\n */\n virtual bool DoesNodemanagerDomainsExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n \n virtual bool DoesServerDirectoryExist(const SCXFilePath& /*path*/)\n {\n return true;\n }\n\n /*\n * Helper Method to Mock out the returned domain-registry.xml\n * for WebLogic 11g R1.\n * \n * <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n * <domain-registry xmlns=\"http://xmlns.oracle.com/weblogic/domain-registry\">\n * <domain location=\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain\"/>\n * </domain-registry>\n * \n */\n virtual SCXHandle<istream> OpenConfigXml(const wstring&)\n {\n SCXHandle<stringstream> xmlcontent( new stringstream );\n\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\n *xmlcontent << \"<domain xsi:schemaLocation=\\\"http://xmlns.oracle.com/weblogic/security/wls http://xmlns.oracle.com/weblogic/security/wls/1.0/wls.xsd http://xmlns.oracle.com/weblogic/domain http://xmlns.oracle.com/weblogic/1.0/domain.xsdhttp://xmlns.oracle.com/weblogic/security http://xmlns.oracle.com/weblogic/1.0/security.xsd http://xmlns.oracle.com/weblogic/security/xacml http://xmlns.oracle.com/weblogic/security/xacml/1.0/xacml.xsd\\\" xmlns=\\\"http://xmlns.oracle.com/weblogic/domain\\\" xmlns:sec=\\\"http://xmlns.oracle.com/weblogic/security\\\" xmlns:wls=\\\"http://xmlns.oracle.com/weblogic/security/wls\\\" xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">\" << endl;\n *xmlcontent << \" <name>base_domain</name>\" << endl;\n *xmlcontent << \" <domain-version>10.3.2.0</domain-version>\" << endl;\n *xmlcontent << \" <security-configuration xmlns:xacml=\\\"http://xmlns.oracle.com/weblogic/security/xacml\\\" xmlns:pas=\\\"http://xmlns.oracle.com/weblogic/security/providers/passwordvalidator\\\">\" << endl;\n *xmlcontent << \" <name>base_domain</name>\" << endl;\n *xmlcontent << \" <realm>\" << endl;\n *xmlcontent << \" <sec:authentication-provider xsi:type=\\\"wls:default-authenticatorType\\\"/>\" << endl;\n *xmlcontent << \" <sec:authentication-provider xsi:type=\\\"wls:default-identity-asserterType\\\">\" << endl;\n *xmlcontent << \" <sec:active-type>AuthenticatedUser</sec:active-type>\" << endl;\n *xmlcontent << \" </sec:authentication-provider>\" << endl;\n *xmlcontent << \" <sec:role-mapper xsi:type=\\\"xacml:xacml-role-mapperType\\\"/>\" << endl;\n *xmlcontent << \" <sec:authorizer xsi:type=\\\"xacml:xacml-authorizerType\\\"/>\" << endl;\n *xmlcontent << \" <sec:adjudicator xsi:type=\\\"wls:default-adjudicatorType\\\"/>\" << endl;\n *xmlcontent << \" <sec:credential-mapper xsi:type=\\\"wls:default-credential-mapperType\\\"/>\" << endl;\n *xmlcontent << \" <sec:cert-path-provider xsi:type=\\\"wls:web-logic-cert-path-providerType\\\"/>\" << endl;\n *xmlcontent << \" <sec:cert-path-builder>WebLogicCertPathProvider</sec:cert-path-builder>\" << endl;\n *xmlcontent << \" <sec:name>myrealm</sec:name>\" << endl;\n *xmlcontent << \" <sec:password-validator xsi:type=\\\"pas:system-password-validatorType\\\">\" << endl;\n *xmlcontent << \" <sec:name>SystemPasswordValidator</sec:name>\" << endl;\n *xmlcontent << \" <pas:min-password-length>8</pas:min-password-length>\" << endl;\n *xmlcontent << \" <pas:min-numeric-or-special-characters>1</pas:min-numeric-or-special-characters>\" << endl;\n *xmlcontent << \" </sec:password-validator>\" << endl;\n *xmlcontent << \" </realm>\" << endl;\n *xmlcontent << \" <default-realm>myrealm</default-realm>\" << endl;\n *xmlcontent << \" <credential-encrypted></credential-encrypted>\" << endl;\n *xmlcontent << \" <node-manager-username>weblogic</node-manager-username>\" << endl;\n *xmlcontent << \" <node-manager-password-encrypted></node-manager-password-encrypted>\" << endl;\n *xmlcontent << \" </security-configuration>\" << endl;\n *xmlcontent << \" <server>\" << endl;\n *xmlcontent << \" <name>AdminServer</name>\" << endl;\n *xmlcontent << \" <ssl>\" << endl;\n *xmlcontent << \" <name>AdminServer</name>\" << endl;\n *xmlcontent << \" <enabled>true</enabled>\" << endl;\n *xmlcontent << \" <listen-port>7012</listen-port>\" << endl;\n *xmlcontent << \" </ssl>\" << endl;\n *xmlcontent << \" <machine>new_UnixMachine_1</machine>\" << endl;\n *xmlcontent << \" <listen-port>7011</listen-port>\" << endl;\n *xmlcontent << \" <listen-address/>\" << endl;\n *xmlcontent << \" </server>\" << endl;\n *xmlcontent << \" <server>\" << endl;\n *xmlcontent << \" <name>new_ManagedServer_1</name>\" << endl;\n *xmlcontent << \" <ssl>\" << endl;\n *xmlcontent << \" <name>new_ManagedServer_1</name>\" << endl;\n *xmlcontent << \" <enabled>true</enabled>\" << endl;\n *xmlcontent << \" <listen-port>7513</listen-port>\" << endl;\n *xmlcontent << \" </ssl>\" << endl;\n *xmlcontent << \" <machine>new_UnixMachine_1</machine>\" << endl;\n *xmlcontent << \" <listen-port>7013</listen-port>\" << endl;\n *xmlcontent << \" <listen-address/>\" << endl;\n *xmlcontent << \" </server>\" << endl;\n *xmlcontent << \" <embedded-ldap>\" << endl;\n *xmlcontent << \" <name>base_domain</name>\" << endl;\n *xmlcontent << \" <credential-encrypted></credential-encrypted>\" << endl;\n *xmlcontent << \" </embedded-ldap>\" << endl;\n *xmlcontent << \" <configuration-version>10.3.2.0</configuration-version>\" << endl;\n *xmlcontent << \" <machine xsi:type=\\\"unix-machineType\\\">\" << endl;\n *xmlcontent << \" <name>new_UnixMachine_1</name>\" << endl;\n *xmlcontent << \" <node-manager>\" << endl;\n *xmlcontent << \" <name>new_UnixMachine_1</name>\" << endl;\n *xmlcontent << \" <listen-address>localhost</listen-address>\" << endl;\n *xmlcontent << \" <listen-port>5566</listen-port>\" << endl;\n *xmlcontent << \" </node-manager>\" << endl;\n *xmlcontent << \" </machine>\" << endl;\n *xmlcontent << \" <admin-server-name>AdminServer</admin-server-name>\" << endl;\n *xmlcontent << \"</domain>\" << endl;\n\n return xmlcontent;\n }\n\n /*\n * Helper Method to Mock out the returned domain-registry.xml\n * for WebLogic 11g R1.\n * \n * <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n * <domain-registry xmlns=\"http://xmlns.oracle.com/weblogic/domain-registry\">\n * <domain location=\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain\"/>\n * </domain-registry>\n * \n */\n virtual SCXHandle<istream> OpenDomainRegistryXml(const wstring&)\n {\n SCXHandle<stringstream> xmlcontent( new stringstream );\n\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\n *xmlcontent << \"<domain-registry xmlns=\\\"http://xmlns.oracle.com/weblogic/domain-registry\\\">\" << endl;\n *xmlcontent << \" <domain location=\\\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain\\\"/>\" << endl;\n *xmlcontent << \"</domain-registry>\" << endl;\n\n return xmlcontent;\n }\n\n /*\n * Helper Method to Mock out the returned nodemanager.domains\n * for WebLogic 10g R3. Note that the first domain appears in both\n * the domain-registry.xml as well as the older nodemanager.domains\n * file.\n * \n * #Domains and directories created by Configuration Wizard\n * #Tue Apr 12 15:23:12 PDT 2011\n * base_domain=/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain\n * \n */\n virtual SCXHandle<istream> OpenNodemanagerDomains(const wstring&)\n {\n SCXHandle<stringstream> content( new stringstream );\n\n *content << \"#Domains and directories created by Configuration Wizard\" << endl;\n *content << \"#Tue Apr 12 15:23:12 PDT 2011\" << endl;\n *content << \"base_domain=/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain\" << endl;\n\n return content;\n } \n};\n\n/*\n * Unit Test mock implementation for a file reader that has one\n * entry in the domain-registry.xml file for WebLogic 11. This in\n * turn points to a simple installation that only has one Admin\n * Server.\n * \n * In essense, this would be the case if a discovery were run on\n * a WebLogic that had just been installed. \n */\nclass WebLogic11Cluster : public StandardWebLogic11\n{\n \npublic:\n WebLogic11Cluster() : StandardWebLogic11() {};\n \n virtual ~WebLogic11Cluster() {};\n\nprotected:\n \n virtual bool DoesServerDirectoryExist(const SCXFilePath& path)\n {\n bool returnValue = false;\n \n if (path.Get() == WEBLOGIC_DEFAULT_ADMIN_SERVER_PATH)\n {\n returnValue = true;\n }\n \n return returnValue;\n }\n};\n\nclass MultipleInstallationsOfWebLogic11 : public StandardWebLogic11\n{\n\n private:\n int m_counter;\n\n public:\n MultipleInstallationsOfWebLogic11() : StandardWebLogic11()\n {\n m_counter = 0;\n };\n\n virtual ~MultipleInstallationsOfWebLogic11() {};\n\n virtual void\n GetInstances(\n const SCXCoreLib::SCXFilePath& domain,\n std::vector<\n SCXCoreLib::SCXHandle<AppServerInstance> >& instances)\n {\n if (m_counter < 1)\n {\n cout << \"bumping counter\" << endl;\n\n ++m_counter;\n }\n else\n {\n cout << \"switch installation path\" << endl;\n m_installationPath = WEBLOGIC_OTHER_INSTALLATION_PATH;\n }\n \n StandardWebLogic11::GetInstances(domain, instances);\n };\n\nprotected:\n virtual SCXCoreLib::SCXHandle<std::istream> OpenDomainRegistryXml(\n const std::wstring& filename)\n {\n if (0 != m_counter )\n {\n SCXHandle<stringstream> xmlcontent( new stringstream );\n\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\n *xmlcontent << \"<domain-registry xmlns=\\\"http://xmlns.oracle.com/weblogic/domain-registry\\\">\" << endl;\n *xmlcontent << \" <domain location=\\\"/opt/Oracle/WebLogic-11-testbed/Middleware/user_projects/domains/base_domain\\\"/>\" << endl;\n *xmlcontent << \"</domain-registry>\" << endl;\n\n return xmlcontent;\n }\n else\n {\n return StandardWebLogic11::OpenDomainRegistryXml(filename);\n }\n }\n\n virtual SCXHandle<istream> OpenNodemanagerDomains(const wstring& filename)\n {\n if (0 != m_counter )\n {\n SCXHandle<stringstream> content( new stringstream );\n return content;\n }\n else\n {\n return StandardWebLogic11::OpenNodemanagerDomains(filename);\n }\n }\n};\n\n/*\n * Unit Tests for the logic of enumerating WebLogic instances.\n * \n * WebLogic is different compared to the other application servers.\n * From the running process, it is not possible to determine \n * specifics about the application server. Instead, from the running\n * process it is necessary to extract the base location of the\n * WebLogic installations, parse the domains from the appropriate file,\n * and then for each domain parse the XML file to find the Admin and\n * Managed servers.\n * \n * For the following tests, the most important piece is to manipulate\n * the parsed XML to represent various user configurations.\n\n */\nclass WebLogicAppServerEnumeration_Test : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( WebLogicAppServerEnumeration_Test );\n\n CPPUNIT_TEST( WebLogicDiscoveryForEmptyInstallationsGoldenCase );\n CPPUNIT_TEST( WebLogicDiscoveryForEmptyInstallationsZeroesResult );\n\n CPPUNIT_TEST( WebLogicDiscoveryForNoDomainsDueToEmptyFiles);\n CPPUNIT_TEST( WebLogicDiscoveryForNoDomainsDueToMissingFiles);\n\n CPPUNIT_TEST( WebLogicDiscoveryForDomainRegistryParsingOnWebLogic10 );\n CPPUNIT_TEST( WebLogicDiscoveryForDomainRegistryParsingOnWebLogic11 );\n CPPUNIT_TEST( WebLogicDiscoveryForWebLogic10ThatRequiresDefaultPorts );\n CPPUNIT_TEST( WebLogicDiscoveryForWebLogic11 );\n CPPUNIT_TEST( WebLogicDiscoveryForWebLogic11Cluster );\n\n CPPUNIT_TEST( WebLogicDiscoveryForWebLogic11WithDuplicateInstallations );\n CPPUNIT_TEST( WebLogicDiscoveryForWebLogic11WithMultipleInstallations );\n\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n\n /*------------------------------------------------------------------*/\n /*\n * Unit Test setup method run before each test.\n */\n void setUp(void)\n {\n }\n\n /*------------------------------------------------------------------*/\n /*\n * Unit Test tear down method run after each test.\n */\n void tearDown(void)\n {\n }\n \n /*------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Factory method for getting an enumerator to test with the default\n * Filesystem access-points mocked-out for unit-testing.\n */\n WebLogicAppServerEnumeration* GetWebLogic10Enumerator(void)\n {\n IWebLogicFileReader* fileReader = new StandardWebLogic10();\n \n return new WebLogicAppServerEnumeration(\n SCXHandle<IWebLogicFileReader>(fileReader));\n } \n\n /*------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Factory method for getting an enumerator to test with the default\n * Filesystem access-points mocked out for unit-testing.\n */\n WebLogicAppServerEnumeration* GetWebLogic11Enumerator(void)\n {\n IWebLogicFileReader* fileReader = new StandardWebLogic11();\n \n return new WebLogicAppServerEnumeration(\n SCXHandle<IWebLogicFileReader>(fileReader));\n } \n\n /*------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Factory method for getting an enumerator to test with the default\n * Filesystem access-points mocked out for unit-testing.\n */\n WebLogicAppServerEnumeration* GetWebLogic11Cluster(void)\n {\n IWebLogicFileReader* fileReader = new WebLogic11Cluster();\n \n return new WebLogicAppServerEnumeration(\n SCXHandle<IWebLogicFileReader>(fileReader));\n } \n\n /*------------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a sample of WegbLogic 11g R1 instance.\n */\n SCXHandle<AppServerInstance> createDefaultWebLogicInstance11(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n WEBLOGIC_DEFAULT_INSTALLATION_PATH,\n APP_SERVER_TYPE_WEBLOGIC));\n instance->SetHttpPort(DEFAULT_WEBLOGIC_HTTP_PORT);\n instance->SetHttpsPort(DEFAULT_WEBLOGIC_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, MOCK_WEBLOGIC_PROTOCOL);\n instance->SetIsRunning(false);\n instance->SetVersion(WEBLOGIC_VERSION_11);\n\n return instance;\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery will always return back\n * zero instances if given an empty list of installations. \n * This is the golden, expected scenario because the supplied \n * result vector is already empty.\n */\n void WebLogicDiscoveryForEmptyInstallationsGoldenCase()\n {\n vector<wstring> installations;\n vector<SCXHandle<AppServerInstance> > result;\n\n CPPUNIT_ASSERT_EQUAL(zeroSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n\n SCXHandle<WebLogicAppServerEnumeration> enumerator(GetWebLogic11Enumerator());\n enumerator->GetInstances(installations, result);\n\n CPPUNIT_ASSERT_EQUAL(zeroSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery will always return back\n * zero instances if given an empty list of installations. \n * This test the supplied result vector is non-empty. This \n * code should verifies that the supplied result vector is\n * treated like an output parameter only.\n */\n void WebLogicDiscoveryForEmptyInstallationsZeroesResult()\n {\n vector<wstring> installations;\n vector<SCXHandle<AppServerInstance> > result;\n\n result.push_back(createDefaultWebLogicInstance11());\n\n CPPUNIT_ASSERT_EQUAL(zeroSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(oneSize, result.size());\n\n SCXHandle<WebLogicAppServerEnumeration> enumerator(GetWebLogic11Enumerator());\n enumerator->GetInstances(installations, result);\n\n CPPUNIT_ASSERT_EQUAL(zeroSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery finds nothing if the\n * XML files that contain domain information are empty. The\n * chances of this logic actually happening would be rare, but\n * concievable could happen if the installation had previously\n * been discovered, then deleted, then the discovery occurs\n * from the cached version. \n */\n void WebLogicDiscoveryForNoDomainsDueToEmptyFiles()\n {\n SCXHandle<IWebLogicFileReader> domainCheck(new EmptyDomainFiles());\n vector<SCXFilePath> result = domainCheck->GetDomains();\n\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n }\n \n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery finds nothing if the\n * XML files that contain domain information are empty. The\n * chances of this logic actually happening would be rare, but\n * concievable could happen if the installation had previously\n * been discovered, then deleted, then the discovery occurs\n * from the cached version. \n */\n void WebLogicDiscoveryForNoDomainsDueToMissingFiles()\n {\n SCXHandle<IWebLogicFileReader> domainCheck(new MissingDomainFiles());\n vector<SCXFilePath> result = domainCheck->GetDomains();\n\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n }\n \n // --------------------------------------------------------\n /*\n * Verify that the WebLogic domain discovery works for the\n * case of a simple installation that has only one domain\n * for WebLogic 10 \n */\n void WebLogicDiscoveryForDomainRegistryParsingOnWebLogic10()\n {\n SCXHandle<IWebLogicFileReader> domainCheck(new StandardWebLogic10());\n vector<SCXFilePath> result = domainCheck->GetDomains();\n\n CPPUNIT_ASSERT_EQUAL(oneSize, result.size());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_DOMAIN_PATH == result[0].Get());\n }\n\n \n // --------------------------------------------------------\n /*\n * Verify that the WebLogic domain discovery works for the\n * case of a simple installation that has only one domain\n * for WebLogic 11\n */\n void WebLogicDiscoveryForDomainRegistryParsingOnWebLogic11()\n {\n SCXHandle<IWebLogicFileReader> domainCheck(new StandardWebLogic11());\n vector<SCXFilePath> result = domainCheck->GetDomains();\n\n CPPUNIT_ASSERT_EQUAL(oneSize, result.size());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_DOMAIN_PATH == result[0].Get());\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery works for the case of\n * a very simple installation. There are no managed servers,\n * only one Admin Server (obviously) only one domain as well.\n */\n void WebLogicDiscoveryForWebLogic10ThatRequiresDefaultPorts()\n {\n vector<wstring> installations;\n installations.push_back(WEBLOGIC_DEFAULT_INSTALLATION_PATH);\n vector<SCXHandle<AppServerInstance> > result;\n\n CPPUNIT_ASSERT_EQUAL(oneSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n\n SCXHandle<WebLogicAppServerEnumeration> enumerator(GetWebLogic10Enumerator());\n enumerator->GetInstances(installations, result);\n\n CPPUNIT_ASSERT_EQUAL(twoSize, result.size());\n \n // Verify the AdminServer\n CPPUNIT_ASSERT(\n DEFAULT_WEBLOGIC_HTTP_PORT == result[0]->GetHttpPort());\n CPPUNIT_ASSERT(\n DEFAULT_WEBLOGIC_HTTPS_PORT == result[0]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_10 == result[0]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_10 == result[0]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_ADMIN_SERVER_PATH == result[0]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_ADMIN == result[0]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[0]->GetType());\n \n // Verify the ManagedServer\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTP_PORT == result[1]->GetHttpPort());\n CPPUNIT_ASSERT(\n DEFAULT_WEBLOGIC_HTTPS_PORT == result[1]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_10 == result[1]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_10 == result[1]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_MANAGED_SERVER_PATH == result[1]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_MANAGED == result[1]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[1]->GetType());\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery works for the case of\n * a very simple installation. There are no managed servers,\n * only one Admin Server (obviously) only one domain as well.\n */\n void WebLogicDiscoveryForWebLogic11()\n {\n vector<wstring> installations;\n installations.push_back(WEBLOGIC_DEFAULT_INSTALLATION_PATH);\n vector<SCXHandle<AppServerInstance> > result;\n\n CPPUNIT_ASSERT_EQUAL(oneSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n\n SCXHandle<WebLogicAppServerEnumeration> enumerator(GetWebLogic11Enumerator());\n enumerator->GetInstances(installations, result);\n\n CPPUNIT_ASSERT_EQUAL(twoSize, result.size());\n \n // Verify the AdminServer\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTP_PORT == result[0]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTPS_PORT == result[0]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[0]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[0]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_ADMIN_SERVER_PATH == result[0]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_ADMIN == result[0]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[0]->GetType());\n \n // Verify the ManagedServer\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTP_PORT == result[1]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTPS_PORT == result[1]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[1]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[1]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_MANAGED_SERVER_PATH == result[1]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_MANAGED == result[1]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[1]->GetType());\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery works for the case of\n * a very simple installation. There are no managed servers,\n * only one Admin Server (obviously) only one domain as well.\n */\n void WebLogicDiscoveryForWebLogic11Cluster()\n {\n vector<wstring> installations;\n installations.push_back(WEBLOGIC_DEFAULT_INSTALLATION_PATH);\n vector<SCXHandle<AppServerInstance> > result;\n\n CPPUNIT_ASSERT_EQUAL(oneSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n\n SCXHandle<WebLogicAppServerEnumeration> enumerator(GetWebLogic11Cluster());\n enumerator->GetInstances(installations, result);\n\n CPPUNIT_ASSERT_EQUAL(oneSize, result.size());\n \n // Verify the AdminServer\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTP_PORT == result[0]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTPS_PORT == result[0]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[0]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[0]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_ADMIN_SERVER_PATH == result[0]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_ADMIN == result[0]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[0]->GetType());\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery works as expected if the\n * input vector of installations contains duplicates. The\n * expected behavior is that the duplicate installations will\n * be discarded and only one set of Application Server instances\n * will be returned. \n */\n void WebLogicDiscoveryForWebLogic11WithDuplicateInstallations()\n {\n vector<wstring> installations;\n installations.push_back(WEBLOGIC_DEFAULT_INSTALLATION_PATH);\n installations.push_back(WEBLOGIC_DEFAULT_INSTALLATION_PATH);\n installations.push_back(WEBLOGIC_DEFAULT_INSTALLATION_PATH);\n vector<SCXHandle<AppServerInstance> > result;\n\n CPPUNIT_ASSERT_EQUAL(threeSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n\n SCXHandle<WebLogicAppServerEnumeration> enumerator(GetWebLogic11Enumerator());\n enumerator->GetInstances(installations, result);\n\n CPPUNIT_ASSERT_EQUAL(twoSize, result.size());\n \n // Verify the AdminServer\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTP_PORT == result[0]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTPS_PORT == result[0]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[0]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[0]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_ADMIN_SERVER_PATH == result[0]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_ADMIN == result[0]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[0]->GetType());\n \n // Verify the ManagedServer\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTP_PORT == result[1]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTPS_PORT == result[1]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[1]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[1]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_MANAGED_SERVER_PATH == result[1]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_MANAGED == result[1]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[1]->GetType());\n }\n\n // --------------------------------------------------------\n /*\n * Verify that the WebLogic discovery works as expected if the\n * input vector of installations contains duplicates. The\n * expected behavior is that the duplicate installations will\n * be discarded and only one set of Application Server instances\n * will be returned. \n */\n void WebLogicDiscoveryForWebLogic11WithMultipleInstallations()\n {\n vector<wstring> installations;\n installations.push_back(WEBLOGIC_DEFAULT_INSTALLATION_PATH);\n installations.push_back(WEBLOGIC_OTHER_INSTALLATION_PATH);\n vector<SCXHandle<AppServerInstance> > result;\n\n CPPUNIT_ASSERT_EQUAL(twoSize, installations.size());\n CPPUNIT_ASSERT_EQUAL(zeroSize, result.size());\n \n IWebLogicFileReader* fileReader = new MultipleInstallationsOfWebLogic11();\n\n SCXHandle<WebLogicAppServerEnumeration> enumerator(\n new WebLogicAppServerEnumeration(\n SCXHandle<IWebLogicFileReader>(fileReader)));\n enumerator->GetInstances(installations, result);\n\n CPPUNIT_ASSERT_EQUAL(fourSize, result.size());\n\n // Verify the AdminServer (Default)\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTP_PORT == result[0]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTPS_PORT == result[0]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[0]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[0]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_ADMIN_SERVER_PATH == result[0]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_ADMIN == result[0]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[0]->GetType());\n\n // Verify the ManagedServer (Managed)\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTP_PORT == result[1]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTPS_PORT == result[1]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[1]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[1]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_DEFAULT_MANAGED_SERVER_PATH == result[1]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_MANAGED == result[1]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[1]->GetType());\n\n // Verify the AdminServer (Default)\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTP_PORT == result[2]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_ADMIN_HTTPS_PORT == result[2]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[2]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[2]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_OTHER_ADMIN_SERVER_PATH == result[2]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_ADMIN == result[2]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[2]->GetType());\n\n // Verify the ManagedServer (Managed)\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTP_PORT == result[3]->GetHttpPort());\n CPPUNIT_ASSERT(\n MOCK_WEBLOGIC_MANAGED_HTTPS_PORT == result[3]->GetHttpsPort());\n CPPUNIT_ASSERT(\n WEBLOGIC_VERSION_11 == result[3]->GetVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_MAJOR_VERSION_11 == result[3]->GetMajorVersion());\n CPPUNIT_ASSERT(\n WEBLOGIC_OTHER_MANAGED_SERVER_PATH == result[3]->GetDiskPath());\n CPPUNIT_ASSERT(\n WEBLOGIC_SERVER_TYPE_MANAGED == result[3]->GetServer());\n CPPUNIT_ASSERT(\n APP_SERVER_TYPE_WEBLOGIC == result[3]->GetType());\n }\n\n \n}; // End WebLogicAppServerEnumeration_Test \n\n} // End namespace\n\nCPPUNIT_TEST_SUITE_REGISTRATION\n( SCXUnitTests::WebLogicAppServerEnumeration_Test);\n" }, { "alpha_fraction": 0.6012068390846252, "alphanum_fraction": 0.6252397894859314, "avg_line_length": 50.574607849121094, "blob_id": "fa6f7986057adde5ef28b6d097eae4278d2d4421", "content_id": "c07ef7ad74004ddeb2d7abc86d0b3a736ee37897", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 125120, "license_type": "permissive", "max_line_length": 532, "num_lines": 2426, "path": "/test/code/providers/appserver_provider/appserverenumeration_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n \n Created date 2011-05-18\n\n Appserver data colletion test class.\n \n Only tests the functionality of the enumeration class.\n The actual data gathering is tested by a separate class.\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n\n#include <appserverenumeration.h>\n#include <appserverinstance.h>\n\n#include <testutils/scxunit.h>\n#include <iostream>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\n/**************************************************************************************/\n// TestSpy design pattern use for this mock object to track calling of the reading and\n// writing to disk of the cache\n/**************************************************************************************/\nclass TestSpyAppServerEnumeration : public AppServerEnumeration\n{\npublic:\n\n /*\n * Simple Constructor with defaults \n * that initializes the TestSpy counters\n */\n TestSpyAppServerEnumeration() : \n AppServerEnumeration(),\n m_ReadInstancesCalledCounter(0),\n m_WriteInstancesCalledCounter(0),\n m_NumberOfCallsToUpdateInstances(0)\n {\n }\n \n /*\n * Constructor that can control the PAL dependencies\n */\n TestSpyAppServerEnumeration(SCXHandle<AppServerPALDependencies> deps) :\n AppServerEnumeration(deps),\n m_ReadInstancesCalledCounter(0),\n m_WriteInstancesCalledCounter(0),\n m_NumberOfCallsToUpdateInstances(0)\n {\n }\n \n /*----------------------------------------------------------------------------*/\n /**\n Update all AppServer data\n\n */\n void UpdateInstances()\n {\n ++m_NumberOfCallsToUpdateInstances;\n AppServerEnumeration::UpdateInstances();\n }\n\n int m_ReadInstancesCalledCounter;\n\n int m_WriteInstancesCalledCounter;\n \n /*\n * Returns back number of times the Update() method\n * has been called.\n */\n int GetNumberOfCallsToUpdateInstances()\n {\n return m_NumberOfCallsToUpdateInstances;\n }\n \nprotected:\n \n /*\n * Overridden base class method to keep track of how many times\n * the method for reading the cache was called.\n */\n void ReadInstancesFromDisk()\n {\n ++m_ReadInstancesCalledCounter;\n }\n \n /*\n * Overridden base class method to keep track of how many times\n * the method for writing the cache was called.\n */\n void WriteInstancesToDisk()\n {\n ++m_WriteInstancesCalledCounter;\n }\n\nprivate:\n /*\n * Counter to track the number of times Update is called\n */\n int m_NumberOfCallsToUpdateInstances;\n \n};\n\n\n/**************************************************************************************/\n// Mock ProcessInstance Class to simulate a ProcessInstance, the \n// GetParameters method will return a set of test parameters\n// \n/**************************************************************************************/\nclass MockProcessInstance : public ProcessInstance\n{\npublic:\n#if defined(hpux)\n MockProcessInstance(scxpid_t pid, struct pst_status *pstatus) : ProcessInstance(pid,pstatus) {}\n#elif defined(aix)\n MockProcessInstance(scxpid_t pid, struct procentry64 *pentry) : ProcessInstance(pid,pentry) {}\n#else\n MockProcessInstance(scxpid_t pid, const char* basename) : ProcessInstance(pid,basename) {}\n#endif\n\n /**************************************************************************************/\n // Mock GetParameters method to return the parameters required to test the ProcessInstance\n // \n /**************************************************************************************/\n bool GetTheParameters(std::vector<std::string>& params)\n {\n for(std::vector<std::string>::iterator pos = m_params.begin(); pos != m_params.end(); ++pos) \n {\n params.push_back(*pos);\n }\n return true;\n }\n \n /**************************************************************************************/\n // Helper method used to add/create process parameters that are returned by\n // GetParameters\n /**************************************************************************************/\n void AddParameter(std::string const val)\n {\n m_params.push_back(val);\n }\n\nprivate:\n std::vector<std::string> m_params;\n};\n\n/**************************************************************************************/\n// Mock AppServerPALDependencies Class, this class is used as a proxy between the \n// AppSServerEnumeration class and the ProcessInstance class. It is meant to injected\n// into AppSServerEnumeration class for testing purposes.\n/**************************************************************************************/\nclass MockAppServerPALDependencies : public AppServerPALDependencies\n{\npublic:\n \n /**************************************************************************************/\n // Mock Find method which emulated the ProcessEnumeration.Find method\n /**************************************************************************************/\n std::vector<SCXCoreLib::SCXHandle<ProcessInstance> > Find(const std::wstring& name)\n {\n std::wstring x = name;\n return m_Inst;\n }\n \n /**************************************************************************************/\n // Helper method to populate ProcessInstances so that the 'Find' method can retrieve \n // good test values.\n /**************************************************************************************/\n SCXCoreLib::SCXHandle<MockProcessInstance> CreateProcessInstance(scxpid_t pid, const char* basename)\n {\n#if defined(hpux)\n struct pst_status stat;\n strcpy(stat.pst_ucomm, basename);\n SCXCoreLib::SCXHandle<MockProcessInstance> inst(new MockProcessInstance(pid, &stat));\n#elif defined(aix)\n struct procentry64 entry;\n strcpy(entry.pi_comm, basename);\n SCXCoreLib::SCXHandle<MockProcessInstance> inst(new MockProcessInstance(pid, &entry));\n#else\n SCXCoreLib::SCXHandle<MockProcessInstance> inst(new MockProcessInstance(pid, basename));\n#endif\n m_Inst.push_back(inst);\n m_InstTest.push_back(inst);\n return inst;\n }\n \n /**************************************************************************************/\n // Mock PAL GetParameters method. This method get the paramerters for a specific \n // ProcessInstance.\n /**************************************************************************************/\n bool GetParameters(SCXCoreLib::SCXHandle<ProcessInstance> inst, std::vector<std::string>& params)\n {\n for (std::vector<SCXCoreLib::SCXHandle<MockProcessInstance> >::iterator it = m_InstTest.begin(); it != m_InstTest.end(); it++)\n {\n if((SCXCoreLib::SCXHandle<ProcessInstance>)(*it) == inst)\n {\n (*it)->GetTheParameters(params);\n return true;\n }\n }\n return false;\n }\n \n /**************************************************************************************/\n // Mock PAL GetWeblogicInstances method. This method creates WeblogicAppserverinstances \n // \n /**************************************************************************************/\n void GetWeblogicInstances(vector<wstring> weblogicProcesses, vector<SCXHandle<AppServerInstance> >& newInst)\n {\n wstring wideHttpPort = L\"7001\";\n wstring wideHttpsPort = L\"7002\";\n wstring wideVersion = L\"10.3.2.0\";\n\n vector<wstring>::iterator tmp = \n unique(weblogicProcesses.begin(), weblogicProcesses.end());\n weblogicProcesses.resize(tmp-weblogicProcesses.begin());\n\n for(tmp=weblogicProcesses.begin();tmp !=weblogicProcesses.end(); ++tmp)\n {\n SCXCoreLib::SCXHandle<AppServerInstance> instance(\n new AppServerInstance (*tmp,L\"Weblogic\") );\n newInst.push_back(instance);\n }\n }\n \nprivate:\n std::vector<SCXCoreLib::SCXHandle<ProcessInstance> > m_Inst;\n std::vector<SCXCoreLib::SCXHandle<MockProcessInstance> > m_InstTest;\n};\n\n/**************************************************************************************/\n// The Unit Test class for AppServerEnumeration.\n/**************************************************************************************/\nclass AppServerEnumeration_Test : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( AppServerEnumeration_Test );\n\n CPPUNIT_TEST( JBoss_Process_Good_Params_space );\n CPPUNIT_TEST( JBoss_Process_Good_Params_equal );\n CPPUNIT_TEST( JBoss_Process_Bad_Params__No_Main );\n CPPUNIT_TEST( JBoss_Process_Bad_Params__No_ClassPath_long );\n CPPUNIT_TEST( JBoss_Process_Bad_Params__No_ClassPath_short );\n CPPUNIT_TEST( JBoss_Process_Bad_Params__No_ClassPath_no_value );\n CPPUNIT_TEST( JBoss_Process_Bad_Params__No_ClassPath_no_value_equal );\n CPPUNIT_TEST( JBoss_Process_Bad_Params__No_RunJar_in_ClassPath );\n CPPUNIT_TEST( JBoss_Process_Bad_Params__No_RunJar_in_longer_ClassPath );\n CPPUNIT_TEST( JBoss_Process_Good_Params_Using_ServerNameProperty );\n CPPUNIT_TEST( JBoss_Process_Good_Params_3_Running );\n CPPUNIT_TEST( JBoss_Process_Good_Params_22_Running );\n CPPUNIT_TEST( JBoss_Domain_Process_Good_Params );\n CPPUNIT_TEST( JBoss_Standalone_Config_Dir );\n CPPUNIT_TEST( JBoss_Standalone_Non_Default_Config );\n CPPUNIT_TEST( JBoss_Standalone_CmdLine_Port_Offset );\n CPPUNIT_TEST( JBoss_Standalone_no_standalone_base_dir );\n CPPUNIT_TEST( testReadInstancesMethodCalledAtInit );\n CPPUNIT_TEST( testWriteInstancesMethodCalledAtCleanup );\n CPPUNIT_TEST( Tomcat_Process_Good_Params );\n CPPUNIT_TEST( Tomcat_Process_Bad_Params_missing_Catalina_home );\n CPPUNIT_TEST( Tomcat_Process_Bad_Params_missing_Catalina_base );\n CPPUNIT_TEST( JBoss_Tomcat_Process_Good_params );\n CPPUNIT_TEST( JBoss_Tomcat_Process_Bad_Good_params );\n CPPUNIT_TEST( JBoss_Tomcat_Process_MixedGoodBad );\n \n CPPUNIT_TEST( WebSphere_Process_NonDefaultProfile );\n CPPUNIT_TEST( WebSphere_Process_Good_Params );\n CPPUNIT_TEST( WebSphere_Process_Fixing_Incorrect_Enumerations );\n CPPUNIT_TEST( WebSphere_Process_Bad_Params_TooFewArgs_Missing_Server );\n CPPUNIT_TEST( WebSphere_Process_Bad_Params_TooFewArgs_Missing_Node );\n CPPUNIT_TEST( WebSphere_Process_Bad_Params_TooFewArgs_Missing_ServerRoot );\n CPPUNIT_TEST( WebSphere_JBoss_Tomcat_Process_MixedGoodBad );\n \n CPPUNIT_TEST( Weblogic_Process_Good_Params );\n\tCPPUNIT_TEST( Weblogic_12cR1_Process_Good_Params );\n CPPUNIT_TEST( Weblogic_Process_Good_Params_NodeManager );\n CPPUNIT_TEST( Weblogic_Process_Bad_Params );\n CPPUNIT_TEST( Weblogic_Process_Good_Params_Two_Instances );\n CPPUNIT_TEST( Weblogic_Process_Good_Params_Two_Instances_One_Home );\n CPPUNIT_TEST( Weblogic_WebSphere_JBoss_Tomcat_Process_MixedGoodBad );\n \n CPPUNIT_TEST( UpdateInstances_Is_Not_Called );\n \n \n CPPUNIT_TEST_SUITE_END();\n\npublic:\n\n /**************************************************************************************/\n //\n // Unit Test Setup: run before each test\n //\n /**************************************************************************************/\n void setUp(void)\n {\n }\n\n /**************************************************************************************/\n //\n // Unit Test Teardown: run after each test\n //\n /**************************************************************************************/\n void tearDown(void)\n {\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters. The classpath key and value are space seperated\n // -classpath classpathvalue:classpathvalue. The values should be corectly parsed out\n // \n /**************************************************************************************/\n void JBoss_Process_Good_Params_space()\n {\n try {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/java/jre1.6.0_10//bin/java\");\n inst->AddParameter(\"-server\");\n inst->AddParameter(\"-Xms128m\");\n inst->AddParameter(\"-Xmx512m\");\n inst->AddParameter(\"-XX:MaxPermSize=256m\");\n inst->AddParameter(\"-Dorg.jboss.resolver.warning=true\");\n inst->AddParameter(\"-Dsun.rmi.dgc.client.gcInterval=3600000\");\n inst->AddParameter(\"-Djava.net.preferIPv4Stack=true\");\n inst->AddParameter(\"-Dprogram.name=run.sh\");\n inst->AddParameter(\"-Djava.library.path=/opt/jboss-6.0/bin/native/lib\");\n inst->AddParameter(\"-Djava.endorsed.dirs=/opt/jboss-6.0/lib/endorsed\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/optjboss-6.0/:/opt/jboss-6.0/bin/run.jar:/usr/lib\");\n inst->AddParameter(\"org.jboss.Main\");\n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n inst->AddParameter(\"-b\");\n inst->AddParameter(\"0.0.0.0\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/opt/jboss-6.0/server/default/\" == (*it)->GetId());\n \n asEnum.CleanUp();\n }\n catch(const std::exception & ex) {\n std::cout<<ex.what()<<std::endl;\n }\n }\n \n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters. The classpath key and value are seperated by an '='\n // -classpath=classpathvalue:classpathvalue. The values should be corectly parsed out\n // \n /**************************************************************************************/\n void JBoss_Process_Good_Params_equal()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/opt/jboss-6.2/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n asEnum.Update(false);\n \n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n\n CPPUNIT_ASSERT(L\"/opt/jboss-6.2/server/default/\" == (*it)->GetId());\n \n asEnum.CleanUp();\n }\n \n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with incorrect parameters. The parameter 'org.jboss.main' must exist\n // in the parameter list for this to be a valid JBoss instance.\n // \n /**************************************************************************************/\n void JBoss_Process_Bad_Params__No_Main()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss_Main\"); //FAIL\n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n asEnum.Update(false);\n \n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n \n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with incorrect parameters. The parameter key '-classpath' must exist\n // in the parameter list for this to be a valid JBoss instance.\n // \n /**************************************************************************************/\n void JBoss_Process_Bad_Params__No_ClassPath_long()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpathx\"); //FAIL\n inst->AddParameter(\"/opt/jboss-6.5/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n asEnum.Update(false);\n \n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n \n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with incorrect parameters. The parameter key '-classpath' must exist\n // in the parameter list for this to be a valid JBoss instance.\n // \n /**************************************************************************************/\n void JBoss_Process_Bad_Params__No_ClassPath_short()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"Classpath\"); //FAIL\n inst->AddParameter(\"/opt/jboss-6.5/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n asEnum.Update(false);\n \n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n \n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with incorrect parameters. The parameter key '-classpath' must exist\n // in the parameter list and must be followed by the classpath value .\n // \n /**************************************************************************************/\n void JBoss_Process_Bad_Params__No_ClassPath_no_value()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n inst->AddParameter(\"-classpath\"); // missing value\n\n asEnum.Update(false);\n \n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n \n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with incorrect parameters. The parameter key '-classpath' must exist\n // in the parameter list and must be followed by the classpath value .\n // \n /**************************************************************************************/\n void JBoss_Process_Bad_Params__No_ClassPath_no_value_equal()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-classpath=\"); // missing value\n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n asEnum.Update(false);\n \n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n \n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with incorrect parameters. The parameter key '-classpath' must exist\n // in the parameter list. The classpath value must contain a path entry for 'bin/run.jar'\n // this is the entry used to identify the home directory.\n // This test is for a single classpath jar file entry.\n // \n /**************************************************************************************/\n void JBoss_Process_Bad_Params__No_RunJar_in_ClassPath()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath\"); \n inst->AddParameter(\"/opt/jboss-6.6/bin/run.jam\"); //FAIL\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n asEnum.Update(false);\n \n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with incorrect parameters. The parameter key '-classpath' must exist\n // in the parameter list. The classpath value must contain a path entry for 'bin/run.jar'\n // this is the entry used to identify the home directory.\n // This test is for a more complex classpath entry containg multiple paths.\n // \n /**************************************************************************************/\n void JBoss_Process_Bad_Params__No_RunJar_in_longer_ClassPath()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath\"); \n inst->AddParameter(\"/opt/jboss-6.6/bin:/usr/lib:/opt/jboss-6.6/bin/run.ja:/opt/jboss-6.6/lib\"); //FAIL\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n asEnum.Update(false);\n \n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Bug #42733:\n // JBoss5 process discovery fails when specifying profile using -Djboss.server.name property\n //\n // For a JBoss application server started with the -Djboss.server.name property, verify that\n // this switch is correctly parsed from the command-line.\n // \n /**************************************************************************************/\n void JBoss_Process_Good_Params_Using_ServerNameProperty()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n // java -Dprogram.name=run.sh -server -Xms128m -Xmx512m -XX:MaxPermSize=256m \n // -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 \n // -Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.net.preferIPv4Stack=true \n // -Djava.endorsed.dirs=/home/ccrammo/AppServers/jboss/jboss-5.1.0.GA/lib/endorsed \n // -classpath /home/ccrammo/AppServers/jboss/jboss-5.1.0.GA/bin/run.jar \n // org.jboss.Main -b 0.0.0.0\n //\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/b/jboss-1234/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n // java -Dprogram.name=run.sh -server -Xms128m -Xmx512m -XX:MaxPermSize=256m \n // -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000 \n // -Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.net.preferIPv4Stack=true \n // -Djava.endorsed.dirs=/home/ccrammo/AppServers/jboss/jboss-5.1.0.GA/lib/endorsed\n // -classpath /home/ccrammo/AppServers/jboss/jboss-5.1.0.GA/bin/run.jar org.jboss.Main\n // -Djboss.service.binding.set=ports-01 -Djboss.server.name=profile2\n inst = pal->CreateProcessInstance(5678, \"5678\");\n inst->AddParameter(\"-classpath=/a/jboss-5678/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n inst->AddParameter(\"-Djboss.server.name=profile2\");\n\n // java -Dprogram.name=run.sh -server -Xms128m -Xmx512m -XX:MaxPermSize=256m\n // -Dorg.jboss.resolver.warning=true -Dsun.rmi.dgc.client.gcInterval=3600000\n // -Dsun.rmi.dgc.server.gcInterval=3600000 -Djava.net.preferIPv4Stack=true\n // -Djava.endorsed.dirs=/home/ccrammo/AppServers/jboss/jboss-5.1.0.GA/lib/endorsed\n // -classpath /home/ccrammo/AppServers/jboss/jboss-5.1.0.GA/bin/run.jar org.jboss.Main\n // -Djboss.service.binding.set=ports-02 -Djboss.server.name=profile 3\n inst = pal->CreateProcessInstance(90, \"90\");\n inst->AddParameter(\"-classpath=/c/jboss-90/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-Djboss.server.name=profile 3\");\n\n asEnum.Update(false);\n CPPUNIT_ASSERT(asEnum.Size() == 3);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/a/jboss-5678/server/profile2/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"/b/jboss-1234/server/default/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"/c/jboss-90/server/profile 3/\" == (*(++it))->GetId());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with correct parameters. Multiple ProcessInstances are created and the \n // AppServerEnumeration adds the correct entries to its list of AppServerInstances.\n // \n /**************************************************************************************/\n void JBoss_Process_Good_Params_3_Running()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/opt/jboss-6.2/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-01\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/jboss-6.4/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c\");\n inst->AddParameter(\"My profile\");\n\n asEnum.Update(false);\n CPPUNIT_ASSERT(asEnum.Size() == 3);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"/jboss-6.4/server/My profile/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"/opt/jboss-6.2/server/default/\" == (*(++it))->GetId());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with correct parameters. Multiple ProcessInstances are created and the \n // AppServerEnumeration adds the correct entries to its list of \n // AppServerInstances as running.\n //\n // This unit test is needed for Bug #49459, which was a bug in the\n // sorting algorithm.\n // \n /**************************************************************************************/\n void JBoss_Process_Good_Params_22_Running()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/adminrx/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c adminrx\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/contextagent/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c contextagent\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/ha/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c ha\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hcservice/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hcservice\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hdm/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hdm\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hdv/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hdv\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hec/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hec\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hed/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hed\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hen/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hen\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hep/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hep\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hep_author/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hep_author\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hhs/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hhs\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hmrcs/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hmrcs\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hocs/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hocs\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hot/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hot\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hpcs/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hpcs\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hqmct/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hqmct\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hscs/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hscs\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/hwc/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c hwc\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/security/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c security\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/updatemgr/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c updatemgr\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-classpath=/u/hcswl1030/apps/vfs/jboss/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-c vfs\");\n\n asEnum.Update(false);\n CPPUNIT_ASSERT(asEnum.Size() == 22);\n\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it;\n for (it = asEnum.Begin(); it != asEnum.End(); ++it)\n {\n CPPUNIT_ASSERT((*it)->GetIsRunning());\n }\n\n // Call update again\n asEnum.Update(false);\n CPPUNIT_ASSERT(asEnum.Size() == 22);\n\n for (it = asEnum.Begin(); it != asEnum.End(); ++it)\n {\n CPPUNIT_ASSERT((*it)->GetIsRunning());\n }\n\n asEnum.CleanUp();\n }\n \n void JBoss_Domain_Process_Good_Params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java\");\n inst->AddParameter(\"-D[Server:server-one]\");\n inst->AddParameter(\"-XX:PermSize=256m\");\n inst->AddParameter(\"-XX:MaxPermSize=256m\");\n inst->AddParameter(\"-Xms64m\");\n inst->AddParameter(\"-Xmx512m\");\n inst->AddParameter(\"-server\");\n inst->AddParameter(\"-Djava.awt.headless=true\");\n inst->AddParameter(\"-Djava.net.preferIPv4Stack=true\");\n inst->AddParameter(\"-Djboss.bind.address=0.0.0.0\");\n inst->AddParameter(\"-Djboss.home.dir=/root/wildfly-8.1.0.CR2/wildfly-8.1.0.CR2\");\n inst->AddParameter(\"-Djboss.modules.system.pkgs=org.jboss.byteman\");\n inst->AddParameter(\"-Djboss.server.log.dir=/root/wildfly-8.1.0.CR2/wildfly-8.1.0.CR2/domain/servers/server-one/log\");\n inst->AddParameter(\"-Djboss.server.temp.dir=/root/wildfly-8.1.0.CR2/wildfly-8.1.0.CR2/domain/servers/server-one/tmp\");\n inst->AddParameter(\"-Djboss.server.data.dir=/root/wildfly-8.1.0.CR2/wildfly-8.1.0.CR2/domain/servers/server-one/data\");\n inst->AddParameter(\"-Dlogging.configuration=file:/root/wildfly-8.1.0.CR2/wildfly-8.1.0.CR2/domain/servers/server-one/data/logging.properties\");\n inst->AddParameter(\"-jar\");\n inst->AddParameter(\"/root/wildfly-8.1.0.CR2/wildfly-8.1.0.CR2/jboss-modules.jar\");\n inst->AddParameter(\"-mp\");\n inst->AddParameter(\"/root/wildfly-8.1.0.CR2/wildfly-8.1.0.CR2/modules\");\n inst->AddParameter(\"org.jboss.as.server\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n \n CPPUNIT_ASSERT_EQUAL(L\"/root/wildfly-8.1.0.CR2/wildfly-8.1.0.CR2/domain/servers/server-one/\",(*it)->GetId());\n \n asEnum.CleanUp();\n }\n \n void JBoss_Standalone_Config_Dir()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java\");\n inst->AddParameter(\"org.jboss.as.standalone\");\n inst->AddParameter(\"-Djboss.home.dir=/konsens/app/jboss-eap-6.4\");\n inst->AddParameter(\"-Djboss.server.base.dir=/konsens/app/rmsvlg/as/4.2.0.2/standalone\");\n inst->AddParameter(\"-Djboss.server.log.dir=/konsens/log/rmsvlg/as/4.2.0.2\");\n inst->AddParameter(\"-Dlogging.configuration=file:/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/logging.properties\");\n inst->AddParameter(\"-b\");\n inst->AddParameter(\"0.0.0.0\");\n\n inst = pal->CreateProcessInstance(12345, \"12345\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java\");\n inst->AddParameter(\"org.jboss.as.standalone\");\n inst->AddParameter(\"-Djboss.home.dir=/konsens/app/jboss-eap-6.4\");\n inst->AddParameter(\"-Djboss.server.base.dir=/konsens/app/rmsvlg/as/4.2.0.2/standalone\");\n inst->AddParameter(\"-Djboss.server.config.dir=/konsens/app/rmsvlg/as/4.2.0.0/standalone/configuration\");\n inst->AddParameter(\"-Djboss.server.log.dir=/konsens/log/rmsvlg/as/4.2.0.2\");\n inst->AddParameter(\"-Dlogging.configuration=file:/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/logging.properties\");\n inst->AddParameter(\"-b\");\n inst->AddParameter(\"0.0.0.0\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java\");\n inst->AddParameter(\"org.jboss.as.standalone\");\n inst->AddParameter(\"-Djboss.home.dir=/konsens/app/jboss-eap-6.4\");\n inst->AddParameter(\"-Djboss.server.log.dir=/konsens/log/rmsvlg/as/4.2.0.2\");\n inst->AddParameter(\"-Dlogging.configuration=file:/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/logging.properties\");\n inst->AddParameter(\"-b\");\n inst->AddParameter(\"0.0.0.0\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 3);\n\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/konsens/app/jboss-eap-6.4/standalone/configuration/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"/konsens/app/rmsvlg/as/4.2.0.0/standalone/configuration/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/\" == (*(++it))->GetId());\n \n asEnum.CleanUp();\n }\n\n void JBoss_Standalone_Non_Default_Config()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java\");\n inst->AddParameter(\"-D[Standalone]\");\n inst->AddParameter(\"-XX:+UseCompressedOops\");\n inst->AddParameter(\"-verbose:gc\");\n inst->AddParameter(\"-Xloggc:/konsens/log/rmsvlg/as/4.2.0.2/gc.log\");\n inst->AddParameter(\"-XX:+PrintGCDetails\");\n inst->AddParameter(\"-server\");\n inst->AddParameter(\"-XX:+PrintGCDateStamps\");\n inst->AddParameter(\"-XX:+UseGCLogFileRotation\");\n inst->AddParameter(\"-XX:NumberOfGCLogFiles=5\");\n inst->AddParameter(\"-XX:GCLogFileSize=3M\");\n inst->AddParameter(\"-XX:-TraceClassUnloading\");\n inst->AddParameter(\"-Xms2048m\");\n inst->AddParameter(\"-Xmx2048m\");\n inst->AddParameter(\"-Dorg.jboss.boot.log.file=/konsens/log/rmsvlg/as/4.2.0.2/server.log\");\n inst->AddParameter(\"-Dlogging.configuration=file:/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/logging.properties\");\n inst->AddParameter(\"-jar\");\n inst->AddParameter(\"/konsens/app/jboss-eap-6.4/jboss-modules.jar \");\n inst->AddParameter(\"-mp\");\n inst->AddParameter(\"/konsens/app/jboss-eap-6.4/modules\");\n inst->AddParameter(\"-jaxpmodule\");\n inst->AddParameter(\"javax.xml.jaxp-provider\");\n inst->AddParameter(\"org.jboss.as.standalone\");\n inst->AddParameter(\"-Djboss.home.dir=/konsens/app/jboss-eap-6.4\");\n inst->AddParameter(\"-Djboss.server.base.dir=/konsens/app/rmsvlg/as/4.2.0.2/standalone\");\n inst->AddParameter(\"-Djboss.server.log.dir=/konsens/log/rmsvlg/as/4.2.0.2\");\n inst->AddParameter(\"-c\");\n inst->AddParameter(\"standalone-full.xml\");\n inst->AddParameter(\"-b\");\n inst->AddParameter(\"0.0.0.0\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n \n CPPUNIT_ASSERT_EQUAL(L\"/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/standalone-full.xml\",(*it)->GetId());\n \n asEnum.CleanUp();\n }\n\n void JBoss_Standalone_CmdLine_Port_Offset()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java\");\n inst->AddParameter(\"org.jboss.as.standalone\");\n inst->AddParameter(\"-Djboss.home.dir=/konsens/app/jboss-eap-6.4\");\n inst->AddParameter(\"-Djboss.server.base.dir=/konsens/app/rmsvlg/as/4.2.0.2/standalone\");\n inst->AddParameter(\"-Djboss.server.log.dir=/konsens/log/rmsvlg/as/4.2.0.2\");\n inst->AddParameter(\"-Dlogging.configuration=file:/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/logging.properties\");\n inst->AddParameter(\"-Djboss.socket.binding.port-offset=1000\");\n inst->AddParameter(\"-b\");\n inst->AddParameter(\"0.0.0.0\");\n\n inst = pal->CreateProcessInstance(12345, \"12345\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java\");\n inst->AddParameter(\"org.jboss.as.standalone\");\n inst->AddParameter(\"-Djboss.home.dir=/konsens/app/jboss-eap-6.4\");\n inst->AddParameter(\"-Djboss.server.base.dir=/konsens/app/rmsvlg/as/4.2.0.2/standalone\");\n inst->AddParameter(\"-Djboss.server.config.dir=/konsens/app/rmsvlg/as/4.2.0.0/standalone/configuration\");\n inst->AddParameter(\"-Djboss.server.log.dir=/konsens/log/rmsvlg/as/4.2.0.2\");\n inst->AddParameter(\"-Dlogging.configuration=file:/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/logging.properties\");\n inst->AddParameter(\"-Djboss.socket.binding.port-offset=2000\");\n inst->AddParameter(\"-c\");\n inst->AddParameter(\"standalone-full.xml\");\n inst->AddParameter(\"-b\");\n inst->AddParameter(\"0.0.0.0\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 2);\n\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/konsens/app/rmsvlg/as/4.2.0.0/standalone/configuration/standalone-full.xml:2000\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"/konsens/app/rmsvlg/as/4.2.0.2/standalone/configuration/:1000\" == (*(++it))->GetId());\n \n asEnum.CleanUp();\n }\n\n void JBoss_Standalone_no_standalone_base_dir()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java\");\n inst->AddParameter(\"org.jboss.as.standalone\");\n inst->AddParameter(\"-Djboss.home.dir=/konsens/app/jboss-eap-6.4\");\n inst->AddParameter(\"-Djboss.server.base.dir=/konsens/app/rmsvlg/as/4.2.0.2/instance0\");\n inst->AddParameter(\"-Djboss.server.log.dir=/konsens/log/rmsvlg/as/4.2.0.2\");\n inst->AddParameter(\"-Dlogging.configuration=file:/konsens/app/rmsvlg/as/4.2.0.2/instance0/configuration/logging.properties\");\n inst->AddParameter(\"-b\");\n inst->AddParameter(\"0.0.0.0\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/konsens/app/rmsvlg/as/4.2.0.2/instance0/configuration/\" == (*it)->GetId());\n \n asEnum.CleanUp();\n }\n\n /*\n * The actual reading and writing to the cache has been mocked out.\n * This test utilizes the test spy pattern because all that we want\n * to verify is that the method to read from the cache was called\n * at initialization. \n */\n void testReadInstancesMethodCalledAtInit()\n {\n TestSpyAppServerEnumeration asEnum;\n\n CPPUNIT_ASSERT_EQUAL(0, asEnum.m_ReadInstancesCalledCounter);\n asEnum.Init();\n CPPUNIT_ASSERT_EQUAL(1, asEnum.m_ReadInstancesCalledCounter);\n }\n \n /*\n * The actual reading and writing to the cache has been mocked out.\n * This test utilizes the test spy pattern because all that we want\n * to verify is that the method to write to the cache was called\n * at clean-up. \n */\n void testWriteInstancesMethodCalledAtCleanup()\n {\n TestSpyAppServerEnumeration asEnum;\n\n CPPUNIT_ASSERT_EQUAL(0, asEnum.m_WriteInstancesCalledCounter);\n asEnum.CleanUp();\n CPPUNIT_ASSERT_EQUAL(1, asEnum.m_WriteInstancesCalledCounter);\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // A valid Tomcat instance should be created.\n // \n /**************************************************************************************/\n void Tomcat_Process_Good_Params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/java/jre1.6.0_10//bin/java\");\n inst->AddParameter(\"-Djava.util.logging.config.file=/opt/apache-tomcat-5.5.29//conf/logging.properties\");\n inst->AddParameter(\"-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager\");\n inst->AddParameter(\"-Djava.endorsed.dirs=/opt/apache-tomcat-5.5.29//common/endorsed\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/apache-tomcat-5.5.29//bin/bootstrap.jar\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/profile1\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Djava.io.tmpdir=/opt/apache-tomcat-5.5.29//temp\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n inst->AddParameter(\"start\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.29/profile1/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the incorrect parameters works correctly. \n // No valid Tomcat instances should be created.\n // \n /**************************************************************************************/\n void Tomcat_Process_Bad_Params_missing_Catalina_home()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/java/jre1.6.0_10//bin/java\");\n inst->AddParameter(\"-Djava.util.logging.config.file=/opt/apache-tomcat-5.5.29//conf/logging.properties\");\n inst->AddParameter(\"-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager\");\n inst->AddParameter(\"-Djava.endorsed.dirs=/opt/apache-tomcat-5.5.29//common/endorsed\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/apache-tomcat-5.5.29//bin/bootstrap.jar\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Djava.io.tmpdir=/opt/apache-tomcat-5.5.29//temp\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n inst->AddParameter(\"start\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // A valid Tomcat instances should be created.\n // This specific test is for when the Catalina.base is not specified.\n // \n /**************************************************************************************/\n void Tomcat_Process_Bad_Params_missing_Catalina_base()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/java/jre1.6.0_10//bin/java\");\n inst->AddParameter(\"-Djava.util.logging.config.file=/opt/apache-tomcat-5.5.29//conf/logging.properties\");\n inst->AddParameter(\"-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager\");\n inst->AddParameter(\"-Djava.endorsed.dirs=/opt/apache-tomcat-5.5.29//common/endorsed\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/apache-tomcat-5.5.29//bin/bootstrap.jar\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Djava.io.tmpdir=/opt/apache-tomcat-5.5.29//temp\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n inst->AddParameter(\"start\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.29/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.29/\" == (*it)->GetDiskPath());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // A valid JBoss and Tomcat instance should be created.\n // This specific test is for a combination of both JBoss and Tomcat.\n // \n /**************************************************************************************/\n void JBoss_Tomcat_Process_Good_params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/java/jre1.6.0_10//bin/java\");\n inst->AddParameter(\"-Djava.util.logging.config.file=/opt/apache-tomcat-5.5.29//conf/logging.properties\");\n inst->AddParameter(\"-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager\");\n inst->AddParameter(\"-Djava.endorsed.dirs=/opt/apache-tomcat-5.5.29//common/endorsed\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/apache-tomcat-5.5.29//bin/bootstrap.jar\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Djava.io.tmpdir=/opt/apache-tomcat-5.5.29//temp\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n inst->AddParameter(\"start\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 2);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal/\" == (*it)->GetId());\n\n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.29/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // A valid JBoss instance should be created and the invalid Tomcat \n // should be ignored.\n // This specific test is for a combination of both JBoss and Tomcat.\n // \n /**************************************************************************************/\n void JBoss_Tomcat_Process_Good_Bad_params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/java/jre1.6.0_10//bin/java\");\n inst->AddParameter(\"-Djava.util.logging.config.file=/opt/apache-tomcat-5.5.29//conf/logging.properties\");\n inst->AddParameter(\"-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager\");\n inst->AddParameter(\"-Djava.endorsed.dirs=/opt/apache-tomcat-5.5.29//common/endorsed\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/apache-tomcat-5.5.29//bin/bootstrap.jar\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Djava.io.tmpdir=/opt/apache-tomcat-5.5.29//temp\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n inst->AddParameter(\"start\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"JBoss\" == (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // A valid Tomcat instance should be created and the invalid JBoss \n // should be ignored.\n // This specific test is for a combination of both JBoss and Tomcat.\n // \n /**************************************************************************************/\n void JBoss_Tomcat_Process_Bad_Good_params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/java/jre1.6.0_10//bin/java\");\n inst->AddParameter(\"-Djava.util.logging.config.file=/opt/apache-tomcat-5.5.29//conf/logging.properties\");\n inst->AddParameter(\"-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager\");\n inst->AddParameter(\"-Djava.endorsed.dirs=/opt/apache-tomcat-5.5.29//common/endorsed\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/apache-tomcat-5.5.29//bin/bootstrap.jar\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Djava.io.tmpdir=/opt/apache-tomcat-5.5.29//temp\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n inst->AddParameter(\"start\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.29/\" == (*(it))->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // Two valid Tomcat instance should be created and two valid JBoss \n // instances should be created. There is one invalid Tomcat and JBoss entry that should be ignored.\n // This specific test is for a combination of both JBoss and Tomcat.\n // \n /**************************************************************************************/\n void JBoss_Tomcat_Process_MixedGoodBad()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.30/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal1\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.31/\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.31/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal2\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 4);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"JBoss\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal1/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"JBoss\" == (*it)->GetType());\n \n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.29/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.31/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n\n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the corret parameters, and non default 'Profiles' path \n // A valid WebSphere instance should be created.\n // \n /**************************************************************************************/\n void WebSphere_Process_NonDefaultProfile()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/java/bin/java\");\n inst->AddParameter(\"-Declipse.security\");\n inst->AddParameter(\"-Dwas.status.socket=56994\");\n inst->AddParameter(\"-Dosgi.install.area=/opt/IBM/WebSphere/AppServer\");\n inst->AddParameter(\"-Dosgi.configuration.area=/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/configuration\");\n inst->AddParameter(\"-Djava.awt.headless=true\");\n inst->AddParameter(\"-Dosgi.framework.extensions=com.ibm.cds\");\n inst->AddParameter(\"-Xshareclasses:name=webspherev61_%g,groupAccess,nonFatal\");\n inst->AddParameter(\"-Xscmx50M\");\n inst->AddParameter(\"-Xbootclasspath/p:/opt/IBM/WebSphere/AppServer/java/jre/lib/ext/ibmorb.jar:/opt/IBM/WebSphere/AppServer/java/jre/lib/ext/ibmext.jar\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/properties:/opt/IBM/WebSphere/AppServer/properties:/opt/IBM/WebSphere/AppServer/lib/startup.jar:/opt/IBM/WebSphere/AppServer/lib/bootstrap.jar:/opt/IBM/WebSphere/AppServer/lib/j2ee.jar:/opt/IBM/WebSphere/AppServer/lib/lmproxy.jar:/opt/IBM/WebSphere/AppServer/lib/urlprotocols.jar:/opt/IBM/WebSphere/AppServer/deploytool/itp/batchboot.jar:/opt/IBM/WebSphere/AppServer/deploytool/itp/batch2.jar:/opt/IBM/WebSphere/AppServer/java/lib/tools.jar\");\n inst->AddParameter(\"-Dibm.websphere.internalClassAccessMode=allow\");\n inst->AddParameter(\"-Xms50m\");\n inst->AddParameter(\"-Xmx256m\"); \n inst->AddParameter(\"-Dws.ext.dirs=/opt/IBM/WebSphere/AppServer/java/lib:/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/classes:/opt/IBM/WebSphere/AppServer/classes:/opt/IBM/WebSphere/AppServer/lib:/opt/IBM/WebSphere/AppServer/installedChannels:/opt/IBM/WebSphere/AppServer/lib/ext:/opt/IBM/WebSphere/AppServer/web/help:/opt/IBM/WebSphere/AppServer/deploytool/itp/plugins/com.ibm.etools.ejbdeploy/runtime\"); \n inst->AddParameter(\"-Dderby.system.home=/opt/IBM/WebSphere/AppServer/derby\"); \n inst->AddParameter(\"-Dcom.ibm.itp.location=/opt/IBM/WebSphere/AppServer/bin\"); \n inst->AddParameter(\"-Djava.util.logging.configureByServer=true\"); \n inst->AddParameter(\"-Duser.install.root=/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01\");\n inst->AddParameter(\"-Djavax.management.builder.initial=com.ibm.ws.management.PlatformMBeanServerBuilder\"); \n inst->AddParameter(\"-Dwas.install.root=/opt/IBM/WebSphere/AppServer\"); \n inst->AddParameter(\"-Dpython.cachedir=/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/temp/cachedir\"); \n inst->AddParameter(\"-Djava.util.logging.manager=com.ibm.ws.bootstrap.WsLogManager\"); \n inst->AddParameter(\"-Dserver.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"-Djava.security.auth.login.config=/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/properties/wsjaas.conf\"); \n inst->AddParameter(\"-Djava.security.policy=/opt/IBM/WebSphere/AppServer/Profiles/AppSrv01/properties/server.policy\"); \n inst->AddParameter(\"com.ibm.wsspi.bootstrap.WSPreLauncher\"); \n inst->AddParameter(\"-nosplash\"); \n inst->AddParameter(\"-application\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n inst->AddParameter(\"server1\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT_EQUAL(L\"AppSrv01-scxjet-rhel5-04Node01Cell-Node01-server1\",(*it)->GetId());\n CPPUNIT_ASSERT_EQUAL(L\"WebSphere\",(*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // A valid WebSphere instance should be created.\n // \n /**************************************************************************************/\n void WebSphere_Process_Good_Params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/java/bin/java\");\n inst->AddParameter(\"-Declipse.security\");\n inst->AddParameter(\"-Dwas.status.socket=56994\");\n inst->AddParameter(\"-Dosgi.install.area=/opt/IBM/WebSphere/AppServer\");\n inst->AddParameter(\"-Dosgi.configuration.area=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/configuration\");\n inst->AddParameter(\"-Djava.awt.headless=true\");\n inst->AddParameter(\"-Dosgi.framework.extensions=com.ibm.cds\");\n inst->AddParameter(\"-Xshareclasses:name=webspherev61_%g,groupAccess,nonFatal\");\n inst->AddParameter(\"-Xscmx50M\");\n inst->AddParameter(\"-Xbootclasspath/p:/opt/IBM/WebSphere/AppServer/java/jre/lib/ext/ibmorb.jar:/opt/IBM/WebSphere/AppServer/java/jre/lib/ext/ibmext.jar\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/properties:/opt/IBM/WebSphere/AppServer/properties:/opt/IBM/WebSphere/AppServer/lib/startup.jar:/opt/IBM/WebSphere/AppServer/lib/bootstrap.jar:/opt/IBM/WebSphere/AppServer/lib/j2ee.jar:/opt/IBM/WebSphere/AppServer/lib/lmproxy.jar:/opt/IBM/WebSphere/AppServer/lib/urlprotocols.jar:/opt/IBM/WebSphere/AppServer/deploytool/itp/batchboot.jar:/opt/IBM/WebSphere/AppServer/deploytool/itp/batch2.jar:/opt/IBM/WebSphere/AppServer/java/lib/tools.jar\");\n inst->AddParameter(\"-Dibm.websphere.internalClassAccessMode=allow\");\n inst->AddParameter(\"-Xms50m\");\n inst->AddParameter(\"-Xmx256m\"); \n inst->AddParameter(\"-Dws.ext.dirs=/opt/IBM/WebSphere/AppServer/java/lib:/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/classes:/opt/IBM/WebSphere/AppServer/classes:/opt/IBM/WebSphere/AppServer/lib:/opt/IBM/WebSphere/AppServer/installedChannels:/opt/IBM/WebSphere/AppServer/lib/ext:/opt/IBM/WebSphere/AppServer/web/help:/opt/IBM/WebSphere/AppServer/deploytool/itp/plugins/com.ibm.etools.ejbdeploy/runtime\"); \n inst->AddParameter(\"-Dderby.system.home=/opt/IBM/WebSphere/AppServer/derby\"); \n inst->AddParameter(\"-Dcom.ibm.itp.location=/opt/IBM/WebSphere/AppServer/bin\"); \n inst->AddParameter(\"-Djava.util.logging.configureByServer=true\"); \n inst->AddParameter(\"-Duser.install.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\");\n inst->AddParameter(\"-Djavax.management.builder.initial=com.ibm.ws.management.PlatformMBeanServerBuilder\"); \n inst->AddParameter(\"-Dwas.install.root=/opt/IBM/WebSphere/AppServer\"); \n inst->AddParameter(\"-Dpython.cachedir=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/temp/cachedir\"); \n inst->AddParameter(\"-Djava.util.logging.manager=com.ibm.ws.bootstrap.WsLogManager\"); \n inst->AddParameter(\"-Dserver.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"-Djava.security.auth.login.config=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/properties/wsjaas.conf\"); \n inst->AddParameter(\"-Djava.security.policy=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/properties/server.policy\"); \n inst->AddParameter(\"com.ibm.wsspi.bootstrap.WSPreLauncher\"); \n inst->AddParameter(\"-nosplash\"); \n inst->AddParameter(\"-application\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n inst->AddParameter(\"server1\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT_EQUAL(L\"AppSrv01-scxjet-rhel5-04Node01Cell-Node01-server1\",(*it)->GetId());\n CPPUNIT_ASSERT_EQUAL(L\"WebSphere\",(*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the incorrect parameters works correctly. \n // No valid WebSphere instance should be created.\n // \n /**************************************************************************************/\n void WebSphere_Process_Bad_Params_TooFewArgs_Missing_Server()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/java/bin/java\");\n inst->AddParameter(\"-Dserver.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"com.ibm.wsspi.bootstrap.WSPreLauncher\"); \n inst->AddParameter(\"-application\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the incorrect parameters works correctly. \n // No valid WebSphere instance should be created.\n // \n /**************************************************************************************/\n void WebSphere_Process_Bad_Params_TooFewArgs_Missing_Node()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/java/bin/java\");\n inst->AddParameter(\"-Dserver.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"com.ibm.wsspi.bootstrap.WSPreLauncher\"); \n inst->AddParameter(\"-application\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"server1\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the incorrect parameters works correctly. \n // No valid WebSphere instance should be created.\n // \n /**************************************************************************************/\n void WebSphere_Process_Bad_Params_TooFewArgs_Missing_ServerRoot()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/java/bin/java\");\n inst->AddParameter(\"com.ibm.wsspi.bootstrap.WSPreLauncher\"); \n inst->AddParameter(\"-application\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n inst->AddParameter(\"server1\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // Two valid Tomcat instance , two valid JBoss \n // instances and two valid WebSphere instances should be created. \n // There is one invalid Tomcat, JBoss and WebSphere entry that should be ignored.\n // This specific test is for a combination of both JBoss, Tomcat and WebSphere.\n // \n /**************************************************************************************/\n void WebSphere_JBoss_Tomcat_Process_MixedGoodBad()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dserver.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n inst->AddParameter(\"Server1\"); \n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.30/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal1\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dserver.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.31/\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.31/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal2\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dserver.root=/opt/IBM1/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n inst->AddParameter(\"Server3\"); \n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 6);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"JBoss\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal1/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"JBoss\" == (*it)->GetType());\n \n CPPUNIT_ASSERT(L\"AppSrv01-scxjet-rhel5-04Node01Cell-Node01-Server1\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"WebSphere\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"AppSrv01-scxjet-rhel5-04Node01Cell-Node01-Server3\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"WebSphere\" == (*it)->GetType());\n \n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.29/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.31/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n\n asEnum.CleanUp();\n }\n\n\n /**************************************************************************************/\n //\n // Verify that a valid instance of WebLogic is discovered, this perticular\n // instance is started via the NodeManager.\n // A valid Weblogic instance should be created.\n // \n /**************************************************************************************/\n void Weblogic_Process_Good_Params_NodeManager()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n \n inst->AddParameter(\"/opt/weblogic/jrockit_160_14_R27.6.5-32/jre/bin/java\");\n inst->AddParameter(\"-Dweblogic.Name=Managed1\");\n inst->AddParameter(\"-Djava.security.policy=/opt/weblogic/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Dweblogic.management.server=http://[2001:4898:e0:3207:226:55ff:feb7:b42b]:7001\");\n inst->AddParameter(\"-Djava.library.path=\\\"/opt/weblogic/jrockit_160_14_R27.6.5-32/jre/lib/i386/jrockit\\\"\" );\n inst->AddParameter(\"-Djava.class.path=/opt/weblogic/patch_wls1032/profiles/default/sys_manifest_classpath/weblogic_patch.jar\"); \n inst->AddParameter(\"-Dweblogic.system.BootIdentityFile=/opt/weblogic/user_projects/domains/base_domain/servers/Managed1/data/nodemanager/boot.properties\"); \n inst->AddParameter(\"-Dweblogic.nodemanager.ServiceEnabled=true\"); \n inst->AddParameter(\"-Dweblogic.security.SSL.ignoreHostnameVerification=false\"); \n inst->AddParameter(\"-Dweblogic.ReverseDNSAllowed=false\"); \n inst->AddParameter(\"weblogic.Server\");\n \n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/opt/weblogic\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"Weblogic\" == (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that a valid instance of WebLogic is discovered, this perticular\n // instance is started using the command line scripts.\n // A valid Weblogic instance should be created.\n // \n /**************************************************************************************/\n void Weblogic_Process_Good_Params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/jdk1.6.0_24/bin/java\");\n inst->AddParameter(\"-client\");\n inst->AddParameter(\"-Xms256m\");\n inst->AddParameter(\"-Xmx512m\");\n inst->AddParameter(\"-XX:CompileThreshold=8000\");\n inst->AddParameter(\"-XX:PermSize=48m\");\n inst->AddParameter(\"-XX:MaxPermSize=128m\");\n inst->AddParameter(\"-Dweblogic.Name=AdminServer\");\n inst->AddParameter(\"-Djava.security.policy=/opt/Oracle/Middleware/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Xverify:none\");\n inst->AddParameter(\"-da\");\n inst->AddParameter(\"-Dplatform.home=/opt/Oracle/Middleware/wlserver_10.3\");\n inst->AddParameter(\"-Dwls.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.management.discover=true\");\n inst->AddParameter(\"-Dwlw.iterativeDev=\");\n inst->AddParameter(\"-Dwlw.testConsole=\");\n inst->AddParameter(\"-Dwlw.logErrorsToConsole=\");\n inst->AddParameter(\"-Dweblogic.ext.dirs=/opt/Oracle/Middleware/patch_wls1032/profiles/default/sysext_manifest_classpath\");\n inst->AddParameter(\"weblogic.Server\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/opt/Oracle/Middleware\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"Weblogic\" == (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n\t/**************************************************************************************/\n //\n // Verify that a valid instance of WebLogic 12.1.3 is discovered, this perticular\n // instance is started using the command line scripts.\n // A valid Weblogic instance should be created.\n\t// \n\t// WebLogic 12.1.2 and 12.1.3 remove the following command line parameters\n\t// -Dbea.home, -Dplatform.home, and -Dweblogic.system.BootIdentityFile\n\t// This test makes sure that using -Dweblogic.home is sufficient\n // \n /**************************************************************************************/\n void Weblogic_12cR1_Process_Good_Params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/bin/java\");\n inst->AddParameter(\"-Xms512m\");\n inst->AddParameter(\"-Xmx512m\");\n inst->AddParameter(\"-Dweblogic.Name=myserver\");\n inst->AddParameter(\"-Djava.security.policy=/root/WebLogic/wls12120/wlserver/server/lib/weblogic.policy\");\n inst->AddParameter(\"/usr/lib/jvm/java-7-openjdk-amd64/jre/lib/endorsed:/root/WebLogic/wls12120/wlserver/../oracle_common/modules/endorsed\");\n\t\tinst->AddParameter(\"-da\");\n inst->AddParameter(\"-Dwls.home=/root/WebLogic/wls12120/wlserver/server\");\n inst->AddParameter(\"-Dweblogic.home=/root/WebLogic/wls12120/wlserver/server\");\n inst->AddParameter(\"weblogic.Server\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Assert correct diskpath/id returned from WebLogic 12.1.3 Instance\", L\"/root/WebLogic/wls12120\", (*it)->GetId());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(\"Assert type of AppServer returned\", L\"Weblogic\", (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that no instance of WebLogic is discovered, this perticular\n // instance is started without the 'platform.home' variable set.\n // No valid Weblogic instance should be created.\n // \n /**************************************************************************************/\n void Weblogic_Process_Bad_Params()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/jdk1.6.0_24/bin/java\");\n inst->AddParameter(\"-client\");\n inst->AddParameter(\"-Xms256m\");\n inst->AddParameter(\"-Xmx512m\");\n inst->AddParameter(\"-XX:CompileThreshold=8000\");\n inst->AddParameter(\"-XX:PermSize=48m\");\n inst->AddParameter(\"-XX:MaxPermSize=128m\");\n inst->AddParameter(\"-Dweblogic.Name=AdminServer\");\n inst->AddParameter(\"-Djava.security.policy=/opt/Oracle/Middleware/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Xverify:none\");\n inst->AddParameter(\"-da\");\n // Without setting the platform.home will cause the failure\n // inst->AddParameter(\"-Dplatform.home=/opt/Oracle/Middleware/wlserver_10.3\");\n inst->AddParameter(\"-Dwls.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n // With addition for -Dweblogic.home as a supported parameter to determine installation directory we \n\t\t// need to remove this in unit test\n\t\t// inst->AddParameter(\"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.management.discover=true\");\n inst->AddParameter(\"-Dwlw.iterativeDev=\");\n inst->AddParameter(\"-Dwlw.testConsole=\");\n inst->AddParameter(\"-Dwlw.logErrorsToConsole=\");\n inst->AddParameter(\"-Dweblogic.ext.dirs=/opt/Oracle/Middleware/patch_wls1032/profiles/default/sysext_manifest_classpath\");\n inst->AddParameter(\"weblogic.Server\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that 2 valid instance of WebLogic are discovered, this perticular\n // scenario a nstance is started using the command line scripts and another\n // is started via the NodeManager.\n // 2 valid Weblogic instances should be created.\n // \n /**************************************************************************************/\n void Weblogic_Process_Good_Params_Two_Instances()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/jdk1.6.0_24/bin/java\");\n inst->AddParameter(\"-client\");\n inst->AddParameter(\"-Xms256m\");\n inst->AddParameter(\"-Xmx512m\");\n inst->AddParameter(\"-XX:CompileThreshold=8000\");\n inst->AddParameter(\"-XX:PermSize=48m\");\n inst->AddParameter(\"-XX:MaxPermSize=128m\");\n inst->AddParameter(\"-Dweblogic.Name=AdminServer\");\n inst->AddParameter(\"-Djava.security.policy=/opt/Oracle/Middleware/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Xverify:none\");\n inst->AddParameter(\"-da\");\n inst->AddParameter(\"-Dplatform.home=/opt/Oracle/Middleware/wlserver_10.3\");\n inst->AddParameter(\"-Dwls.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.management.discover=true\");\n inst->AddParameter(\"-Dwlw.iterativeDev=\");\n inst->AddParameter(\"-Dwlw.testConsole=\");\n inst->AddParameter(\"-Dwlw.logErrorsToConsole=\");\n inst->AddParameter(\"-Dweblogic.ext.dirs=/opt/Oracle/Middleware/patch_wls1032/profiles/default/sysext_manifest_classpath\");\n inst->AddParameter(\"weblogic.Server\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/weblogic/jrockit_160_14_R27.6.5-32/jre/bin/java\");\n inst->AddParameter(\"-Dweblogic.Name=Managed1\");\n inst->AddParameter(\"-Djava.security.policy=/opt/weblogic/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Dweblogic.management.server=http://[2001:4898:e0:3207:226:55ff:feb7:b42b]:7001\");\n inst->AddParameter(\"-Djava.library.path=\\\"/opt/weblogic/jrockit_160_14_R27.6.5-32/jre/lib/i386/jrockit\\\"\" );\n inst->AddParameter(\"-Djava.class.path=/opt/weblogic/patch_wls1032/profiles/default/sys_manifest_classpath/weblogic_patch.jar\"); \n inst->AddParameter(\"-Dweblogic.system.BootIdentityFile=/opt/weblogic/user_projects/domains/base_domain/servers/Managed1/data/nodemanager/boot.properties\"); \n inst->AddParameter(\"-Dweblogic.nodemanager.ServiceEnabled=true\"); \n inst->AddParameter(\"-Dweblogic.security.SSL.ignoreHostnameVerification=false\"); \n inst->AddParameter(\"-Dweblogic.ReverseDNSAllowed=false\"); \n inst->AddParameter(\"weblogic.Server\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 2);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/opt/Oracle/Middleware\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"Weblogic\" == (*it)->GetType());\n \n CPPUNIT_ASSERT(L\"/opt/weblogic\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Weblogic\" == (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that 1 valid instance of WebLogic is discovered, this perticular\n // scenario two process instances are started using the command.\n // As they have the same home directory only one valid Weblogic instances should be created.\n // \n /**************************************************************************************/\n void Weblogic_Process_Good_Params_Two_Instances_One_Home()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/jdk1.6.0_24/bin/java\");\n inst->AddParameter(\"-client\");\n inst->AddParameter(\"-Xms256m\");\n inst->AddParameter(\"-Xmx512m\");\n inst->AddParameter(\"-XX:CompileThreshold=8000\");\n inst->AddParameter(\"-XX:PermSize=48m\");\n inst->AddParameter(\"-XX:MaxPermSize=128m\");\n inst->AddParameter(\"-Dweblogic.Name=AdminServer\");\n inst->AddParameter(\"-Djava.security.policy=/opt/Oracle/Middleware/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Xverify:none\");\n inst->AddParameter(\"-da\");\n inst->AddParameter(\"-Dplatform.home=/opt/Oracle/Middleware/wlserver_10.3\");\n inst->AddParameter(\"-Dwls.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.management.discover=true\");\n inst->AddParameter(\"-Dwlw.iterativeDev=\");\n inst->AddParameter(\"-Dwlw.testConsole=\");\n inst->AddParameter(\"-Dwlw.logErrorsToConsole=\");\n inst->AddParameter(\"-Dweblogic.ext.dirs=/opt/Oracle/Middleware/patch_wls1032/profiles/default/sysext_manifest_classpath\");\n inst->AddParameter(\"weblogic.Server\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/jdk1.6.0_24/bin/java\");\n inst->AddParameter(\"-client\");\n inst->AddParameter(\"-Xms256m\");\n inst->AddParameter(\"-Xmx512m\");\n inst->AddParameter(\"-XX:CompileThreshold=8000\");\n inst->AddParameter(\"-XX:PermSize=48m\");\n inst->AddParameter(\"-XX:MaxPermSize=128m\");\n inst->AddParameter(\"-Dweblogic.Name=ManagedServer\");\n inst->AddParameter(\"-Djava.security.policy=/opt/Oracle/Middleware/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Xverify:none\");\n inst->AddParameter(\"-da\");\n inst->AddParameter(\"-Dplatform.home=/opt/Oracle/Middleware/wlserver_10.3\");\n inst->AddParameter(\"-Dwls.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.management.discover=true\");\n inst->AddParameter(\"-Dwlw.iterativeDev=\");\n inst->AddParameter(\"-Dwlw.testConsole=\");\n inst->AddParameter(\"-Dwlw.logErrorsToConsole=\");\n inst->AddParameter(\"-Dweblogic.ext.dirs=/opt/Oracle/Middleware/patch_wls1032/profiles/default/sysext_manifest_classpath\");\n inst->AddParameter(\"weblogic.Server\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/opt/Oracle/Middleware\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"Weblogic\" == (*it)->GetType());\n \n asEnum.CleanUp();\n }\n\n /**************************************************************************************/\n //\n // Verify that correct number of enumerations is being calculated with WebSphere V8\n // using Customer Log to populate data \n // \n /**************************************************************************************/\n void WebSphere_Process_Fixing_Incorrect_Enumerations()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst1;\n \n inst1 = pal->CreateProcessInstance(1234, \"1234\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/java/bin/java\");\n inst1->AddParameter(\"-Declipse.security\");\n inst1->AddParameter(\"-Dwas.status.socket=36244\");\n inst1->AddParameter(\"-Dosgi.install.area=/usr/WebSphere/WAS8/AppServer\");\n inst1->AddParameter(\"-Dosgi.configuration.area=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/servers/StatementService_lsys401c/configuration\");\n inst1->AddParameter(\"-Djava.awt.headless=true\");\n inst1->AddParameter(\"-Dosgi.framework.extensions=com.ibm.cds,com.ibm.ws.eclipse.adaptors\");\n inst1->AddParameter(\"-Xshareclasses:name=webspherev80_%g,groupAccess,nonFatal\");\n inst1->AddParameter(\"-Dcom.ibm.xtq.processor.overrideSecureProcessing=true\");\n inst1->AddParameter(\"-Xbootclasspath/p:/usr/WebSphere/WAS8/AppServer/java/jre/lib/ibmorb.jar\");\n inst1->AddParameter(\"-classpath\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/properties:/usr/WebSphere/WAS8/AppServer/properties:/usr/WebSphere/WAS8/AppServer/lib/startup.jar:/usr/WebSphere/WAS8/AppServer/lib/bootstrap.jar:/usr/WebSphere/WAS8/AppServer/lib/jsf-nls.jar:/usr/WebSphere/WAS8/AppServer/lib/lmproxy.jar:/usr/WebSphere/WAS8/AppServer/lib/urlprotocols.jar:/usr/WebSphere/WAS8/AppServer/deploytool/itp/batchboot.jar:/usr/WebSphere/WAS8/AppServer/deploytool/itp/batch2.jar:/usr/WebSphere/WAS8/AppServer/java/lib/tools.jar\");\n inst1->AddParameter(\"-Dibm.websphere.internalClassAccessMode=allow\");\n inst1->AddParameter(\"-Xms64m\");\n inst1->AddParameter(\"-Xmx128m\");\n inst1->AddParameter(\"-Xcompressedrefs\");\n inst1->AddParameter(\"-Xscmaxaot4M\");\n inst1->AddParameter(\"-Xscmx90M\");\n inst1->AddParameter(\"-Dws.ext.dirs=/usr/WebSphere/WAS8/AppServer/java/lib:/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/classes:/usr/WebSphere/WAS8/AppServer/classes:/usr/WebSphere/WAS8/AppServer/lib:/usr/WebSphere/WAS8/AppServer/installedChannels:/usr/WebSphere/WAS8/AppServer/lib/ext:/usr/WebSphere/WAS8/AppServer/web/help:/usr/WebSphere/WAS8/AppServer/deploytool/itp/plugins/com.ibm.etools.ejbdeploy/runtime\");\n inst1->AddParameter(\"-Xdump:java+heap:events=user\");\n inst1->AddParameter(\"-Dderby.system.home=/usr/WebSphere/WAS8/AppServer/derby\");\n inst1->AddParameter(\"-Dcom.ibm.itp.location=/usr/WebSphere/WAS8/AppServer/bin\");\n inst1->AddParameter(\"-Djava.util.logging.configureByServer=true\");\n inst1->AddParameter(\"-Duser.install.root=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01\");\n inst1->AddParameter(\"-Djava.ext.dirs=/usr/WebSphere/WAS8/AppServer/tivoli/tam:/usr/WebSphere/WAS8/AppServer/java/jre/lib/ext\");\n inst1->AddParameter(\"-Djavax.management.builder.initial=com.ibm.ws.management.PlatformMBeanServerBuilder\");\n inst1->AddParameter(\"-Dpython.cachedir=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/temp/cachedir\");\n inst1->AddParameter(\"-Dwas.install.root=/usr/WebSphere/WAS8/AppServer\");\n inst1->AddParameter(\"-Djava.util.logging.manager=com.ibm.ws.bootstrap.WsLogManager\");\n inst1->AddParameter(\"-Dserver.root=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01\");\n inst1->AddParameter(\"-Dcom.ibm.security.jgss.debug=off\");\n inst1->AddParameter(\"-Dcom.ibm.security.krb5.Krb5Debug=off\");\n inst1->AddParameter(\"-DWAS_LOG4J=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/log4j/STATEMENTSERVICE\");\n inst1->AddParameter(\"-Xgcpolicy:gencon\");\n inst1->AddParameter(\"-Djava.library.path=/usr/WebSphere/WAS8/AppServer/lib/native/linux/x86_64/:/usr/WebSphere/WAS8/AppServer/lib/native/linux/x86_64/:/usr/WebSphere/WAS8/AppServer/java/jre/lib/amd64/compressedrefs:/usr/WebSphere/WAS8/AppServer/java/jre/lib/amd/usr/WebSphere/WAS8/AppServer/lib/native/linux/x86_64/:/usr/WebSphere/WAS8/AppServer/bin:/usr/lib:\");\n inst1->AddParameter(\"-Djava.endorsed.dirs=/usr/WebSphere/WAS8/AppServer/endorsed_apis:/usr/WebSphere/WAS8/AppServer/java/jre/lib/endorsed\");\n inst1->AddParameter(\"-Djava.security.auth.login.config=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/properties/wsjaas.conf\");\n inst1->AddParameter(\"-Djava.security.policy=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/properties/server.policy\");\n inst1->AddParameter(\"com.ibm.wsspi.bootstrap.WSPreLauncher\");\n inst1->AddParameter(\"-nosplash\");\n inst1->AddParameter(\"-application\");\n inst1->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\");\n inst1->AddParameter(\"com.ibm.ws.runtime.WsServer\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/config\");\n inst1->AddParameter(\"DEV\");\n inst1->AddParameter(\"lsys401cNode01\");\n inst1->AddParameter(\"StatementService_lsys401c\");\n \n //Second Instance of WebSphere V8 with different server\n inst1 = pal->CreateProcessInstance(1235, \"1235\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/java/bin/java\");\n inst1->AddParameter(\"-Declipse.security\");\n inst1->AddParameter(\"-Dwas.status.socket=45529\");\n inst1->AddParameter(\"-Dosgi.install.area=/usr/WebSphere/WAS8/AppServer\");\n inst1->AddParameter(\"-Dosgi.configuration.area=/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01/servers/dmgr/configuration\");\n inst1->AddParameter(\"-Djava.awt.headless=true\");\n inst1->AddParameter(\"-Dosgi.framework.extensions=com.ibm.cds,com.ibm.ws.eclipse.adaptors\");\n inst1->AddParameter(\"-Xshareclasses:name=webspherev80_%g,groupAccess,nonFatal\");\n inst1->AddParameter(\"-Xscmx50M\");\n inst1->AddParameter(\"-Dcom.ibm.xtq.processor.overrideSecureProcessing=true\");\n inst1->AddParameter(\"-Xbootclasspath/p:/usr/WebSphere/WAS8/AppServer/java/jre/lib/ibmorb.jar\");\n inst1->AddParameter(\"-classpath\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01/properties:/usr/WebSphere/WAS8/AppServer/properties:/usr/WebSphere/WAS8/AppServer/lib/startup.jar:/usr/WebSphere/WAS8/AppServer/lib/bootstrap.jar:/usr/WebSphere/WAS8/AppServer/lib/jsf-nls.jar:/usr/WebSphere/WAS8/AppServer/lib/lmproxy.jar:/usr/WebSphere/WAS8/AppServer/lib/urlprotocols.jar:/usr/WebSphere/WAS8/AppServer/deploytool/itp/batchboot.jar:/usr/WebSphere/WAS8/AppServer/deploytool/itp/batch2.jar:/usr/WebSphere/WAS8/AppServer/java/lib/tools.jar\");\n inst1->AddParameter(\"-Dibm.websphere.internalClassAccessMode=allow\");\n inst1->AddParameter(\"-Xms256m\");\n inst1->AddParameter(\"-Xmx512m\");\n inst1->AddParameter(\"-Xcompressedrefs\");\n inst1->AddParameter(\"-Dws.ext.dirs=/usr/WebSphere/WAS8/AppServer/java/lib:/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01/classes:/usr/WebSphere/WAS8/AppServer/classes:/usr/WebSphere/WAS8/AppServer/lib:/usr/WebSphere/WAS8/AppServer/installedChannels:/usr/WebSphere/WAS8/AppServer/lib/ext:/usr/WebSphere/WAS8/AppServer/web/help:/usr/WebSphere/WAS8/AppServer/deploytool/itp/plugins/com.ibm.etools.ejbdeploy/runtime\");\n inst1->AddParameter(\"-Dderby.system.home=/usr/WebSphere/WAS8/AppServer/derby\");\n inst1->AddParameter(\"-Dcom.ibm.itp.location=/usr/WebSphere/WAS8/AppServer/bin\");\n inst1->AddParameter(\"-Djava.util.logging.configureByServer=true\");\n inst1->AddParameter(\"-Duser.install.root=/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01\");\n inst1->AddParameter(\"-Djava.ext.dirs=/usr/WebSphere/WAS8/AppServer/tivoli/tam:/usr/WebSphere/WAS8/AppServer/java/jre/lib/ext\");\n inst1->AddParameter(\"-Djavax.management.builder.initial=com.ibm.ws.management.PlatformMBeanServerBuilder\");\n inst1->AddParameter(\"-Dpython.cachedir=/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01/temp/cachedir\");\n inst1->AddParameter(\"-Dwas.install.root=/usr/WebSphere/WAS8/AppServer\");\n inst1->AddParameter(\"-Djava.util.logging.manager=com.ibm.ws.bootstrap.WsLogManager\");\n inst1->AddParameter(\"-Dserver.root=/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01\");\n inst1->AddParameter(\"-Dcom.ibm.security.jgss.debug=off\");\n inst1->AddParameter(\"-Dcom.ibm.security.krb5.Krb5Debug=off\");\n inst1->AddParameter(\"-Djava.library.path=/usr/WebSphere/WAS8/AppServer/lib/native/linux/x86_64/:/usr/WebSphere/WAS8/AppServer/java/jre/lib/amd64/compressedrefs:/usr/WebSphere/WAS8/AppServer/java/jre/lib/amd64:/usr/WebSphere/WAS8/AppServer/lib/native/linux/x86_64/:/usr/WebSphere/WAS8/AppServer/bin:/usr/lib:\");\n inst1->AddParameter(\"-Djava.endorsed.dirs=/usr/WebSphere/WAS8/AppServer/endorsed_apis:/usr/WebSphere/WAS8/AppServer/java/jre/lib/endorsed\");\n inst1->AddParameter(\"-Djava.security.auth.login.config=/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01/properties/wsjaas.conf\");\n inst1->AddParameter(\"-Djava.security.policy=/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01/properties/server.policy\");\n inst1->AddParameter(\"com.ibm.wsspi.bootstrap.WSPreLauncher\");\n inst1->AddParameter(\"-nosplash\");\n inst1->AddParameter(\"-application\");\n inst1->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\");\n inst1->AddParameter(\"com.ibm.ws.runtime.WsServer\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/profiles/Dmgr01/config\");\n inst1->AddParameter(\"DEV\");\n inst1->AddParameter(\"lsys401cDmgr01\");\n inst1->AddParameter(\"dmgr\");\n \n \n //Third instance of WebSphere Server\n inst1 = pal->CreateProcessInstance(1236, \"1236\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/java/bin/java\");\n inst1->AddParameter(\"-Xmaxt0.5\");\n inst1->AddParameter(\"-Dwas.status.socket=38696\");\n inst1->AddParameter(\"-Declipse.security\");\n inst1->AddParameter(\"-Dosgi.install.area=/usr/WebSphere/WAS8/AppServer\");\n inst1->AddParameter(\"-Dosgi.configuration.area=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/servers/nodeagent/configuration\");\n inst1->AddParameter(\"-Dosgi.framework.extensions=com.ibm.cds,com.ibm.ws.eclipse.adaptors\");\n inst1->AddParameter(\"-Xshareclasses:name=webspherev80_%g,groupAccess,nonFatal\");\n inst1->AddParameter(\"-Dcom.ibm.xtq.processor.overrideSecureProcessing=true\");\n inst1->AddParameter(\"-Xbootclasspath/p:/usr/WebSphere/WAS8/AppServer/java/jre/lib/ibmorb.jar\");\n inst1->AddParameter(\"-Dorg.osgi.framework.bootdelegation=*\");\n inst1->AddParameter(\"-classpath\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/properties:/usr/WebSphere/WAS8/AppServer/properties:/usr/WebSphere/WAS8/AppServer/lib/startup.jar:/usr/WebSphere/WAS8/AppServer/lib/bootstrap.jar:/usr/WebSphere/WAS8/AppServer/lib/jsf-nls.jar:/usr/WebSphere/WAS8/AppServer/lib/lmproxy.jar:/usr/WebSphere/WAS8/AppServer/lib/urlprotocols.jar:/usr/WebSphere/WAS8/AppServer/deploytool/itp/batchboot.jar:/usr/WebSphere/WAS8/AppServer/deploytool/itp/batch2.jar:/usr/WebSphere/WAS8/AppServer/java/lib/tools.jar\");\n inst1->AddParameter(\"-Dorg.osgi.framework.bootdelegation=*\");\n inst1->AddParameter(\"-Dibm.websphere.internalClassAccessMode=allow\");\n inst1->AddParameter(\"-Xms50m\");\n inst1->AddParameter(\"-Xmx256m\");\n inst1->AddParameter(\"-Xcompressedrefs\");\n inst1->AddParameter(\"-Xscmaxaot4M\");\n inst1->AddParameter(\"-Xnoaot\");\n inst1->AddParameter(\"-Xscmx90M\");\n inst1->AddParameter(\"-Dws.ext.dirs=/usr/WebSphere/WAS8/AppServer/java/lib:/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/classes:/usr/WebSphere/WAS8/AppServer/classes:/usr/WebSphere/WAS8/AppServer/lib:/usr/WebSphere/WAS8/AppServer/installedChannels:/usr/WebSphere/WAS8/AppServer/lib/ext:/usr/WebSphere/WAS8/AppServer/web/help:/usr/WebSphere/WAS8/AppServer/deploytool/itp/plugins/com.ibm.etools.ejbdeploy/runtime\");\n inst1->AddParameter(\"-Dderby.system.home=/usr/WebSphere/WAS8/AppServer/derby\");\n inst1->AddParameter(\"-Dcom.ibm.itp.location=/usr/WebSphere/WAS8/AppServer/bin\");\n inst1->AddParameter(\"-Djava.util.logging.configureByServer=true\");\n inst1->AddParameter(\"-Duser.install.root=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01\");\n inst1->AddParameter(\"-Djava.ext.dirs=/usr/WebSphere/WAS8/AppServer/tivoli/tam:/usr/WebSphere/WAS8/AppServer/java/jre/lib/ext\");\n inst1->AddParameter(\"-Djavax.management.builder.initial=com.ibm.ws.management.PlatformMBeanServerBuilder\");\n inst1->AddParameter(\"-Dpython.cachedir=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/temp/cachedir\");\n inst1->AddParameter(\"-Dwas.install.root=/usr/WebSphere/WAS8/AppServer\");\n inst1->AddParameter(\"-Djava.util.logging.manager=com.ibm.ws.bootstrap.WsLogManager\");\n inst1->AddParameter(\"-Dserver.root=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01\");\n inst1->AddParameter(\"-Dcom.ibm.security.jgss.debug=off\");\n inst1->AddParameter(\"-Dcom.ibm.security.krb5.Krb5Debug=off\");\n inst1->AddParameter(\"-Djava.awt.headless=true\");\n inst1->AddParameter(\"-Djava.library.path=/usr/WebSphere/WAS8/AppServer/lib/native/linux/x86_64/:/usr/WebSphere/WAS8/AppServer/java/jre/lib/amd64/compressedrefs:/usr/WebSphere/WAS8/AppServer/java/jre/lib/amd64:/usr/WebSphere/WAS8/AppServer/lib/native/linux/x86_64/:/usr/WebSphere/WAS8/AppServer/bin:/usr/lib:\");\n inst1->AddParameter(\"-Djava.endorsed.dirs=/usr/WebSphere/WAS8/AppServer/endorsed_apis:/usr/WebSphere/WAS8/AppServer/java/jre/lib/endorsed\");\n inst1->AddParameter(\"-Djava.security.auth.login.config=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/properties/wsjaas.conf\");\n inst1->AddParameter(\"-Djava.security.policy=/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/properties/server.policy\");\n inst1->AddParameter(\"com.ibm.wsspi.bootstrap.WSPreLauncher\");\n inst1->AddParameter(\"-nosplash\");\n inst1->AddParameter(\"-application\");\n inst1->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\");\n inst1->AddParameter(\"com.ibm.ws.runtime.WsServer\");\n inst1->AddParameter(\"/usr/WebSphere/WAS8/AppServer/profiles/AppSrv01/config\");\n inst1->AddParameter(\"DEV\");\n inst1->AddParameter(\"lsys401cNode01\");\n inst1->AddParameter(\"nodeagent\");\n \n asEnum.Update(false);\n //We have 3 different WebSphere enumerations\n CPPUNIT_ASSERT_EQUAL(static_cast<size_t>(3),asEnum.Size());\n\n asEnum.CleanUp();\n }\n\n\n /**************************************************************************************/\n //\n // Verify that the mocked out implementation of the ProcessInstance\n // with the correct parameters works correctly. \n // Two valid Tomcat instance , two valid JBoss. two valid Weblogic \n // instances and two valid WebSphere instances should be created. \n // There is one invalid Tomcat, JBoss, Weblogic and WebSphere entry that should be ignored.\n // This specific test is for a combination of both JBoss, Tomcat, Weblogic and WebSphere.\n // \n /**************************************************************************************/\n void Weblogic_WebSphere_JBoss_Tomcat_Process_MixedGoodBad()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dserver.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n inst->AddParameter(\"Server1\"); \n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.30/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"-classpath=/jboss-6.3/bin/run.jar\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal1\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/jdk1.6.0_24/bin/java\");\n inst->AddParameter(\"-Dweblogic.Name=AdminServer\");\n inst->AddParameter(\"-Djava.security.policy=/opt/Oracle/Middleware/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Dplatform.home=/opt/Oracle/Middleware/wlserver_10.3\");\n inst->AddParameter(\"-Dwls.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"weblogic.Server\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dserver.root=/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.31/\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.31/\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n\n inst = pal->CreateProcessInstance(1235, \"1235\");\n inst->AddParameter(\"org.jboss.Main\"); \n inst->AddParameter(\"-Djboss.service.binding.set=ports-02\");\n inst->AddParameter(\"-c minimal2\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/jdk1.6.0_24/bin/java\");\n inst->AddParameter(\"-Dweblogic.Name=AdminServer\");\n inst->AddParameter(\"-Djava.security.policy=/opt/Oracle/Middleware/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Dwls.home=/opt/Oracle1/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"weblogic.Server\");\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"-Dserver.root=/opt/IBM1/WebSphere/AppServer/profiles/AppSrv01\"); \n inst->AddParameter(\"com.ibm.ws.bootstrap.WSLauncher\"); \n inst->AddParameter(\"com.ibm.ws.runtime.WsServer\"); \n inst->AddParameter(\"/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/config\"); \n inst->AddParameter(\"scxjet-rhel5-04Node01Cell\"); \n inst->AddParameter(\"Node01\"); \n inst->AddParameter(\"Server3\"); \n\n\n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/opt/jdk1.6.0_24/bin/java\");\n inst->AddParameter(\"-Dweblogic.Name=AdminServer\");\n inst->AddParameter(\"-Djava.security.policy=/opt/Oracle/Middleware/wlserver_10.3/server/lib/weblogic.policy\");\n inst->AddParameter(\"-Dweblogic.system.BootIdentityFile=/opt/Oracle2/user_projects/domains/base_domain/servers/Managed1/data/nodemanager/boot.properties\"); \n inst->AddParameter(\"-Dwls.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n\t\t// Remove the -Dweblogic.home to complete bad process\n // inst->AddParameter(\"-Dweblogic.home=/opt/Oracle/Middleware/wlserver_10.3/server\");\n inst->AddParameter(\"weblogic.Server\");\n\n asEnum.Update(false);\n\n CPPUNIT_ASSERT(asEnum.Size() == 8);\n \n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >::iterator it = asEnum.Begin();\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal/\" == (*it)->GetId());\n CPPUNIT_ASSERT(L\"JBoss\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"/jboss-6.3/server/minimal1/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"JBoss\" == (*it)->GetType());\n \n CPPUNIT_ASSERT(L\"AppSrv01-scxjet-rhel5-04Node01Cell-Node01-Server1\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"WebSphere\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"AppSrv01-scxjet-rhel5-04Node01Cell-Node01-Server3\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"WebSphere\" == (*it)->GetType());\n \n CPPUNIT_ASSERT(L\"/opt/Oracle/Middleware\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Weblogic\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"/opt/Oracle2\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Weblogic\" == (*it)->GetType());\n \n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.29/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n CPPUNIT_ASSERT(L\"/opt/apache-tomcat-5.5.31/\" == (*(++it))->GetId());\n CPPUNIT_ASSERT(L\"Tomcat\" == (*it)->GetType());\n\n asEnum.CleanUp();\n }\n\n /*************************************************************/\n //\n // Verification of Bug Fix #51490\n //\n // UpdateInstances should not be called when Update() is called.\n // \n /*************************************************************/\n void UpdateInstances_Is_Not_Called()\n {\n SCXCoreLib::SCXHandle<MockAppServerPALDependencies> pal = SCXCoreLib::SCXHandle<MockAppServerPALDependencies>(new MockAppServerPALDependencies());\n TestSpyAppServerEnumeration asEnum(pal);\n\n CPPUNIT_ASSERT(asEnum.Size() == 0);\n CPPUNIT_ASSERT(asEnum.GetNumberOfCallsToUpdateInstances()== 0);\n\n SCXCoreLib::SCXHandle<MockProcessInstance> inst;\n \n inst = pal->CreateProcessInstance(1234, \"1234\");\n inst->AddParameter(\"/usr/java/jre1.6.0_10//bin/java\");\n inst->AddParameter(\"-Djava.util.logging.config.file=/opt/apache-tomcat-5.5.29//conf/logging.properties\");\n inst->AddParameter(\"-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager\");\n inst->AddParameter(\"-Djava.endorsed.dirs=/opt/apache-tomcat-5.5.29//common/endorsed\");\n inst->AddParameter(\"-classpath\");\n inst->AddParameter(\"/opt/apache-tomcat-5.5.29//bin/bootstrap.jar\");\n inst->AddParameter(\"-Dcatalina.base=/opt/apache-tomcat-5.5.29/profile1\");\n inst->AddParameter(\"-Dcatalina.home=/opt/apache-tomcat-5.5.29/\");\n inst->AddParameter(\"-Djava.io.tmpdir=/opt/apache-tomcat-5.5.29//temp\");\n inst->AddParameter(\"org.apache.catalina.startup.Bootstrap\");\n inst->AddParameter(\"start\");\n\n CPPUNIT_ASSERT(asEnum.GetNumberOfCallsToUpdateInstances()== 0);\n\n asEnum.Update(true);\n\n CPPUNIT_ASSERT(asEnum.Size() == 1);\n CPPUNIT_ASSERT(asEnum.GetNumberOfCallsToUpdateInstances()== 0);\n\n asEnum.CleanUp();\n }\n\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( AppServerEnumeration_Test );\n" }, { "alpha_fraction": 0.611501157283783, "alphanum_fraction": 0.613772451877594, "avg_line_length": 29.363636016845703, "blob_id": "dff3e794dfee067d3bf19fcbf4c7bc812ecab071", "content_id": "f60db36147c2e99891e7ba5fe0d6ab7eb4cf3d03", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9686, "license_type": "permissive", "max_line_length": 137, "num_lines": 319, "path": "/source/code/providers/SCX_ProcessorStatisticalInformation_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_ProcessorStatisticalInformation_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n\n \\date 03-22-2013 17:48:44\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_ProcessorStatisticalInformation_Class_Provider.h\"\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/stringaid.h>\n#include <scxsystemlib/cpuenumeration.h>\n\n#include \"support/startuplog.h\"\n#include \"support/scxcimutils.h\"\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nnamespace\n{\n class CPUProvider\n {\n public:\n virtual ~CPUProvider() { };\n void Load()\n {\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.cpuprovider\");\n SCXCore::LogStartup();\n SCX_LOGTRACE(m_log, L\"CPUProvider::Load()\");\n\n m_cpusEnum = new CPUEnumeration();\n m_cpusEnum->Init();\n }\n }\n\n void Unload()\n {\n SCX_LOGTRACE(m_log, L\"CPUProvider::Unload()\");\n if (0 == --ms_loadCount)\n {\n if (m_cpusEnum != NULL)\n {\n m_cpusEnum->CleanUp();\n m_cpusEnum == NULL;\n }\n }\n }\n\n SCXCoreLib::SCXHandle<SCXSystemLib::CPUEnumeration> GetEnumCPUs() const\n {\n return m_cpusEnum;\n }\n\n SCXLogHandle& GetLogHandle() { return m_log; }\n\n private:\n //! PAL implementation retrieving CPU information for local host\n SCXCoreLib::SCXHandle<SCXSystemLib::CPUEnumeration> m_cpusEnum;\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n };\n CPUProvider g_CPUProvider;\n int CPUProvider::ms_loadCount = 0;\n\n}\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(\n Context& context,\n SCX_ProcessorStatisticalInformation_Class& inst,\n bool keysOnly,\n SCXHandle<SCXSystemLib::CPUInstance> cpuinst)\n{\n // Populate the key values\n std::wstring name = cpuinst->GetProcName();\n inst.Name_value(StrToMultibyte(name).c_str());\n\n if (!keysOnly)\n {\n inst.Caption_value(\"Processor information\");\n inst.Description_value(\"CPU usage statistics\");\n\n scxulong data;\n\n inst.IsAggregate_value(cpuinst->IsTotal());\n\n if (cpuinst->GetProcessorTime(data))\n {\n inst.PercentProcessorTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetIdleTime(data))\n {\n inst.PercentIdleTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetUserTime(data))\n {\n inst.PercentUserTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetNiceTime(data))\n {\n inst.PercentNiceTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetPrivilegedTime(data))\n {\n inst.PercentPrivilegedTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetIowaitTime(data))\n {\n inst.PercentIOWaitTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetInterruptTime(data))\n {\n inst.PercentInterruptTime_value(static_cast<unsigned char> (data));\n }\n\n if (cpuinst->GetDpcTime(data))\n {\n inst.PercentDPCTime_value(static_cast<unsigned char> (data));\n }\n }\n context.Post(inst);\n}\n\nSCX_ProcessorStatisticalInformation_Class_Provider::SCX_ProcessorStatisticalInformation_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_ProcessorStatisticalInformation_Class_Provider::~SCX_ProcessorStatisticalInformation_Class_Provider()\n{\n}\n\nvoid SCX_ProcessorStatisticalInformation_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for CPUProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::CPUProvider::Lock\"));\n g_CPUProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(g_CPUProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_ProcessorStatisticalInformation_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_ProcessorStatisticalInformation_Class_Provider::Load\", g_CPUProvider.GetLogHandle() );\n}\n\nvoid SCX_ProcessorStatisticalInformation_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for CPUProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"CPUProvider::Lock\"));\n g_CPUProvider.Unload();\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_ProcessorStatisticalInformation_Class_Provider:::Unload\", g_CPUProvider.GetLogHandle() );\n}\n\nvoid SCX_ProcessorStatisticalInformation_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = g_CPUProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"ProcessorStat EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for CPUProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"CPUProvider::Lock\"));\n\n // Prepare ProcessorStatisticalInformation Enumeration\n // (Note: Only do full update if we're not enumerating keys)\n SCXHandle<SCXSystemLib::CPUEnumeration> cpuEnum = g_CPUProvider.GetEnumCPUs();\n cpuEnum->Update(!keysOnly);\n\n for(size_t i = 0; i < cpuEnum->Size(); i++)\n {\n SCX_ProcessorStatisticalInformation_Class inst;\n SCXHandle<SCXSystemLib::CPUInstance> cpuInst = cpuEnum->GetInstance(i);\n EnumerateOneInstance(context, inst, keysOnly, cpuInst);\n }\n\n // Enumerate Total instance\n SCXHandle<SCXSystemLib::CPUInstance> totalInst = cpuEnum->GetTotalInstance();\n if (totalInst != NULL)\n {\n // There will always be one total instance\n SCX_ProcessorStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, keysOnly, totalInst);\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_ProcessorStatisticalInformation_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"ProcessorStat EnumerateInstances end\");\n}\n\nvoid SCX_ProcessorStatisticalInformation_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_ProcessorStatisticalInformation_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for CPUProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"CPUProvider::Lock\"));\n\n SCXHandle<SCXSystemLib::CPUEnumeration> cpuEnum = g_CPUProvider.GetEnumCPUs();\n cpuEnum->Update(true);\n\n const std::string name = instanceName.Name_value().Str();\n\n if (name.size() == 0)\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n bool instFound = false;\n SCXHandle<SCXSystemLib::CPUInstance> cpuInst;\n for(size_t i=0; i<cpuEnum->Size(); i++)\n {\n cpuInst = cpuEnum->GetInstance(i);\n // Compare key values of input args and the current instance\n if (cpuInst->GetProcName() == StrFromUTF8(name))\n {\n // Match\n instFound = true;\n break;\n }\n }\n\n if (instFound == false)\n {\n // As last resort, check if we the request is for the _Total instance\n if (cpuEnum->GetTotalInstance() != NULL)\n {\n cpuInst = cpuEnum->GetTotalInstance();\n if (cpuInst->GetProcName() == StrFromUTF8(name))\n {\n instFound = true;\n }\n }\n\n if (instFound == false)\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n }\n\n SCX_ProcessorStatisticalInformation_Class inst;\n EnumerateOneInstance(context, inst, false, cpuInst);\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_ProcessorStatisticalInformation_Class_Provider::GetInstance\",\n g_CPUProvider.GetLogHandle() );\n}\n\nvoid SCX_ProcessorStatisticalInformation_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_ProcessorStatisticalInformation_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_ProcessorStatisticalInformation_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_ProcessorStatisticalInformation_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_ProcessorStatisticalInformation_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_ProcessorStatisticalInformation_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.5941693782806396, "alphanum_fraction": 0.5962517261505127, "avg_line_length": 29.864286422729492, "blob_id": "c5da2dea87ef7d4282f0c189e2e05ed177fd1825", "content_id": "79bc8aad61c3c93961e5d168725612d863329bd1", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4322, "license_type": "permissive", "max_line_length": 127, "num_lines": 140, "path": "/source/code/shared/tools/scx_admin/cmdparser.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief scx admin config API for SCX.\n\n \\date 8/27/2008\n\n*/\n#ifndef _CMD_PARSER_H\n#define _CMD_PARSER_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n\n#include <iostream>\n#include <vector>\n#include <string>\n#include \"admin_api.h\"\n\n/// helper define that returns number of elements in static array\n#define DIM(x) (static_cast<int>(sizeof(x)/sizeof((x)[0])))\n\n\nnamespace SCX_Admin {\n\n/*----------------------------------------------------------------------------*/\n/**\n struct to store output result from \"parse\" function\n that's the direct translation from one command line command\n with all required options set (including default values)\n \n*/ \nstruct Operation {\n //! operation type\n enum enumOperationType {\n eOpType_Unknown,\n eOpType_GlobalOption_Quiet,\n eOpType_Global_Usage,\n \n#if !defined(SCX_STACK_ONLY)\n eOpType_Config_List,\n eOpType_Config_Set,\n eOpType_Config_Reset,\n#endif \n eOpType_Log_List,\n eOpType_Log_Rotate,\n eOpType_Log_Reset,\n eOpType_Log_Set,\n eOpType_Log_Prov_Reset,\n eOpType_Log_Prov_Set,\n eOpType_Log_Prov_Remove,\n\n eOpType_Show_Version,\n\n eOpType_Svc_Start,\n eOpType_Svc_Stop,\n eOpType_Svc_Restart,\n eOpType_Svc_Status\n };\n\n //! scope\n enum enumComponentType {\n eCompType_Unknown,\n eCompType_Default, // not set explicitly\n eCompType_All,\n eCompType_CIMom,\n eCompType_Provider\n };\n\n //! default ctor\n Operation() : m_eType(eOpType_Unknown), m_eComponent(eCompType_Unknown), m_eLogLevel(SCX_AdminLogAPI::eLogLevel_Verbose) {}\n \n // data\n enumOperationType m_eType; ///< operation type\n enumComponentType m_eComponent; ///< operation scope\n // name/value pair or just name\n std::wstring m_strName; ///< name in \"name/value\" pair (optional)\n std::wstring m_strValue; ///< value in \"name/value\" pair (optional)\n SCX_AdminLogAPI::LogLevelEnum m_eLogLevel; ///< required log level (optional)\n \n};\n\n/*----------------------------------------------------------------------------*/\n/**\n helper class to encode information about one command line argument\n \n*/ \nclass Argument {\npublic:\n /// command line argument type \n enum enumArgType { eString, eComponent, eLogLevel, ePair, eName };\n\n /**\n default ctor\n \\param[in] eType type of argument\n \\param[in] bOptional flag if argument is optional\n \\param[in] str string value of argument (for string type)\n \n */ \n Argument( enumArgType eType, bool bOptional, std::wstring str = std::wstring() ) : \n m_eType(eType), m_bOptional(bOptional), m_strString(str) {}\n\n bool DoesMatch( std::wstring str, int& pos, Operation& op );\n static Operation::enumComponentType Str2Component( std::wstring str );\n \n \n enumArgType m_eType; ///< type of argument\n bool m_bOptional; ///< flag if givne parameter is optional\n std::wstring m_strString; ///< exact string value, like \"-log-list\"; for \"string\" type only\n};\n\n\n/*----------------------------------------------------------------------------*/\n/**\n helper class to store information about one command line command.\n it usually consists of several arguments, some of them may be optional\n \n*/ \nclass Command {\npublic:\n /// ctor to create a new command with given arguments\n Command( const std::vector< Argument >& aArguments, Operation::enumOperationType eOperationType ):\n m_aArguments(aArguments), m_eOperationType(eOperationType) {}\n\n bool DoesMatch( int argc, const char *argv[], int& pos, Operation& op );\n bool HasMandatoryAfter( unsigned int pos ) const;\n\n std::vector< Argument > m_aArguments; ///< arguments\n Operation::enumOperationType m_eOperationType; ///< resulting operation type\n};\n\n\nbool ParseAllParameters( int argc, const char *argv[], std::vector< Operation >& operations, std::wstring& error_msg );\n\n\n}\n#endif /* _ADMIN_API_H */\n\n" }, { "alpha_fraction": 0.532420814037323, "alphanum_fraction": 0.5388620495796204, "avg_line_length": 33.82242965698242, "blob_id": "1eb6fcad727c38a72957ca5f30cc479299019338", "content_id": "04395a59adbf69276a939f0e610f139ad353e3e0", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 18630, "license_type": "permissive", "max_line_length": 141, "num_lines": 535, "path": "/source/code/shared/tools/scx_ssl_config/scx_ssl_config.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief openSSL configuration tool for SCX install tasks.\n\n \\date 1-30-2008\n\n*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxnameresolver.h>\n#include <scxcorelib/scxdefaultlogpolicyfactory.h> // Using the default log policy.\n\n#include \"scxsslcert.h\"\n\n#include <errno.h>\n#include <iostream>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <unistd.h>\n#include <pwd.h>\n\nusing std::wcerr;\nusing std::cout;\nusing std::wcout;\nusing std::endl;\nusing std::string;\nusing std::wstring;\nusing SCXCoreLib::SCXFilePath;\n\nstatic void usage(const char * name, int exitValue);\nstatic int DoGenerate(const wstring & targetPath, int startDays, int endDays,\n const wstring & hostname, const wstring & domainname, int bits, bool bDebug = false, bool clientCert = false);\nint UpdateKeyOwnership(SCXFilePath keyPath);\nconst int ERROR_CERT_GENERATE = 3;\n\n\n/*----------------------------------------------------------------------------*/\n/**\n main function.\n\n \\param argc size of \\a argv[]\n \\param argv array of string pointers from the command line.\n \\returns 0 on success, otherwise, 1 on error.\n\n Usage: scxgencert [-d domain] [-h hostname] [-g targetpath] [-e days] [-s days]\n \\n -v toggle the debug flag.\n \\n -? print the help message and exit.\n \\n -g targetpath target path where certificates should be written\n \\n -s days days to offset valid start date with\n \\n -e days days to offset valid end date with\n \\n -d domain domain name\n \\n -h host hostname\n \\n -b bits number of key bits (defaults to 2048)\n\n Result Code\n \\n -1 an exception has occured\n \\n 0 success\n \\n >1 an error occured while executing the command.\n\n*/\nint main(int argc, char *argv[])\n{\n // commandline switches\n const string helpFlag (\"-?\");\n const string bitsFlag (\"-b\");\n const string domainFlag (\"-d\");\n const string enddaysFlag (\"-e\");\n const string forceFlag (\"-f\");\n const string generateFlag (\"-g\");\n const string hostFlag (\"-h\");\n const string startdaysFlag (\"-s\");\n const string debugFlag (\"-v\");\n const string clientcertFlag (\"-c\");\n const string testFlag (\"-t\"); // Undocummented, for testing only\n\n // Control variables built from command line arguments (defaulted as needed by SCX)\n bool debugMode = false;\n bool testMode = false;\n bool doGenerateCert = false;\n wstring targetPath = L\"/etc/opt/omi/ssl\";\n int startDays = -365;\n int endDays = 7300;\n bool clientCert = false;\n#if defined(hpux) && defined(hppa)\n int bits = 1024;\n#else\n int bits = 2048;\n#endif\n\n SCXCoreLib::NameResolver mi;\n wstring hostname;\n wstring domainname;\n\n wstring specified_hostname;\n wstring specified_domainname;\n\n int i = 1;\n for (; i < argc; ++i)\n {\n if (debugFlag == argv[i])\n {\n debugMode = ! debugMode;\n wcout << L\"Setting debugMode=\" << (debugMode ? L\"true\" :L\"false\") << endl;\n }\n else if (helpFlag == argv[i])\n {\n usage(argv[0], 0);\n }\n else if (forceFlag == argv[i])\n {\n doGenerateCert = true;\n }\n else if(bitsFlag == argv[i])\n {\n if (++i >= argc)\n {\n wcout << L\"Enter number of bits.\" << endl;\n usage(argv[0], 1);\n }\n bits = (int) SCXCoreLib::StrToLong(SCXCoreLib::StrFromUTF8(argv[i]));\n if (0 == bits || 0 != bits%512)\n {\n wcout << L\"Bits must be non-zero dividable by 512.\" << endl;\n usage(argv[0], 1);\n }\n }\n else if(domainFlag == argv[i])\n {\n if (++i >= argc)\n {\n wcout << L\"Enter a domain name.\" << endl;\n usage(argv[0], 1);\n }\n\n // Some platforms fail to convert if locale is not right (SLES 11 for instance).\n // Note we do not print domain name because wcout will also fail to\n // properly convert, displaying a mangled string and further confusing\n // the user. Using cout is not an option because it will not print a\n // non-convertible string at all....\n try\n {\n specified_domainname = SCXCoreLib::StrFromMultibyte(argv[i], true);\n }\n catch(const SCXCoreLib::SCXStringConversionException &ex)\n {\n wcout << L\"Not able to convert domain name. Consider adjusting your locale setting. Exiting.\" << endl;\n exit(3);\n }\n }\n else if(hostFlag == argv[i])\n {\n if (++i >= argc)\n {\n wcout << \"Enter a hostname.\" << endl;\n usage(argv[0], 1);\n }\n\n // Host name is expected to be 7 bit so conversion is in most cases a no-op\n // If it fails prompt user and quit\n try\n {\n specified_hostname = SCXCoreLib::StrFromMultibyte(argv[i], true);\n }\n catch(const SCXCoreLib::SCXStringConversionException &e)\n {\n wcout << L\"Not able to convert host name, \\'\" << argv[i] << \"\\'.\" << endl;\n wcout << L\"Please specify a host name that uses only 7-bit ASCII characters.\" << endl;\n exit(4);\n }\n }\n else if (generateFlag == argv[i])\n {\n // Ensure the path argument exists.\n if (++i >= argc)\n {\n wcout << \"Enter a target path to generate certificates.\" << endl;\n usage(argv[0], 1);\n }\n\n try\n {\n targetPath = SCXCoreLib::StrFromMultibyte(argv[i], true);\n }\n catch(SCXCoreLib::SCXStringConversionException)\n {\n wcout << L\"Not able to convert target path, \\'\" << argv[i] << \"\\'.\" << endl;\n wcout << L\"Consider adjusting your locale by changing the LC_CTYPE environment variable.\" << endl;\n exit(4);\n }\n }\n else if (startdaysFlag == argv[i])\n {\n // Ensure the value argument exists.\n if (++i >= argc)\n {\n wcout << \"Enter a value for start days.\" << endl;\n usage(argv[0], 1);\n }\n startDays = (int) SCXCoreLib::StrToLong(SCXCoreLib::StrFromUTF8(argv[i]));\n }\n else if (enddaysFlag == argv[i])\n {\n // Ensure the value argument exists.\n if (++i >= argc || SCXCoreLib::StrToLong(SCXCoreLib::StrFromUTF8(argv[i])) == 0)\n {\n wcout << \"Enter a non-zero value for end days.\" << endl;\n usage(argv[0], 1);\n }\n endDays = (int) SCXCoreLib::StrToLong(SCXCoreLib::StrFromUTF8(argv[i]));\n }\n else if (clientcertFlag == argv[i])\n {\n \tclientCert = true;\n }\n else if (testFlag == argv[i])\n {\n testMode = true;\n }\n else\n {\n break;\n }\n }\n\n // Fail if all arguments are not used.\n if (i < argc) {\n wcout << L\"Unused arguments:\" << endl;\n for (; i < argc; ++i)\n {\n wcout << L\"\\t\" << argv[i] << endl;\n }\n wcout << endl;\n usage(argv[0], 1);\n }\n\n hostname = specified_hostname;\n domainname = specified_domainname;\n\n if(hostname.empty())\n {\n std::string hostname_raw = \"\";\n try\n {\n // This can fail because there are string conversions done in GetHostname()\n hostname = mi.GetHostname(&hostname_raw);\n }\n catch(SCXCoreLib::SCXStringConversionException)\n {\n // Note: We should never see this because host names are s'pose to be 7 bit ASCII\n // Can get away with conversion of stdout here because we are dying, and can do it exactly once ...\n fwide(stdout, -1);\n cout << \"Unable to convert default host name \\'\" << hostname_raw << \"\\'.\" << endl;\n cout << \"This might be caused by a host name that contains UTF-8 characters that are invalid given your current locale.\" << endl;\n // MUST exit here, due to fwide() call above ... cannot call fwide() more than once w/out closing/reopening handle\n exit(3);\n }\n catch(SCXCoreLib::SCXErrnoERANGE_Exception &e)\n {\n cout << SCXCoreLib::StrToUTF8(e.Where()) << endl\n << SCXCoreLib::StrToUTF8(e.What()) << endl;\n exit(3);\n }\n }\n\n // If the user did not supply a domain name, use default.\n if(domainname.empty())\n {\n domainname = mi.GetDomainname();\n }\n\n if(debugMode)\n {\n // Show what we would have used - even if user specified specific host/domain\n wcout << L\"Generated hostname: \\\"\" << mi.GetHostname()\n << L\"\\\" (\" << mi.DumpSourceString(mi.GetHostnameSource()) << L\")\" << endl;\n wcout << L\"Generated domainname: \\\"\" << mi.GetDomainname()\n << L\"\\\" (\" << mi.DumpSourceString(mi.GetDomainnameSource()) << L\")\" << endl << endl;\n\n wcout << L\"Using Host Name: \" << hostname << endl;\n wcout << L\"Using Domain Name: \" << domainname << endl;\n wcout << L\"Start Days: \" << startDays << endl;\n wcout << L\"End Days: \" << endDays << endl;\n wcout << L\"Cert Length: \" << bits << endl;\n wcout << L\"Target Path: \" << targetPath << endl << endl;\n }\n\n // We only generate the certificate if \"-f\" was specified, or if no certificate exists\n // (Note: If no certificate exists, we should still return a success error code!)\n int rc = 0;\n if (!doGenerateCert)\n {\n SCXFilePath keyPath;\n keyPath.SetDirectory(targetPath);\n keyPath.SetFilename(L\"omikey.pem\");\n\n SCXCoreLib::SCXFileInfo keyInfo(keyPath);\n if ( ! keyInfo.Exists() )\n {\n doGenerateCert = true;\n }\n else\n {\n wcerr << L\"Certificate not generated - '\" << keyPath.Get() << \"' exists\" << endl;\n // Upgrade from 2012R2 should update the key ownership to omi:omi\n rc = UpdateKeyOwnership(keyPath);\n }\n }\n\n if (doGenerateCert)\n {\n rc = DoGenerate(targetPath, startDays, endDays, hostname, domainname, bits, debugMode, clientCert);\n\n // When the domain or host name is specified through the command line we do not allow recovery.\n // Add an exception to this rule for testing purposes.\n if ( (specified_domainname.empty() && specified_hostname.empty()) || testMode )\n {\n // When the domain or hostname is not RFC compliant, openssl fails to generate a cerificate.\n // We will try to fallback.\n if ( rc == ERROR_CERT_GENERATE )\n {\n wcout << \"Hostname or domain likely not RFC compliant, trying fallback: \\\"localhost.local\\\"\" << endl;\n rc = DoGenerate(targetPath, startDays, endDays, L\"localhost\", L\"local\", bits, debugMode);\n }\n }\n }\n\n if (debugMode)\n {\n wcout << L\"return code = \" << rc << endl;\n }\n exit(rc);\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Generate Key and Certificate\n \\param[in] targetPath Path where the certificates should be written.\n \\param[in] startDays Days to offset valid start date.\n \\param[in] endDays Days to offset valid end date.\n \\param[in] hostname Hostname to put into the certificate.\n \\param[in] domainname Domainname to put into the certificate.\n \\param[in] bits Number of bits in key.\n \\returns Zero on success.\n*/\nstatic int DoGenerate(const wstring & targetPath, int startDays, int endDays,\n const wstring & hostname, const wstring & domainname,\n int bits, bool bDebug, bool clientCert)\n{\n // Output what we'll be using for certificate generation\n wcout << L\"Generating certificate with hostname=\\\"\" << hostname << L\"\\\"\";\n if (domainname.length())\n {\n wcout << L\", domainname=\\\"\" << domainname << L\"\\\"\" ;\n }\n wcout << endl;\n\n std::wstring c_certFilename(L\"omi-host-\"); // Remainder must be generated\n const std::wstring c_keyFilename(L\"omikey.pem\");\n\n int rc = 0;\n // Do not allow an exception to slip out\n try\n {\n // The certificate filename must be something like omi-host-<hostname>.pem; generate it\n c_certFilename.append(hostname);\n c_certFilename.append(L\".pem\");\n\n SCXFilePath keyPath;\n keyPath.SetDirectory(targetPath);\n keyPath.SetFilename(c_keyFilename);\n SCXFilePath certPath;\n certPath.SetDirectory(targetPath);\n certPath.SetFilename(c_certFilename);\n SCXSSLCertificateLocalizedDomain cert(keyPath, certPath, startDays, endDays, hostname, domainname, bits, clientCert);\n\n std::ostringstream debugChatter;\n debugChatter << endl;\n\n try\n {\n cert.Generate(debugChatter);\n }\n catch(const SCXCoreLib::SCXStringConversionException &ex)\n {\n if(bDebug)\n wcout << debugChatter.str().c_str();\n\n wcerr << endl << \"Generation of certificate raised an exception\" << endl;\n wcerr << ex.Where() << endl;\n wcerr << ex.What() << endl;\n\n return 2;\n }\n catch(const SCXSSLException &e_ssl)\n {\n if(bDebug)\n {\n wcout << debugChatter.str().c_str();\n debugChatter.str(\"\");\n }\n\n wcerr << e_ssl.What() << endl;\n return ERROR_CERT_GENERATE;\n }\n catch(const SCXCoreLib::SCXFilePathNotFoundException &ex)\n {\n wcerr << endl << \"Generation of certificate raised an exception\" << endl;\n wcerr << \"Output path \\\"\" << ex.GetPath().Get() << \"\\\" does not exist\" << endl;\n return 4;\n }\n\n if(bDebug)\n {\n wcout << debugChatter.str().c_str();\n }\n\n /*\n ** We actually have three certificate files in total:\n **\n ** Certificate File: omi-host-<hostname>.pem (public)\n ** Key File: omi-key.pem (private)\n ** Soft link: omi.pem (soft link to certificate file, used by openwsman)\n **\n **\n ** Create the soft link to point to the certificate file.\n */\n\n SCXFilePath fpLinkFile;\n fpLinkFile.SetDirectory(targetPath);\n fpLinkFile.SetFilename(L\"omi.pem\");\n\n std::string sLinkFile = SCXCoreLib::StrToMultibyte(fpLinkFile.Get());\n std::string sCertFile = SCXCoreLib::StrToMultibyte(certPath.Get());\n\n rc = unlink(sLinkFile.c_str());\n if (0 != rc && ENOENT != errno) {\n throw SCXCoreLib::SCXErrnoFileException(L\"unlink\", fpLinkFile.Get(), errno, SCXSRCLOCATION);\n }\n\n rc = symlink(sCertFile.c_str(), sLinkFile.c_str());\n if (0 != rc) {\n throw SCXCoreLib::SCXErrnoFileException(L\"unlink\", fpLinkFile.Get(), errno, SCXSRCLOCATION);\n }\n\n /*\n ** Finally, make sure the permissions are right:\n ** The pub key gets 444, the priv key gets 400\n */\n\n rc = chmod(sCertFile.c_str(), 00444);\n if (0 != rc) {\n throw SCXCoreLib::SCXErrnoFileException(L\"chmod\", certPath.Get(), errno, SCXSRCLOCATION);\n }\n\n std::string sKeyFile = SCXCoreLib::StrToMultibyte(keyPath.Get());\n rc = chmod(sKeyFile.c_str(), 00400);\n if (0 != rc) {\n throw SCXCoreLib::SCXErrnoFileException(L\"chmod\", keyPath.Get(), errno, SCXSRCLOCATION);\n }\n\n rc = UpdateKeyOwnership(keyPath);\n\n }\n catch(const SCXCoreLib::SCXException & e)\n {\n wcout << e.Where() << endl\n << e.What() << endl;\n // use -1 to indicate an exception occured.\n rc = -1;\n }\n return rc;\n}\n\nint UpdateKeyOwnership(SCXFilePath keyPath)\n{\n int rc = 0;\n try\n {\n std::string keyFile = SCXCoreLib::StrToMultibyte(keyPath.Get());\n struct passwd *pwd=NULL;\n errno = 0;\n if ((pwd = getpwnam(\"omi\")) != NULL) {\n rc = chown(keyFile.c_str(),pwd->pw_uid,pwd->pw_gid);\n if (0 != rc){\n throw SCXCoreLib::SCXErrnoFileException(L\"chown\", keyPath.Get(), errno, SCXSRCLOCATION);\n }\n } \n else if(errno !=0 && errno !=ENOENT && errno !=ESRCH) {\n const char* isTestEnv = getenv(\"SCX_TESTRUN_ACTIVE\");\n if(!isTestEnv)\n throw SCXErrnoUserNameException(L\"getpwnam\", L\"omi\", errno, SCXSRCLOCATION);\n }\n }\n catch(const SCXCoreLib::SCXException & e)\n {\n wcout << e.Where() << endl\n << e.What() << endl;\n rc = -1;\n }\n return rc; \n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Output a usage message.\n\n \\param name Application name (derived from argv[0]).\n \\param exitValue Value to return after writing the usage message.\n \\return Does not return.\n*/\nstatic void usage(char const * const name, int exitValue)\n{\n wcout << L\"Usage: \" << name << L\" [-v] [-s days] [-e days] [-d domain] [-h host] [-g targetpath] [-c]\" << endl\n << endl\n << L\"-v - toggle debug flag\" << endl\n << L\"-g targetpath - generate certificates in targetpath\" << endl\n << L\"-s days - days to offset valid start date with (0)\" << endl\n << L\"-e days - days to offset valid end date with (3650)\" << endl\n << L\"-f - force certificate to be generated even if one exists\" << endl\n << L\"-d domain - domain name\" << endl\n << L\"-h host - host name\" << endl\n << L\"-b bits - number of key bits\" << endl\n << L\"-c - generate certificate with extended key usage as clientAuth\" << endl\n << L\"-? - this help message\" << endl\n ;\n exit(exitValue);\n}\n" }, { "alpha_fraction": 0.5345192551612854, "alphanum_fraction": 0.537060558795929, "avg_line_length": 37.08064651489258, "blob_id": "fee01b2abf052fd127c9f268573c1ed17798c5fb", "content_id": "19d7503403c06dea75552560f6961352f63d9a54", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4722, "license_type": "permissive", "max_line_length": 133, "num_lines": 124, "path": "/source/code/providers/support/appserver/persistappserverinstances.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file persistappserverinstances.h\n\n \\brief Persist instances of discovered application servers\n\n \\date 11-05-19 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef PERSISTAPPSERVERINSTANCES_H\n#define PERSISTAPPSERVERINSTANCES_H\n\n#include <string>\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n\n#include \"source/code/scxcorelib/util/persist/scxfilepersistmedia.h\"\n\n#include \"appserverinstance.h\"\n#include \"removenonexistentappserverinstances.h\"\n\nnamespace SCXSystemLib\n{\n const static std::wstring APP_SERVER_NUMBER = L\"NumberOfAppServers\";\n const static std::wstring APP_SERVER_INSTANCE = L\"AppServerInstance\";\n const static std::wstring APP_SERVER_PROVIDER = L\"AppServerProvider\";\n const static std::wstring APP_SERVER_METADATA = L\"MetaData\";\n const static std::wstring APP_SERVER_ID = L\"Id\";\n const static std::wstring APP_SERVER_DISK_PATH = L\"DiskPath\";\n const static std::wstring APP_SERVER_HTTP_PORT = L\"HttpPort\";\n const static std::wstring APP_SERVER_HTTPS_PORT = L\"HttpsPort\";\n const static std::wstring APP_SERVER_PROTOCOL = L\"Protocol\";\n const static std::wstring APP_SERVER_IS_DEEP_MONITORED= L\"IsDeepMonitored\";\n const static std::wstring APP_SERVER_IS_RUNNING = L\"IsRunning\";\n const static std::wstring APP_SERVER_TYPE = L\"Type\";\n const static std::wstring APP_SERVER_VERSION = L\"Version\";\n const static std::wstring APP_SERVER_PROFILE = L\"Profile\";\n const static std::wstring APP_SERVER_CELL = L\"Cell\";\n const static std::wstring APP_SERVER_NODE = L\"Node\";\n const static std::wstring APP_SERVER_SERVER = L\"Server\";\n\n /*--------------------------------------------------------*/\n /**\n Class that represents an how to persist application server instances \n */\n class PersistAppServerInstances\n {\n\n public:\n \n /*\n * Default no-arg constructor, uses the\n * default/production values\n */\n PersistAppServerInstances();\n\n /*\n * Constructor where the location of the persisted\n * directory can be overriden\n * \n * \\param[in] directory Location to read/write persisted data to\n * \n */\n PersistAppServerInstances(const SCXCoreLib::SCXFilePath& directory);\n\n /*\n * Destructor\n */\n virtual ~PersistAppServerInstances();\n\n /*--------------------------------------------------------*/\n /**\n Remove all Application Server Instances from disk\n */\n void EraseFromDisk(void);\n\n /*--------------------------------------------------------*/\n /**\n Read list of Application Server Instances from disk\n */\n void ReadFromDisk(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& instances);\n\n /*--------------------------------------------------------*/\n /**\n Given a list of instances, remove the instances that are\n can no longer be found on disk\n */\n virtual void RemoveNonExistentInstances(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& instances,\n SCXSystemLib::RemoveNonexistentAppServerInstances remover = SCXSystemLib::RemoveNonexistentAppServerInstances());\n\n /*--------------------------------------------------------*/\n /**\n Write a list of Application Server Instances to disk\n */\n void WriteToDisk(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& instances);\n\n protected:\n //!< Log handle\n SCXCoreLib::SCXLogHandle m_log;\n\n // Handle to the persistence of the media\n SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> m_pmedia;\n\n private:\n /*--------------------------------------------------------*/\n /**\n Helper method for reading instances from disk\n */\n bool ReadFromDiskHelper(\n SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistDataReader>& preader,\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& instances);\n\n };\n\n}\n\n#endif /* PERSISTAPPSERVERINSTANCES_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6682153344154358, "alphanum_fraction": 0.688075065612793, "avg_line_length": 47.35682678222656, "blob_id": "6a55da6c337316a714db80f017ca4a11a170ebb5", "content_id": "e64f4aeb207178f29bac88cfd5abb0490001bd38", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10977, "license_type": "permissive", "max_line_length": 123, "num_lines": 227, "path": "/test/code/providers/network_provider/networkprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the network provider\n\n \\date 2008-03-14 09:00\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <scxsystemlib/networkinterface.h>\n#include <networkprovider.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n#include \"SCX_EthernetPortStatistics_Class_Provider.h\"\n#include \"SCX_IPProtocolEndpoint_Class_Provider.h\"\n#include \"SCX_LANEndpoint_Class_Provider.h\"\n\n//! The provider relies on PAL(s) to provide information to return. This class makes\n//! it possible to simulate PAL output to take control over the dependencies of\n//! the provider. That makes it possible to correlate actual output with expected output.\nclass InjectedNetworkProviderDependencies : public SCXCore::NetworkProviderDependencies {\npublic:\n void InitIntf() {\n }\n\n void SetInstances(const vector< SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> >& instances) {\n m_instances = instances;\n }\n\n void CleanUpIntf() {\n }\n\n void UpdateIntf(bool,wstring interface=L\"\", size_t *pos=NULL) {\n }\n\n size_t IntfCount() const {\n return m_instances.size();\n }\n\n SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> GetIntf(size_t pos) const {\n return m_instances[pos];\n }\n\n SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> GetIntf(const std::wstring& intfId) const {\n for (size_t i = 0; i < m_instances.size() ; i++)\n {\n if (intfId == m_instances[i]->GetName())\n {\n return m_instances[i];\n }\n }\n return SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance>();\n }\n\nprivate:\n vector< SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> > m_instances;\n};\n\nclass SCXNetworkProviderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXNetworkProviderTest );\n CPPUNIT_TEST( TestVerifyKeyCompletePartialEthernetPortStatistics );\n CPPUNIT_TEST( TestVerifyKeyCompletePartialIPProtocolEndpoint );\n CPPUNIT_TEST( TestVerifyKeyCompletePartialLANEndpoint );\n CPPUNIT_TEST( TestEnumIPProtocolEndpointInstances );\n CPPUNIT_TEST( TestEnumLANEndpointInstances );\n CPPUNIT_TEST( TestEnumEthernetPortStatisticsInstances );\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector<std::wstring> m_keyNamesEPS;// SCX_EthernetPortStatistics key names.\n std::vector<std::wstring> m_keyNamesIPPE;// SCX_IPProtocolEndpoint key names.\n std::vector<std::wstring> m_keyNamesLANE;// SCX_LANEndpoint key names.\n\npublic:\n void setUp(void)\n {\n m_keyNamesEPS.push_back(L\"InstanceID\");\n\n m_keyNamesIPPE.push_back(L\"Name\");\n m_keyNamesIPPE.push_back(L\"SystemCreationClassName\");\n m_keyNamesIPPE.push_back(L\"SystemName\");\n m_keyNamesIPPE.push_back(L\"CreationClassName\");\n\n m_keyNamesLANE.push_back(L\"Name\");\n m_keyNamesLANE.push_back(L\"SystemCreationClassName\");\n m_keyNamesLANE.push_back(L\"SystemName\");\n m_keyNamesLANE.push_back(L\"CreationClassName\");\n\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_EthernetPortStatistics_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_IPProtocolEndpoint_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_LANEndpoint_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n\n vector< SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> > originalInstances;\n const unsigned allProperties = static_cast<unsigned> (-1);\n const unsigned noOptionalProperties = 0;\n originalInstances.push_back( SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance>(\n new NetworkInterfaceInstance(NetworkInterfaceInfo(\n L\"eth0\", allProperties,\n// L\"0a123C4Defa6\",\n L\"192.168.0.34\", L\"255.255.255.0\", L\"192.168.0.255\",\n 10000, 20000, 100, 200, 1, 2, 3, true, true, SCXCoreLib::SCXHandle<NetworkInterfaceDependencies>(0)))));\n originalInstances.push_back(SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance>(\n new NetworkInterfaceInstance(NetworkInterfaceInfo(\n L\"eth1\", noOptionalProperties,\n// L\"001122334455\",\n L\"192.168.1.35\", L\"255.255.255.0\", L\"192.168.1.255\",\n 20000, 40000, 200, 400, 2, 4, 6, false, false, SCXCoreLib::SCXHandle<NetworkInterfaceDependencies>(0)))));\n \n SCXHandle<InjectedNetworkProviderDependencies> deps(new InjectedNetworkProviderDependencies());\n deps->SetInstances(originalInstances);\n SCXCore::g_NetworkProvider.UpdateDependencies(deps);\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_EthernetPortStatistics_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_IPProtocolEndpoint_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_LANEndpoint_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void TestVerifyKeyCompletePartialEthernetPortStatistics()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_EthernetPortStatistics_Class_Provider,\n mi::SCX_EthernetPortStatistics_Class>(m_keyNamesEPS, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartialIPProtocolEndpoint()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_IPProtocolEndpoint_Class_Provider,\n mi::SCX_IPProtocolEndpoint_Class>(m_keyNamesIPPE, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartialLANEndpoint()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_LANEndpoint_Class_Provider,\n mi::SCX_LANEndpoint_Class>(m_keyNamesLANE, CALL_LOCATION(errMsg));\n }\n\n void TestEnumLANEndpointInstances(void)\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_LANEndpoint_Class_Provider>(\n m_keyNamesLANE, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 2u, context.Size());\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"eth0\",\n context[0].GetKey(L\"Name\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"SCX_ComputerSystem\",\n context[0].GetKey(L\"SystemCreationClassName\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, GetFQHostName(CALL_LOCATION(errMsg)),\n context[0].GetKey(L\"SystemName\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"SCX_LANEndpoint\",\n context[0].GetKey(L\"CreationClassName\", CALL_LOCATION(errMsg)));\n }\n\n void TestEnumIPProtocolEndpointInstances(void)\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_IPProtocolEndpoint_Class_Provider>(\n m_keyNamesIPPE, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 2u, context.Size());\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"eth0\",\n context[0].GetKey(L\"Name\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"SCX_ComputerSystem\",\n context[0].GetKey(L\"SystemCreationClassName\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, GetFQHostName(CALL_LOCATION(errMsg)),\n context[0].GetKey(L\"SystemName\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"SCX_IPProtocolEndpoint\",\n context[0].GetKey(L\"CreationClassName\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"192.168.0.34\",\n context[0].GetProperty(L\"IPv4Address\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"255.255.255.0\",\n context[0].GetProperty(L\"SubnetMask\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n }\n\n void TestEnumEthernetPortStatisticsInstances(void)\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_EthernetPortStatistics_Class_Provider>(\n m_keyNamesEPS, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 2u, context.Size());\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"eth0\", context[0].GetKey(L\"InstanceID\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 10000u,\n context[0].GetProperty(L\"BytesTransmitted\", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 20000u,\n context[0].GetProperty(L\"BytesReceived\", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 30000u,\n context[0].GetProperty(L\"BytesTotal\", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 100u,\n context[0].GetProperty(L\"PacketsTransmitted\", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 200u,\n context[0].GetProperty(L\"PacketsReceived\", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 1u,\n context[0].GetProperty(L\"TotalTxErrors\", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 2u,\n context[0].GetProperty(L\"TotalRxErrors\", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 3u,\n context[0].GetProperty(L\"TotalCollisions\", CALL_LOCATION(errMsg)).GetValue_MIUint64(CALL_LOCATION(errMsg)));\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXNetworkProviderTest ); /* CUSTOMIZE: Name must be same as classname */\n" }, { "alpha_fraction": 0.4983029067516327, "alphanum_fraction": 0.5021915435791016, "avg_line_length": 43.297821044921875, "blob_id": "a0378e5beddec790e0e9b59fac504afb0198081a", "content_id": "c86fe1a372e94eb65cd67b5097bad11ad07ac6e0", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 74834, "license_type": "permissive", "max_line_length": 317, "num_lines": 1652, "path": "/source/code/providers/support/appserver/jbossappserverinstance.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "\r\n/*--------------------------------------------------------------------------------\r\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\r\n*/\r\n/**\r\n \\file jbossappserverinstance.cpp\r\n\r\n \\brief PAL representation of a JBoss application server\r\n\r\n \\date 11-05-18 12:00:00\r\n*/\r\n/*----------------------------------------------------------------------------*/\r\n\r\n#include <scxcorelib/scxcmn.h>\r\n\r\n#include <string>\r\n#include <iostream>\r\n#include <fstream>\r\n#include <errno.h>\r\n#include <cstring>\r\n#include <scxcorelib/stringaid.h>\r\n#include <scxcorelib/scxfile.h>\r\n#include <scxcorelib/scxdirectoryinfo.h>\r\n#include <scxcorelib/scxprocess.h>\r\n#include <scxcorelib/scxfilepath.h>\r\n#include <scxcorelib/scxregex.h>\r\n#include <util/XElement.h>\r\n\r\n#include \"appserverconstants.h\"\r\n#include \"jbossappserverinstance.h\"\r\n\r\nusing namespace std;\r\nusing namespace SCXCoreLib;\r\nusing namespace SCX::Util::Xml;\r\n\r\nnamespace SCXSystemLib\r\n{\r\n\r\n /**\r\n Returns a stream for reading from jar-versions.xml\r\n\r\n \\param[in] filename Name of file to open\r\n */\r\n SCXHandle<istream> JBossAppServerInstancePALDependencies::OpenXmlVersionFile(wstring filename)\r\n {\r\n return SCXFile::OpenFstream(filename, ios::in);\r\n }\r\n\r\n /**\r\n Returns a stream for reading from bindings-jboss-beans.xml\r\n\r\n \\param[in] filename Name of file to open\r\n */\r\n SCXHandle<istream> JBossAppServerInstancePALDependencies::OpenXmlPortsFile(wstring filename)\r\n {\r\n return SCXFile::OpenFstream(filename, ios::in);\r\n }\r\n\r\n /**\r\n Returns a stream for reading from jboss-service.xml\r\n\r\n \\param[in] filename Name of file to open\r\n */\r\n SCXHandle<istream> JBossAppServerInstancePALDependencies::OpenXmlServiceFile(wstring filename)\r\n {\r\n return SCXFile::OpenFstream(filename, ios::in);\r\n }\r\n\r\n /**\r\n Returns a stream for reading from server.xml\r\n\r\n \\param[in] filename Name of file to open\r\n */\r\n SCXHandle<istream> JBossAppServerInstancePALDependencies::OpenXmlServerFile(wstring filename)\r\n {\r\n return SCXFile::OpenFstream(filename, ios::in);\r\n }\r\n\r\n /**\r\n Returns a stream for reading from the service binder XML file\r\n\r\n \\param[in] filename Name of file to open\r\n */\r\n SCXHandle<istream> JBossAppServerInstancePALDependencies::OpenXmlBindingFile(wstring filename)\r\n {\r\n return SCXFile::OpenFstream(filename, ios::in);\r\n }\r\n\r\n\t/**\r\n Returns a stream for reading from hosts.xml\r\n\r\n \\param[in] filename Name of file to open\r\n */\r\n SCXHandle<istream> JBossAppServerInstancePALDependencies::OpenDomainHostXmlFile(wstring filename)\r\n {\r\n return SCXFile::OpenFstream(filename, ios::in);\r\n }\r\n\r\n\t/**\r\n Returns a stream for reading from module.xml\r\n\r\n \\param[in] filename Name of file to open\r\n */\r\n SCXHandle<istream> JBossAppServerInstancePALDependencies::OpenModuleXmlFile(wstring filename)\r\n {\r\n return SCXFile::OpenFstream(filename, ios::in);\r\n }\r\n\r\n\r\n\t/**\r\n Returns a stream for reading from domain.xml\r\n\r\n \\param[in] filename Name of file to open\r\n */\r\n SCXHandle<istream> JBossAppServerInstancePALDependencies::OpenDomainXmlFile(wstring filename)\r\n {\r\n return SCXFile::OpenFstream(filename, ios::in);\r\n }\r\n\r\n /**\r\n Returns a boolean on whether or not a jboss process is version 7 or 8\r\n\r\n \\param[in] filename Name of file to use\r\n\t \\param[in] enum to modify to specify which file to open\r\n */\r\n bool JBossAppServerInstancePALDependencies::versionJBossWildfly(SCXCoreLib::SCXFilePath filepath, jboss_version_type &version)\r\n {\r\n\t\twstring filePathForJB7 = L\"/modules/org/jboss/as/server/main/module.xml\";\r\n\t\twstring filePathForWF8 = L\"/modules/system/layers/base/org/jboss/as/version/main/module.xml\";\r\n\r\n\t\tSCXCoreLib::SCXFilePath baseFilePathJB7(filepath);\r\n\t\tSCXCoreLib::SCXFilePath baseFilePathWF8(filepath);\r\n\r\n\t\tbaseFilePathJB7.Append(filePathForJB7);\r\n\t\tbaseFilePathWF8.Append(filePathForWF8);\r\n\r\n\t\tif(SCXFile::Exists(baseFilePathJB7))\r\n\t\t{\r\n\t\t\tversion = jboss_version_7;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(SCXFile::Exists(baseFilePathWF8))\r\n\t\t{\r\n\t\t\tversion = jboss_version_8;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n }\r\n \r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Constructor\r\n\r\n \\param[in] id Identifier for the appserver (= install path for the appserver)\r\n \\param[in] config Configuration name used\r\n \\param[in] portsBinding ports binding configuration used\r\n \\param[in] deps Dependency instance to use\r\n */\r\n JBossAppServerInstance::JBossAppServerInstance(\r\n wstring id, wstring config, wstring portsBinding,\r\n SCXHandle<JBossAppServerInstancePALDependencies> deps, wstring deployment) : \r\n AppServerInstance(id, APP_SERVER_TYPE_JBOSS), \r\n m_config(config), m_portsBinding(portsBinding), m_deps(deps)\r\n {\r\n bool fJBossStandaloneCheck = false;\r\n bool fJBossDomainCheck = false;\r\n\r\n // If we have no config given, we will use default\r\n if (L\"\" == config)\r\n {\r\n m_config = L\"default\";\r\n }\r\n \r\n // If we recieved a standalone instance we will have standalone in the file path\r\n // If we recieved a domain instance we will have domain in the file path\r\n wstring fJBossStandaloneStr = L\"/standalone/\";\r\n wstring fJBossDomainStr = L\"/domain/\";\r\n\r\n if ((config.find(fJBossStandaloneStr) != std::string::npos) || (deployment.compare(L\"standalone\") == 0)) \r\n {\r\n fJBossStandaloneCheck = true;\r\n m_jbossStandaloneConfigFile = config;\r\n m_config = L\"\";\r\n }\r\n else if (config.find(fJBossDomainStr) != std::string::npos)\r\n {\r\n fJBossDomainCheck = true;\r\n m_config = L\"/domain/servers/\";\r\n\r\n // Since we have a domain configuration we need to extract the server name\r\n // With the server name we can determine the associated ports with the server\r\n SCXRegex serverRe(L\"(.*)/(.*)/data\");\r\n vector<wstring> v_serverName;\r\n if(serverRe.ReturnMatch(config,v_serverName,0))\r\n {\r\n m_serverName = v_serverName[2];\r\n m_config += (m_serverName); \r\n }\r\n }\r\n \r\n SCXFilePath installPath;\r\n installPath.SetDirectory(id);\r\n m_basePath = installPath.Get();\r\n \r\n // If not JBoss Standalone or Domain (v7 and v8)\r\n // Then we default to JBoss 4, 5, 6 standard\r\n if(!fJBossStandaloneCheck && !fJBossDomainCheck)\r\n {\r\n installPath.AppendDirectory(L\"server\");\r\n }\r\n installPath.AppendDirectory(m_config);\r\n\r\n /* JBoss standalone mode allows running multiple instances using same installation.\r\n The identifying component among instances is the port offset.\r\n Our agent assumes that each instance has it's own disk path but in this scenario\r\n that is not the case.\r\n Hence \":PortOffset\" is added to the standalone config dir/file to uniquely identify \r\n the instance. The disk path is later appropriately parsed to identify if the server\r\n is still installed. \r\n */\r\n if(fJBossStandaloneCheck && m_portsBinding.size() > 0)\r\n {\r\n SetId(m_jbossStandaloneConfigFile + L\":\" + m_portsBinding); \r\n }\r\n else if(fJBossStandaloneCheck)\r\n {\r\n SetId(m_jbossStandaloneConfigFile);\r\n }\r\n else\r\n {\r\n SetId(installPath.Get());\r\n }\r\n m_diskPath = GetId();\r\n\r\n SCX_LOGTRACE(m_log, wstring(L\"JBossAppServerInstance default constructor - \").append(GetId()));\r\n }\r\n\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Constructor used to created from cached entry\r\n\r\n \\param[in] diskPath Path for the configuration\r\n \\param[in] deps Dependency instance to use\r\n */\r\n JBossAppServerInstance::JBossAppServerInstance(\r\n wstring diskPath,\r\n SCXHandle<JBossAppServerInstancePALDependencies> deps) : \r\n AppServerInstance(diskPath, APP_SERVER_TYPE_JBOSS), \r\n m_config(L\"\"), m_portsBinding(L\"\"), m_deps(deps)\r\n {\r\n SCX_LOGTRACE(m_log, wstring(L\"JBossAppServerInstance cache constructor - \").append(GetId()));\r\n }\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Destructor\r\n */\r\n JBossAppServerInstance::~JBossAppServerInstance()\r\n {\r\n SCX_LOGTRACE(m_log, wstring(L\"JBossAppServerInstance destructor - \").append(GetId()));\r\n }\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Try to read an integer from a string\r\n\r\n \\param[in] result Variable to assign the parsed integer to\r\n \\param[in] found Set to true if successful\r\n \\param[in] value string to read from\r\n \\param[in] erroText Text to log if fails\r\n */\r\n void JBossAppServerInstance::TryReadInteger(unsigned int& result, bool& found, const wstring& value, const wstring& errorText)\r\n {\r\n try\r\n {\r\n result = StrToUInt(value);\r\n found = true;\r\n }\r\n catch (SCXNotSupportedException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::TryReadInteger() - \").append(GetId()).append(L\" - \").append(errorText).append(L\": \").append(value));\r\n }\r\n }\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Update ports for JBoss 4 from the service binding configuration\r\n\r\n Load the given XML file\r\n Get node /service-bindings/server where name property is <sererName> \r\n Get node service-config where name propety is jboss.web:service=WebServer\r\n Get node binding\r\n Get attribute port as HTTP Port\r\n Set HTTPS port as HTTP port + 363\r\n\r\n \\param[in] filename Name of XML file to load\r\n \\param[in] servername Name of server to use from the XML file\r\n */\r\n void JBossAppServerInstance::UpdateJBoss4PortsFromServiceBinding(wstring filename, string servername)\r\n {\r\n const string cServiceBindingNodeName(\"service-bindings\");\r\n const string cServerNodeName(\"server\");\r\n const string cServiceNodeName(\"service-config\");\r\n const string cNameAttributeName(\"name\");\r\n const string cPortAttributeName(\"port\");\r\n const string cWebServerName(\"jboss.web:service=WebServer\");\r\n const string cBindingNodeName(\"binding\");\r\n const unsigned int HTTPSOffset = 363;\r\n\r\n try {\r\n string xmlcontent;\r\n SCXHandle<istream> mystream = m_deps->OpenXmlBindingFile(filename);\r\n GetStringFromStream(mystream, xmlcontent);\r\n\r\n XElementPtr serviceBindNode;\r\n XElement::Load(xmlcontent, serviceBindNode);\r\n if (serviceBindNode->GetName() == cServiceBindingNodeName)\r\n {\r\n XElementList serverNodes;\r\n bool foundnode = false;\r\n\r\n serviceBindNode->GetChildren(serverNodes);\r\n for (size_t serverNodeIdx = 0; !foundnode && serverNodeIdx < serverNodes.size(); ++serverNodeIdx)\r\n {\r\n string nameprop;\r\n\r\n if (serverNodes[serverNodeIdx]->GetName() == cServerNodeName && \r\n serverNodes[serverNodeIdx]->GetAttributeValue(cNameAttributeName, nameprop) && \r\n servername == nameprop)\r\n {\r\n foundnode = true;\r\n\r\n XElementList serviceNodes;\r\n bool foundservicenode = false;\r\n\r\n serverNodes[serverNodeIdx]->GetChildren(serviceNodes);\r\n for (size_t serviceNodeIdx = 0; !foundservicenode && serviceNodeIdx < serviceNodes.size(); ++serviceNodeIdx)\r\n {\r\n if (serviceNodes[serviceNodeIdx]->GetName() == cServiceNodeName && \r\n serviceNodes[serviceNodeIdx]->GetAttributeValue(cNameAttributeName, nameprop) && \r\n cWebServerName == nameprop)\r\n {\r\n foundservicenode = true;\r\n XElementPtr bindingNode;\r\n\r\n if (serviceNodes[serviceNodeIdx]->GetChild(cBindingNodeName, bindingNode))\r\n {\r\n string portprop;\r\n\r\n if (bindingNode->GetAttributeValue(cPortAttributeName, portprop))\r\n {\r\n unsigned int httpPort;\r\n bool foundport;\r\n TryReadInteger(httpPort, foundport, StrFromUTF8(portprop), L\"Failed to parse HTTP port\");\r\n if (foundport)\r\n {\r\n m_httpPort = StrFrom(httpPort);\r\n m_httpsPort = StrFrom(httpPort + HTTPSOffset);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4PortsFromServiceBinding() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4PortsFromServiceBinding() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\r\n }\r\n catch (XmlException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4PortsFromServiceBinding() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\r\n }\r\n }\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Update ports for JBoss 4 from the serve configuration\r\n\r\n Load XML file <ConfigPath>\\deploy\\jboss-web.deployer\\server.xml\r\n Get node /Server/Service/Connector where attribute protocol is HTTP/1.1 and secure is true\r\n Get attribute named port for HTTPS Port\r\n Get node /Server/Service/Connector where attribute protocol is HTTP/1.1 and no attribute named secure exist\r\n Get attribute named port for HTTP Port\r\n */\r\n void JBossAppServerInstance::UpdateJBoss4PortsFromServerConfiguration()\r\n {\r\n const string cServerNodeName(\"Server\");\r\n const string cServiceNodeName(\"Service\");\r\n const string cConnectorNodeName(\"Connector\");\r\n const string cProtocolAttributeName(\"protocol\");\r\n const string cSecureAttributeName(\"secure\");\r\n const string cPortAttributeName(\"port\");\r\n const string cHTTP11Name(\"HTTP/1.1\");\r\n const string cTrueName(\"true\");\r\n\r\n SCXFilePath filename(m_diskPath);\r\n\r\n string xmlcontent;\r\n filename.Append(L\"/deploy/jboss-web.deployer/server.xml\");\r\n\r\n try {\r\n SCXHandle<istream> mystream = m_deps->OpenXmlServerFile(filename.Get());\r\n GetStringFromStream(mystream, xmlcontent);\r\n\r\n XElementPtr serverNode;\r\n XElement::Load(xmlcontent, serverNode);\r\n if (serverNode->GetName() == cServerNodeName)\r\n {\r\n XElementPtr serviceNode;\r\n\r\n if (serverNode->GetChild(cServiceNodeName, serviceNode))\r\n {\r\n XElementList connectorNodes;\r\n bool foundHTTPnode = false;\r\n bool foundHTTPSnode = false;\r\n\r\n serviceNode->GetChildren(connectorNodes);\r\n for (size_t idx = 0; !(foundHTTPnode && foundHTTPSnode) && idx < connectorNodes.size(); ++idx)\r\n {\r\n string protocolprop;\r\n\r\n if (connectorNodes[idx]->GetName() == cConnectorNodeName && \r\n connectorNodes[idx]->GetAttributeValue(cProtocolAttributeName, protocolprop) && \r\n cHTTP11Name == protocolprop)\r\n {\r\n string secureprop;\r\n string portprop;\r\n\r\n if (connectorNodes[idx]->GetAttributeValue(cPortAttributeName, portprop))\r\n {\r\n if (connectorNodes[idx]->GetAttributeValue(cSecureAttributeName, secureprop) && \r\n cTrueName == secureprop)\r\n {\r\n m_httpsPort = StrFromUTF8(portprop);\r\n foundHTTPSnode = true;\r\n }\r\n else\r\n {\r\n m_httpPort = StrFromUTF8(portprop);\r\n foundHTTPnode = true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4PortsFromServerConfiguration() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4PortsFromServerConfiguration() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\r\n }\r\n catch (XmlException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4PortsFromServerConfiguration() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\r\n }\r\n }\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Update ports for JBoss 4\r\n\r\n Load XML file <ConfigPath>/conf/jboss-service.xml\r\n\r\n Get node /server/mbean where code property is org.jboss.services.binding.ServiceBindingManager\r\n if that exist\r\n Get node attribute where name property is ServerName and save as port name\r\n Get node attribute where name property is StoreURL\r\n Replace ${jboss.home.url} with ConfigPath and load the XML file\r\n Get node /service-bindings/server where name property is <port name> \r\n Get node service-config where name propety is jboss.web:service=WebServer\r\n Get node binding\r\n Get attribute port as HTTP Port\r\n Set HTTPS port as HTTP port + 363\r\n If not exists\r\n Load XML file <ConfigPath>\\deploy\\jboss-web.deployer\\server.xml\r\n Get node /Server/Service/Connector where attribute protocol is HTTP/1.1 and secure is true\r\n Get attribute named port for HTTPS Port\r\n Get node /Server/Service/Connector where attribute protocol is HTTP/1.1 and no attribute named secure exist\r\n Get attribute named port for HTTP Port\r\n */\r\n void JBossAppServerInstance::UpdateJBoss4Ports()\r\n {\r\n const string cServerNodeName(\"server\");\r\n const string cMbeanNodeName(\"mbean\");\r\n const string cCodeAttributeName(\"code\");\r\n const string cServiceBindingManagerName(\"org.jboss.services.binding.ServiceBindingManager\");\r\n const string cAttributeNodeName(\"attribute\");\r\n const string cNameAttributeName(\"name\");\r\n const string cServerNameName(\"ServerName\");\r\n const string cStoreUrlName(\"StoreURL\");\r\n const wstring cHomeUrlName(L\"${jboss.home.url}/\");\r\n\r\n SCXFilePath filename(m_diskPath);\r\n\r\n string xmlcontent;\r\n filename.Append(L\"/conf/jboss-service.xml\");\r\n\r\n try {\r\n SCXHandle<istream> mystream = m_deps->OpenXmlServiceFile(filename.Get());\r\n GetStringFromStream(mystream, xmlcontent);\r\n\r\n XElementPtr serverNode;\r\n XElement::Load(xmlcontent, serverNode);\r\n if (serverNode->GetName() == cServerNodeName)\r\n {\r\n XElementList mbeanNodes;\r\n bool foundnode = false;\r\n\r\n serverNode->GetChildren(mbeanNodes);\r\n for (size_t mbeanNodeIdx = 0; !foundnode && mbeanNodeIdx < mbeanNodes.size(); ++mbeanNodeIdx)\r\n {\r\n string codeprop;\r\n\r\n if (mbeanNodes[mbeanNodeIdx]->GetName() == cMbeanNodeName && \r\n mbeanNodes[mbeanNodeIdx]->GetAttributeValue(cCodeAttributeName, codeprop) && \r\n cServiceBindingManagerName == codeprop)\r\n {\r\n XElementList attrNodes;\r\n bool foundname = false;\r\n bool foundurl = false;\r\n string serverName(\"\");\r\n wstring storeUrl(L\"\");\r\n\r\n foundnode = true;\r\n\r\n mbeanNodes[mbeanNodeIdx]->GetChildren(attrNodes);\r\n for (size_t attrNodeIdx = 0; !(foundname && foundurl) && attrNodeIdx < attrNodes.size(); ++attrNodeIdx)\r\n {\r\n string nameprop;\r\n\r\n if (attrNodes[attrNodeIdx]->GetName() == cAttributeNodeName && \r\n attrNodes[attrNodeIdx]->GetAttributeValue(cNameAttributeName, nameprop))\r\n {\r\n if (cServerNameName == nameprop)\r\n {\r\n foundname = true;\r\n attrNodes[attrNodeIdx]->GetContent(serverName);\r\n }\r\n else if (cStoreUrlName == nameprop)\r\n {\r\n foundurl = true;\r\n attrNodes[attrNodeIdx]->GetContent(storeUrl);\r\n }\r\n }\r\n }\r\n\r\n if (foundname && foundurl)\r\n {\r\n size_t homePos = storeUrl.find(cHomeUrlName);\r\n if (homePos != wstring::npos)\r\n {\r\n storeUrl.replace(homePos, cHomeUrlName.length(), m_basePath);\r\n }\r\n UpdateJBoss4PortsFromServiceBinding(storeUrl, serverName);\r\n }\r\n }\r\n }\r\n\r\n if (!foundnode)\r\n {\r\n UpdateJBoss4PortsFromServerConfiguration();\r\n }\r\n }\r\n }\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4Ports() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4Ports() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\r\n }\r\n catch (XmlException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss4Ports() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\r\n }\r\n }\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Given a XML element list find the element containing \"${jboss.service.binding.set:xxx}\"\r\n in it value and return the associated part e.g. \"xxx\"\r\n */\r\n bool GetPortsBinding (XElementList paramNodes, wstring & portsBinding)\r\n {\r\n const string cBindingObjectDefaultSet (\"${jboss.service.binding.set:\");\r\n bool foundBinding = false;\r\n \r\n for (size_t idx = 0; !(foundBinding) && idx < paramNodes.size(); ++idx)\r\n {\r\n string content;\r\n paramNodes[0]->GetContent(content);\r\n if(content.length() > cBindingObjectDefaultSet.length())\r\n {\r\n if (content.compare(0,cBindingObjectDefaultSet.length(),cBindingObjectDefaultSet) == 0) \r\n {\r\n portsBinding = StrFromUTF8(content.substr(cBindingObjectDefaultSet.length(),content.length() - cBindingObjectDefaultSet.length() - 1) );\r\n foundBinding = true;\r\n }\r\n }\r\n }\r\n return foundBinding;\r\n }\r\n \r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Update ports for JBoss 5\r\n\r\n Load XML file <ConfigPath>/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\r\n\r\n If no portsBinding has been set (no command line option specified) we get the \r\n assiciated factory from the \"ServiceBindingManager\". Once we have got the factory we use its value to\r\n to get the default portsBinding. This is done by getting the properties for the factory and looking for the \r\n \"${jboss.service.binding.set:XXX\" value. If we still do not have a portsBinding value we use \"ports-default\"\r\n as the value.\r\n \r\n Get nodes /deployment/bean where class property is org.jboss.services.binding.impl.ServiceBindingSet\r\n For each of those nodes get the nodes constructor/parameter\r\n If the first of those nodes has the text equal to the portsBinding, set the offset to the text from the third node\r\n\r\n Get node /deployment/bean where name property is StandardBindings\r\n For that node get all nodes constructor/parameter/set/bean\r\n Find the one node among those that have a subnode property where \r\n name property is serviceName and text is jboss.web:service=WebServer\r\n Then get text of subnode property where name property is port\r\n Then get text of subnode property where name property is bindingName\r\n If no node exist with name property being bindingName, use port for HttpPort\r\n If node with name property being bindingNamehas text HttpConnector, use port for HttpPort\r\n If node with name property being bindingNamehas text HttpsConnector, use port for HttpsPort\r\n \r\n */\r\n void JBossAppServerInstance::UpdateJBoss5Ports()\r\n {\r\n const string cDeploymentNodeName(\"deployment\");\r\n const string cBeanNodeName(\"bean\");\r\n const string cSetNodeName(\"set\");\r\n const string cPropertyNodeName(\"property\");\r\n const string cClassAttributeName(\"class\");\r\n const string cConstructorNodeName(\"constructor\");\r\n const string cServiceBindingSetName(\"org.jboss.services.binding.impl.ServiceBindingSet\");\r\n const string cParameterNodeName(\"parameter\");\r\n const string cNameAttributeName(\"name\");\r\n const string cStandardBindingsName(\"StandardBindings\");\r\n const string cServiceName(\"serviceName\");\r\n const string cWebServerName(\"jboss.web:service=WebServer\");\r\n const string cBindingName(\"bindingName\");\r\n const string cPortName(\"port\");\r\n const string cHttpConnectorName(\"HttpConnector\");\r\n const string cHttpsConnectorName(\"HttpsConnector\");\r\n const string cServiceBindingManagerAttributeName(\"ServiceBindingManager\");\r\n const string cFactoryNodeName(\"factory\");\r\n const string cBeanAttributeName(\"bean\");\r\n const wstring cPortsDefault(L\"ports-default\");\r\n\r\n string xmlcontent;\r\n SCXFilePath filename(m_diskPath);\r\n\r\n filename.Append(L\"/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n\r\n try {\r\n SCXHandle<istream> mystream = m_deps->OpenXmlPortsFile(filename.Get());\r\n GetStringFromStream(mystream, xmlcontent);\r\n\r\n XElementPtr depNode;\r\n XElement::Load(xmlcontent, depNode);\r\n if (depNode->GetName() == cDeploymentNodeName)\r\n {\r\n XElementList beanNodes;\r\n depNode->GetChildren(beanNodes);\r\n bool foundset = false;\r\n bool foundbase = false;\r\n unsigned int portOffset = 0; // Use offset 0 if no offset can be found\r\n XElementPtr baseNode;\r\n string bindingManager;\r\n bool foundBinding = false;\r\n\r\n // No PortsBinding has been specified on the commandline, check for the default value set in the XML file. \r\n // We start by finding the factory used by the \"ServiceBindingManager\"\r\n //\r\n // <bean name=\"ServiceBindingManager\" class=\"org.jboss.services.binding.ServiceBindingManager\">\r\n // <annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name=\"jboss.system:service=ServiceBindingManager\", exposedInterface=org.jboss.services.binding.ServiceBindingManagerMBean.class, registerDirectly=true)</annotation>\r\n // <constructor factoryMethod=\"getServiceBindingManager\">\r\n // <factory bean=\"ServiceBindingManagementObject\"/>\r\n // </constructor>\r\n // </bean>\r\n\r\n if ( m_portsBinding.empty() )\r\n {\r\n for (size_t idx = 0; !(foundBinding) && idx < beanNodes.size(); ++idx)\r\n {\r\n string nameprop;\r\n string classprop;\r\n\r\n // Get the \"ServiceBindingManager\" from the XML file\r\n if (beanNodes[idx]->GetName() == cBeanNodeName && \r\n beanNodes[idx]->GetAttributeValue(cNameAttributeName, classprop) && \r\n cServiceBindingManagerAttributeName == classprop)\r\n {\r\n XElementPtr constrNode;\r\n if (beanNodes[idx]->GetChild(cConstructorNodeName, constrNode))\r\n {\r\n XElementPtr factoryNode;\r\n if (constrNode->GetChild(cFactoryNodeName, factoryNode))\r\n {\r\n factoryNode->GetAttributeValue(cBeanAttributeName, bindingManager);\r\n } \r\n }\r\n }\r\n \r\n // Once we have the factory associated with the \"ServiceBindingManager\" we need to find the \r\n // parameter containing the default value \"${jboss.service.binding.set:ports-01}\" and get the configuration option\r\n // specified e.g. \"ports-01\"\r\n //\r\n // <bean name=\"ServiceBindingManagementObject\" class=\"org.jboss.services.binding.managed.ServiceBindingManagementObject\">\r\n // <constructor>\r\n // <parameter>${jboss.service.binding.set:ports-01}</parameter>\r\n // <parameter>\r\n // <set>\r\n // <inject bean=\"PortsDefaultBindings\"/>\r\n // <inject bean=\"Ports01Bindings\"/>\r\n // <inject bean=\"Ports02Bindings\"/>\r\n // <inject bean=\"Ports03Bindings\"/>\r\n // </set>\r\n // </parameter>\r\n // <parameter>\r\n // <inject bean=\"StandardBindings\"/>\r\n // </parameter>\r\n // </constructor>\r\n // </bean>\r\n if(bindingManager.length() > 0)\r\n {\r\n if (beanNodes[idx]->GetName() == cBeanNodeName && \r\n beanNodes[idx]->GetAttributeValue(cNameAttributeName, classprop) && \r\n bindingManager == classprop)\r\n {\r\n XElementPtr constrNode;\r\n if (beanNodes[idx]->GetChild(cConstructorNodeName, constrNode))\r\n {\r\n XElementList paramNodes;\r\n \r\n constrNode->GetChildren(paramNodes);\r\n foundBinding = GetPortsBinding (paramNodes, m_portsBinding);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n // No PortsBinding has been specified on the commandline and we never found the\r\n // default setting in the ServiceBindingManager so we will atempt to use the default\r\n if ( m_portsBinding.empty() )\r\n {\r\n m_portsBinding = cPortsDefault;\r\n }\r\n\r\n for (size_t idx = 0; !(foundset && foundbase) && idx < beanNodes.size(); ++idx)\r\n {\r\n string nameprop;\r\n string classprop;\r\n\r\n if (beanNodes[idx]->GetName() == cBeanNodeName && \r\n beanNodes[idx]->GetAttributeValue(cClassAttributeName, classprop) && \r\n cServiceBindingSetName == classprop)\r\n {\r\n XElementPtr constrNode;\r\n if (beanNodes[idx]->GetChild(cConstructorNodeName, constrNode))\r\n {\r\n XElementList paramNodes;\r\n constrNode->GetChildren(paramNodes);\r\n if (paramNodes.size() >= 3 &&\r\n paramNodes[0]->GetName() == cParameterNodeName &&\r\n paramNodes[0]->GetContent() == StrToUTF8(m_portsBinding))\r\n {\r\n std::wstring content;\r\n paramNodes[2]->GetContent(content);\r\n\r\n TryReadInteger(portOffset, foundset, content, L\"Failed to parse port offset\");\r\n }\r\n }\r\n }\r\n\r\n if (beanNodes[idx]->GetName() == cBeanNodeName && \r\n beanNodes[idx]->GetAttributeValue(cNameAttributeName, nameprop) && \r\n cStandardBindingsName == nameprop)\r\n {\r\n baseNode = beanNodes[idx];\r\n foundbase = true;\r\n }\r\n }\r\n\r\n // use baseNode to figure out base HTTP & HTTPS ports\r\n // add portOffset to that\r\n XElementPtr constrNode;\r\n XElementPtr paramNode;\r\n XElementPtr setNode;\r\n if (foundbase && \r\n baseNode->GetChild(cConstructorNodeName, constrNode) && \r\n constrNode->GetChild(cParameterNodeName, paramNode) &&\r\n paramNode->GetChild(cSetNodeName, setNode))\r\n {\r\n XElementList setBeanNodes;\r\n setNode->GetChildren(setBeanNodes);\r\n bool foundHttp = false;\r\n bool foundHttps = false;\r\n unsigned int baseHttpPort = 0;\r\n unsigned int baseHttpsPort = 0;\r\n for (size_t idx = 0; !(foundHttp && foundHttps) && idx < setBeanNodes.size(); ++idx)\r\n {\r\n XElementList propNodes;\r\n string nameprop;\r\n std::wstring content;\r\n\r\n setBeanNodes[idx]->GetChildren(propNodes);\r\n if (propNodes.size() >= 2 &&\r\n propNodes[0]->GetName() == cPropertyNodeName &&\r\n propNodes[0]->GetAttributeValue(cNameAttributeName, nameprop) &&\r\n cServiceName == nameprop &&\r\n propNodes[0]->GetContent() == cWebServerName)\r\n {\r\n if (propNodes.size() >= 3 &&\r\n propNodes[1]->GetName() == cPropertyNodeName &&\r\n propNodes[1]->GetAttributeValue(cNameAttributeName, nameprop) &&\r\n cBindingName == nameprop &&\r\n propNodes[2]->GetName() == cPropertyNodeName &&\r\n propNodes[2]->GetAttributeValue(cNameAttributeName, nameprop) &&\r\n cPortName == nameprop)\r\n {\r\n if (propNodes[1]->GetContent() == cHttpConnectorName)\r\n {\r\n propNodes[2]->GetContent(content);\r\n TryReadInteger(baseHttpPort, foundHttp, content, L\"Failed to parse HTTP port\");\r\n }\r\n else if (propNodes[1]->GetContent() == cHttpsConnectorName)\r\n {\r\n propNodes[2]->GetContent(content);\r\n TryReadInteger(baseHttpsPort, foundHttps, content, L\"Failed to parse HTTPS port\");\r\n }\r\n }\r\n else if (propNodes[1]->GetName() == cPropertyNodeName &&\r\n propNodes[1]->GetAttributeValue(cNameAttributeName, nameprop) &&\r\n cPortName == nameprop)\r\n {\r\n propNodes[1]->GetContent(content);\r\n TryReadInteger(baseHttpPort, foundHttp, content, L\"Failed to parse HTTP port\");\r\n }\r\n }\r\n }\r\n // calculate ports if found\r\n if (foundHttp)\r\n {\r\n m_httpPort = StrFrom(baseHttpPort + portOffset);\r\n }\r\n if (foundHttps)\r\n {\r\n m_httpsPort = StrFrom(baseHttpsPort + portOffset);\r\n }\r\n }\r\n }\r\n }\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss5Ports() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss5Ports() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\r\n }\r\n catch (XmlException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss5Ports() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\r\n }\r\n }\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Update ports for JBoss 7\r\n\r\n If in standalone mode we can load XML file <disk_path>/standalone/standalone.xml\r\n No need for bindings file, All located in standalone.xml\r\n\r\n If in domain mode we need to Load XML file <disk_path>/domain/host.xml\r\n we will then need to match serverName to its respective port-offset\r\n \r\n In Standalon.xml navigate to socket-binding group and check for port-offset\r\n attribute. if not found set to 0. Get list of all socket-binding group's children\r\n and traverse to retrieve http and https. If modifications are to be made in the future\r\n for inclusion of osgi applications, traverse same file.\r\n \r\n \r\n */\r\n void JBossAppServerInstance::UpdateJBoss7Ports()\r\n {\r\n string xmlcontent;\r\n SCXFilePath filename(m_basePath);\r\n\r\n if (m_serverName.length() == 0)\r\n {\r\n const string cServerNodeName(\"server\");\r\n const string cHostNodeName(\"host\");\r\n const string cServersNodeName(\"servers\");\r\n const string cServerGroupName(\"server-group\");\r\n const string cSocketBindingGroupNodeName(\"socket-binding-group\");\r\n const string cPortOffsetAttributeName(\"port-offset\");\r\n const string cSocketBindingNodeName(\"socket-binding\");\r\n const string cNameAttributeName(\"name\");\r\n const string cHttpName(\"http\");\r\n const string cHttpsName(\"https\");\r\n const string cPortAttributeName(\"port\");\r\n if(m_jbossStandaloneConfigFile.find(L\".xml\") != std::string::npos)\r\n {\r\n filename.Set(m_jbossStandaloneConfigFile);\r\n }\r\n else\r\n {\r\n filename.Set(m_jbossStandaloneConfigFile + L\"standalone.xml\");\r\n }\r\n\r\n try \r\n {\r\n SCXHandle<istream> mystream = m_deps->OpenXmlPortsFile(filename.Get());\r\n GetStringFromStream(mystream, xmlcontent);\r\n\r\n XElementPtr topNode;\r\n XElement::Load(xmlcontent, topNode);\r\n if (topNode->GetName() == cServerNodeName)\r\n {\r\n XElementPtr socketBindingGroupNode;\r\n if(topNode->GetChild(cSocketBindingGroupNodeName, socketBindingGroupNode))\r\n {\r\n bool httpPortFound = false;\r\n bool httpsPortFound = false;\r\n bool portsFound = false;\r\n bool portOffsetFound = false;\r\n unsigned int baseHttpPort = 0;\r\n unsigned int baseHttpsPort = 0;\r\n unsigned int portOffset = 0;\r\n string HttpPort;\r\n string HttpsPort;\r\n string offset;\r\n \r\n //Regex for port-offset and http/https\r\n SCXRegex re(L\"[0-9]+\");\r\n\r\n if(m_portsBinding.size() > 0)\r\n {\r\n TryReadInteger(portOffset, portOffsetFound, m_portsBinding, L\"Failed to Parse port offset\");\r\n }\r\n // chek if port-offset attribute, if not then value is preset to 0\r\n else if(socketBindingGroupNode->GetAttributeValue(cPortOffsetAttributeName,offset))\r\n {\r\n // There are two ways to set port-offset, one with port-offset=\"100\",\r\n // and the second with port-offset=\"${jboss.socket.binding.port-offset:100}\";\r\n // check if it includes jboss.socket.bind.port-offset beginning and parse accordingly\r\n \r\n wstring wPortOffset = SCXCoreLib::StrFromUTF8(offset);\r\n std::vector<std::wstring> v_offset;\r\n \r\n if(re.ReturnMatch(wPortOffset,v_offset,0))\r\n {\r\n wPortOffset = v_offset[0];\r\n }\r\n TryReadInteger(portOffset, portOffsetFound, wPortOffset, L\"Failed to Parse port offset\");\r\n }\r\n \r\n // XMl Document Example for Standalone.xml\r\n // <socket-binding-group name=\"standard sockets>\r\n // <socket-binding name=\"http\" port=\"8080\"/>\r\n // <socket-binding name=\"https\" port=\"8443\"/>\r\n // <socket-binding name=\".....\" port=\"....\"/>\r\n // </socket-binding group>\r\n \r\n XElementList socketBindings;\r\n socketBindingGroupNode->GetChildren(socketBindings);\r\n \r\n // In WildFly (JBoss AS 8 the ports can be set\r\n // using ${jboss.http:8080}\r\n // will use Regex re from above\r\n // to determine the numbers from ports\r\n \r\n std::vector<std::wstring> v_ports;\r\n\r\n for(size_t idx = 0; !portsFound && idx <socketBindings.size();++idx)\r\n {\r\n string name;\r\n if(socketBindings[idx]->GetName() == cSocketBindingNodeName &&\r\n socketBindings[idx]->GetAttributeValue(cNameAttributeName, name))\r\n {\r\n if(cHttpName == name &&\r\n socketBindings[idx]->GetAttributeValue(cPortAttributeName, HttpPort))\r\n {\r\n wstring wHttpPort;\r\n wHttpPort = SCXCoreLib::StrFromUTF8(HttpPort);\r\n if(re.ReturnMatch(wHttpPort, v_ports,0))\r\n {\r\n wHttpPort = v_ports[0];\r\n }\r\n TryReadInteger(baseHttpPort, httpPortFound, wHttpPort, L\"Failed to parse HTTP port\");\r\n }\r\n else if(cHttpsName == name &&\r\n socketBindings[idx]->GetAttributeValue(cPortAttributeName, HttpsPort))\r\n {\r\n wstring wHttpsPort;\r\n wHttpsPort = SCXCoreLib::StrFromUTF8(HttpsPort);\r\n \r\n // Clear port vector for use with https\r\n v_ports.clear();\r\n\r\n if(re.ReturnMatch(wHttpsPort, v_ports,0))\r\n {\r\n wHttpsPort = v_ports[0];\r\n }\r\n TryReadInteger(baseHttpsPort, httpsPortFound, wHttpsPort, L\"Failed to parse HTTPS port\");\r\n }\r\n\r\n if(httpPortFound && httpsPortFound) portsFound = true;\r\n }\r\n }\r\n if(httpPortFound)\r\n {\r\n m_httpPort = StrFrom(baseHttpPort + portOffset);\r\n }\r\n if(httpsPortFound)\r\n {\r\n m_httpsPort = StrFrom(baseHttpsPort + portOffset);\r\n }\r\n }\r\n }\r\n }\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss7Ports() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss7Ports() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\r\n }\r\n catch (XmlException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss7Ports() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\r\n }\r\n }\r\n else\r\n {\r\n try\r\n {\r\n\t\t\t\tvector<wstring> a = GetJBossWildflyServerHostXmlInformation();\r\n\t\t\t\t\r\n\r\n\t\t\t\tconst string cDomainNodeName = \"domain\";\r\n\t\t\t\tconst string cServerGroupsNodeName = \"server-groups\";\r\n\t\t\t\tconst string cServerGroupNodeName = \"server-group\";\r\n\t\t\t\tconst string cNameAttributeName = \"name\";\r\n\t\t\t\tconst string cSocketBindingGroupNodeName = \"socket-binding-group\";\r\n\t\t\t\tconst string cRefAttributeName = \"ref\";\r\n\r\n\t\t\t\tconst string cSocketBindingGroupsNodeName = \"socket-binding-groups\";\r\n\t\t\t\tconst string cSocketBindingNodeName = \"socket-binding\";\r\n\t\t\t\tconst string cPortAttributeName = \"port\";\r\n\t\t\t\tconst string cHttpName = \"http\";\r\n\t\t\t\tconst string cHttpsName = \"https\";\r\n\r\n\t\t\t\tunsigned int baseHttpPort = 0;\r\n unsigned int baseHttpsPort = 0;\r\n unsigned int portOffset = 0;\r\n\t\t\t\t\r\n\t\t\t\tbool httpPortFound = false;\r\n bool httpsPortFound = false;\r\n bool portsFound = false;\r\n bool portOffsetFound = false;\r\n\t\t\t\tbool socketReferenceFound = false;\r\n\r\n\t\t\t\twstring varServerGroupName = a[0];\r\n\t\t\t\twstring varPortOffset = a[1];\r\n\t\t\t\twstring wSocketReference = L\"\"; \r\n\r\n\t\t\t\t// Convert retrieved port offset to integer if exists\r\n\t\t\t\tif(varPortOffset != L\"\")\r\n\t\t\t\t{\r\n\t\t\t\t\tTryReadInteger(portOffset, portOffsetFound, varPortOffset, L\"Failed to parse HTTPS port\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfilename.Append(L\"domain/configuration/domain.xml\");\r\n\r\n\t\t\t\tSCXHandle<istream> mystream = m_deps->OpenDomainXmlFile(filename.Get());\r\n\t\t\t\tSCXRegex re(L\"[0-9]+\");\r\n\t\t\t\tGetStringFromStream(mystream, xmlcontent);\r\n\r\n\t\t\t\tXElementPtr topNode;\r\n\t\t\t\tXElement::Load(xmlcontent, topNode);\r\n\r\n\t\t\t\tif(topNode->GetName() == cDomainNodeName)\r\n\t\t\t\t{\r\n\t\t\t\t\tXElementPtr serverGroupsNode;\r\n\t\t\t\t\tif(topNode->GetChild(cServerGroupsNodeName, serverGroupsNode))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tXElementList serverGroups;\r\n\t\t\t\t\t\tserverGroupsNode->GetChildren(serverGroups);\r\n\t\t\t\t\t\t// Iterate through the server-group tags to find node \r\n\t\t\t\t\t\t// associated with groupName retrieved from GetJBossWildflyServerHostXmlInformation()\r\n\t\t\t\t\t\t// ex: <server-group name=\"main-server-group\" profile=\"full\">\r\n\t\t\t\t\t\tfor(size_t idx = 0; idx<serverGroups.size(); ++idx)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tstring name;\r\n\t\t\t\t\t\t\tif(serverGroups[idx]->GetName() == cServerGroupNodeName &&\r\n\t\t\t\t\t\t\t serverGroups[idx]->GetAttributeValue(cNameAttributeName, name))\r\n\t\t\t\t\t\t\t{\t\r\n\t\t\t\t\t\t\t\tif(StrFromUTF8(name) == varServerGroupName)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tXElementList socketBindingGroups;\r\n\t\t\t\t\t\t\t\t\tserverGroups[idx]->GetChildren(socketBindingGroups);\r\n\t\t\t\t\t\t\t\t\t// Find server-group node and iterate through children\r\n\t\t\t\t\t\t\t\t\t// to find the socket-binding-group child\r\n\t\t\t\t\t\t\t\t\t// and retrieve the socket reference attribute\r\n\t\t\t\t\t\t\t\t\t// ex:\r\n\t\t\t\t\t\t\t\t\t// <server-group name=\"main-server-group\" profile=\"full\">\r\n\t\t\t\t\t\t\t\t\t//\t\t<jvm name=\"default\">\r\n\t\t\t\t\t\t\t\t\t//\t\t\t<heap size=\"64m\" max-size=\"512m\"/>\r\n\t\t\t\t\t\t\t\t\t//\t\t</jvm>\r\n\t\t\t\t\t\t\t\t\t//\t\t<socket-binding-group ref=\"full-sockets\"/>\r\n\t\t\t\t\t\t\t\t\t// </server-group>\r\n\t\t\t\t\t\t\t\t\tfor(size_t jdx = 0; jdx<socketBindingGroups.size(); ++jdx)\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tstring ref;\r\n\t\t\t\t\t\t\t\t\t\tif(socketBindingGroups[jdx]->GetName() == cSocketBindingGroupNodeName &&\r\n\t\t\t\t\t\t\t\t\t\t socketBindingGroups[jdx]->GetAttributeValue(cRefAttributeName, ref))\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\twSocketReference = StrFromUTF8(ref);\r\n\t\t\t\t\t\t\t\t\t\t\tsocketReferenceFound = true;\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\t// If we found the socket reference in domain.xml then we can proceed with determining the port values\r\n\t\t\t\t\t\tif(socketReferenceFound)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tXElementPtr socketBindingParentGroup;\r\n\t\t\t\t\t\t\tif(topNode->GetChild(cSocketBindingGroupsNodeName, socketBindingParentGroup))\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tXElementList socketBindingGroups;\r\n\t\t\t\t\t\t\t\tsocketBindingParentGroup->GetChildren(socketBindingGroups);\r\n\t\t\t\t\t\t\t\t// Iterate through the socket-binding-group and determine if the name matches the socket reference\r\n\t\t\t\t\t\t\t\t// We can then retrieve ports from the child class\r\n\t\t\t\t\t\t\t\t// ex:\r\n\t\t\t\t\t\t\t\t// <socket-binding-groups name = \"socket reference\" >\r\n\t\t\t\t\t\t\t\t//\t\t<socket-binding name = \"http\" port = \"${jboss.http.port:8080}\"/>\r\n\t\t\t\t\t\t\t\t// </socket-binding-groups>\r\n\t\t\t\t\t\t\t\tfor(size_t idx = 0; idx < socketBindingGroups.size(); ++idx)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tstring socketRef;\r\n\t\t\t\t\t\t\t\t\tif(socketBindingGroups[idx]->GetName() == cSocketBindingGroupNodeName &&\r\n\t\t\t\t\t\t\t\t\t socketBindingGroups[idx]->GetAttributeValue(cNameAttributeName, socketRef))\r\n\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\tif(StrFromUTF8(socketRef) == wSocketReference)\r\n\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\tXElementList socketBindings;\r\n\t\t\t\t\t\t\t\t\t\t\tsocketBindingGroups[idx]->GetChildren(socketBindings);\r\n\r\n\t\t\t\t\t\t\t\t\t\t\tstd::vector<std::wstring> v_ports;\r\n\t\t\t\t\t\t\t\t\t\t\tfor(size_t jdx = 0; !portsFound && jdx < socketBindings.size(); ++jdx)\r\n\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\tstring name;\r\n\t\t\t\t\t\t\t\t\t\t\t\tif(socketBindings[jdx]->GetName() == cSocketBindingNodeName &&\r\n\t\t\t\t\t\t\t\t\t\t\t\t socketBindings[jdx]->GetAttributeValue(cNameAttributeName, name))\r\n\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tstring HttpPort, HttpsPort;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(cHttpName == name &&\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t socketBindings[jdx]->GetAttributeValue(cPortAttributeName, HttpPort))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twstring wHttpPort;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twHttpPort = SCXCoreLib::StrFromUTF8(HttpPort);\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(re.ReturnMatch(wHttpPort, v_ports,0))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twHttpPort = v_ports[0];\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tTryReadInteger(baseHttpPort, httpPortFound, wHttpPort, L\"Failed to parse HTTP port\");\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\telse if(cHttpsName == name &&\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tsocketBindings[jdx]->GetAttributeValue(cPortAttributeName, HttpsPort))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twstring wHttpsPort;\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\twHttpsPort = SCXCoreLib::StrFromUTF8(HttpsPort);\r\n \r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t// Clear port vector for use with https\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tv_ports.clear();\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tif(re.ReturnMatch(wHttpsPort, v_ports,0))\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twHttpsPort = v_ports[0];\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tTryReadInteger(baseHttpsPort, httpsPortFound, wHttpsPort, L\"Failed to parse HTTPS port\");\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tif(httpPortFound && httpsPortFound) portsFound = true;\r\n\t\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif(httpPortFound)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tm_httpPort = StrFrom(baseHttpPort + portOffset);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\tif(httpsPortFound)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tm_httpsPort = StrFrom(baseHttpsPort + portOffset);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss7Ports() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss7Ports() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\r\n }\r\n catch (XmlException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateJBoss7Ports() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\r\n }\r\n }\r\n }\r\n \r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Get server associated Server Group Name for JBoss and Wildfly servers \r\n running in Domain mode\r\n \r\n Load XML file <DiskPath>/domain/configuration/host.xml\r\n Get value of attribute group.\r\n\t <host>\r\n\t\t <severs>\r\n\t\t\t<server name=\"server-one\" group=\"main-server-group\">\r\n\t\t\t\t<socket-bindings port-offset=\"150\">\r\n\t\t\t</server>\r\n\t\t </servers>\r\n\t </host>\r\n\r\n\t vector[0] will contain a wstring for the server group name\r\n\t vector[1] will contain a wstring for the port offset\r\n */\r\n vector<wstring> JBossAppServerInstance::GetJBossWildflyServerHostXmlInformation()\r\n {\r\n const string cHostNodeName = \"host\";\r\n const string cServersNodeName = \"servers\";\r\n const string cServerNodeName = \"server\";\r\n const string cGroupAttributeName = \"group\";\r\n const string cNameAttributeName = \"name\";\r\n\t\tconst string cSocketBindingsName = \"socket-bindings\";\r\n\t\tconst string cPortOffsetName = \"port-offset\";\r\n \r\n string xmlcontent;\r\n\r\n\t\tvector<wstring> hostXmlVector;\r\n \r\n\t\twstring wGroupName = L\"\";\r\n wstring wPortOffset = L\"0\";\r\n\r\n\t\tSCXFilePath filename(m_basePath);\r\n filename.Append(L\"/domain/configuration/host.xml\");\r\n try\r\n {\r\n SCXHandle<istream> mystream = m_deps->OpenDomainHostXmlFile(filename.Get());\r\n GetStringFromStream(mystream, xmlcontent);\r\n\t\t\t\r\n XElementPtr topNode;\r\n XElement::Load(xmlcontent, topNode);\r\n\t\t\t\r\n if (topNode->GetName() == cHostNodeName)\r\n {\r\n XElementPtr serversNode;\r\n if(topNode->GetChild(cServersNodeName, serversNode))\r\n {\r\n XElementList servers;\r\n serversNode->GetChildren(servers);\r\n\t\t\t\t\t// Iterate through the server tags to determine group attribute value for\r\n\t\t\t\t\t// discovered server\r\n\t\t\t\t\t// ex: <server name=\"server-one\" group=\"main-server-group\">\r\n for(size_t idx = 0; idx<servers.size(); ++idx)\r\n {\r\n\t\t\t\t\t\tstring name;\r\n if(servers[idx]->GetName() == cServerNodeName &&\r\n servers[idx]->GetAttributeValue(cNameAttributeName, name))\r\n {\r\n string groupName;\r\n if(m_serverName == StrFromUTF8(name) &&\r\n servers[idx]->GetAttributeValue(cGroupAttributeName, groupName))\r\n {\r\n wGroupName = StrFromUTF8(groupName);\r\n\t\t\t\t\t\t\t XElementPtr socketBindingsNode;\r\n\t\t\t\t\t\t\t // If there is a socket-bindings we can then check for port-offset attribute\r\n\t\t\t\t\t\t\t if(servers[idx]->GetChild(cSocketBindingsName, socketBindingsNode))\r\n\t\t\t\t\t\t\t {\r\n\t\t\t\t\t\t\t\t string portOffset;\r\n\t\t\t\t\t\t\t\t if(socketBindingsNode->GetAttributeValue(cPortOffsetName, portOffset))\r\n\t\t\t\t\t\t\t\t {\r\n\t\t\t\t\t\t\t\t\t wPortOffset = StrFromUTF8(portOffset);\r\n\t\t\t\t\t\t\t\t }\r\n\t\t\t\t\t\t\t }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::GetJBossWildflyServerHostXmlInformation() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::GetJBossWildflyServerHostXmlInformation() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\r\n }\r\n catch (XmlException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::GetJBossWildflyServerHostXmlInformation() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\r\n }\r\n\r\n\t\thostXmlVector.push_back(wGroupName);\r\n\t\thostXmlVector.push_back(wPortOffset);\r\n\r\n return hostXmlVector;\r\n }\r\n\r\n\r\n // remove shell character from the output of a command\r\n void removeShellCharacter(string &str)\r\n {\r\n int i = 0;\r\n while (!(str[i]=='0' && str[i+1]=='m'))\r\n {\r\n i++;\r\n }\r\n str.erase(0,i+2);\r\n }\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Update version\r\n\r\n Load XML file <DiskPath>/jar-versions.xml\r\n Get node /jar-versions/jar where name property is jboss.jar\r\n Read specVersion property for that node\r\n */\r\n void JBossAppServerInstance::UpdateVersion()\r\n { \r\n const char* isTestEnv = getenv(\"SCX_TESTRUN_ACTIVE\");\r\n if (!isTestEnv)\r\n {\r\n SCXFilePath filename(m_basePath);\r\n SCXFilePath moduleFilename(m_basePath);\r\n #if defined (linux)\r\n moduleFilename.Append(L\"/bin/standalone.sh -version | tail -1 |sed -r 's/\\x1b\\[[0-9]*[m|K]//g'\");\r\n #else\r\n moduleFilename.Append(L\"/bin/standalone.sh -version | tail -1 \");\r\n #endif \r\n wstring script = L\"sh \";\r\n script.append(moduleFilename);\r\n string command = SCXCoreLib::StrToUTF8(script);\r\n char buffer[128];\r\n wstring result =L\"\";\r\n string tmpResult = \"\";\r\n try {\r\n FILE* pipe = popen(command.c_str(), \"r\");\r\n if (pipe)\r\n {\r\n while (fgets(buffer, 128, pipe) != NULL) {\r\n tmpResult = buffer;\r\n }\r\n pclose(pipe);\r\n #if !defined (linux)\r\n removeShellCharacter(tmpResult); \r\n #endif \r\n result = SCXCoreLib::StrTrim(SCXCoreLib::StrFromUTF8(tmpResult));\r\n SetVersion(result);\r\n }\r\n else{\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - popen sytem call failed with error no: \").append(SCXCoreLib::StrFromUTF8(std::strerror(errno))));\r\n }\r\n }catch(...){\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - could not get the version from: \").append(filename));\r\n }\r\n \r\n }\r\n else{\r\n\r\n\r\n const string cJarVersionsNodeName(\"jar-versions\");\r\n const string cJarNodeName(\"jar\");\r\n const string cNameAttributeName(\"name\");\r\n const string cJbossJarName(\"jboss.jar\");\r\n const string cSpecVersionAttributeName(\"specVersion\");\r\n const string cModuleNodeName(\"module\");\r\n const string cResourcesNodeName(\"resources\");\r\n const string cResourcesRootNodeName(\"resource-root\");\r\n const string cPathAttributeName(\"path\");\r\n\r\n bool fJboss7Check = false;\r\n\r\n string xmlcontent;\r\n SCXFilePath filename(m_basePath);\r\n SCXFilePath moduleFilename(m_basePath);\r\n \r\n\r\n filename.Append(L\"jar-versions.xml\");\r\n\r\n try {\r\n SCXHandle<istream> mystream = m_deps->OpenXmlVersionFile(filename.Get());\r\n GetStringFromStream(mystream, xmlcontent);\r\n\r\n XElementPtr topNode;\r\n XElement::Load(xmlcontent, topNode);\r\n if (topNode->GetName() == cJarVersionsNodeName)\r\n {\r\n XElementList versionNodes;\r\n topNode->GetChildren(versionNodes);\r\n bool found = false;\r\n for (size_t idx = 0; !found && idx < versionNodes.size(); ++idx)\r\n {\r\n string name;\r\n if (versionNodes[idx]->GetName() == cJarNodeName && \r\n versionNodes[idx]->GetAttributeValue(cNameAttributeName, name) && \r\n cJbossJarName == name)\r\n {\r\n string version;\r\n if (versionNodes[idx]->GetAttributeValue(cSpecVersionAttributeName, version))\r\n {\r\n SetVersion(StrFromUTF8(version));\r\n found = true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n fJboss7Check = true;\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\r\n }\r\n catch (XmlException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\r\n }\r\n \r\n if(fJboss7Check)\r\n {\r\n\r\n try {\r\n // For JBoss 7.x we can traverse the java package files and retrieve the\r\n // module.xml file that contains the name of the server jar file needed\r\n // This server jar file contains the version number\r\n // e.g\r\n // <module xmlns=\"urn:jboss:module:1.0\" name=\"org.jboss.as.server\">\r\n // <main-class name=\"org.jboss.as.server.DomainServerMain\"/>\r\n // <resources>\r\n // <resource-root path=\"jboss-as-server-7.0.0.Final.jar\"/>\r\n // </resources>\r\n // </module>\r\n //\r\n // From this resource node, we can retrieve the name\r\n\r\n // For Wildfly and JBoss Enterprise Application Server the module file\r\n // can be found inside a version folder, with the same xml format\r\n\r\n \r\n // For JBoss 7 the module xml file is located at\r\n // <server dir>/modules/org/jboss/as/server/main/module.xml\r\n // For Wildfly and JBoss EAS the module xml file is located at\r\n // <server dir>/modules/system/layers/base/org/jboss/as/version/main/module.xml\r\n\r\n wstring filePathForJB7 = L\"/modules/org/jboss/as/server/main/module.xml\";\r\n wstring filePathForWF8 = L\"/modules/system/layers/base/org/jboss/as/version/main/module.xml\";\r\n wstring wildflyVersionPrefix = L\"wildfly-version-\";\r\n string::size_type prefixLen = wildflyVersionPrefix.length();\r\n\r\n // If version returned we load the procedure\r\n // Else report error in Log for no file found\r\n jboss_version_type vers;\r\n\r\n if(m_deps->versionJBossWildfly(moduleFilename, vers))\r\n {\r\n if(vers == jboss_version_7)\r\n {\r\n moduleFilename.Append(filePathForJB7);\r\n }\r\n else if(vers == jboss_version_8)\r\n {\r\n moduleFilename.Append(filePathForWF8);\r\n }\r\n SCXHandle<istream> mystream = m_deps->OpenModuleXmlFile(moduleFilename.Get());\r\n GetStringFromStream(mystream, xmlcontent);\r\n XElementPtr topNode;\r\n XElement::Load(xmlcontent, topNode);\r\n if(topNode->GetName() == cModuleNodeName)\r\n {\r\n XElementList resourcesNodes;\r\n topNode->GetChildren(resourcesNodes);\r\n bool found = false;\r\n for (size_t idx = 0; !found && idx < resourcesNodes.size(); ++idx)\r\n {\r\n string name;\r\n if (resourcesNodes[idx]->GetName() == cResourcesNodeName)\r\n {\r\n XElementList resourcesRootNodes;\r\n resourcesNodes[idx]->GetChildren(resourcesRootNodes);\r\n for(size_t jdx = 0; jdx < resourcesRootNodes.size(); ++jdx)\r\n {\r\n string version;\r\n if (resourcesRootNodes[jdx]->GetName() == cResourcesRootNodeName &&\r\n resourcesRootNodes[jdx]->GetAttributeValue(cPathAttributeName, version))\r\n {\r\n vector<wstring> v_version;\r\n SCXRegex re(L\"([0-9]+.[0-9].[0-9]..*)(.jar)\");\r\n /* Wildfly 9 onwards version is written\r\n as wildfly-version-1.0..., where 1\r\n corresponds to 9. To handle this we\r\n are adding 8 to the major version so\r\n that port information can be\r\n retrieved correctly */\r\n if(StrIsPrefix(StrFromUTF8(version), wildflyVersionPrefix, true))\r\n {\r\n size_t pos = version.find(\".\");\r\n string mVer = version.substr(prefixLen ,pos-prefixLen);\r\n int ver = atoi(mVer.c_str());\r\n //Revisit for wildfly 16\r\n if(ver < 8)\r\n {\r\n int updatedVer = 8+ver;\r\n stringstream ss;\r\n ss<<updatedVer;\r\n string newVer = ss.str();\r\n version.replace(prefixLen, mVer.length(), newVer);\r\n }\r\n }\r\n if(re.ReturnMatch(StrFromUTF8(version), v_version,0))\r\n {\r\n SetVersion(v_version[1]);\r\n found = true;\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n else\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - Could not find file: \").append(filename).append(L\"- Or find file: \").append(moduleFilename).append(filePathForJB7).append(L\"- Or find file: \").append(moduleFilename).append(filePathForWF8));\r\n }\r\n }\r\n catch (SCXFilePathNotFoundException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - Could not find file: \").append(filename).append(L\"- Or find file: \").append(moduleFilename));\r\n }\r\n catch (SCXUnauthorizedFileSystemAccessException&)\r\n {\r\n SCX_LOGERROR(m_log, wstring(L\"JBossAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - not authorized to open file: \").append(moduleFilename));\r\n }\r\n }\r\n }\r\n } \r\n \r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Update values\r\n\r\n */\r\n void JBossAppServerInstance::Update()\r\n {\r\n SCX_LOGTRACE(m_log, wstring(L\"JBossAppServerInstance::Update() - \").append(GetId()));\r\n UpdateVersion();\r\n if (m_majorVersion.length() > 0)\r\n {\r\n if(StrToLong(m_majorVersion) >= 7)\r\n {\r\n UpdateJBoss7Ports(); //JBoss is version 7 or higher\r\n }\r\n else if (StrToLong(m_majorVersion) >= 5) //JBoss is version 5 or 6\r\n {\r\n UpdateJBoss5Ports();\r\n }\r\n else\r\n {\r\n UpdateJBoss4Ports();\r\n }\r\n }\r\n }\r\n\r\n /*----------------------------------------------------------------------------*/\r\n /**\r\n Read all lines from a stream and save in a string\r\n\r\n \\param[in] mystream Stream to read from\r\n \\param[out] content String to return content in\r\n */\r\n void JBossAppServerInstance::GetStringFromStream(SCXHandle<istream> mystream, string& content)\r\n {\r\n content = \"\";\r\n while (SCXStream::IsGood(*mystream))\r\n {\r\n string tmp;\r\n getline(*mystream, tmp);\r\n content.append(tmp);\r\n content.append(\"\\n\");\r\n }\r\n }\r\n\r\n /*--------------------------------------------------------------------*/\r\n /**\r\n Check if the application server is still installed.\r\n \r\n This overrides the default logic\r\n\r\n */\r\n bool JBossAppServerInstance::IsStillInstalled()\r\n {\r\n SCXFilePath diskPath;\r\n std::string::size_type loc = m_diskPath.find(L\":\");\r\n if(loc != std::string::npos)\r\n {\r\n diskPath.Set(m_diskPath.substr(0,loc));\r\n }\r\n else\r\n {\r\n diskPath.Set(m_diskPath);\r\n }\r\n return (SCXDirectory::Exists(diskPath) || SCXFile::Exists(diskPath));\r\n }\r\n\r\n}\r\n\r\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\r\n" }, { "alpha_fraction": 0.5738215446472168, "alphanum_fraction": 0.5780438780784607, "avg_line_length": 39.69577407836914, "blob_id": "e4e5d2912b10984578b24e42eeea65fdb09c6124", "content_id": "e020337cb11302cb5397341cc2ce36e17ef132a8", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14447, "license_type": "permissive", "max_line_length": 210, "num_lines": 355, "path": "/source/code/providers/support/runasprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file runasprovider.cpp\n\n \\brief RunAs provider implementation\n\n \\date 05-15-13 \n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxprocess.h>\n#include <scxcorelib/scxdirectoryinfo.h>\n#include <scxcorelib/logsuppressor.h>\n#include <scxsystemlib/scxsysteminfo.h>\n#include \"startuplog.h\"\n#include \"scxrunasconfigurator.h\"\n#include \"runasprovider.h\"\n\nconst std::wstring s_defaultTmpDir = L\"/etc/opt/microsoft/scx/conf/tmpdir/\";\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nnamespace SCXCore\n{\n void RunAsProvider::Load()\n {\n SCXASSERT( ms_loadCount >= 0 );\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.runasprovider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"RunAsProvider::Load()\");\n\n if ( NULL == m_Configurator )\n {\n m_Configurator = SCXCoreLib::SCXHandle<RunAsConfigurator> (new RunAsConfigurator());\n }\n\n ParseConfiguration();\n // set tmpdir location when RunAs provider gets loaded. This will later be used in \n // every ExecuteScript call. Check for existence of directory will be done in\n // ExecuteScript method so that latest state is taken.\n m_defaultTmpDir = s_defaultTmpDir;\n }\n }\n\n void RunAsProvider::Unload()\n {\n SCX_LOGTRACE(m_log, L\"OSProvider::Unload()\");\n\n SCXASSERT( ms_loadCount >= 1 );\n if (0 == --ms_loadCount)\n {\n m_Configurator = NULL;\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Execute a command\n\n \\param[in] command Command to execute\n \\param[out] resultOut Result string from stdout\n \\param[out] resultErr Result string from stderr\n \\param[out] returncode Return code from command\n \\param[in] timeout Accepted number of seconds to wait\n \\param[in] elevationtype Elevation type \n \\returns true if command succeeded, else false\n \\throws SCXAccessViolationException If execution is prohibited by configuration\n */\n bool RunAsProvider::ExecuteCommand(const std::wstring &command, std::wstring &resultOut, std::wstring &resultErr,\n int& returncode, unsigned timeout, const std::wstring &elevationtype)\n {\n SCX_LOGTRACE(m_log, L\"RunAsProvider ExecuteCommand\");\n\n if ( ! m_Configurator->GetAllowRoot() )\n {\n SCXUser currentUser;\n if (currentUser.IsRoot())\n {\n throw SCXAccessViolationException(L\"Configuration prohibits execution with user: root\", SCXSRCLOCATION);\n }\n }\n\n std::istringstream processInput;\n std::ostringstream processOutput;\n std::ostringstream processError;\n \n // Construct the command by considering the elevation type. It simply returns the command\n // when elevation type is not empty or the current user is already privilege.\n // The elevated command will become a shell command by the design. \n std::wstring elecommand = ConstructCommandWithElevation(command, elevationtype);\n\n try\n {\n returncode = SCXCoreLib::SCXProcess::Run(elecommand, processInput, processOutput, processError, timeout * 1000,\n m_Configurator->GetCWD(), m_Configurator->GetChRootPath());\n SCX_LOGHYSTERICAL(m_log, L\"\\\"\" + elecommand + L\"\\\" returned \" + StrFrom(returncode));\n resultOut = StrFromMultibyte(processOutput.str());\n SCX_LOGHYSTERICAL(m_log, L\"stdout: \" + resultOut);\n resultErr = StrFromMultibyte(processError.str());\n SCX_LOGHYSTERICAL(m_log, L\"stderr: \" + resultErr);\n\n // Trim output if necessary\n if ( OutputLimiter(resultOut, resultErr) )\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"ExecuteCommand: Exceeded maximum output size for provider (64k), output truncated. Monitoring will not be reliable! Command executed: \", command));\n }\n }\n catch (SCXCoreLib::SCXException& e)\n {\n resultOut = StrFromMultibyte(processOutput.str());\n resultErr = StrFromMultibyte(processError.str()) + e.What();\n returncode = -1;\n }\n\n return (returncode == 0);\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Execute a command in the default shell.\n\n \\param[in] command Command to execute\n \\param[out] resultOut Result string from stdout\n \\param[out] resultErr Result string from stderr\n \\param[out] returncode Return code from command\n \\param[in] timeout Accepted number of seconds to wait\n \\param[in] elevationtype Elevation type\n \\returns true if command succeeded, else false\n \\throws SCXAccessViolationException If execution is prohibited by configuration\n */\n bool RunAsProvider::ExecuteShellCommand(const std::wstring &command, std::wstring &resultOut, std::wstring &resultErr,\n int& returncode, unsigned timeout, const std::wstring &elevationtype)\n {\n SCX_LOGTRACE(m_log, L\"RunAsProvider ExecuteShellCommand\");\n\n if ( ! m_Configurator->GetAllowRoot() )\n {\n SCXUser currentUser;\n if (currentUser.IsRoot())\n {\n throw SCXAccessViolationException(L\"Configuration prohibits execution with user: root\", SCXSRCLOCATION);\n }\n }\n\n std::istringstream processInput;\n std::ostringstream processOutput;\n std::ostringstream processError;\n \n // Construct the shell command with the given command and elevation type.\n // Please be noted that the constructed shell command use the single quotes. Hence,\n // the current limitation is that the shell command fails if the given command has \n // single quote. \n std::wstring shellcommand = ConstructShellCommandWithElevation(command, elevationtype);\n\n try\n {\n returncode = SCXCoreLib::SCXProcess::Run(shellcommand, processInput, processOutput, processError,\n timeout * 1000, m_Configurator->GetCWD(), m_Configurator->GetChRootPath());\n\n SCX_LOGHYSTERICAL(m_log, L\"\\\"\" + shellcommand + L\"\\\" returned \" + StrFrom(returncode));\n resultOut = StrFromMultibyte(processOutput.str());\n SCX_LOGHYSTERICAL(m_log, L\"stdout: \" + resultOut);\n resultErr = StrFromMultibyte(processError.str());\n SCX_LOGHYSTERICAL(m_log, L\"stderr: \" + resultErr);\n\n // Trim output if necessary\n if ( OutputLimiter(resultOut, resultErr) )\n {\n SCX_LOGWARNING(m_log, StrAppend(L\"ExecuteShellCommand: Exceeded maximum output size for provider (64k), output truncated. Monitoring will not be reliable! Command executed: \", command));\n }\n }\n catch (SCXCoreLib::SCXException& e)\n {\n resultOut = L\"\";\n resultErr = e.What();\n returncode = -1;\n }\n\n return (returncode == 0);\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Execute a script\n\n \\param[in] script Script to execute\n \\param[in] arguments Command line arguments to script\n \\param[out] resultOut Result string from stdout\n \\param[out] resultErr Result string from stderr\n \\param[out] returncode Return code from command\n \\param[in] timeout Accepted number of seconds to wait\n \\param[in] elevationtype Elevation type\n\n \\returns true if script succeeded, else false\n \\throws SCXAccessViolationException If execution is prohibited by configuration */\n bool RunAsProvider::ExecuteScript(const std::wstring &script, const std::wstring &arguments, std::wstring &resultOut,\n std::wstring &resultErr, int& returncode, unsigned timeout,\n const std::wstring &elevationtype)\n {\n SCX_LOGTRACE(m_log, L\"SCXRunAsProvider ExecuteScript\");\n\n if ( ! m_Configurator->GetAllowRoot() )\n {\n SCXUser currentUser;\n if (currentUser.IsRoot())\n {\n throw SCXAccessViolationException(L\"Configuration prohibits execution with user: root\", SCXSRCLOCATION);\n }\n }\n\n std::istringstream processInput;\n std::ostringstream processOutput;\n std::ostringstream processError;\n SCXFilePath scriptfile;\n std::wstring command;\n\n try\n {\n bool tmpDirExists = SCXCoreLib::SCXDirectory::Exists(m_defaultTmpDir);\n std::wstring tmpDir = tmpDirExists ? m_defaultTmpDir : L\"/tmp/\";\n if(!tmpDirExists) {\n static SCXCoreLib::LogSuppressor suppressor(SCXCoreLib::eWarning, SCXCoreLib::eHysterical);\n SCX_LOG(m_log, suppressor.GetSeverity(m_defaultTmpDir), L\"Default tmp Directory does not exist. Falling back to /tmp\");\n }\n\n scriptfile = SCXFile::CreateTempFile(script, tmpDir);\n SCXFileSystem::Attributes attribs = SCXFileSystem::GetAttributes(scriptfile);\n attribs.insert(SCXFileSystem::eUserExecute);\n SCXFile::SetAttributes(scriptfile, attribs);\n\n command = scriptfile.Get();\n command.append(L\" \").append(arguments);\n\n // Construct the command with the given elevation type.\n command = ConstructCommandWithElevation(command, elevationtype);\n\n returncode = SCXCoreLib::SCXProcess::Run(command,\n processInput, processOutput, processError, timeout * 1000,\n m_Configurator->GetCWD(), m_Configurator->GetChRootPath());\n SCXFile::Delete(scriptfile);\n\n SCX_LOGHYSTERICAL(m_log, L\"\\\"\" + command + L\"\\\" returned \" + StrFrom(returncode));\n resultOut = StrFromMultibyte(processOutput.str());\n SCX_LOGHYSTERICAL(m_log, L\"stdout: \" + resultOut);\n resultErr = StrFromMultibyte(processError.str());\n SCX_LOGHYSTERICAL(m_log, L\"stderr: \" + resultErr);\n\n // Trim output if necessary\n if ( OutputLimiter(resultOut, resultErr) )\n {\n SCX_LOGWARNING(m_log, L\"ExecuteScript: Exceeded maximum output size for provider (64k), output truncated. Monitoring will not be reliable! Script contents logged only with hysterical logging.\");\n }\n }\n catch (SCXCoreLib::SCXException& e)\n {\n SCX_LOGHYSTERICAL(m_log, L\"\\\"\" + command + L\"\\\" returned \" + e.What());\n\n // Delete the script file if one was created\n if ( ! scriptfile.Get().empty() )\n {\n SCXFile::Delete(scriptfile);\n }\n\n resultOut = L\"\";\n resultErr = e.What();\n returncode = -1;\n }\n\n return (returncode == 0);\n }\n \n std::wstring RunAsProvider::ConstructCommandWithElevation(const std::wstring &command, \n const std::wstring &elevationtype)\n {\n // Construct the command by considering the elevation type.\n // Noted that SystemInfo GetElevatedCommand function will return a\n // shell command when the elevation type is sudo (it simply returns\n // the command when the current user is already elevated).\n\n SCXSystemLib::SystemInfo si;\n if (elevationtype == L\"sudo\")\n {\n return si.GetElevatedCommand(command);\n }\n\n return command;\n }\n\n // Construct a shell command for the given command and the elevation type. \n std::wstring RunAsProvider::ConstructShellCommandWithElevation(const std::wstring &command,\n const std::wstring &elevationtype)\n {\n SCXSystemLib::SystemInfo si;\n\n std::wstring newCommand(si.GetShellCommand(command));\n\n // Only when current user is not priviledged and elevation type is sudo\n // the command need to be elevated.\n // Force a shell command so we get a shell (even if already elevated)\n if (elevationtype == L\"sudo\")\n {\n newCommand = si.GetElevatedCommand(newCommand);\n }\n\n return newCommand;\n }\n\n // Limit stdout/stderr length to avoid bumping up against OMI's 64k limit per instance\n // (Not a whole lot of sense in raising that, since WS-Man has a limit as well)\n bool RunAsProvider::OutputLimiter(std::wstring& resultOut, std::wstring& resultErr)\n {\n const size_t maxOutputSize = 60*1024;\n\n // Do we need to truncate the output?\n if (resultOut.size() + resultErr.size() <= maxOutputSize)\n {\n // Nope, we're good\n return false;\n }\n\n if ( resultErr.size() == 0 )\n {\n // Truncate stdout only\n resultOut = resultOut.substr(0, maxOutputSize-1);\n }\n else if ( resultOut.size() == 0 )\n {\n // Truncate stderr only\n resultErr = resultErr.substr(0, maxOutputSize-1);\n }\n else\n {\n // They are both non-zero in size. There are a number of ways to do\n // this, but PM said to keep it simple and do this ...\n\n resultOut = resultOut.substr(0, maxOutputSize - 1 - 1024);\n resultErr = resultErr.substr(0, 1024 - 1);\n }\n\n return true;\n }\n\n // Only construct ApplicationServer class once\n int RunAsProvider::ms_loadCount = 0;\n RunAsProvider g_RunAsProvider;\n}\n\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.43421053886413574, "alphanum_fraction": 0.4392712414264679, "avg_line_length": 34.28571319580078, "blob_id": "51bdbd4a016c9e04e470e3b4be9ba2150dfef868", "content_id": "d8078c6854c2e5212f6cc9de4da9fedc011a296d", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 1976, "license_type": "permissive", "max_line_length": 85, "num_lines": 56, "path": "/build/Makefile.pf.HPUXGCC", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-10-12\n# \n# Overrides to the HPUX makefile when using GCC\n# \n#--------------------------------------------------------------------------------\n\ninclude Makefile.pf.posix\n\n#--------------------------------------------------------------------------------\n# Paths\n#--------------------------------------------------------------------------------\n\n# Path to where the CPPUNIT libraries are checked in \nCPPUNIT_LIB_PATH=$(TST_EXT_LIB_DIR)/hpux/$(ARCH)/cppunit\n\n#--------------------------------------------------------------------------------\n# Tools on this platform\n#--------------------------------------------------------------------------------\n\n# Common compiler flags (sent to compile command and link commands)\nCOMMONFLAGS=-pthread -milp32\n\n# CXX Compiler flags (Redefined to include COMMONFLAGS)\nCXXFLAGS=$(COMMONFLAGS) $(DEFINES) $(CXX_WARN_FLAGS)\n\n# Link an executable\nLINK=g++ $(COMMONFLAGS) -L. -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR)\n\n# Link a dynamic lib \nLINK_DYNLIB = g++ -shared $(COMMONFLAGS) -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR)\n\n#--------------------------------------------------------------------------------\n# Link switches for this platform, per target\n#--------------------------------------------------------------------------------\n\nLDFLAGS_DYNLIB =\nLDFLAGS_EXECUTABLE =\n\n# The Core Provider Module links with these \nLDFLAGS_COREPROVIDERMODULE = $(LDFLAGS_DYNLIB)\n\n# The Test Provider Module links with these\nLDFLAGS_TESTPROVIDERMODULE = $(LDFLAGS_DYNLIB)\n\n# The testrunner links with these\nLDFLAGS_TESTRUNNER = $(LDFLAGS_EXECUTABLE)\n\n# Currently building only TAR on Solaris\nPF_KIT_FILE_SUFFIX=tar\n\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.5727482438087463, "alphanum_fraction": 0.576212465763092, "avg_line_length": 28.3389835357666, "blob_id": "1c4a593de3d52aa8d429d156ba9ef28a6bf0f6bc", "content_id": "828f43bdf7e30e1215e14cb35ff3ac22ed4a7b11", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1732, "license_type": "permissive", "max_line_length": 108, "num_lines": 59, "path": "/source/code/providers/support/osprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file osprovider.h\n\n \\brief OS provider\n\n \\date 04-22-03\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef OSPROVIDER_H\n#define OSPROVIDER_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n#include <scxsystemlib/memoryenumeration.h>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXCore\n{\n class OSProvider\n {\n public:\n OSProvider();\n virtual ~OSProvider();\n\n void Load();\n void Unload();\n\n SCXHandle<OSEnumeration> GetOS_Enumerator() { return m_osEnum; }\n SCXHandle<MemoryEnumeration> GetMemory_Enumerator() { return m_memEnum; }\n SCXHandle<SCXOSTypeInfo> GetOSTypeInfo() { return m_OSTypeInfo; }\n SCXLogHandle& GetLogHandle() { return m_log; }\n virtual const std::wstring DumpString() const { return L\"OSProvider\"; }\n\n private:\n //! PAL implementation representing os information for local host\n SCXCoreLib::SCXHandle<OSEnumeration> m_osEnum;\n\n //! PAL implementation representing memory information for local host\n SCXCoreLib::SCXHandle<MemoryEnumeration> m_memEnum;\n\n //! PAL for providing static OS information\n SCXCoreLib::SCXHandle<SCXOSTypeInfo> m_OSTypeInfo;\n\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n };\n\n extern OSProvider g_OSProvider;\n}\n\n#endif /* OSPROVIDER_H */\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n\n" }, { "alpha_fraction": 0.5909552574157715, "alphanum_fraction": 0.5947662591934204, "avg_line_length": 36.846153259277344, "blob_id": "02f27ec918062732b82eaa033c8b3d6c69a72e3b", "content_id": "37a44cc0ae1e83992a6760b0c391837eff284ae6", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3936, "license_type": "permissive", "max_line_length": 135, "num_lines": 104, "path": "/source/code/providers/support/networkprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file networkprovider.h\n\n \\brief Declarations of the Network Provider class and its dependencies.\n\n \\date 12-03-20 11:00\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef NETWORKPROVIDER_H\n#define NETWORKPROVIDER_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxlog.h>\n#include <scxsystemlib/networkinterfaceinstance.h> // for NetworkInterfaceInstance\n#include <scxsystemlib/networkinterfaceenumeration.h> // for NetworkInterfaceEnumeration\n#include \"startuplog.h\"\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\nusing namespace std;\n\nnamespace SCXCore\n{\n /*----------------------------------------------------------------------------*/\n //! Encapsulates the dependencies of the Network Provider\n //!\n class NetworkProviderDependencies \n {\n public:\n NetworkProviderDependencies() : m_interfaces(0) {}\n virtual void InitIntf();\n virtual void CleanUpIntf();\n virtual void UpdateIntf(bool updateInstances=true,wstring interface=L\"\", size_t *pos=NULL);\n virtual size_t IntfCount() const;\n virtual SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> GetIntf(size_t pos) const;\n virtual SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> GetIntf(const std::wstring& intfId) const;\n\n //! Virtual destructor preparing for subclasses\n virtual ~NetworkProviderDependencies() { }\n private:\n //! PAL implementation retrieving network information for local host\n SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceEnumeration> m_interfaces;\n }; // End of class NetworkProviderDependencies\n\n /*----------------------------------------------------------------------------*/\n /**\n Network provider\n\n Provide base system information to the Network providers including:\n SCX_EthernetPortStatistics, SCX_LANEndpoint, and SCX_IPProtocolEndpoint.\n */\n class NetworkProvider\n {\n public:\n NetworkProvider() : m_deps(0) { }\n\n virtual ~NetworkProvider() { };\n\n void Load()\n {\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.Network_provider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"NetworkProvider::Load()\");\n\n // Create dependencies\n SCX_LOGTRACE(m_log, L\"NetworkProvider::Load() Creating dependencies\");\n m_deps = new SCXCore::NetworkProviderDependencies();\n\n // Initialize the interface\n SCX_LOGTRACE(m_log, L\"NetworkProvider::Load() Initializing interface\");\n m_deps->InitIntf();\n SCX_LOGTRACE(m_log, L\"NetworkProvider::Load() helper exit\");\n }\n }\n\n void Unload()\n {\n SCX_LOGTRACE(m_log, L\"NetworkProvider::Unload()\");\n if ( 0 == --ms_loadCount )\n {\n m_deps->CleanUpIntf();\n m_deps = 0;\n }\n }\n\n SCXLogHandle& GetLogHandle(){ return m_log; }\n void UpdateDependencies(SCXHandle<SCXCore::NetworkProviderDependencies> deps) { m_deps = deps; }\n SCXCoreLib::SCXHandle<SCXCore::NetworkProviderDependencies> getDependencies() { return m_deps; }\n private:\n static int ms_loadCount;\n SCXCoreLib::SCXHandle<SCXCore::NetworkProviderDependencies> m_deps; //!< External functionality the provider is dependent upon.\n SCXCoreLib::SCXLogHandle m_log; //!< Handle to log file.\n\n }; // End of class NetworkProvider\n\n extern NetworkProvider g_NetworkProvider;\n} // End of namespace SCXCore\n\n#endif /* NETWORKPROVIDER_H */\n" }, { "alpha_fraction": 0.5833333134651184, "alphanum_fraction": 0.5862963199615479, "avg_line_length": 33.177215576171875, "blob_id": "c3f0ff0bfd8c6629d2cc03121604557ee3db9f2b", "content_id": "3bdc3c90cc12a2f659e7d29bbee669dbca922699", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2700, "license_type": "permissive", "max_line_length": 108, "num_lines": 79, "path": "/source/code/providers/support/diskprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n * \n * */\n /**\n \\file diskprovider.h\n\n \\brief Disk provider\n\n \\date 03-21-13\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef DISKPROVIDER_H\n#define DISKPROVIDER_H\n\n#include <scxcorelib/scxlog.h>\n#include \"startuplog.h\"\n#include <scxsystemlib/diskdepend.h>\n#include <scxsystemlib/entityenumeration.h>\n#include <scxsystemlib/staticphysicaldiskenumeration.h>\n#include <scxsystemlib/statisticalphysicaldiskenumeration.h>\n#include <scxcorelib/scxhandle.h>\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXCore\n{\n /*------------------------------------------------------------------------------*/\n /**\n * DiskProvider \n * Helper class to handle the dependency and Logging\n */\n class DiskProvider\n {\n public:\n DiskProvider()\n : m_staticPhysicaldeps(0),\n m_statisticalPhysicsdeps(0) { };\n virtual ~DiskProvider() { };\n virtual void UpdateDependency(SCXHandle<SCXSystemLib::DiskDepend> staticPhysicaldeps,\n SCXHandle<SCXSystemLib::DiskDepend> statisticalPhysicsdeps) \n { \n m_staticPhysicaldeps = staticPhysicaldeps;\n m_statisticalPhysicsdeps = statisticalPhysicsdeps;\n }\n\n SCXLogHandle& GetLogHandle() { return m_log; }\n void Load();\n void UnLoad();\n\n SCXHandle<SCXSystemLib::StatisticalPhysicalDiskEnumeration> getEnumstatisticalPhysicalDisks() const\n {\n return m_statisticalPhysicalDisks;\n }\n\n SCXHandle<SCXSystemLib::StaticPhysicalDiskEnumeration> getEnumstaticPhysicalDisks() const\n {\n return m_staticPhysicalDisks;\n }\n\n private:\n SCXHandle<SCXSystemLib::DiskDepend> m_staticPhysicaldeps, m_statisticalPhysicsdeps;\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n\n //!PAL implementation retrieving physical disk information for local host\n SCXHandle<SCXSystemLib::StatisticalPhysicalDiskEnumeration> m_statisticalPhysicalDisks;\n //! PAL implementation retrieving static physical disk information for local host\n SCXHandle<SCXSystemLib::StaticPhysicalDiskEnumeration> m_staticPhysicalDisks;\n };\n\n extern SCXCore::DiskProvider g_DiskProvider;\n}\n\n#endif /* DISKPROVIDER_H */\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5747663378715515, "alphanum_fraction": 0.5942636132240295, "avg_line_length": 33.865169525146484, "blob_id": "dd2ec7c1a2ff565a03fa9e82ac649392c0c269bd", "content_id": "29022b96cbcc598b102ba64a0b3b9522facffd9a", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 6206, "license_type": "permissive", "max_line_length": 170, "num_lines": 178, "path": "/build/Makefile.pf.HPUX", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n# \n# Platform-specific overrides to the general POSIX platform file\n# \n#--------------------------------------------------------------------------------\n\n# UNIX_STD affects the behaviour of certain C-lib functions.\nexport UNIX_STD=2003\n\n\n# Define flags. (These will be submitted to all commands that use the preprocesor)\nDEFINES=-Dhpux -D$(ARCH) -D_XOPEN_SOURCE=600 -DPF_MAJOR=$(PF_MAJOR) -DPF_MINOR=$(PF_MINOR) -D_PSTAT64=1 -D_LARGEFILE64_SOURCE=1\n\nifeq ($(SCX_STACK_ONLY), true)\n\tDEFINES += -DSCX_STACK_ONLY\nendif\n\n# Compiler flags that regulates warning levels\n# The following aCC warnings are currently disabled:\n# warning #2236-D: controlling expression is constant\n# warning #2111-D: statement is unreachable\n# warning #2815-D: type qualifier on return type is meaningless\n# warning #4232-D: conversion to a more strictly aligned type may cause misaligned access\nCXX_WARN_STRICT_FLAGS=+W2236,2111,2815\nCXX_WARN_STRICT_FLAGS_PROVIDERS=+W2236,2111,2815,4232\n\nCXX_WARN_FLAGS=\n\n# Common compiler flags (sent to compile command and link commands)\n# The following flags get set:\n# -D__hpux -D__ia64=1 -D_BIG_ENDIAN=1 -D__STDCPP__\n# -D__HP_aCC=version-string -D_HP_NAMESPACE_STD\nCOMMONFLAGS=+DD64 -AA -mt +Z\n\n# Use \"warnings as errors\", if available\nifeq ($(ARCH),ia64)\n\tCOMMONFLAGS += +check=stack\n\t# Note: -We exists in the PARISC compiler also, but is buggy and \n\t# exits with \"fatal error #523:\" for many files.\n\tCXX_WARN_FLAGS += +We\n\t# Enable security diagnostics at compile \n#\tCXX_WARN_FLAGS += +wsecurity=2 +wlint Currently disabled, see WI 11173\n# COMMONFLAGS += +check=all Currently disabled, see WI 11173\nendif\n\n# CXX Compiler flags (Redefined to include COMMONFLAGS)\nCXXFLAGS=$(COMMONFLAGS) $(DEFINES) $(CXX_WARN_FLAGS) $(CXX_WARN_STRICT_FLAGS)\nCFLAGS=$(COMMONFLAGS) -ext $(DEFINES) $(CXX_WARN_FLAGS) $(CXX_WARN_STRICT_FLAGS)\n\n# CXX Debug flags for debug builds\nifeq ($(BUILD_TYPE),Debug)\n\tCXXFLAGS += -g1\n\tDEFINES += -D_DEBUG\nelse\n\tCXXFLAGS += +O1\n\tifeq ($(ARCH),ia64)\n\t\tCXXFLAGS += +Osize\n\tendif\n\tDEFINES += -DNDEBUG\nendif\n\n# Linker flags\nLINK_OUTFLAG=-o $@\nLINK_STATLIB_OUTFLAG=$@\n\n# Add profiling flags to compile/link command, if requested. (-p not available on PA-RISC)\nifeq ($(BUILD_PROFILING), prof)\n COMMONFLAGS += -p\nendif\nifeq ($(BUILD_PROFILING), gprof)\n COMMONFLAGS += -G\nendif\n\n#--------------------------------------------------------------------------------\n# Tools for this platform\n\n# Compiler for CPP files\nCXX=aCC\n\n# Link command for executables\n# Link an executable\nLINK=aCC $(COMMONFLAGS) -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR) -L$(SCXOMI_LIBS)\n\n# Link command for static libraries (archives)\n# Be sure to use local ar, not gnu-ar. That ar won't accept -o.\nLINK_STATLIB=/bin/ar -rc\n\n# Link a dynamic lib\nLINK_DYNLIB = aCC $(COMMONFLAGS) -b -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR)\nifeq ($(ARCH),ia64)\n# See:\n# http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/Online_Help/distributing.htm#linking \n# for special linkage considerations\nLINK_DYNLIB += -lstd_v2 -lCsup -lunwind -lm\nendif\n\n# Include flags are redefined since aCC can't take the -i option.\nINCLUDES=-I$(SCX_SHARED_INCLUDE_DIR) -I$(INT_INCLUDE_DIR) -I$(SCXPAL_INT_INCLUDE_DIR) -I$(SCX_BRD) -I$(SCXPAL_DIR) -I$(SCX_SHARED_TST_EXT_INCLUDE_DIR) -I$(SCXOMI_INCLUDE)\nUNITTEST_EXTRA_INCLUDES=-I$(SCXPAL_TEST_ROOT)/include -I$(SCX_SHARED_SRC_ROOT)\n\n# No operation, i.e. suppressing a command\nNOOP=@echo Step suppressed \n\n# Command for making dependecies\nMKDEP=aCC +make -E\n\n#--------------------------------------------------------------------------------\n# File type suffixes\n\nPF_OBJ_FILE_SUFFIX=o\nPF_STAT_LIB_FILE_SUFFIX=a\nifeq ($(ARCH),ia64)\n\tPF_DYN_LIB_FILE_SUFFIX=so\nelse\n\tPF_DYN_LIB_FILE_SUFFIX=sl\nendif\nPF_EXE_FILE_SUFFIX=\nPF_KIT_FILE_SUFFIX=tar\n\n#--------------------------------------------------------------------------------\n# Flags depending on PF_. Placed here since ifeq does not work with forward vars.\n#--------------------------------------------------------------------------------\n# Use new compiler fronend on PA-RISC (that makes it more like IA-64)\nifeq ($(ARCH),hppa)\nifneq ($(PF_MINOR),23)\n\tCOMMONFLAGS += +hpxstd98\nendif\nendif\n\n#--------------------------------------------------------------------------------\n# Paths\n#--------------------------------------------------------------------------------\n\n# Path to where the CPPUNIT libraries are checked in \nCPPUNIT_LIB_PATH=$(SCX_SHARED_TST_EXT_LIB_DIR)/hpuxacc/$(ARCH)/cppunit_64bit\n\n#--------------------------------------------------------------------------------\n# Link switches for this platform, per target\n#--------------------------------------------------------------------------------\n\nLDFLAGS_DYNLIB =\nLDFLAGS_EXECUTABLE =\n\n# The Core Provider Module links with these \nLDFLAGS_COREPROVIDERMODULE = $(LDFLAGS_DYNLIB)\n\n# The Test Provider Module links with these\nLDFLAGS_TESTPROVIDERMODULE = $(LDFLAGS_DYNLIB)\n\n# The testrunner links with these\nLDFLAGS_TESTRUNNER = $(LDFLAGS_EXECUTABLE)\n\n# Transforms a list of symbols that should be exposed to the correct link flags\n# Example: \"symbol1 symbol2\" will give you \"-u symbol1 -Wl,+esymbol1 -u symbol2 -Wl,+esymbol2\"\nget_ld_flags_for_retaining_symbols=$(foreach EXPOSED_SYM,$(1), -u $(EXPOSED_SYM) -Wl,+e$(EXPOSED_SYM))\n\n# Use pkg-config to get ssl library options\n# (SSL_CFLAGS isn't used yet)\nSSL_CFLAGS := $(shell pkg-config --cflags openssl)\nSSL_LIBS := $(shell pkg-config --libs openssl)\n\n#--------------------------------------------------------------------------------\n# InstallBuilder datafile determination\n#--------------------------------------------------------------------------------\n\nPF_DEPENDENT_DATAFILES = HPUX.data\nifeq ($(PF_ARCH), pa-risc)\nPF_DEPENDENT_DATAFILES += HPUX_pa-risc.data\nendif\nifeq ($(PF_ARCH), ia64)\nPF_DEPENDENT_DATAFILES += HPUX_ia64.data\nendif\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.6131187081336975, "alphanum_fraction": 0.6173268556594849, "avg_line_length": 42.14409255981445, "blob_id": "e079405887a5ab2d78104694166d6f83a3e56799", "content_id": "2dcf57d567471f959edd380cca98d2d47d8cbae1", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14971, "license_type": "permissive", "max_line_length": 142, "num_lines": 347, "path": "/test/code/providers/process_provider/processprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the process provider\n\n \\date 2008-04-10 12:02\n\n Only tests the functionality of the provider class.\n The actual data gathering is tested by a separate class.\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n#include \"SCX_UnixProcess_Class_Provider.h\"\n#include \"SCX_UnixProcessStatisticalInformation_Class_Provider.h\"\n\n#include \"testutilities.h\"\n\n//WI567597: Property ModulePath not returned during pbuild on ostcdev64-sles11-01, ostcdev-sles10-01, ostcdev64-rhel4-01 and ostcdev-rhel4-10.\n//WI567598: Property Parameters not returned on ostcdev-sles9-10.\nstatic bool brokenProvider = true;\n\nusing namespace SCXCoreLib;\n\nclass SCXProcessProviderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXProcessProviderTest );\n\n CPPUNIT_TEST( TestUnixProcessEnumerateInstances );\n CPPUNIT_TEST( TestUnixProcessStatisticalInformationEnumerateInstances );\n\n CPPUNIT_TEST( TestUnixProcessGetInstance );\n CPPUNIT_TEST( TestUnixProcessStatisticalInformationGetInstance );\n\n CPPUNIT_TEST( TestUnixProcessGetThisInstance );\n CPPUNIT_TEST( TestUnixProcessStatisticalInformationGetThisInstance );\n\n CPPUNIT_TEST( TestUnixProcessInvokeTopResourceConsumers );\n CPPUNIT_TEST( TestUnixProcessInvokeTopResourceConsumersFail );\n\n\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessEnumerateInstances, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessStatisticalInformationEnumerateInstances, SLOW);\n\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessGetInstance, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessStatisticalInformationGetInstance, SLOW);\n\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessGetThisInstance, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessStatisticalInformationGetThisInstance, SLOW);\n\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessInvokeTopResourceConsumers, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestUnixProcessInvokeTopResourceConsumersFail, SLOW);\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector<std::wstring> m_keyNamesUP;// SCX_UnixProcess key names.\n std::vector<std::wstring> m_keyNamesUPS;// SCX_UnixProcessStatisticalInformation key names.\n\npublic:\n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_UnixProcess_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n SetUpAgent<mi::SCX_UnixProcessStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n \n m_keyNamesUP.push_back(L\"CSCreationClassName\");\n m_keyNamesUP.push_back(L\"CSName\");\n m_keyNamesUP.push_back(L\"OSCreationClassName\");\n m_keyNamesUP.push_back(L\"OSName\");\n m_keyNamesUP.push_back(L\"CreationClassName\");\n m_keyNamesUP.push_back(L\"Handle\");\n\n m_keyNamesUPS.push_back(L\"Name\");\n m_keyNamesUPS.push_back(L\"CSCreationClassName\");\n m_keyNamesUPS.push_back(L\"CSName\");\n m_keyNamesUPS.push_back(L\"OSCreationClassName\");\n m_keyNamesUPS.push_back(L\"OSName\");\n m_keyNamesUPS.push_back(L\"Handle\");\n m_keyNamesUPS.push_back(L\"ProcessCreationClassName\");\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_UnixProcess_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n TearDownAgent<mi::SCX_UnixProcessStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void TestUnixProcessEnumerateInstances()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_UnixProcess_Class_Provider>(\n m_keyNamesUP, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_MESSAGE(ERROR_MESSAGE, context.Size() > 10);\n\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void TestUnixProcessStatisticalInformationEnumerateInstances()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_UnixProcessStatisticalInformation_Class_Provider>(\n m_keyNamesUPS, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_MESSAGE(ERROR_MESSAGE, context.Size() > 10);\n\n ValidateInstanceStatisticalInformation(context, CALL_LOCATION(errMsg));\n }\n\n void TestUnixProcessGetInstance()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestGetInstance<mi::SCX_UnixProcess_Class_Provider,\n mi::SCX_UnixProcess_Class>(\n context, m_keyNamesUP.size(), CALL_LOCATION(errMsg));\n\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void TestUnixProcessStatisticalInformationGetInstance()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestGetInstance<mi::SCX_UnixProcessStatisticalInformation_Class_Provider,\n mi::SCX_UnixProcessStatisticalInformation_Class>(\n context, m_keyNamesUPS.size(), CALL_LOCATION(errMsg));\n\n ValidateInstanceStatisticalInformation(context, CALL_LOCATION(errMsg));\n }\n\n void TestUnixProcessGetThisInstance()\n {\n std::wstring errMsg;\n TestableContext context;\n\n std::vector<std::wstring> keyValues;\n keyValues.push_back(L\"SCX_ComputerSystem\");\n keyValues.push_back(GetFQHostName(CALL_LOCATION(errMsg)));\n keyValues.push_back(L\"SCX_OperatingSystem\");\n keyValues.push_back(SCXCore::GetActualDistributionName(CALL_LOCATION(errMsg)));\n keyValues.push_back(L\"SCX_UnixProcess\");\n keyValues.push_back(SCXCoreLib::StrFrom(getpid()));\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, MI_RESULT_OK, (GetInstance<\n mi::SCX_UnixProcess_Class_Provider, mi::SCX_UnixProcess_Class>(\n m_keyNamesUP, keyValues, context, CALL_LOCATION(errMsg))));\n \n // Yes, but is it us?\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"testrunner\", context[0].GetProperty(\"Name\",\n CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void TestUnixProcessStatisticalInformationGetThisInstance()\n {\n std::wstring errMsg;\n TestableContext context;\n\n std::vector<std::wstring> keyValues;\n keyValues.push_back(L\"testrunner\");// Looking for us.\n keyValues.push_back(L\"SCX_ComputerSystem\");\n keyValues.push_back(GetFQHostName(CALL_LOCATION(errMsg)));\n keyValues.push_back(L\"SCX_OperatingSystem\");\n keyValues.push_back(SCXCore::GetActualDistributionName(CALL_LOCATION(errMsg)));\n keyValues.push_back(SCXCoreLib::StrFrom(getpid()));\n keyValues.push_back(L\"SCX_UnixProcessStatisticalInformation\");\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, MI_RESULT_OK, (GetInstance<\n mi::SCX_UnixProcessStatisticalInformation_Class_Provider, mi::SCX_UnixProcessStatisticalInformation_Class>(\n m_keyNamesUPS, keyValues, context, CALL_LOCATION(errMsg))));\n\n ValidateInstanceStatisticalInformation(context, CALL_LOCATION(errMsg));\n }\n\n bool GetTopResourceConsumers(const char* resourceName, std::wstring errMsg)\n {\n TestableContext context;\n mi::SCX_UnixProcess_Class instanceName;\n mi::SCX_UnixProcess_TopResourceConsumers_Class param;\n param.resource_value(resourceName);\n param.count_value(10);\n\n mi::Module Module;\n mi::SCX_UnixProcess_Class_Provider agent(&Module);\n agent.Invoke_TopResourceConsumers(context, NULL, instanceName, param);\n if (context.GetResult() == MI_RESULT_OK)\n {\n const std::vector<TestableInstance> &instances = context.GetInstances();\n // We expect one instance to be returned.\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 1u, instances.size());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"PID\", instances[0].GetProperty(\"MIReturn\",\n CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)).substr(1, 3));\n return true;\n }\n return false;\n }\n\n void TestUnixProcessInvokeTopResourceConsumers()\n {\n std::wstring errMsg;\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, GetTopResourceConsumers(\"CPUTime\", CALL_LOCATION(errMsg)));\n }\n\n void TestUnixProcessInvokeTopResourceConsumersFail()\n {\n std::wstring errMsg;\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false,\n GetTopResourceConsumers(\"InvalidResource\", CALL_LOCATION(errMsg)));\n }\n\n void ValidateInstance(const TestableContext& context, std::wstring errMsg)\n {\n for (size_t n = 0; n < context.Size(); n++)\n {\n const TestableInstance &instance = context[n];\n\n std::vector<std::wstring> tmpExpectedProperties;\n std::vector<std::wstring> tmpPossibleProperties;\n tmpExpectedProperties.push_back(L\"Caption\");\n tmpExpectedProperties.push_back(L\"Description\");\n tmpExpectedProperties.push_back(L\"Name\");\n tmpExpectedProperties.push_back(L\"CSCreationClassName\");\n tmpExpectedProperties.push_back(L\"CSName\");\n tmpExpectedProperties.push_back(L\"OSCreationClassName\");\n tmpExpectedProperties.push_back(L\"OSName\");\n tmpExpectedProperties.push_back(L\"CreationClassName\");\n tmpExpectedProperties.push_back(L\"Handle\");\n tmpExpectedProperties.push_back(L\"ExecutionState\");\n tmpExpectedProperties.push_back(L\"CreationDate\");\n tmpPossibleProperties.push_back(L\"TerminationDate\");\n tmpExpectedProperties.push_back(L\"KernelModeTime\");\n tmpExpectedProperties.push_back(L\"UserModeTime\");\n tmpExpectedProperties.push_back(L\"ParentProcessID\");\n tmpExpectedProperties.push_back(L\"RealUserID\");\n tmpExpectedProperties.push_back(L\"ProcessGroupID\");\n tmpExpectedProperties.push_back(L\"ProcessNiceValue\");\n tmpExpectedProperties.push_back(L\"Priority\");\n tmpExpectedProperties.push_back(L\"PercentBusyTime\");\n tmpExpectedProperties.push_back(L\"UsedMemory\");\n#if defined(hpux)\n tmpPossibleProperties.push_back(L\"ProcessSessionID\");\n#else\n tmpExpectedProperties.push_back(L\"ProcessSessionID\");\n#endif\n#if !(defined(linux) || defined(aix) || defined(sun))\n tmpExpectedProperties.push_back(L\"ProcessTTY\");\n#endif\n#if defined(linux)\n if (brokenProvider == true)\n {\n tmpPossibleProperties.push_back(L\"ModulePath\");\n tmpPossibleProperties.push_back(L\"Parameters\");\n }\n else\n {\n tmpExpectedProperties.push_back(L\"ModulePath\");\n tmpExpectedProperties.push_back(L\"Parameters\");\n }\n#else// linux\n#if defined(hpux) || defined(aix) || (defined(sun) && PF_MAJOR == 5 && PF_MINOR > 9)\n tmpPossibleProperties.push_back(L\"ModulePath\");\n#else\n tmpExpectedProperties.push_back(L\"ModulePath\");\n#endif\n tmpPossibleProperties.push_back(L\"Parameters\");\n#endif// linux\n#if !(defined(hpux) || defined(aix) || defined(sun))\n tmpPossibleProperties.push_back(L\"ProcessWaitingForEvent\");\n#endif\n\n VerifyInstancePropertyNames(instance, &tmpExpectedProperties[0], tmpExpectedProperties.size(),\n &tmpPossibleProperties[0], tmpPossibleProperties.size(), CALL_LOCATION(errMsg));\n }\n }\n\n void ValidateInstanceStatisticalInformation(const TestableContext& context, std::wstring errMsg)\n {\n for (size_t n = 0; n < context.Size(); n++)\n {\n const TestableInstance &instance = context[n];\n\n std::wstring tmpExpectedProperties[] = {\n L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"CSCreationClassName\",\n L\"CSName\",\n L\"OSCreationClassName\",\n L\"OSName\",\n L\"Handle\",\n L\"ProcessCreationClassName\",\n L\"CPUTime\",\n L\"VirtualData\",\n L\"CpuTimeDeadChildren\",\n L\"SystemTimeDeadChildren\",\n L\"PercentUserTime\",\n L\"PercentPrivilegedTime\",\n L\"UsedMemory\",\n L\"PercentUsedMemory\",\n#if !(defined(linux) || defined(sun) || defined(aix))\n L\"RealText\",\n L\"RealData\",\n L\"RealStack\",\n L\"VirtualMemoryMappedFileSize\",\n#endif\n#if !defined(aix)\n L\"VirtualText\",\n L\"PagesReadPerSec\",\n#endif\n#if !defined(linux)\n L\"VirtualStack\",\n#endif\n#if !(defined(sun) || defined(aix))\n L\"VirtualSharedMemory\",\n#endif\n#if !(defined(linux) || defined(aix))\n L\"BlockReadsPerSecond\",\n L\"BlockWritesPerSecond\",\n L\"BlockTransfersPerSecond\",\n#endif\n };\n\n const size_t numprops = sizeof(tmpExpectedProperties) / sizeof(tmpExpectedProperties[0]);\n VerifyInstancePropertyNames(instance, tmpExpectedProperties, numprops, CALL_LOCATION(errMsg));\n }\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXProcessProviderTest );\n" }, { "alpha_fraction": 0.6078066825866699, "alphanum_fraction": 0.6208178400993347, "avg_line_length": 26.58974266052246, "blob_id": "ef86d54e1276302af59b2798f278aac054f22a71", "content_id": "c8fc67508bf6210cfa6e1170fa5dbb0c352181d9", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1076, "license_type": "permissive", "max_line_length": 103, "num_lines": 39, "path": "/source/code/shared/tools/scx_prune_repository/commandlineparser.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n#\n##\n# Contains the command line parser\n#\n# Date: 2008-10-28 16:17:23\n#\n\nfrom optparse import OptionParser\n\n##\n# This class takes care of parsing the\n# command line parameters of the program\n#\nclass CommandLineParser(OptionParser):\n ##\n # Constructor does the parsing\n #\n def __init__(self):\n OptionParser.__init__(self, 'usage: %prog [options]')\n self.add_option(\"--cim_schema_dir\",\n type=\"string\",\n dest=\"cim_schema_dir\",\n help=\"Path to a directory housing all mof files of a complete cim repository.\")\n (options, self.arguments) = self.parse_args()\n self.cimSchemaDir = options.cim_schema_dir\n\n ##\n # Returns the value sent in as --cim_schema_dir\n #\n def getCIMSchemaDir(self):\n return self.cimSchemaDir\n\n ##\n # Returns a list of all arguments (except --cim_schema_dir)\n #\n def getArguments(self):\n return self.arguments\n" }, { "alpha_fraction": 0.6127923130989075, "alphanum_fraction": 0.6162310838699341, "avg_line_length": 35.349998474121094, "blob_id": "4062e4b1b5cfb38f139a201f7bab5951baaf3488", "content_id": "9c225886a8034d385cc633cc881376a8bc82d0a6", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2908, "license_type": "permissive", "max_line_length": 107, "num_lines": 80, "path": "/test/code/shared/tools/scx_prune_repository/moffile_test.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "import unittest\nimport os\nimport sys\nsys.path.append('../../../../source/code/tools/scx_prune_repository')\nfrom moffile import MofFile\n\nclass MofFileTestCase(unittest.TestCase):\n def setUp(self):\n pass\n \n def tearDown(self):\n try:\n os.remove('EmptyFile.mof')\n os.remove('FileWithNoDependentClasses.mof')\n os.remove('FileWithOneDependentClass.mof')\n os.remove('TwoSubClasses.mof')\n os.remove('SameFileDependency.mof')\n except OSError:\n pass\n \n def testNoSuchFile(self):\n moffile = MofFile('ThisFileShouldNotExist.mof')\n self.assertEqual(moffile.GetDependentClasses(), [])\n\n def testEmptyFile(self):\n open('EmptyFile.mof', 'w')\n moffile = MofFile('EmptyFile.mof')\n self.assertEqual(moffile.GetDependentClasses(), [])\n\n def testMofFileWithNoDependentClasses(self):\n out = open('FileWithNoDependentClasses.mof', 'w')\n out.write('class TestClass {\\n')\n out.write(' string Caption\\n')\n out.write('}')\n out.close()\n moffile = MofFile('FileWithNoDependentClasses.mof')\n self.assertEqual(moffile.GetDependentClasses(), [])\n\n def testMofFileWithOneDependentClass(self):\n out = open('FileWithOneDependentClass.mof', 'w')\n out.write('class TestClass : DependentClass {\\n')\n out.write(' string Caption\\n')\n out.write('}')\n out.close()\n moffile = MofFile('FileWithOneDependentClass.mof')\n self.assertEqual(moffile.GetDependentClasses(), ['DependentClass'])\n\n def testMofFileWithTwoClassesWithOneBaseClass(self):\n out = open('TwoSubClasses.mof', 'w')\n out.write('class SubClass1 : BaseClass {\\n')\n out.write('}')\n out.write('class SubClass2 : BaseClass {\\n')\n out.write('}')\n out.close()\n moffile = MofFile('TwoSubClasses.mof')\n self.assertEqual(moffile.GetDependentClasses(), ['BaseClass'])\n\n def testMofFileWithInterDependency(self):\n out = open('SameFileDependency.mof', 'w')\n out.write('class BaseClass {\\n')\n out.write('}')\n out.write('class SubClass2 : BaseClass {\\n')\n out.write('}')\n out.close()\n moffile = MofFile('SameFileDependency.mof')\n self.assertEqual(moffile.GetDependentClasses(), [])\n\n def testDefinedClasses(self):\n out = open('SameFileDependency.mof', 'w')\n out.write('class BaseClass {\\n')\n out.write('}')\n out.write('class SubClass1 : BaseClass {\\n')\n out.write('}')\n out.write('class SubClass2 : BaseClass {\\n')\n out.write('}')\n out.write('class SubClass3 : SubClass1 {\\n')\n out.write('}')\n out.close()\n moffile = MofFile('SameFileDependency.mof')\n self.assertEqual(moffile.GetDefinedClasses(), ['BaseClass', 'SubClass1', 'SubClass2', 'SubClass3'])\n" }, { "alpha_fraction": 0.5978352427482605, "alphanum_fraction": 0.6033673882484436, "avg_line_length": 33.21810531616211, "blob_id": "48c8fcdfa8db48a6ebe44486804d044dc91018b1", "content_id": "9e780d45a274968bcf935ad84217b09376773d7b", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8315, "license_type": "permissive", "max_line_length": 97, "num_lines": 243, "path": "/test/code/providers/logfile_provider/logfilereader_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the logfile reader (CLI program)\n\n \\date 2011-04-18 13:18:00\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <cppunit/extensions/HelperMacros.h>\n#include <testutils/scxunit.h>\n#include <scxcorelib/scxmarshal.h>\n#include <scxcorelib/scxprocess.h>\n#include <scxcorelib/stringaid.h>\n\n#include <string>\n\n// dynamic_cast fix - wi 11220\n#ifdef dynamic_cast\n#undef dynamic_cast\n#endif\n\nusing namespace std;\nusing namespace SCXCoreLib;\n\nclass LogFileReaderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( LogFileReaderTest );\n CPPUNIT_TEST( testDisplayVersion );\n CPPUNIT_TEST( testDisplayHelp );\n CPPUNIT_TEST( testDisplayShortHelp );\n CPPUNIT_TEST( testInvalidParameter );\n CPPUNIT_TEST( testParameterMarshaling );\n CPPUNIT_TEST( testParameterMarshalingWithManyMatches );\n\n SCXUNIT_TEST_ATTRIBUTE(testDisplayVersion, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testDisplayHelp, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testDisplayShortHelp, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testInvalidParameter, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testParameterMarshaling, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testParameterMarshalingWithManyMatches, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n wstring m_imageName;\n\npublic:\n LogFileReaderTest()\n {\n // We assume that 'scxlogfilereader' is in the path. This makes it\n // much easier to compare results, since the path to 'scxlogfilereader'\n // will be part of the output if path information was used to launch\n // the program.\n //\n // Modifed testrun framework to add base target directory to path.\n\n m_imageName = L\"scxlogfilereader\";\n }\n\n void setUp(void)\n {\n }\n\n void tearDown(void)\n {\n }\n\n void testDisplayVersion()\n {\n int returnCode;\n std::istringstream processInput;\n std::ostringstream processOutput;\n std::ostringstream processError;\n\n returnCode = SCXProcess::Run(StrAppend(m_imageName, L\" -v\"),\n processInput, processOutput, processError);\n\n CPPUNIT_ASSERT_EQUAL(string(\"\"), processError.str());\n CPPUNIT_ASSERT_EQUAL(0, returnCode);\n\n CPPUNIT_ASSERT_EQUAL(string(\"Version: \"),\n processOutput.str().substr(0, 9));\n }\n\n void testDisplayHelp()\n {\n int returnCode;\n std::istringstream processInput;\n std::ostringstream processOutput;\n std::ostringstream processError;\n\n returnCode = SCXProcess::Run(StrAppend(m_imageName, L\" -h\"),\n processInput, processOutput, processError);\n\n ostringstream expectedHelpText;\n expectedHelpText << \"Usage: scxlogfilereader\" << endl << endl\n << \"Options:\" << endl\n << \" -h:\\tDisplay detailed help information\" << endl\n << \" -g:\\tReset all log file states (for internal use only)\" << endl\n << \" \\t(Requires parameter for ResetOnRead: 1/true/0/false)\" << endl\n << \" -i:\\tInteractive use (for debugging purposes only)\" << endl\n << \" -m:\\tRun marshal unit tests (debugging purposes only)\" << endl\n << \" -p:\\tProvider interface (for internal use only)\" << endl\n << \" -r:\\tReset log file state (for internal use only)\" << endl\n << \" -t:\\tProvide hooks for testrunner environmental setup\" << endl\n << \" -v:\\tDisplay version information\" << endl;\n\n CPPUNIT_ASSERT_EQUAL(string(\"\"), processError.str());\n CPPUNIT_ASSERT_EQUAL(0, returnCode);\n\n CPPUNIT_ASSERT_EQUAL(expectedHelpText.str(), processOutput.str());\n }\n\n void testDisplayShortHelp()\n {\n int returnCode;\n std::istringstream processInput;\n std::ostringstream processOutput;\n std::ostringstream processError;\n\n returnCode = SCXProcess::Run(StrAppend(m_imageName, L\" -?\"),\n processInput, processOutput, processError);\n\n CPPUNIT_ASSERT_EQUAL(string(\"\"), processError.str());\n CPPUNIT_ASSERT_EQUAL(0, returnCode);\n\n CPPUNIT_ASSERT_EQUAL(\n string(\"scxlogfilereader: Try 'scxlogfilereader -h' for more information.\\n\"),\n processOutput.str());\n }\n\n void testInvalidParameter()\n {\n int returnCode;\n std::istringstream processInput;\n std::ostringstream processOutput;\n std::ostringstream processError;\n\n // Call with some invalid parameter ('-z' in this case)\n returnCode = SCXProcess::Run(StrAppend(m_imageName, L\" -z\"),\n processInput, processOutput, processError);\n\n CPPUNIT_ASSERT_EQUAL(string(\"scxlogfilereader: invalid option -- 'z'\\n\"),\n processError.str());\n CPPUNIT_ASSERT_EQUAL(64, returnCode);\n\n CPPUNIT_ASSERT_EQUAL(\n string(\"scxlogfilereader: Try 'scxlogfilereader -h' for more information.\\n\"),\n processOutput.str());\n }\n\n void internalTestParameterMarshaling(int matchedLinesCount)\n {\n // Marshal specific input for the log file reader\n\n int returnCode;\n std::stringstream processInput;\n std::stringstream processOutput;\n std::ostringstream processError;\n\n std::wstring filename(L\"This_is_a_random_filename\");\n std::wstring qid(L\"This_is_a_random_QID\");\n vector<SCXRegexWithIndex> regexps;\n\n for (int i=0; i < 10; i++)\n {\n SCXRegexWithIndex regind;\n regind.regex = new SCXRegex(StrAppend(L\"Regular expression number \", i));\n regind.index = i;\n regexps.push_back(regind);\n }\n\n Marshal send(processInput);\n send.Write(filename);\n send.Write(qid);\n send.Write(regexps);\n send.Write(matchedLinesCount);\n send.Flush();\n\n // Call the logfilereader with the marshal test flag\n returnCode = SCXProcess::Run(StrAppend(m_imageName, L\" -m\"),\n processInput, processOutput, processError);\n\n CPPUNIT_ASSERT_EQUAL(0, returnCode);\n\n // UnMarshal the results and validate\n\n std::wstring retFilename, retQid;\n vector<SCXRegexWithIndex> retRegexps;\n int wasPartialRead;\n int retMatchedLinesCount;\n vector<std::wstring> matchedLines;\n\n UnMarshal receive(processOutput);\n receive.Read(retFilename);\n receive.Read(retQid);\n receive.Read(retRegexps);\n receive.Read(retMatchedLinesCount);\n receive.Read(wasPartialRead);\n receive.Read(matchedLines);\n\n CPPUNIT_ASSERT_EQUAL(StrToMultibyte(filename), StrToMultibyte(retFilename));\n CPPUNIT_ASSERT_EQUAL(StrToMultibyte(qid), StrToMultibyte(retQid));\n\n CPPUNIT_ASSERT_EQUAL(regexps.size(), retRegexps.size());\n for (size_t i=0; i < regexps.size(); i++)\n {\n CPPUNIT_ASSERT_EQUAL(regexps[i].index, retRegexps[i].index);\n CPPUNIT_ASSERT(regexps[i].regex->Get() == retRegexps[i].regex->Get());\n }\n\n CPPUNIT_ASSERT_EQUAL(65536, wasPartialRead);\n\n CPPUNIT_ASSERT_EQUAL(matchedLinesCount, retMatchedLinesCount);\n CPPUNIT_ASSERT_EQUAL(static_cast<size_t> (matchedLinesCount), matchedLines.size());\n for (int i=0; i < matchedLinesCount; i++)\n {\n std::stringstream ss;\n ss << \"This is entry number \" << i << \" in the vector\";\n CPPUNIT_ASSERT_EQUAL(ss.str(), StrToMultibyte(matchedLines[i]));\n }\n }\n\n void testParameterMarshaling()\n {\n // Use a small number of returned matched lines\n internalTestParameterMarshaling(20);\n }\n\n void testParameterMarshalingWithManyMatches()\n {\n // Use a large number of returned matched lines\n internalTestParameterMarshaling(10000);\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( LogFileReaderTest );\n" }, { "alpha_fraction": 0.6445807814598083, "alphanum_fraction": 0.6473470330238342, "avg_line_length": 43.859405517578125, "blob_id": "3329758079d615a80d3c7f101b20a1c467f856be", "content_id": "ae61e8c17434490d6837c23194e6f95840d7118f", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 67962, "license_type": "permissive", "max_line_length": 119, "num_lines": 1515, "path": "/test/code/providers/appserver_provider/persistappserverinstances_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. \n \n */\n/**\n \\file persistappserverinstances_test.cpp\n\n \\brief Tests the persistence of application servers\n\n \\date 11-05-19 12:00:00\n\n */\n/*-----------------------------------------------------------------*/\n\n#include <sys/wait.h>\n#if defined(aix)\n#include <unistd.h>\n#endif\n#include <string>\n\n#include <testutils/scxunit.h>\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxpersistence.h>\n#include <scxcorelib/stringaid.h>\n\n#include \"source/code/scxcorelib/util/persist/scxfilepersistmedia.h\"\n\n#include \"appserverconstants.h\"\n#include \"appserverinstance.h\"\n#include \"weblogicappserverinstance.h\"\n#include \"websphereappserverinstance.h\"\n#include \"persistappserverinstances.h\"\n#include \"removenonexistentappserverinstances.h\"\n\n/*\n * dynamic_cast fix - wi 11220\n * Using this fix because this unit-test is very\n * similar to the scxpersistence_test.cpp. This\n * unit-test requires this fix, see WI for details.\n */\n#ifdef dynamic_cast\n#undef dynamic_cast\n#endif\n\nusing namespace std;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXUnitTests\n{\n const static std::wstring JBOSS_SIMPLE_PATH = L\"/opt/jboss/jboss-5.1.0/default/\";\n\n const static std::wstring JBOSS_SIMPLE_HTTP_PORT = L\"8080\";\n\n const static std::wstring JBOSS_SIMPLE_HTTPS_PORT = L\"8443\";\n\n const static std::wstring JBOSS_SIMPLE_PROTOCOL = PROTOCOL_HTTP;\n\n const static std::wstring JBOSS_SIMPLE_TYPE = APP_SERVER_TYPE_JBOSS;\n\n const static std::wstring JBOSS_SIMPLE_VERSION = L\"5.1.0-GA\";\n\n const static std::wstring JBOSS_WITH_SPACE_PATH = L\"/opt/jboss app server/jboss-5.1.0/default number one/\";\n\n const static std::wstring JBOSS_WITH_SPACE_HTTP_PORT = L\"8081\";\n\n const static std::wstring JBOSS_WITH_SPACE_HTTPS_PORT = L\"8444\";\n\n const static std::wstring JBOSS_WITH_SPACE_PROTOCOL = PROTOCOL_HTTP;\n\n const static std::wstring JBOSS_WITH_SPACE_TYPE = APP_SERVER_TYPE_JBOSS;\n\n const static std::wstring JBOSS_WITH_SPACE_VERSION = L\"5.1.1-GA\";\n\n const static std::wstring JBOSS_NOT_RUNNING_PATH = L\"/opt/jbossNotRunning/jboss-5.1.0/default/\";\n\n const static std::wstring JBOSS_NOT_RUNNING_HTTP_PORT = L\"8082\";\n\n const static std::wstring JBOSS_NOT_RUNNING_HTTPS_PORT = L\"8445\";\n\n const static std::wstring JBOSS_NOT_RUNNING_PROTOCOL = PROTOCOL_HTTP;\n\n const static std::wstring JBOSS_NOT_RUNNING_TYPE = APP_SERVER_TYPE_JBOSS;\n\n const static std::wstring JBOSS_NOT_RUNNING_VERSION = L\"5.1.2-GA\";\n\n const static std::wstring WEBSPHERE_PATH = L\"/opt/websphere/AppServer/profiles/AppSrv01/\";\n\n const static std::wstring WEBSPHERE_ID = L\"AppSrv01-Node01Cell-Node01-server1\";\n\n const static std::wstring WEBSPHERE_HTTP_PORT = L\"9080\";\n\n const static std::wstring WEBSPHERE_HTTPS_PORT = L\"9443\";\n\n const static std::wstring WEBSPHERE_PROTOCOL = PROTOCOL_HTTP;\n\n const static std::wstring WEBSPHERE_TYPE = APP_SERVER_TYPE_WEBSPHERE;\n\n const static std::wstring WEBSPHERE_VERSION = L\"7.0.0.0\";\n\n const static std::wstring WEBSPHERE_PROFILE = L\"AppSrv01\";\n\n const static std::wstring WEBSPHERE_CELL = L\"Node01Cell\";\n\n const static std::wstring WEBSPHERE_NODE = L\"Node01\";\n\n const static std::wstring WEBSPHERE_SERVER = L\"server1\";\n\n const static std::wstring WEBLOGIC_PATH = L\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain/\";\n\n const static std::wstring WEBLOGIC_ID = L\"/opt/Oracle/WebLogic-11/Middleware/user_projects/domains/base_domain/\";\n\n const static std::wstring WEBLOGIC_HTTP_PORT = L\"7011\";\n\n const static std::wstring WEBLOGIC_HTTPS_PORT = L\"7012\";\n\n const static std::wstring WEBLOGIC_PROTOCOL = PROTOCOL_HTTP;\n\n const static std::wstring WEBLOGIC_TYPE = APP_SERVER_TYPE_WEBLOGIC;\n\n const static std::wstring WEBLOGIC_VERSION = L\"10.3.2.0\";\n\n const static std::wstring WEBLOGIC_SERVER = WEBLOGIC_SERVER_TYPE_ADMIN;\n\n/*\n * Mock implementation of the real PersistAppServerInstances\n * class. This implementation allows for the overriding of some \n * functionality. For instance, this object will not remove any\n * instances because they could not be found on disk.\n * \n */\nclass MockPersistAppServerInstances: \n public SCXSystemLib::PersistAppServerInstances\n{\n\npublic:\n\n /*\n * Default constructor (no args)\n */\n MockPersistAppServerInstances() :\n PersistAppServerInstances()\n {\n }\n\n /*-----------------------------------------------------------------*/\n /**\n Constructor where the path of to write persisted output to disk\n */\n MockPersistAppServerInstances(const SCXFilePath& directory)\n {\n // Need to convert a handle of the SCXPersistMedia to\n // a type of SCXFilePersistMedia\n SCXHandle<SCXPersistMedia> physicalTestMedia;\n physicalTestMedia = GetPersistMedia();\n SCXFilePersistMedia\n * m =\n dynamic_cast<SCXFilePersistMedia*> (physicalTestMedia.GetData());\n m->SetBasePath(directory);\n m_pmedia = physicalTestMedia;\n }\n \n /*-----------------------------------------------------------------------*/\n /*\n * Overriden Function from Base Class\n * \n * For unit-tests, this class will make it look like all instances \n * can be found on disk\n */\n void RemoveNonExistentInstances(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& /* instances*/,\n SCXSystemLib::RemoveNonexistentAppServerInstances)\n {\n // Do nothing (i.e. do not remove any instances)\n }\n};\n \n /*\n * Mock implementation of the real PersistAppServerInstances\n * class. This object will remove all instances because they \n * could not be found on disk.\n */\n class MockPersistAppServerInstancesWithNothingOnDisk: \n public SCXSystemLib::PersistAppServerInstances\n {\n\n public:\n /*\n * Default constructor (no args)\n */\n MockPersistAppServerInstancesWithNothingOnDisk() :\n PersistAppServerInstances()\n {\n }\n\n /*-----------------------------------------------------------------*/\n /**\n Constructor where the path of to write persisted output to disk\n */\n MockPersistAppServerInstancesWithNothingOnDisk(const SCXFilePath& directory)\n {\n // Need to convert a handle of the SCXPersistMedia to\n // a type of SCXFilePersistMedia\n SCXHandle<SCXPersistMedia> physicalTestMedia;\n physicalTestMedia = GetPersistMedia();\n SCXFilePersistMedia\n * m =\n dynamic_cast<SCXFilePersistMedia*> (physicalTestMedia.GetData());\n m->SetBasePath(directory);\n m_pmedia = physicalTestMedia;\n }\n \n /*-----------------------------------------------------------------------*/\n /*\n * Overriden Function from Base Class\n * \n * For unit-tests, this class will make it look like all instances \n * can NOT be found on disk.\n */\n void RemoveNonExistentInstances(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& instances,\n SCXSystemLib::RemoveNonexistentAppServerInstances)\n {\n instances.clear();\n }\n };\n\n/*\n * The Unit Test class for PersistAppServerInstances.\n * This extends the CPPUNIT (because it is a unit test) and\n * PersistAppServerInstances (because access is needed to \n * the protected method GetPersistedAppServerName()).\n */\nclass PersistAppServerInstancesTest: public CPPUNIT_NS::TestFixture,\n public SCXSystemLib::PersistAppServerInstances\n{\n CPPUNIT_TEST_SUITE( PersistAppServerInstancesTest);\n CPPUNIT_TEST( TestRemovingNonExistentItemsRemovesNothing );\n CPPUNIT_TEST( TestRemovingNonExistentItemsRemovesEverything );\n CPPUNIT_TEST( TestReadingNonExistentCache );\n CPPUNIT_TEST( TestReadingEmptyCache );\n CPPUNIT_TEST( TestReadingSingleEntryCache );\n CPPUNIT_TEST( TestReadingSingleEntryCacheWithEmptyHttpPort );\n CPPUNIT_TEST( TestReadingMultiEntryCache );\n CPPUNIT_TEST( TestReadingMultiEntryCacheButAllEntriesAreDeleted );\n CPPUNIT_TEST( TestReadingMangledCacheHasWrongPositiveNumber );\n CPPUNIT_TEST( TestReadingMangledCacheHasWrongNegativeNumber );\n CPPUNIT_TEST( TestReadingMangledCacheMissingProperty );\n CPPUNIT_TEST( TestReadingMangledCacheHasMissingInstance );\n CPPUNIT_TEST( TestPersistingInstancesArraySizeZero);\n CPPUNIT_TEST( TestPersistingInstancesArraySizeOne);\n CPPUNIT_TEST( TestPersistingInstancesArraySizeFour);\n CPPUNIT_TEST( TestUnpersistingInstancesArraySizeZeroForNoPreviousWrite );\n CPPUNIT_TEST( TestUnpersistingInstancesArraySizeZeroForPreviousWrite );\n CPPUNIT_TEST( TestReadingSingleEntryCache_WebSphere );\n CPPUNIT_TEST( TestReadingSingleEntryCache_WebLogic );\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n /*\n * Overriden location of where to persist data\n */\n SCXFilePath m_path;\n\n /*\n * Directly read the persisted media for verification\n */\n SCXHandle<SCXPersistMedia> m_pmedia;\n\npublic:\n /*\n * Default constructor\n */\n PersistAppServerInstancesTest(void)\n {\n m_path = SCXFilePath(L\"./\");\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Unit Test Setup: run before each test\n */\n void setUp(void)\n {\n m_pmedia = GetPersistMedia();\n SCXCoreLib::SCXFilePersistMedia* m =\n dynamic_cast<SCXCoreLib::SCXFilePersistMedia*> (m_pmedia.GetData());\n CPPUNIT_ASSERT(m != 0);\n m->SetBasePath(m_path);\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Unit Test Teardown: run after each test\n * \n */\n void tearDown(void)\n {\n UnpersistAllInstances();\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a plain, vanilla instance of JBoss\n */\n SCXHandle<AppServerInstance> createPlainRunningJBossInstance(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_SIMPLE_PATH,\n JBOSS_SIMPLE_TYPE));\n instance->SetHttpPort(JBOSS_SIMPLE_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_SIMPLE_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_SIMPLE_PROTOCOL);\n instance->SetIsRunning(true);\n instance->SetVersion(JBOSS_SIMPLE_VERSION);\n\n return instance;\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a instance of WebSphere\n */\n SCXHandle<AppServerInstance> createWebSphereInstance(void)\n {\n SCXHandle<WebSphereAppServerInstance> instance(\n new WebSphereAppServerInstance (\n WEBSPHERE_ID, WEBSPHERE_CELL, WEBSPHERE_NODE, WEBSPHERE_PROFILE, WEBSPHERE_SERVER));\n instance->SetDiskPath(WEBSPHERE_PATH);\n instance->SetHttpPort(WEBSPHERE_HTTP_PORT);\n instance->SetHttpsPort(WEBSPHERE_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, WEBSPHERE_PROTOCOL);\n instance->SetIsRunning(false);\n instance->SetVersion(WEBSPHERE_VERSION);\n\n return instance;\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a instance of WebLogic\n */\n SCXHandle<AppServerInstance> createWebLogicInstance(void)\n {\n SCXHandle<AppServerInstance> instance(new WebLogicAppServerInstance(WEBLOGIC_ID));\n instance->SetDiskPath(WEBLOGIC_PATH);\n instance->SetHttpPort(WEBLOGIC_HTTP_PORT);\n instance->SetHttpsPort(WEBLOGIC_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, WEBLOGIC_PROTOCOL);\n instance->SetIsRunning(false);\n instance->SetVersion(WEBLOGIC_VERSION);\n instance->SetServer(WEBLOGIC_SERVER);\n return instance;\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a JBoss instance with a space in the path that is not running.\n * This is the same as the other JBoss instance with a space, but not running\n * (i.e. represent data from a cache)\n */\n SCXHandle<AppServerInstance> createNotRunningJBossInstanceWithSpaceInPath(void)\n {\n SCXHandle<AppServerInstance> instance(\n createRunningJBossInstanceWithSpaceInPath());\n instance->SetIsRunning(false);\n return instance;\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a JBoss instance with a space in the path that is running\n */\n SCXHandle<AppServerInstance> createRunningJBossInstanceWithSpaceInPath(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_WITH_SPACE_PATH,\n JBOSS_WITH_SPACE_TYPE));\n instance->SetHttpPort(JBOSS_WITH_SPACE_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_WITH_SPACE_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_WITH_SPACE_PROTOCOL);\n instance->SetIsRunning(true);\n instance->SetVersion(JBOSS_WITH_SPACE_VERSION);\n\n return instance;\n }\n\n \n /*-----------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Create a JBoss instance that is not running\n */\n SCXHandle<AppServerInstance> createJBossInstanceNotRunning(void)\n {\n SCXHandle<AppServerInstance> instance(\n new AppServerInstance (\n JBOSS_NOT_RUNNING_PATH,\n JBOSS_NOT_RUNNING_TYPE));\n instance->SetHttpPort(JBOSS_NOT_RUNNING_HTTP_PORT);\n instance->SetHttpsPort(JBOSS_NOT_RUNNING_HTTPS_PORT);\n instance->SetIsDeepMonitored(true, JBOSS_NOT_RUNNING_PROTOCOL);\n instance->SetIsRunning(false);\n instance->SetVersion(JBOSS_NOT_RUNNING_VERSION);\n\n return instance;\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Helper Method\n * \n * Use the underlying persistence framework to remove\n * any persisted data that would have been created during\n * the unit-test.\n */\n void UnpersistAllInstances(void)\n {\n try\n {\n m_pmedia->UnPersist(APP_SERVER_PROVIDER);\n }\n catch (PersistDataNotFoundException&)\n {\n // Ignore.\n }\n }\n\n /*\n * Verify that the mocked out implementation of removing\n * non-existent application servers works as expected. This\n * really tests the test code, but it it is broken then\n * other tests will fail that depend on this fake functionality.\n * \n * The expect behavior is that all of the application servers\n * are found on disk and thus the returned list of instances is unchanged.\n */\n void TestRemovingNonExistentItemsRemovesNothing(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n\n vector<SCXHandle<AppServerInstance> > instances;\n instances.push_back(createPlainRunningJBossInstance());\n instances.push_back(createRunningJBossInstanceWithSpaceInPath());\n instances.push_back(createJBossInstanceNotRunning());\n\n size_t checkSize = 3;\n CPPUNIT_ASSERT_EQUAL(checkSize, instances.size());\n\n // Run the Test\n RemoveNonexistentAppServerInstances unusedRemover;\n CPPUNIT_ASSERT_NO_THROW(\n sut->RemoveNonExistentInstances(instances, unusedRemover));\n \n // Verify that the mock implementation does not remove any of the \n // instances because the necessary method has been overridden to\n // always think that items are on disk.\n CPPUNIT_ASSERT_EQUAL(checkSize, instances.size());\n }\n\n /*\n * Verify that the mocked out implementation of removing\n * non-existent application servers works as expected. This\n * really tests the test code, but it it is broken then\n * other tests will fail that depend on this fake functionality.\n * \n * The expect behavior is that none of the application servers\n * are found on disk and thus the returned list of instances is empty.\n */\n void TestRemovingNonExistentItemsRemovesEverything(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstancesWithNothingOnDisk> sut( \n new MockPersistAppServerInstancesWithNothingOnDisk(m_path) );\n\n vector<SCXHandle<AppServerInstance> > instances;\n instances.push_back(createPlainRunningJBossInstance());\n instances.push_back(createRunningJBossInstanceWithSpaceInPath());\n instances.push_back(createJBossInstanceNotRunning());\n\n size_t three = 3;\n CPPUNIT_ASSERT_EQUAL(three, instances.size());\n\n // Run the Test\n RemoveNonexistentAppServerInstances unusedRemover;\n CPPUNIT_ASSERT_NO_THROW(\n sut->RemoveNonExistentInstances(instances, unusedRemover));\n \n // Verify that the mock implementation does not remove any of the \n // instances because the necessary method has been overridden to\n // always think that items are on disk.\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL(zero, instances.size());\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Verify no errors are thrown if reading an empty cache\n */\n void TestReadingEmptyCache(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n pwriter->WriteStartGroup(APP_SERVER_METADATA);\n pwriter->WriteValue(APP_SERVER_NUMBER, L\"0\");\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array is STILL empty\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n }\n \n /*-----------------------------------------------------------------*/\n /*\n * Verify no errors are thrown if reading a non-existent cache\n */\n void TestReadingNonExistentCache(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // This is run as part of the setup, but re-run just to be sure\n UnpersistAllInstances();\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array is STILL empty\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Verify the reading the cache behaves as expected if corrupted.\n * If it cannot be read, then assume it is corrupt and disregard the cache.\n *\n * In this case the cache looks right, but someone has adjust the number\n * of instances to be a number larger than the actual number of written\n * in the persistent store.\n */\n void TestReadingMangledCacheHasWrongPositiveNumber(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteStartGroup(APP_SERVER_METADATA));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_NUMBER, L\"8\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_WITH_SPACE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_WITH_SPACE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_WITH_SPACE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_WITH_SPACE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_WITH_SPACE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_WITH_SPACE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 0\n \n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_SIMPLE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 1\n\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n //CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n sut->ReadFromDisk(readInstances);\n\n // Test Verification\n // Verify after the call nothing was returned\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Verify the reading the cache behaves as expected if corrupted.\n * If it cannot be read, then assume it is corrupt and disregard the cache.\n *\n * In this case the cache looks right, but someone has adjust the number\n * of instances to be a negative number. \n */\n void TestReadingMangledCacheHasWrongNegativeNumber(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteStartGroup(APP_SERVER_METADATA));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_NUMBER, L\"-1\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_SIMPLE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 0\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n //CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n sut->ReadFromDisk(readInstances);\n\n // Test Verification\n // Verify after the call the test that the array has one entry\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Verify the reading the cache behaves as expected if corrupted.\n * If it cannot be read, then assume it is corrupt and disregard the cache.\n *\n * In this case the cache looks right, but someone has remove a property.\n * In theory any property should do, so this test has chosen HTTP PORT.\n */\n void TestReadingMangledCacheMissingProperty(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteStartGroup(APP_SERVER_METADATA));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_NUMBER, L\"1\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_SIMPLE_PATH);\n // Purposely NOT writing HTTP PORT\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 0\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n //CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n sut->ReadFromDisk(readInstances);\n\n // Test Verification\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n }\n\n \n /*-----------------------------------------------------------------*/\n /*\n * Verify the reading the cache behaves reasonable well if the cache\n * has been corrupted. In this case, some nefarious person has\n * overwritten the number of instances to contain a number less\n * than the number of values in the cache.\n */\n void TestReadingMangledCacheHasMissingInstance(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( \n new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteStartGroup(APP_SERVER_METADATA));\n // this should be 2, but someone lied and made it one\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_NUMBER, L\"1\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteStartGroup(APP_SERVER_INSTANCE));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_ID, JBOSS_SIMPLE_PATH));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_SIMPLE_HTTP_PORT));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true)));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_PROFILE, L\"\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_CELL, L\"\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_NODE, L\"\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_SERVER, L\"\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing this instance 0\n\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteStartGroup(APP_SERVER_INSTANCE));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_NOT_RUNNING_PATH));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_ID, JBOSS_NOT_RUNNING_PATH));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_NOT_RUNNING_HTTP_PORT));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_NOT_RUNNING_HTTPS_PORT));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true)));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_NOT_RUNNING_TYPE));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_NOT_RUNNING_VERSION));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_PROFILE, L\"\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_CELL, L\"\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_NODE, L\"\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteValue(APP_SERVER_SERVER, L\"\"));\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing this instance 1\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n \n // Test Verification\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n }\n\n \n /*-----------------------------------------------------------------*/\n /*\n * Verify no errors are thrown if reading a single entry cache\n * with some fairly bland data.\n */\n void TestReadingSingleEntryCache(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n pwriter->WriteStartGroup(APP_SERVER_METADATA);\n pwriter->WriteValue(APP_SERVER_NUMBER, L\"1\");\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_SIMPLE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_SIMPLE_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 0\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array has one entry\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, readInstances.size());\n \n // Verify that data is correct\n SCXHandle<AppServerInstance> inst = readInstances[0];\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == inst->GetId());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == inst->GetDiskPath());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTP_PORT == inst->GetHttpPort());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTPS_PORT == inst->GetHttpsPort());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PROTOCOL == inst->GetProtocol());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTP_PORT == inst->GetPort());\n CPPUNIT_ASSERT(true == inst->GetIsDeepMonitored());\n CPPUNIT_ASSERT(false == inst->GetIsRunning());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_TYPE == inst->GetType());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_VERSION == inst->GetVersion());\n CPPUNIT_ASSERT(L\"\" == inst->GetProfile());\n CPPUNIT_ASSERT(L\"\" == inst->GetCell());\n CPPUNIT_ASSERT(L\"\" == inst->GetNode());\n CPPUNIT_ASSERT(L\"\" == inst->GetServer());\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Verify no errors are thrown if reading a single entry cache\n * with some fairly bland data without the Id & WebSphere data saved.\n */\n void TestReadingSingleEntryCacheWithoutWebSphereData(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n pwriter->WriteStartGroup(APP_SERVER_METADATA);\n pwriter->WriteValue(APP_SERVER_NUMBER, L\"1\");\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_SIMPLE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_SIMPLE_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION);\n pwriter->WriteEndGroup(); // Closing this instance 0\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array has one entry\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, readInstances.size());\n \n // Verify that data is correct\n SCXHandle<AppServerInstance> inst = readInstances[0];\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == inst->GetId());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == inst->GetDiskPath());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTP_PORT == inst->GetHttpPort());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTPS_PORT == inst->GetHttpsPort());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PROTOCOL == inst->GetProtocol());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTP_PORT == inst->GetPort());\n CPPUNIT_ASSERT(true == inst->GetIsDeepMonitored());\n CPPUNIT_ASSERT(false == inst->GetIsRunning());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_TYPE == inst->GetType());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_VERSION == inst->GetVersion());\n CPPUNIT_ASSERT(L\"\" == inst->GetProfile());\n CPPUNIT_ASSERT(L\"\" == inst->GetCell());\n CPPUNIT_ASSERT(L\"\" == inst->GetNode());\n CPPUNIT_ASSERT(L\"\" == inst->GetServer());\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Verify no errors are thrown if reading a single entry cache\n * with some fairly bland data. What is interesting is that the\n * HTTP Port is empty.\n */\n void TestReadingSingleEntryCacheWithEmptyHttpPort(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n pwriter->WriteStartGroup(APP_SERVER_METADATA);\n pwriter->WriteValue(APP_SERVER_NUMBER, L\"1\");\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, L\"\");\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_SIMPLE_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 0\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array has one entry\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, readInstances.size());\n \n // Verify that data is correct\n SCXHandle<AppServerInstance> inst = readInstances[0];\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == inst->GetDiskPath());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == inst->GetId());\n CPPUNIT_ASSERT(L\"\" == inst->GetHttpPort());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTPS_PORT == inst->GetHttpsPort());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PROTOCOL == inst->GetProtocol());\n CPPUNIT_ASSERT(L\"\" == inst->GetPort());\n CPPUNIT_ASSERT(true == inst->GetIsDeepMonitored());\n CPPUNIT_ASSERT(false == inst->GetIsRunning());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_TYPE == inst->GetType());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_VERSION == inst->GetVersion());\n }\n\n /*\n * Verify no errors are thrown if reading a multiple entries from cache.\n */\n void TestReadingMultiEntryCache(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n pwriter->WriteStartGroup(APP_SERVER_METADATA);\n pwriter->WriteValue(APP_SERVER_NUMBER, L\"3\");\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_SIMPLE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_SIMPLE_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 0\n \n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_NOT_RUNNING_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_NOT_RUNNING_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_NOT_RUNNING_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_NOT_RUNNING_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_NOT_RUNNING_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_NOT_RUNNING_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_NOT_RUNNING_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 1\n\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_WITH_SPACE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_WITH_SPACE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_WITH_SPACE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_WITH_SPACE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_WITH_SPACE_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_WITH_SPACE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_WITH_SPACE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 2\n\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array has one entry\n size_t three = 3;\n CPPUNIT_ASSERT_EQUAL( three, readInstances.size());\n \n // Verify that data is correct\n SCXHandle<AppServerInstance> inst = readInstances[0];\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == inst->GetDiskPath());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == inst->GetId());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTP_PORT == inst->GetHttpPort());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTPS_PORT == inst->GetHttpsPort());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PROTOCOL == inst->GetProtocol());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTP_PORT == inst->GetPort());\n CPPUNIT_ASSERT(true == inst->GetIsDeepMonitored());\n CPPUNIT_ASSERT(false == inst->GetIsRunning());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_TYPE == inst->GetType());\n CPPUNIT_ASSERT(JBOSS_SIMPLE_VERSION == inst->GetVersion());\n \n inst = readInstances[1];\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_PATH == inst->GetDiskPath());\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_PATH == inst->GetId());\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_HTTP_PORT == inst->GetHttpPort());\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_HTTPS_PORT == inst->GetHttpsPort());\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_PROTOCOL == inst->GetProtocol());\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_HTTP_PORT == inst->GetPort());\n CPPUNIT_ASSERT(true == inst->GetIsDeepMonitored());\n CPPUNIT_ASSERT(false == inst->GetIsRunning());\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_TYPE == inst->GetType());\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_VERSION == inst->GetVersion());\n\n inst = readInstances[2];\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_PATH == inst->GetDiskPath());\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_PATH == inst->GetId());\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_HTTP_PORT == inst->GetHttpPort());\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_HTTPS_PORT == inst->GetHttpsPort());\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_PROTOCOL == inst->GetProtocol());\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_HTTP_PORT == inst->GetPort());\n CPPUNIT_ASSERT(true == inst->GetIsDeepMonitored());\n CPPUNIT_ASSERT(false == inst->GetIsRunning());\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_TYPE == inst->GetType());\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_VERSION == inst->GetVersion());\n }\n \n /**\n * This unit test has a version of the cache that has entries, but\n * thinks that none of them are on disk. Thus the list of items\n * returned from the cache is empty.\n */\n void TestReadingMultiEntryCacheButAllEntriesAreDeleted(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstancesWithNothingOnDisk> sut(\n new MockPersistAppServerInstancesWithNothingOnDisk(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = \n m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n pwriter->WriteStartGroup(APP_SERVER_METADATA);\n pwriter->WriteValue(APP_SERVER_NUMBER, L\"3\");\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_SIMPLE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_SIMPLE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_SIMPLE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_SIMPLE_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_SIMPLE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_SIMPLE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 0\n \n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_NOT_RUNNING_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_NOT_RUNNING_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_NOT_RUNNING_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_NOT_RUNNING_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_NOT_RUNNING_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_NOT_RUNNING_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_NOT_RUNNING_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 1\n\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, JBOSS_WITH_SPACE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, JBOSS_WITH_SPACE_PATH);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, JBOSS_WITH_SPACE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, JBOSS_WITH_SPACE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, JBOSS_WITH_SPACE_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, JBOSS_WITH_SPACE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, JBOSS_WITH_SPACE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, L\"\");\n pwriter->WriteValue(APP_SERVER_CELL, L\"\");\n pwriter->WriteValue(APP_SERVER_NODE, L\"\");\n pwriter->WriteValue(APP_SERVER_SERVER, L\"\");\n pwriter->WriteEndGroup(); // Closing this instance 2\n\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array has one entry\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Persisting a list of zero application servers should succeed\n * without any errors, but nothing will happen on disk.\n */\n void TestPersistingInstancesArraySizeZero(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > zeroInstances;\n \n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, zeroInstances.size());\n \n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->WriteToDisk(zeroInstances));\n \n // Test Verification\n SCXHandle<SCXPersistDataReader> preader;\n CPPUNIT_ASSERT_NO_THROW(\n preader = m_pmedia->CreateReader(APP_SERVER_PROVIDER));\n\n // Verify number of entries\n CPPUNIT_ASSERT(preader->ConsumeStartGroup(APP_SERVER_METADATA));\n CPPUNIT_ASSERT(L\"0\" == preader->ConsumeValue(APP_SERVER_NUMBER));\n CPPUNIT_ASSERT(preader->ConsumeEndGroup(true)); // APP_SERVER_METADATA\n\n // Verify there is nothing else\n CPPUNIT_ASSERT_THROW(\n m_pmedia->CreateReader(L\"0\"), \n PersistDataNotFoundException);\n }\n\n /*\n * Given a list of one application server to persist that\n * is a real instance, verify that said information is persisted\n * to the disk.\n */\n void TestPersistingInstancesArraySizeOne(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n\n vector<SCXHandle<AppServerInstance> > oneInstance;\n oneInstance.push_back(createPlainRunningJBossInstance());\n\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL(one, oneInstance.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->WriteToDisk(oneInstance));\n\n //Test Verification\n SCXHandle<SCXPersistDataReader> preader;\n CPPUNIT_ASSERT_NO_THROW(\n preader = m_pmedia->CreateReader(APP_SERVER_PROVIDER)\n );\n\n // Verify number of entries\n CPPUNIT_ASSERT(preader->ConsumeStartGroup(APP_SERVER_METADATA));\n CPPUNIT_ASSERT(L\"1\" == preader->ConsumeValue(APP_SERVER_NUMBER));\n CPPUNIT_ASSERT(preader->ConsumeEndGroup(true)); // APP_SERVER_METADATA\n\n // Verify the only entry\n CPPUNIT_ASSERT(preader->ConsumeStartGroup(APP_SERVER_INSTANCE));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == preader->ConsumeValue(APP_SERVER_DISK_PATH));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == preader->ConsumeValue(APP_SERVER_ID));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTP_PORT == preader->ConsumeValue(APP_SERVER_HTTP_PORT));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTPS_PORT == preader->ConsumeValue(APP_SERVER_HTTPS_PORT));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PROTOCOL == preader->ConsumeValue(APP_SERVER_PROTOCOL));\n CPPUNIT_ASSERT(L\"1\" == preader->ConsumeValue(APP_SERVER_IS_DEEP_MONITORED));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_TYPE == preader->ConsumeValue(APP_SERVER_TYPE));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_VERSION == preader->ConsumeValue(APP_SERVER_VERSION));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_PROFILE));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_CELL));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_NODE));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_SERVER));\n CPPUNIT_ASSERT(preader->ConsumeEndGroup(true)); // JBOSS_SIMPLE_PATH\n \n CPPUNIT_ASSERT_THROW(\n m_pmedia->CreateReader(L\"1\"), \n PersistDataNotFoundException);\n }\n\n /*\n * Given a list of four application server to persist that\n * is a real instance, verify that said information is persisted\n * to the disk.\n */\n void TestPersistingInstancesArraySizeFour(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n\n vector<SCXHandle<AppServerInstance> > instances;\n instances.push_back(createPlainRunningJBossInstance());\n instances.push_back(createRunningJBossInstanceWithSpaceInPath());\n instances.push_back(createJBossInstanceNotRunning());\n instances.push_back(createWebSphereInstance());\n\n size_t checkSize = 4;\n CPPUNIT_ASSERT_EQUAL(checkSize, instances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->WriteToDisk(instances));\n\n //Test Verification\n SCXHandle<SCXPersistDataReader> preader;\n CPPUNIT_ASSERT_NO_THROW(\n preader = m_pmedia->CreateReader(APP_SERVER_PROVIDER)\n );\n \n // Verify number of entries\n CPPUNIT_ASSERT(preader->ConsumeStartGroup(APP_SERVER_METADATA));\n CPPUNIT_ASSERT(L\"4\" == preader->ConsumeValue(APP_SERVER_NUMBER));\n CPPUNIT_ASSERT(preader->ConsumeEndGroup(true)); // APP_SERVER_METADATA\n\n \n // Verify the simple instance (again)\n CPPUNIT_ASSERT(preader->ConsumeStartGroup(APP_SERVER_INSTANCE));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == preader->ConsumeValue(APP_SERVER_DISK_PATH));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PATH == preader->ConsumeValue(APP_SERVER_ID));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTP_PORT == preader->ConsumeValue(APP_SERVER_HTTP_PORT));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_HTTPS_PORT == preader->ConsumeValue(APP_SERVER_HTTPS_PORT));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_PROTOCOL == preader->ConsumeValue(APP_SERVER_PROTOCOL));\n CPPUNIT_ASSERT(L\"1\" == preader->ConsumeValue(APP_SERVER_IS_DEEP_MONITORED));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_TYPE == preader->ConsumeValue(APP_SERVER_TYPE));\n CPPUNIT_ASSERT(JBOSS_SIMPLE_VERSION == preader->ConsumeValue(APP_SERVER_VERSION));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_PROFILE));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_CELL));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_NODE));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_SERVER));\n CPPUNIT_ASSERT(preader->ConsumeEndGroup(true)); // JBOSS_SIMPLE_PATH\n \n // Verify the instance with a space in the path\n CPPUNIT_ASSERT(preader->ConsumeStartGroup(APP_SERVER_INSTANCE));\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_PATH == preader->ConsumeValue(APP_SERVER_DISK_PATH));\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_PATH == preader->ConsumeValue(APP_SERVER_ID));\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_HTTP_PORT == preader->ConsumeValue(APP_SERVER_HTTP_PORT));\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_HTTPS_PORT == preader->ConsumeValue(APP_SERVER_HTTPS_PORT));\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_PROTOCOL == preader->ConsumeValue(APP_SERVER_PROTOCOL));\n CPPUNIT_ASSERT(L\"1\" == preader->ConsumeValue(APP_SERVER_IS_DEEP_MONITORED));\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_TYPE == preader->ConsumeValue(APP_SERVER_TYPE));\n CPPUNIT_ASSERT(JBOSS_WITH_SPACE_VERSION == preader->ConsumeValue(APP_SERVER_VERSION));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_PROFILE));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_CELL));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_NODE));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_SERVER));\n CPPUNIT_ASSERT(preader->ConsumeEndGroup(true)); // JBOSS_WITH_SPACE_PATH\n \n // Verify the instance that is not running\n CPPUNIT_ASSERT(preader->ConsumeStartGroup(APP_SERVER_INSTANCE));\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_PATH == preader->ConsumeValue(APP_SERVER_DISK_PATH));\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_PATH == preader->ConsumeValue(APP_SERVER_ID));\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_HTTP_PORT == preader->ConsumeValue(APP_SERVER_HTTP_PORT));\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_HTTPS_PORT == preader->ConsumeValue(APP_SERVER_HTTPS_PORT));\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_PROTOCOL == preader->ConsumeValue(APP_SERVER_PROTOCOL));\n CPPUNIT_ASSERT(L\"1\" == preader->ConsumeValue(APP_SERVER_IS_DEEP_MONITORED));\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_TYPE == preader->ConsumeValue(APP_SERVER_TYPE));\n CPPUNIT_ASSERT(JBOSS_NOT_RUNNING_VERSION == preader->ConsumeValue(APP_SERVER_VERSION));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_PROFILE));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_CELL));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_NODE));\n CPPUNIT_ASSERT(L\"\" == preader->ConsumeValue(APP_SERVER_SERVER));\n CPPUNIT_ASSERT(preader->ConsumeEndGroup(true)); // JBOSS_NOT_RUNNING_PATH\n \n // Verify the WebSphere instance\n CPPUNIT_ASSERT(preader->ConsumeStartGroup(APP_SERVER_INSTANCE));\n CPPUNIT_ASSERT(WEBSPHERE_PATH == preader->ConsumeValue(APP_SERVER_DISK_PATH));\n CPPUNIT_ASSERT(WEBSPHERE_ID == preader->ConsumeValue(APP_SERVER_ID));\n CPPUNIT_ASSERT(WEBSPHERE_HTTP_PORT == preader->ConsumeValue(APP_SERVER_HTTP_PORT));\n CPPUNIT_ASSERT(WEBSPHERE_HTTPS_PORT == preader->ConsumeValue(APP_SERVER_HTTPS_PORT));\n CPPUNIT_ASSERT(WEBSPHERE_PROTOCOL == preader->ConsumeValue(APP_SERVER_PROTOCOL));\n CPPUNIT_ASSERT(L\"1\" == preader->ConsumeValue(APP_SERVER_IS_DEEP_MONITORED));\n CPPUNIT_ASSERT(WEBSPHERE_TYPE == preader->ConsumeValue(APP_SERVER_TYPE));\n CPPUNIT_ASSERT(WEBSPHERE_VERSION == preader->ConsumeValue(APP_SERVER_VERSION));\n CPPUNIT_ASSERT(WEBSPHERE_PROFILE == preader->ConsumeValue(APP_SERVER_PROFILE));\n CPPUNIT_ASSERT(WEBSPHERE_CELL == preader->ConsumeValue(APP_SERVER_CELL));\n CPPUNIT_ASSERT(WEBSPHERE_NODE == preader->ConsumeValue(APP_SERVER_NODE));\n CPPUNIT_ASSERT(WEBSPHERE_SERVER == preader->ConsumeValue(APP_SERVER_SERVER));\n CPPUNIT_ASSERT(preader->ConsumeEndGroup(true)); // WEBSPHERE\n \n CPPUNIT_ASSERT_THROW(\n m_pmedia->CreateReader(APP_SERVER_INSTANCE), \n PersistDataNotFoundException);\n }\n\n /*\n * Unpersisting a list of zero application servers should succeed\n * without any errors when nothing has ever been writen on disk\n */\n void TestUnpersistingInstancesArraySizeZeroForNoPreviousWrite(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > zeroInstances;\n \n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, zeroInstances.size());\n \n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->EraseFromDisk());\n \n // Test Verification\n CPPUNIT_ASSERT_THROW(\n m_pmedia->CreateReader(APP_SERVER_PROVIDER),\n PersistDataNotFoundException);\n\n CPPUNIT_ASSERT_THROW(\n m_pmedia->CreateReader(JBOSS_SIMPLE_PATH), \n PersistDataNotFoundException);\n }\n\n /*\n * Unpersisting a list of zero application servers should succeed\n * without any errors when something is there already\n */\n void TestUnpersistingInstancesArraySizeZeroForPreviousWrite(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > zeroInstances;\n \n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, zeroInstances.size());\n \n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->WriteToDisk(zeroInstances));\n CPPUNIT_ASSERT_NO_THROW(sut->EraseFromDisk());\n \n // Test Verification\n CPPUNIT_ASSERT_THROW(\n m_pmedia->CreateReader(APP_SERVER_PROVIDER),\n PersistDataNotFoundException);\n\n CPPUNIT_ASSERT_THROW(\n m_pmedia->CreateReader(JBOSS_SIMPLE_PATH), \n PersistDataNotFoundException);\n }\n\n /*-----------------------------------------------------------------*/\n /*\n * Verify no errors are thrown if reading a single entry cache\n * with some fairly bland data.\n * This test is specifically tailored for WebSphere as the ID is created from the \n * cell,node.profile and server.\n */\n void TestReadingSingleEntryCache_WebSphere(void)\n {\n // Test setup\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n SCXHandle<SCXPersistDataWriter> pwriter = m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n pwriter->WriteStartGroup(APP_SERVER_METADATA);\n pwriter->WriteValue(APP_SERVER_NUMBER, L\"1\");\n CPPUNIT_ASSERT_NO_THROW(pwriter->WriteEndGroup()); // Closing APP_SERVER_METADATA\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n pwriter->WriteValue(APP_SERVER_DISK_PATH, WEBSPHERE_PATH);\n pwriter->WriteValue(APP_SERVER_ID, WEBSPHERE_ID);\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, WEBSPHERE_HTTP_PORT);\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, WEBSPHERE_HTTPS_PORT);\n pwriter->WriteValue(APP_SERVER_PROTOCOL, WEBSPHERE_PROTOCOL);\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, StrFrom(true));\n pwriter->WriteValue(APP_SERVER_TYPE, WEBSPHERE_TYPE);\n pwriter->WriteValue(APP_SERVER_VERSION, WEBSPHERE_VERSION);\n pwriter->WriteValue(APP_SERVER_PROFILE, WEBSPHERE_PROFILE);\n pwriter->WriteValue(APP_SERVER_CELL, WEBSPHERE_CELL);\n pwriter->WriteValue(APP_SERVER_NODE, WEBSPHERE_NODE);\n pwriter->WriteValue(APP_SERVER_SERVER, WEBSPHERE_SERVER);\n pwriter->WriteEndGroup(); // Closing this instance 0\n CPPUNIT_ASSERT_NO_THROW(pwriter->DoneWriting()); // Closing APP_SERVER_PROVIDER\n\n // Verify before the call that the array is empty\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array has one entry\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL( one, readInstances.size());\n \n // Verify that data is correct\n SCXHandle<AppServerInstance> inst = readInstances[0];\n\n CPPUNIT_ASSERT(WEBSPHERE_PATH == inst->GetDiskPath());\n CPPUNIT_ASSERT(WEBSPHERE_ID == inst->GetId());\n CPPUNIT_ASSERT(WEBSPHERE_HTTP_PORT == inst->GetHttpPort());\n CPPUNIT_ASSERT(WEBSPHERE_HTTPS_PORT == inst->GetHttpsPort());\n CPPUNIT_ASSERT(WEBSPHERE_PROTOCOL == inst->GetProtocol());\n CPPUNIT_ASSERT(true == inst->GetIsDeepMonitored());\n CPPUNIT_ASSERT(WEBSPHERE_TYPE == inst->GetType());\n CPPUNIT_ASSERT(WEBSPHERE_VERSION == inst->GetVersion());\n CPPUNIT_ASSERT(WEBSPHERE_PROFILE == inst->GetProfile());\n CPPUNIT_ASSERT(WEBSPHERE_CELL == inst->GetCell());\n CPPUNIT_ASSERT(WEBSPHERE_NODE == inst->GetNode());\n CPPUNIT_ASSERT(WEBSPHERE_SERVER == inst->GetServer());\n }\n\n \n /*-----------------------------------------------------------------*/\n /*\n * Verify no errors are thrown if reading a single entry cache\n * with some fairly bland data.\n * This test is specifically tailored for WebLogic to test the specific version\n * numbering for WebLogic\n */\n void TestReadingSingleEntryCache_WebLogic(void)\n {\n SCXHandle<MockPersistAppServerInstances> sut( new MockPersistAppServerInstances(m_path) );\n vector<SCXHandle<AppServerInstance> > instances;\n\n instances.push_back(createWebLogicInstance());\n\n size_t one = 1;\n CPPUNIT_ASSERT_EQUAL(one, instances.size());\n\n CPPUNIT_ASSERT(WEBLOGIC_BRANDED_VERSION_11 == instances[0]->GetMajorVersion());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->WriteToDisk(instances));\n\n vector<SCXHandle<AppServerInstance> > readInstances;\n\n size_t zero = 0;\n CPPUNIT_ASSERT_EQUAL( zero, readInstances.size());\n\n // Run the Test\n CPPUNIT_ASSERT_NO_THROW(sut->ReadFromDisk(readInstances));\n\n // Test Verification\n // Verify after the call the test that the array has one entry\n CPPUNIT_ASSERT_EQUAL( one, readInstances.size());\n \n // Verify that data is correct\n SCXHandle<AppServerInstance> inst = readInstances[0];\n \n CPPUNIT_ASSERT(WEBLOGIC_PATH == inst->GetDiskPath());\n CPPUNIT_ASSERT(WEBLOGIC_ID == inst->GetId());\n CPPUNIT_ASSERT(WEBLOGIC_HTTP_PORT == inst->GetHttpPort());\n CPPUNIT_ASSERT(WEBLOGIC_HTTPS_PORT == inst->GetHttpsPort());\n CPPUNIT_ASSERT(WEBLOGIC_PROTOCOL == inst->GetProtocol());\n CPPUNIT_ASSERT(true == inst->GetIsDeepMonitored());\n CPPUNIT_ASSERT(WEBLOGIC_TYPE == inst->GetType());\n CPPUNIT_ASSERT(WEBLOGIC_VERSION == inst->GetVersion());\n CPPUNIT_ASSERT(WEBLOGIC_SERVER == inst->GetServer());\n CPPUNIT_ASSERT(WEBLOGIC_BRANDED_VERSION_11 == inst->GetMajorVersion());\n }\n \n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( PersistAppServerInstancesTest);\n}\n" }, { "alpha_fraction": 0.5038735270500183, "alphanum_fraction": 0.5067193508148193, "avg_line_length": 44.503597259521484, "blob_id": "96dba468c2fa1e0598faef1f8e590530c4bccbf4", "content_id": "188894bd4a3b3e987e3f41be2337631eec59d75a", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6325, "license_type": "permissive", "max_line_length": 118, "num_lines": 139, "path": "/test/code/providers/cpu_provider/cpuprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n Created date 2008-05-29 12:41:51\n\n CPU provider test class.\n\n Only tests the functionality of the provider class.\n The actual data gathering is tested by a separate class.\n\n*/\n/*----------------------------------------------------------------------------*/\n#include <scxcorelib/scxcmn.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n#include <cppunit/extensions/HelperMacros.h>\n#include \"SCX_ProcessorStatisticalInformation_Class_Provider.h\"\n\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nclass CPUProvider_Test : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( CPUProvider_Test );\n CPPUNIT_TEST( TestEnumerateInstancesKeysOnly );\n CPPUNIT_TEST( TestEnumerateInstances );\n CPPUNIT_TEST( TestGetInstance );\n CPPUNIT_TEST( TestVerifyKeyCompletePartial );\n\n SCXUNIT_TEST_ATTRIBUTE(TestEnumerateInstancesKeysOnly, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestEnumerateInstances, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestGetInstance, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestVerifyKeyCompletePartial, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector<std::wstring> m_keyNames;\npublic:\n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_ProcessorStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n m_keyNames.push_back(L\"Name\");\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_ProcessorStatisticalInformation_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void TestEnumerateInstancesKeysOnly()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_ProcessorStatisticalInformation_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n }\n\n void TestEnumerateInstances()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_ProcessorStatisticalInformation_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void TestVerifyKeyCompletePartial()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_ProcessorStatisticalInformation_Class_Provider,\n mi::SCX_ProcessorStatisticalInformation_Class>(m_keyNames, CALL_LOCATION(errMsg));\n }\n\n void TestGetInstance()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestGetInstance<mi::SCX_ProcessorStatisticalInformation_Class_Provider,\n mi::SCX_ProcessorStatisticalInformation_Class>(context, m_keyNames.size(), CALL_LOCATION(errMsg));\n ValidateInstance(context, CALL_LOCATION(errMsg));\n }\n\n void ValidateInstance(const TestableContext& context, std::wstring errMsg)\n {\n for (size_t n = 0; n < context.Size(); n++)\n {\n const TestableInstance &instance = context[n];\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, m_keyNames[0], instance.GetKeyName(0, CALL_LOCATION(errMsg)));\n\n#if defined(linux)\n std::wstring tmpExpectedProperties[] = {L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"IsAggregate\",\n L\"PercentIdleTime\",\n L\"PercentUserTime\",\n L\"PercentNiceTime\",\n L\"PercentPrivilegedTime\",\n L\"PercentInterruptTime\",\n L\"PercentDPCTime\",\n L\"PercentProcessorTime\",\n L\"PercentIOWaitTime\"};\n#elif defined(sun) | defined(aix)\n std::wstring tmpExpectedProperties[] = {L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"IsAggregate\",\n L\"PercentIdleTime\",\n L\"PercentUserTime\",\n L\"PercentPrivilegedTime\",\n L\"PercentProcessorTime\",\n L\"PercentIOWaitTime\"};\n#elif defined(hpux)\n std::wstring tmpExpectedProperties[] = {L\"Caption\",\n L\"Description\",\n L\"Name\",\n L\"IsAggregate\",\n L\"PercentIdleTime\",\n L\"PercentUserTime\",\n L\"PercentNiceTime\",\n L\"PercentPrivilegedTime\",\n L\"PercentProcessorTime\",\n L\"PercentIOWaitTime\"};\n#endif\n\n const size_t numprops = sizeof(tmpExpectedProperties) / sizeof(tmpExpectedProperties[0]);\n VerifyInstancePropertyNames(instance, tmpExpectedProperties, numprops, CALL_LOCATION(errMsg));\n }\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( CPUProvider_Test );\n" }, { "alpha_fraction": 0.6414523720741272, "alphanum_fraction": 0.6414523720741272, "avg_line_length": 25.783782958984375, "blob_id": "0fe96889f687e12b962ff7298dbc60d2b0f48496", "content_id": "ff855d1b4257d318f3c07610d6f0da0ad65a27c7", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1983, "license_type": "permissive", "max_line_length": 80, "num_lines": 74, "path": "/source/code/providers/SCX_ProcessorStatisticalInformation_Class_Provider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/* @migen@ */\n#ifndef _SCX_ProcessorStatisticalInformation_Class_Provider_h\n#define _SCX_ProcessorStatisticalInformation_Class_Provider_h\n\n#include \"SCX_ProcessorStatisticalInformation.h\"\n#ifdef __cplusplus\n# include <micxx/micxx.h>\n# include \"module.h\"\n\nMI_BEGIN_NAMESPACE\n\n/*\n**==============================================================================\n**\n** SCX_ProcessorStatisticalInformation provider class declaration\n**\n**==============================================================================\n*/\n\nclass SCX_ProcessorStatisticalInformation_Class_Provider\n{\n/* @MIGEN.BEGIN@ CAUTION: PLEASE DO NOT EDIT OR DELETE THIS LINE. */\nprivate:\n Module* m_Module;\n\npublic:\n SCX_ProcessorStatisticalInformation_Class_Provider(\n Module* module);\n\n ~SCX_ProcessorStatisticalInformation_Class_Provider();\n\n void Load(\n Context& context);\n\n void Unload(\n Context& context);\n\n void EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter);\n\n void GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_ProcessorStatisticalInformation_Class& instance,\n const PropertySet& propertySet);\n\n void CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_ProcessorStatisticalInformation_Class& newInstance);\n\n void ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_ProcessorStatisticalInformation_Class& modifiedInstance,\n const PropertySet& propertySet);\n\n void DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_ProcessorStatisticalInformation_Class& instance);\n\n/* @MIGEN.END@ CAUTION: PLEASE DO NOT EDIT OR DELETE THIS LINE. */\n};\n\nMI_END_NAMESPACE\n\n#endif /* __cplusplus */\n\n#endif /* _SCX_ProcessorStatisticalInformation_Class_Provider_h */\n\n" }, { "alpha_fraction": 0.617914617061615, "alphanum_fraction": 0.6277117133140564, "avg_line_length": 32.23255920410156, "blob_id": "ff437da07601336f81ca4dd79392654226f7f8d1", "content_id": "6d5e410f468f9f78c0f3adb5ea6d6b07db045add", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1429, "license_type": "permissive", "max_line_length": 100, "num_lines": 43, "path": "/source/code/shared/tools/scx_admin/runasadminprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief SCX RunAs configuration tool for SCX.\n\n \\date 2008-08-28 16:34:24\n\n*/\n#ifndef _RUNAS_CONFIGURATOR_H\n#define _RUNAS_CONFIGURATOR_H\n\n#include \"scxrunasconfigurator.h\"\n#include \"admin_api.h\"\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Class wrapping the configuration capabilities of the runas provider.\n\n*/\nclass SCX_RunAsAdminProvider : public SCX_AdminProviderConfigAPI {\npublic:\n SCX_RunAsAdminProvider();\n SCX_RunAsAdminProvider( SCXCoreLib::SCXHandle<SCXCore::ConfigurationParser> parser,\n SCXCoreLib::SCXHandle<SCXCore::ConfigurationWriter> writer,\n const SCXCoreLib::SCXFilePath& sshdConfPath);\n ~SCX_RunAsAdminProvider();\n\n bool Print(std::wostringstream& buf) const;\n bool Reset( const std::wstring& name );\n bool Set(const std::wstring& name, const std::wstring& value);\n\nprivate:\n bool GetSSHDConfPermitRootSetting(const SCXCoreLib::SCXFilePath& sshdConfPath) const;\n\n SCXCore::RunAsConfigurator m_Configurator; //!< Does the actual configuration.\n bool m_AllowRootDefault; //!< Value that AllowRoot should get after a call to reset.\n};\n\n#endif /* _RUNAS_CONFIGURATOR_H */\n" }, { "alpha_fraction": 0.7131197452545166, "alphanum_fraction": 0.7553560733795166, "avg_line_length": 27.660818099975586, "blob_id": "3ee1dda00b830885d445e6fee3bf17e2f7986e61", "content_id": "4159ebbf2d53e821bf246aee11b94dfca9fcc9d2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4901, "license_type": "permissive", "max_line_length": 115, "num_lines": 171, "path": "/test/util/artifacts/runas-memleak/README.md", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# Memory Leak Test in RunAs Provider\n\nThe RunAs provider (part of the `SCX_OperatingSystem` class) runs\nprocesses on the system running the SCX agent.\n\nIt turns out that this provider exhibited a memory leak such that,\nafter a sufficiently long period of time, the provider would cease to\nfunction.\n\nIn order to help diagnose this, some tests were written to track\nmemory usage and allow us to quickly determine if the issue was\nproperly resolved.\n\nThe tests consist of two files:\n\n- [measureleak.sh][]: Measures current utilization of SCX agent\n- [testleak.sh][]: Runs the RunAs provider repeatedly to detect leaks\n\n[measureleak.sh]: https://github.com/Microsoft/SCXcore/blob/master/test/util/artifacts/runas-memleak/measureleak.sh\n[testleak.sh]: https://github.com/Microsoft/SCXcore/blob/master/test/util/artifacts/runas-memleak/testleak.sh\n\nTo run the tests, `cd` into the directory containing the tests and\nexecute script `testleak.sh`, like this:\n\n```\ncd opsmgr/test/util/artifacts/runas-memleak\n./testleak.sh\n```\n\nResults from this test will be in three sections:\n\n- [Startup](#output-from-startup)\n- [Stabilization](#output-from-stabilization)\n- [Leak Detection](#output-from-leak-detection)\n\n##### Output from Startup\n\n```\n> ./testleak.sh \nInvoking RunAs provider (to insure it's running) ...\ninstance of ExecuteShellCommand\n{\n ReturnValue=true\n ReturnCode=0\n StdOut=Hello World\n\n StdErr=\n}\n\nStarting values for omiagent process:\nPID 29574\nThread count 3\nFD count 40\nMemstats:\n PID RSS VSZ COMMAND\n29574 4648 16348 omiagent\n\n```\n##### Output from Stabilization\n```\n\nWill now exercise Provide_ExShell_Load RunAs provider under load:\n..............\n\nIntermediate values for Provide_ExShell_Load RunAs provider:\nPID 29574\nThread count 3\nFD count 40\nMemstats:\n PID RSS VSZ COMMAND\n29574 4648 16376 omiagent\n\nWill now exercise Provide_ExScript_Load RunAs provider under load:\n..............\n\nIntermediate values for Provide_ExScript_Load RunAs provider:\nPID 29574\nThread count 3\nFD count 40\nMemstats:\n PID RSS VSZ COMMAND\n29574 4736 16376 omiagent\n\nWill now exercise Provide_ExCommand_Load RunAs provider under load:\n..............\n\nIntermediate values for Provide_ExCommand_Load RunAs provider:\nPID 29574\nThread count 3\nFD count 40\nMemstats:\n PID RSS VSZ COMMAND\n29574 4752 16376 omiagent\n\n```\n##### Output from Leak Detection\n```\n\nWill exercise Provide_ExShell_Load RunAs provider again under load:\n..............\n\nCurrent values for Provide_ExShell_Load RunAs provider:\nPID 29574\nThread count 3\nFD count 40\nMemstats:\n PID RSS VSZ COMMAND\n29574 4756 16376 omiagent\n\nWill exercise Provide_ExScript_Load RunAs provider again under load:\n..............\n\nCurrent values for Provide_ExScript_Load RunAs provider:\nPID 29574\nThread count 3\nFD count 40\nMemstats:\n PID RSS VSZ COMMAND\n29574 4756 16376 omiagent\n\nWill exercise Provide_ExCommand_Load RunAs provider again under load:\n..............\n\nCurrent values for Provide_ExCommand_Load RunAs provider:\nPID 29574\nThread count 3\nFD count 40\nMemstats:\n PID RSS VSZ COMMAND\n29574 4756 16376 omiagent\n\nNote: These values should be very close to intermediate values!\n If they are not very close, this must be investigated.\n```\n\n### Interpreting Output\n\nDuring the Startup phase, the script will launch the RunAs provider\n(if not already running) and will print startup statistics about it's\nsize, thread count, and file descriptor count.\n\nDuring the stabilization phase, the test will then enumerate each RunAs\nprovider [ExecuteShellCommand, ExecuteScript, ExecuteCommand] 350 times \nto reach a *baseline* for memory utilization. After this, the test will \ndisplay intermediate statistics for the provider.\n\nDuring the leak detection phase, the test will enumerate each RunAs\nprovider 350 times. Finally, the test will print final statistics\nand exit.\n\nOf particular interest is the output after the stabilization phase and\nthe output after the leak detection phase. In the example above, the\nstabilization phase and leak detection phase indicated the following\nvalues:\n\nPhase | PID | Threads | FDs | RSS | VSZ\n----- | --- | ------- | --- | --- | ---\nIntermediate | 29574 | 3 | 40 | 4648 | 16348\nLeak Detection | 29574 | 3 | 40 | 4756 | 16376\n\nThe RSS for Intermediate and Leak Detection phases should be very close\n(within 250 or so), and the VSZ should be within 50,000 or so. In this\nparticular example, the values were identical, which is common.\n\nIf you're uncertain, after a single script execution, that memory is\nstable, then you can run `testleak.sh` again. Simply note the values\nafter the initial stabilization run, then run the script as many times\nas desired (each run will execute the RunAs provider 2000 times).\nCompare the initial stabilization values with the final leak detection\nvalues. Again: small changes are acceptable, but memory should become\nstable quickly.\n" }, { "alpha_fraction": 0.6308788657188416, "alphanum_fraction": 0.6308788657188416, "avg_line_length": 25.299999237060547, "blob_id": "cc1a9b8f5026caad05f4f58960b591929f9c095e", "content_id": "1228e9c99ecb6efadfd774b93f2f2f4def62904d", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2105, "license_type": "permissive", "max_line_length": 80, "num_lines": 80, "path": "/source/code/providers/SCX_EthernetPortStatistics_Class_Provider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/* @migen@ */\n#ifndef _SCX_EthernetPortStatistics_Class_Provider_h\n#define _SCX_EthernetPortStatistics_Class_Provider_h\n\n#include \"SCX_EthernetPortStatistics.h\"\n#ifdef __cplusplus\n# include <micxx/micxx.h>\n# include \"module.h\"\n\nMI_BEGIN_NAMESPACE\n\n/*\n**==============================================================================\n**\n** SCX_EthernetPortStatistics provider class declaration\n**\n**==============================================================================\n*/\n\nclass SCX_EthernetPortStatistics_Class_Provider\n{\n/* @MIGEN.BEGIN@ CAUTION: PLEASE DO NOT EDIT OR DELETE THIS LINE. */\nprivate:\n Module* m_Module;\n\npublic:\n SCX_EthernetPortStatistics_Class_Provider(\n Module* module);\n\n ~SCX_EthernetPortStatistics_Class_Provider();\n\n void Load(\n Context& context);\n\n void Unload(\n Context& context);\n\n void EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter);\n\n void GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_EthernetPortStatistics_Class& instance,\n const PropertySet& propertySet);\n\n void CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_EthernetPortStatistics_Class& newInstance);\n\n void ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_EthernetPortStatistics_Class& modifiedInstance,\n const PropertySet& propertySet);\n\n void DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_EthernetPortStatistics_Class& instance);\n\n void Invoke_ResetSelectedStats(\n Context& context,\n const String& nameSpace,\n const SCX_EthernetPortStatistics_Class& instanceName,\n const SCX_EthernetPortStatistics_ResetSelectedStats_Class& in);\n\n/* @MIGEN.END@ CAUTION: PLEASE DO NOT EDIT OR DELETE THIS LINE. */\n};\n\nMI_END_NAMESPACE\n\n#endif /* __cplusplus */\n\n#endif /* _SCX_EthernetPortStatistics_Class_Provider_h */\n\n" }, { "alpha_fraction": 0.5732441544532776, "alphanum_fraction": 0.5799331068992615, "avg_line_length": 29.14583396911621, "blob_id": "e2fd33902e78b81e5f387cb8f45b41bb4d36e6f8", "content_id": "507c705be8872cf8a3d860b1b3e365beb38fcfeb", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2990, "license_type": "permissive", "max_line_length": 192, "num_lines": 96, "path": "/tools/chroot/suse-sles10/scx-wsmand.chroot", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/bash\r\n##\r\n# Copyright (c) Microsoft Corporation. All rights reserved. \r\n#\r\n# Contains settings for the SCX WS-Management Deamon.\r\n#\r\n#\r\n\r\n### BEGIN INIT INFO\r\n# Provides: scx-wsmand\r\n# Required-Start: $network scx-cimd\r\n# Required-Stop: $network scx-cimd\r\n# Default-Start: 3 5\r\n# Default-Stop: 0 1 2 6\r\n# Short-Description: Microsoft SCX WS-Management Daemon\r\n# Description: Microsoft System Center Agent - WS-Management daemon\r\n### END INIT INFO\r\n\r\nSCX_HOME=/opt/microsoft/scx\r\nSCX_WSMAND_NAME=\"Microsoft SCX WS-Management Daemon\"\r\n\r\nSCX_WSMAND_BIN=/opt/microsoft/scx/bin/openwsmand\r\ntest -x $SCX_WSMAND_BIN || { echo \"$SCX_WSMAND_BIN not installed\"; \r\n if [ \"$1\" = \"stop\" ]; then exit 0;\r\n else exit 5; fi; }\r\n\r\n# Check for existence of needed config file and read it\r\nSCX_WSMAND_CONFIG=/etc/opt/microsoft/scx/conf/openwsman.conf\r\ntest -r $SCX_WSMAND_CONFIG || { echo \"$SCX_WSMAND_CONFIG not existing\";\r\n if [ \"$1\" = \"stop\" ]; then exit 0;\r\n else exit 6; fi; }\r\n\r\n# PID File\r\nSCX_WSMAND_PIDFILE=/var/opt/microsoft/scx/tmp/scx-wsmand.pid\r\n\r\n# CHROOT\r\nSCX_WSMAND_CHROOT=/var/opt/microsoft/scx/chroot/wsmand\r\n\r\nif test -e /etc/rc.status; then\r\n . /etc/rc.status\r\nelse\r\n echo \"Could not source /etc/rc.status.\"\r\n exit 1\r\nfi\r\n\r\n# Reset status of this service\r\nrc_reset\r\n\r\ncase \"$1\" in\r\n start)\r\n if [ -d $SCX_WSMAND_CHROOT ]; then\r\n LD_LIBRARY_PATH=$SCX_HOME/lib; export LD_LIBRARY_PATH\r\n service scx-cimd status\r\n if [ $? -eq 0 ]; then\r\n echo -n \"Creating cim.socket in jail\"\r\n rm -f ${SCX_WSMAND_CHROOT}/var/opt/microsoft/scx/tmp/cim.socket\r\n ln /var/opt/microsoft/scx/tmp/cim.socket ${SCX_WSMAND_CHROOT}/var/opt/microsoft/scx/tmp/cim.socket\r\n if [ $? -eq 0 ]; then\r\n rc_status -v\r\n echo -n \"Starting $SCX_WSMAND_NAME \"\r\n startproc -v -p ${SCX_WSMAND_CHROOT}${SCX_WSMAND_PIDFILE} /usr/bin/chroot ${SCX_WSMAND_CHROOT} $SCX_WSMAND_BIN -S --config-file=$SCX_WSMAND_CONFIG --pid-file=$SCX_WSMAND_PIDFILE \r\n\t /bin/true; rc_status -v\r\n else\r\n /bin/false; rc_status -v\r\n fi\r\n else\r\n echo -n \"scx-cimd has not been started\"\r\n /bin/false; rc_status -v\r\n fi\r\n else\r\n echo -n \"Jail does not exist in $SCX_WSMAND_CHROOT\"\r\n /bin/false; rc_status -v\r\n fi\r\n ;;\r\n stop)\r\n echo -n \"Shutting down $SCX_WSMAND_NAME \"\r\n killall openwsmand\r\n rm -f ${SCX_WSMAND_CHROOT}/var/opt/microsoft/scx/tmp/cim.socket\r\n rc_status -v\r\n ;;\r\n restart)\r\n $0 stop\r\n $0 start\r\n rc_status\r\n ;;\r\n status)\r\n echo -n \"Checking for service $SCX_WSMAND_NAME \"\r\n checkproc -p $SCX_WSMAND_PIDFILE $SCX_WSMAND_BIN\r\n rc_status -v\r\n ;;\r\n *)\r\n echo \"Usage: $0 {start|stop|status|restart}\"\r\n exit 1\r\n ;;\r\nesac\r\nrc_exit\r\n" }, { "alpha_fraction": 0.5702826976776123, "alphanum_fraction": 0.5728259682655334, "avg_line_length": 48.7469596862793, "blob_id": "2dd2a6d4c75d331faf7cdf19d2cfd0613d8b2c54", "content_id": "048353cc9a207432971bd9b5ef2d6a6a23ddc179", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 20446, "license_type": "permissive", "max_line_length": 299, "num_lines": 411, "path": "/build/Makefile.components", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*- \n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#--------------------------------------------------------------------------------\n\n#================================================================================\n# Static Libraries\n#================================================================================\n\ninclude $(SCX_BRD)/build/Makefile.sslconfig\ninclude $(SCX_BRD)/build/Makefile.providers\n\n#--------------------------------------------------------------------------------\n# Log policy\n\nSTATIC_LOGPOLICYLIB_SRCFILES = \\\n\t$(SCX_SRC_ROOT)/providers/support/logpolicy.cpp\n\nSTATIC_LOGPOLICYLIB_OBJFILES = $(call src_to_obj,$(STATIC_LOGPOLICYLIB_SRCFILES))\n\n$(INTERMEDIATE_DIR)/liblogpolicy.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_LOGPOLICYLIB_OBJFILES)\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\n#--------------------------------------------------------------------------------\n# ProductDependencies static library\n\nSTATIC_PRODUCTDEPENDENCIES_SRCFILES = \\\n\t$(SCX_SRC_ROOT)/providers/support/productdependencies.cpp\n\nSTATIC_PRODUCTDEPENDENCIES_OBJFILES = $(call src_to_obj,$(STATIC_PRODUCTDEPENDENCIES_SRCFILES))\n\nSTATIC_PRODUCTDEPENDENCIES_DEPFILES = \\\n\t$(INTERMEDIATE_DIR)/libProductDependencies.$(PF_STAT_LIB_FILE_SUFFIX)\n\n$(INTERMEDIATE_DIR)/libProductDependencies.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_PRODUCTDEPENDENCIES_OBJFILES)\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\n#================================================================================\n# Dynamic libraries\n#================================================================================\n\n#--------------------------------------------------------------------------------\n# The Core Provider Module library\n\n# The static libraries prerequisite list, expands to e.g. libXYZ.a\n\nSCXPAL_STATICLIB_DEPS = \\\n\tpalsystem \\\n\tscxassertabort \\\n\tUtil \\\n\tscxcore\n\nCOREPROVIDERMODULE_STATICLIB_DEPS = \\\n\tomprovider\n\n# Foreach XYZ in the list above, reference $(SCXPAL_TARGET_DIR)/libXYZ.a\n\nSTATIC_SCXPAL_DEPFILES = $(addprefix $(SCXPAL_TARGET_DIR)/lib, $(addsuffix .$(PF_STAT_LIB_FILE_SUFFIX), $(SCXPAL_STATICLIB_DEPS)))\n\nSCXPAL_STATICLIB_DEPFILES_NODUPS = \\\n\t$(STATIC_SCXPAL_DEPFILES) \\\n\t$(STATIC_PRODUCTDEPENDENCIES_DEPFILES)\n\n# Note the circular dependency: We need the PAL, ProductDependencies, and PAL\n#\n# The issue is that PAL references things in ProductDeps (for logging project\n# specific data), which needs PAL support. So to deal with linkage, we need to\n# first pull PAL (to call for required logging methods)) + ProjectDeps + PAL\n# (one more time) to get things that ProjectDeps needed from PAL.\n\nSCXPAL_STATICLIB_DEPFILES = $(SCXPAL_STATICLIB_DEPFILES_NODUPS) $(STATIC_SCXPAL_DEPFILES)\n\n# Foreach XYZ in the list above, build $(INTERMEDIATE_DIR)/libXYZ.a\nCOREPROVIDERMODULE_STATICLIB_DEPFILES = $(addprefix $(INTERMEDIATE_DIR)/lib, $(addsuffix .$(PF_STAT_LIB_FILE_SUFFIX), $(COREPROVIDERMODULE_STATICLIB_DEPS)))\n\n# Foreach XYZ in the list above, build -lXYZ\nSCXPAL_LINK_STATICLIBS = $(addprefix -l, $(SCXPAL_STATICLIB_DEPS)) \\\n\t-lProductDependencies \\\n\t-llogpolicy\n\nCOREPROVIDERMODULE_LINK_STATICLIBS = $(addprefix -l, $(COREPROVIDERMODULE_STATICLIB_DEPS))\n\nOMI_FORCED_TARGETS=$(STATIC_PROVIDERLIB_OBJFILES)\nOMI_DYNAMIC_LIBS=-lmicxx\n\n$(INTERMEDIATE_DIR)/libSCXCoreProviderModule.$(PF_DYN_LIB_FILE_SUFFIX) : $(COREPROVIDERMODULE_STATICLIB_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES) $(INTERMEDIATE_DIR)/liblogpolicy.$(PF_STAT_LIB_FILE_SUFFIX)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)\n\t$(PROFILING) $(LINK_DYNLIB) $(COREPROVIDERMODULE_EXTRA_LINKFLAGS) $(LINK_OUTFLAG) $(OMI_FORCED_TARGETS) -L$(SCXOMI_LIBS) $(COREPROVIDERMODULE_LINK_STATICLIBS) $(OMI_DYNAMIC_LIBS) $(SCXPAL_LINK_STATICLIBS) $(LDFLAGS_COREPROVIDERMODULE) $(CXX_CGEN_FLAGS) $(SCXPAL_SRC_ROOT)/scxcorelib/pal/noop.cpp\n\n#--------------------------------------------------------------------------------\n# The Test Provider Module library\n\n# The static libraries prerequisite list, expands to e.g. libXYZ.a\nTESTPROVIDERMODULE_STATICLIB_DEPS = \\\n\ttestprovider \\\n\tprovidersupport \\\n\tlogpolicy \\\n\n# Foreach XYZ in the list above, build $(INTERMEDIATE_DIR)/libXYZ.a\nTESTPROVIDERMODULE_STATICLIB_DEPFILES = $(addprefix $(INTERMEDIATE_DIR)/lib, $(addsuffix .$(PF_STAT_LIB_FILE_SUFFIX), $(TESTPROVIDERMODULE_STATICLIB_DEPS)))\n\n# Foreach XYZ in the list above, build -lXYZ\nTESTPROVIDERMODULE_LINK_STATICLIBS = $(addprefix -l, $(TESTPROVIDERMODULE_STATICLIB_DEPS))\n\n# Get the flags used for retaining exposed symbols\nTESTPROVIDERMODULE_SYMBOLS_LINKFLAGS = $(call get_ld_flags_for_retaining_symbols,$(TESTPROVIDERMODULE_EXPOSED_SYMS))\n\n$(INTERMEDIATE_DIR)/libSCXTestProviderModule.$(PF_DYN_LIB_FILE_SUFFIX) : $(TESTPROVIDERMODULE_STATICLIB_DEPFILES) $(INTERMEDIATE_DIR)/testprovider.map $(INTERMEDIATE_DIR)/testprovider.exp\n\t-$(MKPATH) $(INTERMEDIATE_DIR)\n\t$(PROFILING) $(LINK_DYNLIB) $(TESTPROVIDERMODULE_EXTRA_LINKFLAGS) $(LINK_OUTFLAG) $(TESTPROVIDERMODULE_SYMBOLS_LINKFLAGS) $(TESTPROVIDERMODULE_LINK_STATICLIBS) $(SCXPAL_LINK_STATICLIBS) $(LDFLAGS_TESTPROVIDERMODULE) $(PF_TESTPROVIDERLIB_EXTRA_LIBS)\n\n$(INTERMEDIATE_DIR)/testprovider.map:\n\t@echo \"{ global: \" > $@\n\t@echo \"$(addsuffix ;, $(TESTPROVIDERMODULE_EXPOSED_SYMS))\" >> $@\n\t@echo \"local: *; };\" >> $@\n\n$(INTERMEDIATE_DIR)/testprovider.exp:\n\t$(foreach SYM,$(TESTPROVIDERMODULE_EXPOSED_SYMS),$(shell echo $(EXPOSED_SYMS_PREFIX)$(SYM) >> $@))\n\n\n#================================================================================\n# Administration Tool\n#================================================================================\n\nSCXADMIN_DIR=$(SCX_SRC_ROOT)/shared/tools/scx_admin\n\n# Static lib files for admin tool\nSTATIC_SCXADMIN_SRCFILES = \\\n\t$(SCXADMIN_DIR)/servicecontrol.cpp \\\n\t$(SCXADMIN_DIR)/cimconfigurator.cpp \\\n\t$(SCXADMIN_DIR)/logconfigurator.cpp \\\n\t$(SCXADMIN_DIR)/cmdparser.cpp \\\n\t$(SCXADMIN_DIR)/runasadminprovider.cpp\n\n# We need to include include this module WITHOUT pulling in the provider library.\n# On AIX, this causes OMI dependencies to be dragged in. We want better separation.\nSTATIC_SCXADMIN_SRCFILES += \\\n\t$(PROVIDER_SUPPORT_DIR)/scxrunasconfigurator.cpp\n\n$(INTERMEDIATE_DIR)/source/code/shared/tools/scx_admin/%.d: INCLUDES += -I$(PROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/source/code/shared/tools/scx_admin/%.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(PROVIDER_SUPPORT_DIR)\n\nSTATIC_SCXADMIN_OBJFILES = $(call src_to_obj,$(STATIC_SCXADMIN_SRCFILES))\n\n$(INTERMEDIATE_DIR)/libscxadmin.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXADMIN_OBJFILES)\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\n# The main program\nSCXADMIN_SRCFILES=\\\n\t$(SCXADMIN_DIR)/scx_admin.cpp\n\nSCXADMIN_OBJFILES = $(call src_to_obj,$(SCXADMIN_SRCFILES))\n\n\nSCXADMIN_DEPFILES=$(SCXADMIN_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d) $(STATIC_SCXADMIN_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d) \n\n# Static dependencies on POSIX platforms\nSCXADMIN_STATICLIB_DEPS = \\\n\tscxadmin\n\n#\tomprovider \\\n#\tprovidersupport \\\n#\tmetaprovider\n\nifneq ($(SCX_STACK_ONLY), true) # For a full agent, also include these:\n#SCXADMIN_STATICLIB_DEPS += \\\n#\trunasprovider \\\n\nendif\n\n# Foreach XYZ in the list above, build $(INTERMEDIATE_DIR)/libXYZ.a\nSCXADMIN_STATICLIB_DEPFILES = $(addprefix $(INTERMEDIATE_DIR)/lib, $(addsuffix .$(PF_STAT_LIB_FILE_SUFFIX), $(SCXADMIN_STATICLIB_DEPS)))\n\n$(INTERMEDIATE_DIR)/scxadmin$(PF_EXE_FILE_SUFFIX): \\\n\t$(SCXADMIN_OBJFILES) $(INTERMEDIATE_DIR)/libscxadmin.$(PF_STAT_LIB_FILE_SUFFIX) $(SCXADMIN_DEPFILES) $(SCXADMIN_STATICLIB_DEPFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\t$(PROFILING) $(LINK) $(LINK_OUTFLAG) $(SCXADMIN_OBJFILES) $(SCXADMIN_STATICLIB_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES) $(LDFLAGS_SCX_ADMIN_TOOL) $(LDFLAGS_EXECUTABLE)\n\n#================================================================================\n# Logfile Reader Command Line Program\n#================================================================================\n\nLOGFILEREADER_DIR=$(SCX_SRC_ROOT)/providers/support\n\n# Static lib files for scxlogfilereader command line program\nSTATIC_LOGFILEREADER_SRCFILES = \\\n\t$(LOGFILEREADER_DIR)/logfileutils.cpp \\\n\t$(LOGFILEREADER_DIR)/logpolicy.cpp\n\nSTATIC_LOGFILEREADER_OBJFILES = $(call src_to_obj,$(STATIC_LOGFILEREADER_SRCFILES))\n\n$(INTERMEDIATE_DIR)/libscxlogfilereader.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_LOGFILEREADER_OBJFILES)\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\n# The main program\nLOGFILEREADER_SRCFILES=\\\n\t$(LOGFILEREADER_DIR)/logfilereader.cpp\n\nLOGFILEREADER_OBJFILES = $(call src_to_obj,$(LOGFILEREADER_SRCFILES))\n\nLOGFILEREADER_DEPFILES=$(LOGFILEREADER_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d) $(STATIC_LOGFILEREADER_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d) \n\n# Static dependencies on POSIX platforms\nLOGFILEREADER_STATICLIB_DEPS = \\\n\tscxlogfilereader\n\n# Foreach XYZ in the list above, build $(INTERMEDIATE_DIR)/libXYZ.a\nLOGFILEREADER_STATICLIB_DEPFILES = $(addprefix $(INTERMEDIATE_DIR)/lib, $(addsuffix .$(PF_STAT_LIB_FILE_SUFFIX), $(LOGFILEREADER_STATICLIB_DEPS)))\n\n$(INTERMEDIATE_DIR)/scxlogfilereader$(PF_EXE_FILE_SUFFIX): \\\n\t$(LOGFILEREADER_OBJFILES) $(INTERMEDIATE_DIR)/libscxlogfilereader.$(PF_STAT_LIB_FILE_SUFFIX) $(LOGFILEREADER_DEPFILES) $(LOGFILEREADER_STATICLIB_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\t$(PROFILING) $(LINK) $(LINK_OUTFLAG) $(LOGFILEREADER_OBJFILES) $(LOGFILEREADER_STATICLIB_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES) $(LDFLAGS_SCX_ADMIN_TOOL) $(LDFLAGS_EXECUTABLE)\n\n#================================================================================\n# Regular Expression Test Tool\n#================================================================================\n\nREGEX_TEST_DIR=$(SCX_SRC_ROOT)/shared/tools/regex_test\n\nREGEX_TEST_SRCFILES=\\\n\t$(REGEX_TEST_DIR)/regex_test.cpp\n\nREGEX_TEST_OBJFILES = $(call src_to_obj,$(REGEX_TEST_SRCFILES))\n\nREGEX_TEST_DEPFILES=$(REGEX_TEST_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d)\n\n$(INTERMEDIATE_DIR)/regex_test$(PF_EXE_FILE_SUFFIX): \\\n\t$(REGEX_TEST_OBJFILES) $(REGEX_TEST_DEPFILES) $(REGEX_TEST_STATICLIB_DEPFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\t$(PROFILING) $(LINK) $(LINK_OUTFLAG) $(REGEX_TEST_OBJFILES) $(SCXPAL_STATICLIB_DEPFILES) $(LDFLAGS_TESTRUNNER) $(LDFLAGS_EXECUTABLE)\n\n#================================================================================\n# OMI Pre-exec Directory Creation Tool\n#================================================================================\n\nOMI_PREEXEC_DIR=$(SCX_SRC_ROOT)/shared/tools/omi_preexec\nPAL_STRERROR_LOC=$(SCXPAL_DIR)/source/code/scxcorelib/util\n\n# Note that strerror.cpp lives in the PAL, but omi_preexec doesn't link against\n# the PAL. To resolve, create a link to the real file and built it ourselves.\n\n$(OMI_PREEXEC_DIR)/strerror.cpp : \n# We need to recreate the symlink if the link is older than what it points to.\n# Touch will not work, and ln -fs does not work on Sun5.9\n\trm -f $(OMI_PREEXEC_DIR)/strerror.cpp\n\tln -s $(PAL_STRERROR_LOC)/strerror.cpp $(OMI_PREEXEC_DIR)/strerror.cpp\n\nOMI_PREEXEC_SRCFILES=\\\n\t$(OMI_PREEXEC_DIR)/omi_preexec.cpp \\\n\t$(OMI_PREEXEC_DIR)/strerror.cpp\n\nOMI_PREEXEC_OBJFILES = $(call src_to_obj,$(OMI_PREEXEC_SRCFILES))\n\nOMI_PREEXEC_DEPFILES=$(OMI_PREEXEC_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d)\n\n$(INTERMEDIATE_DIR)/omi_preexec$(PF_EXE_FILE_SUFFIX): $(OMI_PREEXEC_OBJFILES) $(OMI_PREEXEC_DEPFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\t$(PROFILING) $(LINK) $(LINK_OUTFLAG) $(OMI_PREEXEC_OBJFILES) $(LDFLAGS_EXECUTABLE)\n\n#================================================================================\n# Development Convenience Targets\n#================================================================================\n\nlogfilereader-tool: $(INTERMEDIATE_DIR)/scxlogfilereader$(PF_EXE_FILE_SUFFIX)\nadmin-tool: $(INTERMEDIATE_DIR)/scxadmin$(PF_EXE_FILE_SUFFIX)\nregex-test: $(INTERMEDIATE_DIR)/regex_test$(PF_EXE_FILE_SUFFIX)\nomi-preexec: $(INTERMEDIATE_DIR)/omi_preexec$(PF_EXE_FILE_SUFFIX)\n\nifeq ($(COMBINED_PACKAGES),1)\n ifeq ($(PF_ARCH),x64)\n ssl-tool: $(INTERMEDIATE_DIR)/$(OPENSSL098DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX) $(INTERMEDIATE_DIR)/$(OPENSSL100DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX) $(INTERMEDIATE_DIR)/$(OPENSSL110DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX) $(INTERMEDIATE_DIR)/$(OPENSSL300DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX)\n else\n ssl-tool: $(INTERMEDIATE_DIR)/$(OPENSSL098DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX) $(INTERMEDIATE_DIR)/$(OPENSSL100DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX)\n endif\nelse\nssl-tool: $(INTERMEDIATE_DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX)\nendif\n\n# All SCX tools\nscx-tools: logfilereader-tool admin-tool regex-test omi-preexec ssl-tool\n\ncoreprovider: \\\n\t$(INTERMEDIATE_DIR)/libSCXCoreProviderModule.$(PF_DYN_LIB_FILE_SUFFIX)\n\nproviders: \\\n\t$(INTERMEDIATE_DIR)/libSCXTestProviderModule.$(PF_DYN_LIB_FILE_SUFFIX) \\\n\t$(INTERMEDIATE_DIR)/libSCXCoreProviderModule.$(PF_DYN_LIB_FILE_SUFFIX)\n\n# An alias \nomi: omi_all\n\nomi_all:\n\t$(ECHO) \"========================= Performing make omi\"\n\t$(MAKE) -C $(SCXOMI_DIR) all\n\n# Testing tool (needs to be built on each of our platforms)\n$(TARGET_DIR)/testapp :\n\t$(ECHO) \"========================= Performing make testapp\"\n\t$(MAKE) -C $(SCX_BRD)/test/util/testapp\n\n# Used to generate compontents necessary for other projects to compile with the \n# core components\ndevel-deps: $(COREPROVIDERMODULE_STATICLIB_DEPFILES) $(SCXPAL_TARGET_DIR)/libscxassertcppunit.$(PF_STAT_LIB_FILE_SUFFIX) $(TARGET_DIR)/testapp omi\n\t$(ECHO) \"========================= Performing building devel-deps\"\n\t-$(RMDIR) $(INTERMEDIATE_DIR)/scxcore-devel\nifeq ($(COMBINED_PACKAGES),1)\n\t$(MKPATH) $(INTERMEDIATE_DIR)/scxcore-devel/lib/$(OPENSSL098DIR)\n\t$(MKPATH) $(INTERMEDIATE_DIR)/scxcore-devel/lib/$(OPENSSL100DIR)\n ifeq ($(PF_ARCH),x64)\n\t $(MKPATH) $(INTERMEDIATE_DIR)/scxcore-devel/lib/$(OPENSSL110DIR)\n\t $(MKPATH) $(INTERMEDIATE_DIR)/scxcore-devel/lib/$(OPENSSL300DIR)\n endif\nelse\n\t$(MKPATH) $(INTERMEDIATE_DIR)/scxcore-devel/lib\nendif\n\t$(COPYDIR) $(SCX_SHARED_INCLUDE_DIR) $(INTERMEDIATE_DIR)/scxcore-devel/shared\n\t$(COPY) $(SCXPAL_STATICLIB_DEPFILES_NODUPS) $(INTERMEDIATE_DIR)/scxcore-devel/lib\n\t$(COPY) $(COREPROVIDERMODULE_STATICLIB_DEPFILES) $(INTERMEDIATE_DIR)/scxcore-devel/lib\n\t$(COPY) $(SCXPAL_TARGET_DIR)/libscxassertcppunit.$(PF_STAT_LIB_FILE_SUFFIX) $(INTERMEDIATE_DIR)/scxcore-devel/lib\n\t$(MKPATH) $(INTERMEDIATE_DIR)/scxcore-devel/include/testutils\n\t$(COPY) $(SCXPAL_TEST_ROOT)/include/testutils/scxunit.h $(INTERMEDIATE_DIR)/scxcore-devel/include/testutils\nifeq ($(LOCAL_OMI),1)\n\t# Create an OMI development area for use in running utilities\n\t# TODO - Is there an alias for mkdir? Not $(MKDIR) or $(MAKEDIR), those didn't work\n\t$(RMDIR) -rf $(INTERMEDIATE_DIR)/omi \n\t-mkdir -p $(INTERMEDIATE_DIR)/omi/etc/omiregister/root-scx\n\t$(COPY) -r $(SCXOMI_DIR)/etc $(INTERMEDIATE_DIR)/omi\n\t$(COPY) -r $(SCXOMI_DEV_ROOT)/* $(INTERMEDIATE_DIR)/omi\n\t$(COPY) -r $(SCXOMI_DIR)/share $(INTERMEDIATE_DIR)/omi\nendif\n\n#================================================================================\n# Doxygen Targets\n#================================================================================\n\n# Build the Doxygen documentation for the SCXCore lib\ndoxygen_corelib:\n\t-$(RMDIR) $(DOXYGEN_OUTPUT_DIR)/scxcore_doc\n\t$(MKPATH) $(DOXYGEN_OUTPUT_DIR)/scxcore_doc\n\t( cat doxygen_scxcore.cfg ; \\\n\t echo \"STRIP_FROM_PATH=$(SCX_SRC_ROOT)\"; \\\n\t echo \"OUTPUT_DIRECTORY=$(DOXYGEN_OUTPUT_DIR)/scxcore_doc\"; \\\n\t echo \"WARN_LOGFILE=$(INTERMEDIATE_DIR)/doxygen_build.log\"; ) | doxygen -\n\tif [ -s $(INTERMEDIATE_DIR)/doxygen_build.log ] ; then echo \"$(INTERMEDIATE_DIR)/doxygen_build.log:1:Warnings in doxygenlog\"; fi\n\ndoxygen_clean:\n\t-$(RMDIR) $(DOXYGEN_OUTPUT_DIR)/scxcore_doc\n\n#================================================================================\n# Dependency generation Targets\n#================================================================================\n\n# Rule for automatically generating dependencies.\nOBJFILES=$(STATIC_CORELIB_OBJFILES) \\\n\t$(STATIC_ASSERT_ABORTLIB_OBJFILES) \\\n\t$(STATIC_PROVIDERLIB_OBJFILES) \\\n\t$(STATIC_SCXADMIN_OBJFILES) \\\n\t$(SCXADMIN_OBJFILES) \\\n\t$(SCXSSLCONFIG_OBJFILES) \\\n\t$(REGEX_TEST_OBJFILES)\n\nDEPFILES=$(OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d)\n\n#================================================================================\n# Version information header file\n#================================================================================\n\n $(INT_INCLUDE_DIR)/buildversion.h : $(SCX_BRD)/build/Makefile.version\n\t-$(MKPATH) $(@D)\n\t@$(ECHO) \"Creating $@\" \n\t@$(call pf_fwrite,\"/*------------------------------------------------------------------------------\", $@)\n\t@$(call pf_fappend,\" Copyright (C) 2007 Microsoft Corp. \", $@)\n\t@$(call pf_fappend,\" \", $@)\n\t@$(call pf_fappend,\"*/ \", $@)\n\t@$(call pf_fappend,\"/** \", $@)\n\t@$(call pf_fappend,\" \\file \", $@)\n\t@$(call pf_fappend,\" \", $@)\n\t@$(call pf_fappend,\" \\brief Auto generated file containing build version information \", $@)\n\t@$(call pf_fappend,\" \", $@)\n\t@$(call pf_fappend,\" \\author Automated Build System \", $@)\n\t@$(call pf_fappend,\" \", $@)\n\t@$(call pf_fappend,\" DO NOT EDIT THIS FILE! \", $@)\n\t@$(call pf_fappend,\" DO NOT CHECK IN THIS FILE! \", $@)\n\t@$(call pf_fappend,\"*/ \", $@)\n\t@$(call pf_fappend,\"/*----------------------------------------------------------------------------*/\", $@)\n\t@$(call pf_fappend,\"#ifndef BUILDVERSION_H \", $@)\n\t@$(call pf_fappend,\"#define BUILDVERSION_H \", $@)\n\t@$(call pf_fappend,\" \", $@)\n\t@$(call pf_fappend,\"#include <string> \", $@)\n\t@$(call pf_fappend,\" \", $@)\n\t@$(call pf_fappend,\"/** Major version number */ \", $@)\n\t@$(call pf_fappend,\"const int SCX_BUILDVERSION_MAJOR = $(SCX_BUILDVERSION_MAJOR); \", $@)\n\t@$(call pf_fappend,\"/** Minor version number */ \", $@)\n\t@$(call pf_fappend,\"const int SCX_BUILDVERSION_MINOR = $(SCX_BUILDVERSION_MINOR); \", $@)\n\t@$(call pf_fappend,\"/** Patch version number */ \", $@)\n\t@$(call pf_fappend,\"const int SCX_BUILDVERSION_PATCH = $(SCX_BUILDVERSION_PATCH); \", $@)\n\t@$(call pf_fappend,\"/** Build number */ \", $@)\n\t@$(call pf_fappend,\"const int SCX_BUILDVERSION_BUILDNR = $(SCX_BUILDVERSION_BUILDNR); \", $@)\n\t@$(call pf_fappend,\"/** Build date */ \", $@)\n\t@$(call pf_fappend,\"const std::wstring SCX_BUILDVERSION_DATE(L\\\"$(SCX_BUILDVERSION_DATE)\\\"); \", $@)\n\t@$(call pf_fappend,\"/** Build status */ \", $@)\n\t@$(call pf_fappend,\"const std::wstring SCX_BUILDVERSION_STATUS(L\\\"$(SCX_BUILDVERSION_STATUS)\\\"); \", $@)\n\t@$(call pf_fappend,\" \", $@)\n\t@$(call pf_fappend,\"#endif /* BUILDVERSION_H */ \", $@)\n\t@$(call pf_fappend,\"/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\", $@)\n\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.621835470199585, "alphanum_fraction": 0.621835470199585, "avg_line_length": 20.066667556762695, "blob_id": "060fb8cd16df82d48b3fd6c53757abd26666ba83", "content_id": "246c0968a12ae2c8414e56113859203c76298e12", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 632, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/test/util/testapp/memdata.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n */\n#pragma once\n \n#include <string>\n\nusing namespace std;\n \nclass MEMData\n{\npublic:\n MEMData(void);\n virtual ~MEMData(void);\n \n int UpdateData(void);\n\n unsigned int MEMTotalMB;\n unsigned int MEMUsedPercent;\n unsigned int MEMUsedMB;\n unsigned int MEMFreePercent;\n unsigned int MEMFreeMB;\n\n unsigned int MEMSwapTotalMB;\n unsigned int MEMSwapUsedPercent;\n unsigned int MEMSwapUsedMB;\n unsigned int MEMSwapFreePercent;\n unsigned int MEMSwapFreeMB;\n};\n" }, { "alpha_fraction": 0.6342913508415222, "alphanum_fraction": 0.6342913508415222, "avg_line_length": 26.509090423583984, "blob_id": "7a1830700865457da19db307f84a15155627bb06", "content_id": "005e51331c454c57ac4f900d49231b7d5dcd9985", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3027, "license_type": "permissive", "max_line_length": 80, "num_lines": 110, "path": "/source/code/providers/SCX_OperatingSystem_Class_Provider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/* @migen@ */\n#ifndef _SCX_OperatingSystem_Class_Provider_h\n#define _SCX_OperatingSystem_Class_Provider_h\n\n#include \"SCX_OperatingSystem.h\"\n#ifdef __cplusplus\n# include <micxx/micxx.h>\n# include \"module.h\"\n\nMI_BEGIN_NAMESPACE\n\n/*\n**==============================================================================\n**\n** SCX_OperatingSystem provider class declaration\n**\n**==============================================================================\n*/\n\nclass SCX_OperatingSystem_Class_Provider\n{\n/* @MIGEN.BEGIN@ CAUTION: PLEASE DO NOT EDIT OR DELETE THIS LINE. */\nprivate:\n Module* m_Module;\n\npublic:\n SCX_OperatingSystem_Class_Provider(\n Module* module);\n\n ~SCX_OperatingSystem_Class_Provider();\n\n void Load(\n Context& context);\n\n void Unload(\n Context& context);\n\n void EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter);\n\n void GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instance,\n const PropertySet& propertySet);\n\n void CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& newInstance);\n\n void ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& modifiedInstance,\n const PropertySet& propertySet);\n\n void DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instance);\n\n void Invoke_RequestStateChange(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_RequestStateChange_Class& in);\n\n void Invoke_Reboot(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_Reboot_Class& in);\n\n void Invoke_Shutdown(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_Shutdown_Class& in);\n\n void Invoke_ExecuteCommand(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_ExecuteCommand_Class& in);\n\n void Invoke_ExecuteShellCommand(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_ExecuteShellCommand_Class& in);\n\n void Invoke_ExecuteScript(\n Context& context,\n const String& nameSpace,\n const SCX_OperatingSystem_Class& instanceName,\n const SCX_OperatingSystem_ExecuteScript_Class& in);\n\n/* @MIGEN.END@ CAUTION: PLEASE DO NOT EDIT OR DELETE THIS LINE. */\n};\n\nMI_END_NAMESPACE\n\n#endif /* __cplusplus */\n\n#endif /* _SCX_OperatingSystem_Class_Provider_h */\n\n" }, { "alpha_fraction": 0.6171779036521912, "alphanum_fraction": 0.6269938945770264, "avg_line_length": 25.29032325744629, "blob_id": "0a39f1e6275da0cae70733b7858d639218bec56e", "content_id": "5f116f1fc80f88d0edd67b8933996472446c9ad1", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1630, "license_type": "permissive", "max_line_length": 109, "num_lines": 62, "path": "/source/code/shared/tools/scx_prune_repository/moffile.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n#\n##\n# Contains the MofFile class\n#\n# Date: 2008-10-28 16:18:50\n#\n\nimport re\n\n##\n# Class representing necessary information\n# from a mof file.\n#\nclass MofFile:\n\n ##\n # Constructor\n # Parses the mof file to find all class definitions.\n # The defined class names and their base classes are saved\n # for later access.\n #\n def __init__(self, filename):\n self.filename = filename\n\n self.definedClasses = []\n self.dependentClasses = []\n\n try:\n content = open(self.filename, 'r')\n except IOError:\n return\n\n pattern = re.compile('class\\s+(\\S+)\\s*(:\\s*(\\S+)\\s*)?{')\n iterator = pattern.finditer(content.read())\n for match in iterator:\n (cimclass, baseclass) = match.group(1, 3)\n \n if baseclass and baseclass not in self.dependentClasses and baseclass not in self.definedClasses:\n self.dependentClasses.append(baseclass)\n self.definedClasses.append(cimclass)\n\n ##\n # Retrieve the filename that this MofFile was created with.\n #\n def GetFileName(self):\n return self.filename\n\n ##\n # Retrieve the names of all external cim classes that are refered\n # to as base classes in this mof file as a list of strings.\n #\n def GetDependentClasses(self):\n return self.dependentClasses\n\n ##\n # Retrieve the class names of all cim classes defined in this\n # mof file.\n #\n def GetDefinedClasses(self):\n return self.definedClasses\n" }, { "alpha_fraction": 0.41582247614860535, "alphanum_fraction": 0.42788228392601013, "avg_line_length": 29.940298080444336, "blob_id": "0e74d28dc37bb1926328596b2851e6b0492db28b", "content_id": "30c5d8024179f3213072e29d4bdb4afaf6d1f4af", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4146, "license_type": "permissive", "max_line_length": 106, "num_lines": 134, "path": "/source/code/providers/support/appserver/weblogicappserverinstance.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file weblogicappserverinstances.cpp\n\n \\brief PAL representation of a WebLogic application server\n\n \\date 11-08-18 12:00:00\n */\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <string>\n#include <scxcorelib/stringaid.h>\n\n#include \"appserverconstants.h\"\n#include \"appserverinstance.h\"\n#include \"weblogicappserverinstance.h\"\n\nusing namespace std;\nusing namespace SCXCoreLib;\n\nnamespace SCXSystemLib {\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor\n\n \\param[in] id Identifier for the appserver (= install \n path for the appserver)\n \\param[in] deps Dependency instance to use\n */\n WebLogicAppServerInstance::WebLogicAppServerInstance(const wstring& id) :\n AppServerInstance(id, APP_SERVER_TYPE_WEBLOGIC) {\n SCX_LOGTRACE(m_log, wstring(L\"WebLogicAppServerInstance default constructor - \").append(GetId()));\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Destructor\n */\n WebLogicAppServerInstance::~WebLogicAppServerInstance()\n {\n SCX_LOGTRACE(m_log, wstring(L\"WebLogicAppServerInstance destructor - \").append(GetId()));\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Update values\n\n */\n void WebLogicAppServerInstance::Update()\n {\n SCX_LOGTRACE(m_log, wstring(L\"WebLogicAppServerInstance::Update() - \").append(GetId()));\n }\n\n \n /**\n Extract the major version number from the complete version\n\n \\param[in] version version of the application server\n Retval: major version number\n */\n wstring WebLogicAppServerInstance::ExtractMajorVersion(const wstring& version)\n {\n vector<wstring> parts;\n\n StrTokenizeStr(version, parts, L\".\");\n wstring returnValue = L\"\";\n \n if (parts.size() >= 3)\n {\n // version consists of:\n //\n // major.minor.revision\n //\n // i.e. 10.3.2 maps to\n //\n // major: 10\n // minor: 3\n // revision: 2\n unsigned int major = StrToUInt(parts[0]);\n unsigned int minor = StrToUInt(parts[1]);\n unsigned int revision = StrToUInt(parts[2]);\n \n switch (major)\n {\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n case 9:\n returnValue = parts[0];\n break;\n case 10:\n if (WEBLOGIC_VERSION_MINOR == minor)\n {\n if (0 == revision)\n {\n returnValue = WEBLOGIC_BRANDED_VERSION_10; \n }\n else\n {\n returnValue = WEBLOGIC_BRANDED_VERSION_11;\n } \n }\n else if (minor < WEBLOGIC_VERSION_MINOR)\n {\n returnValue = WEBLOGIC_BRANDED_VERSION_10;\n }\n else //if (minor > WEBLOGIC_VERSION_MINOR)\n {\n returnValue = WEBLOGIC_BRANDED_VERSION_11;\n }\n \n break;\n case 12:\n returnValue = parts[0];\n break;\n default:\n returnValue = WEBLOGIC_BRANDED_VERSION_11;\n }\n }\n\n return returnValue;\n }\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6432949304580688, "alphanum_fraction": 0.6466382145881653, "avg_line_length": 34.893333435058594, "blob_id": "ba2bd2df7ab5b64ce63ef596c35d1ec354b0aac9", "content_id": "09d6a2a61ea70c4e47a97504ca933e3dde87e2dd", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10768, "license_type": "permissive", "max_line_length": 130, "num_lines": 300, "path": "/source/code/providers/SCX_LANEndpoint_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_LANEndpoint_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-14-2013 11:09:45\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_LANEndpoint_Class_Provider.h\"\n#include \"SCX_LANEndpoint.h\"\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxthreadlock.h>\n#include <scxcorelib/scxnameresolver.h>\n#include <scxsystemlib/networkinterfaceenumeration.h>\n#include \"support/networkprovider.h\"\n#include \"support/scxcimutils.h\"\n#include <sstream>\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/scxpatternfinder.h>\n\n# define QLENGTH 1000\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\nusing namespace SCXCore;\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(Context& context,\n SCX_LANEndpoint_Class& inst, bool keysOnly,\n SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> intf)\n{\n // Add the key properperties first.\n inst.CreationClassName_value(\"SCX_LANEndpoint\");\n inst.Name_value(StrToMultibyte(intf->GetName()).c_str());\n\n // Add the scoping systems keys.\n inst.SystemCreationClassName_value(\"SCX_ComputerSystem\");\n SCXCoreLib::NameResolver mi;\n inst.SystemName_value(StrToMultibyte(mi.GetHostDomainname()).c_str());\n if (!keysOnly)\n {\n inst.InstanceID_value(StrToMultibyte(intf->GetName()).c_str());\n inst.Caption_value(\"LAN endpoint caption information\");\n inst.Description_value(\"LAN Endpoint description information\");\n \n inst.ElementName_value(StrToMultibyte(intf->GetName()).c_str());\n\n std::wstring text;\n if(intf->GetMACAddressRAW(text))\n {\n inst.MACAddress_value(StrToMultibyte(text).c_str());\n intf->GetMACAddress(text, '-', true);\n inst.FormattedMACAddress_value(StrToMultibyte(text).c_str());\n }\n }\n context.Post(inst);\n}\n\nSCX_LANEndpoint_Class_Provider::SCX_LANEndpoint_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_LANEndpoint_Class_Provider::~SCX_LANEndpoint_Class_Provider()\n{\n}\n\nvoid SCX_LANEndpoint_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for NetworkProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::NetworkProvider::Lock\"));\n SCXCore::g_NetworkProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_NetworkProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_LANEndpoint_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_LANEndpoint_Class_Provider::Load\", SCXCore::g_NetworkProvider.GetLogHandle() );\n}\n\nvoid SCX_LANEndpoint_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for NetworkProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::NetworkProvider::Lock\"));\n SCXCore::g_NetworkProvider.Unload();\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_LANEndpoint_Class_Provider::Unload\", SCXCore::g_NetworkProvider.GetLogHandle() );\n}\n\nvoid SCX_LANEndpoint_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_NetworkProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"LANEndpoint Provider EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for NetworkProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::NetworkProvider::Lock\"));\n\n // Update network PAL instance. If filter parameter provided then \"interfaceString\" will be not blank.\n // If \"interfaceString\" is blank this will update both number of interfaces and returns current statistics for\n // each interfaces else update the instance for the interface given as parameter and return statistics of that interface.\n\n SCXHandle<SCXCore::NetworkProviderDependencies> deps = SCXCore::g_NetworkProvider.getDependencies();\n\n\twstring interfaceString=L\"\";\n size_t instancePos=(size_t)-1;\n\n if(filter) {\n char* exprStr[QLENGTH]={NULL};\n char* qtypeStr[QLENGTH]={NULL};\n\n const MI_Char** expr=(const MI_Char**)&exprStr;\n const MI_Char** qtype=(const MI_Char**)&qtypeStr;\n\n MI_Filter_GetExpression(filter, qtype, expr);\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"LANEndpoint Provider Filter Set with Expression: \",*expr));\n\n\t std::wstring filterQuery(SCXCoreLib::StrFromUTF8(*expr));\n\n SCXCoreLib::SCXPatternFinder::SCXPatternCookie s_patternID = 0, id=0;\n SCXCoreLib::SCXPatternFinder::SCXPatternMatch param;\n std::wstring s_pattern(L\"select * from SCX_LANEndpoint where Name=%name\");\n\n SCXCoreLib::SCXPatternFinder patterenfinder;\n patterenfinder.RegisterPattern(s_patternID, s_pattern);\n\n bool status=patterenfinder.Match(filterQuery, id, param);\n\n if ( status && param.end() != param.find(L\"name\") && id == s_patternID )\n {\n interfaceString=param.find(L\"name\")->second;\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"LANEndpoint Provider Enum Requested for Interface: \",interfaceString));\n }\n }\n\n deps->UpdateIntf(false, interfaceString, interfaceString==L\"\"?NULL:&instancePos);\n\n if (interfaceString == L\"\"){\n SCX_LOGTRACE(log, StrAppend(L\"Number of interfaces = \", deps->IntfCount()));\n for(size_t i = 0; i < deps->IntfCount(); i++)\n {\n SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> intf = deps->GetIntf(i);\n SCX_LANEndpoint_Class inst;\n EnumerateOneInstance(context, inst, keysOnly, intf);\n }\n }\n else if (instancePos != (size_t)-1){\n SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> intf = deps->GetIntf(instancePos);\n SCX_LANEndpoint_Class inst;\n EnumerateOneInstance(context, inst, keysOnly, intf);\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_LANEndpoint_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"LANEndpoint Provider EnumerateInstances end\");\n}\n\nvoid SCX_LANEndpoint_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_LANEndpoint_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for NetworkProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::NetworkProvider::Lock\"));\n\n // We have 4-part key:\n // [Key] Name=eth0\n // [Key] SystemCreationClassName=SCX_ComputerSystem\n // [Key] SystemName=jeffcof64-rhel6-01.scx.com\n // [Key] CreationClassName=SCX_IPProtocolEndpoint\n\n if (!instanceName.Name_exists() || !instanceName.SystemCreationClassName_exists() ||\n !instanceName.SystemName_exists() || !instanceName.CreationClassName_exists())\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n std::string csName;\n try {\n NameResolver mi;\n csName = StrToMultibyte(mi.GetHostDomainname()).c_str();\n } catch (SCXException& e) {\n SCX_LOGWARNING(SCXCore::g_NetworkProvider.GetLogHandle(), StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n // Now compare (case insensitive for the class names, case sensitive for the others)\n if ( 0 != strcasecmp(\"SCX_ComputerSystem\", instanceName.SystemCreationClassName_value().Str())\n || 0 != strcmp(csName.c_str(), instanceName.SystemName_value().Str())\n || 0 != strcasecmp(\"SCX_LANEndpoint\", instanceName.CreationClassName_value().Str()))\n {\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n SCX_LOGTRACE(SCXCore::g_NetworkProvider.GetLogHandle(), L\"LANEndpoint Provider GetInstance\");\n\n // Update network PAL instance. This is both update of number of interfaces and\n // current statistics for each interfaces.\n SCXHandle<SCXCore::NetworkProviderDependencies> deps = SCXCore::g_NetworkProvider.getDependencies();\n deps->UpdateIntf(false);\n\n const std::string interfaceId = instanceName.Name_value().Str();\n\n if (interfaceId.size() == 0)\n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n SCXCoreLib::SCXHandle<SCXSystemLib::NetworkInterfaceInstance> intf = deps->GetIntf(StrFromUTF8(interfaceId));\n\n if (intf == NULL)\n {\n // Didn't find a match.\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n // Found a Match. Enumerate the properties for the instance.\n SCX_LANEndpoint_Class inst;\n EnumerateOneInstance(context, inst, false, intf);\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_LANEndpoint_Class_Provider::GetInstance\", SCXCore::g_NetworkProvider.GetLogHandle() );\n}\n\nvoid SCX_LANEndpoint_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_LANEndpoint_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_LANEndpoint_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_LANEndpoint_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_LANEndpoint_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_LANEndpoint_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_LANEndpoint_Class_Provider::Invoke_RequestStateChange(\n Context& context,\n const String& nameSpace,\n const SCX_LANEndpoint_Class& instanceName,\n const SCX_LANEndpoint_RequestStateChange_Class& in)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.40422722697257996, "alphanum_fraction": 0.41479524970054626, "avg_line_length": 38.78947448730469, "blob_id": "8ec2dfed92aa8884787fef7264fdea06405a6186", "content_id": "ec1346f000204db802345fcdb41b7aedfda95983", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 757, "license_type": "permissive", "max_line_length": 81, "num_lines": 19, "path": "/build/Makefile.stub", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-03-20\n# This target can be used by tfsbuild to make the target dir for debugging the\n# TFSbuild process without doing the whole make. \n#--------------------------------------------------------------------------------\n\nSTUBREADME=$(TARGET_DIR)/README.TXT\n\nstub : $(STUBREADME)\n\n$(STUBREADME) :\n\techo TDIR: $(TARGET_DIR)\n\t$(MKPATH) $(TARGET_DIR)\n\techo \"place holder for stub directory from make stub\" > $(STUBREADME)\n\n#-------------------------------- End of File -----------------------------------\n\n" }, { "alpha_fraction": 0.5733333230018616, "alphanum_fraction": 0.581818163394928, "avg_line_length": 21.29729652404785, "blob_id": "a363c9aa4f13518a643cf78ad0fd744f51e7151f", "content_id": "b8c1b466bdc88f0a21c294248ea6e11524758e80", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 825, "license_type": "permissive", "max_line_length": 100, "num_lines": 37, "path": "/source/code/shared/tools/scx_admin/cimconfigurator.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief scx cim configuration tool for SCX.\n\n \\date 8/27/2008\n\n*/\n#ifndef _CIM_CONFIGURATOR_H\n#define _CIM_CONFIGURATOR_H\n\n#include <scxcorelib/scxcmn.h>\n#include \"admin_api.h\"\n\n#include <iostream>\n\nnamespace SCXCoreLib\n{\n /**\n Class for administration of Pegasus via scxadmin tool\n */\n class SCX_CimConfigurator : public SCX_AdminLogAPI {\n public:\n SCX_CimConfigurator();\n ~SCX_CimConfigurator();\n\n bool LogRotate();\n bool Print(std::wostringstream& buf) const;\n bool Reset();\n bool Set(LogLevelEnum level);\n };\n}\n\n#endif /* _CIM_CONFIGURATOR_H */\n" }, { "alpha_fraction": 0.4879145622253418, "alphanum_fraction": 0.4940977990627289, "avg_line_length": 27.22222137451172, "blob_id": "c350ef2ef0bf977a20709926044a1e037d9bf906", "content_id": "4dc155920712107446db113970012cba3f1ea7cd", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1779, "license_type": "permissive", "max_line_length": 108, "num_lines": 63, "path": "/source/code/providers/support/appserver/appserverprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file appserverprovider.cpp\n\n \\brief App Server provider implementation\n\n \\date 05-08-13 \n*/\n/*----------------------------------------------------------------------------*/\n\n#include \"../startuplog.h\"\n#include \"appserverenumeration.h\"\n#include \"appserverprovider.h\"\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nnamespace SCXCore\n{\n void ApplicationServerProvider::Load()\n {\n SCXASSERT( ms_loadCount >= 0 );\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.appserverprovider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"ApplicationServerProvider::Load()\");\n\n if ( NULL == m_deps )\n {\n m_deps = new AppServerProviderPALDependencies();\n }\n\n m_appservers = m_deps->CreateEnum();\n m_appservers->Init();\n }\n }\n\n void ApplicationServerProvider::Unload()\n {\n SCX_LOGTRACE(m_log, L\"ApplicationServerProvider::Unload()\");\n\n SCXASSERT( ms_loadCount >= 1 );\n if ( 0 == --ms_loadCount )\n {\n if (NULL != m_appservers)\n {\n m_appservers->CleanUp();\n m_appservers = NULL;\n }\n\n m_deps = NULL;\n }\n }\n\n // Only construct ApplicationServer class once\n int ApplicationServerProvider::ms_loadCount = 0;\n ApplicationServerProvider g_AppServerProvider;\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n\n" }, { "alpha_fraction": 0.5606287717819214, "alphanum_fraction": 0.565119743347168, "avg_line_length": 32.400001525878906, "blob_id": "48b8b9971658b539ad33166e1a530a85569bc970", "content_id": "9df97c554c79ba13c722999eef247adbdded3971", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2672, "license_type": "permissive", "max_line_length": 102, "num_lines": 80, "path": "/source/code/shared/tools/scx_admin/servicecontrol.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n \n*/\n/**\n \\file \n\n \\brief Defines the service control classes.\n \n \\date 2008-08-28 08:49\n\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef SERVICECONTROL_H\n#define SERVICECONTROL_H\n\n#include \"admin_api.h\"\n\n/*----------------------------------------------------------------------------*/\n/**\n Base class for Admin service controls implementing the service control API.\n\n Implements the common default behaviour for SCX services.\n*/\nclass SCX_AdminServiceControl : public SCX_AdminServiceManagementAPI\n{\npublic:\n SCX_AdminServiceControl( const std::wstring& name, \n const std::wstring& start_command,\n const std::wstring& stop_command);\n virtual ~SCX_AdminServiceControl();\n\n virtual bool Start( std::wstring& info ) const;\n virtual bool Stop( std::wstring& info ) const;\n virtual bool Restart( std::wstring& info ) const;\n virtual bool Status( std::wstring& info ) const;\n\n unsigned int CountProcessesAlive( ) const;\n\nprotected:\n std::wstring m_name; //!< Process name of the service.\n std::wstring m_start; //!< Service start command.\n std::wstring m_stop; //!< Service stop command.\n\n void ExecuteCommand( const std::wstring& command, std::wstring& info ) const;\n\n SCX_AdminServiceControl(); //!< Intentionally protected.\n SCX_AdminServiceControl( SCX_AdminServiceControl& ); //!< Intentionally protected.\n SCX_AdminServiceControl& operator= (SCX_AdminServiceControl& ); //!< Intentionally protected.\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n Implements the cimom service controller.\n*/\nclass SCX_CimomServiceControl : public SCX_AdminServiceControl\n{\npublic:\n SCX_CimomServiceControl();\n virtual ~SCX_CimomServiceControl();\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n Implements the provider service controller.\n*/\nclass SCX_ProviderServiceControl : public SCX_AdminServiceControl\n{\npublic:\n SCX_ProviderServiceControl();\n\n virtual ~SCX_ProviderServiceControl();\n\n virtual bool Start( std::wstring& info ) const;\n virtual bool Stop( std::wstring& info ) const;\n virtual bool Restart( std::wstring& info ) const;\n virtual bool Status( std::wstring& info ) const;\n};\n#endif /* SERVICECONTROL_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6216443777084351, "alphanum_fraction": 0.6247283816337585, "avg_line_length": 32.334110260009766, "blob_id": "3f537154940921347f18de5ebc855103c827d3f4", "content_id": "515866e02a6621d9ca65892cdc48d8f53b5625f5", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14267, "license_type": "permissive", "max_line_length": 145, "num_lines": 428, "path": "/source/code/providers/SCX_UnixProcessStatisticalInformation_Class_Provider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file SCX_UnixProcessStatisticalInformation_Class_Provider.cpp\n\n \\brief Provider support using OMI framework.\n \n \\date 03-22-2013 17:48:44\n*/\n/*----------------------------------------------------------------------------*/\n\n/* @migen@ */\n#include <MI.h>\n#include \"SCX_UnixProcessStatisticalInformation_Class_Provider.h\"\n#include \"SCX_UnixProcessStatisticalInformation.h\"\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxthreadlock.h>\n#include <scxcorelib/scxnameresolver.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <scxsystemlib/processinstance.h>\n#include \"support/scxcimutils.h\"\n#include \"support/processprovider.h\"\n#include <sstream>\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/scxpatternfinder.h>\n#include <string>\n\n# define QLENGTH 1000\n\nusing namespace SCXSystemLib;\nusing namespace SCXCoreLib;\n\nMI_BEGIN_NAMESPACE\n\nstatic void EnumerateOneInstance(Context& context,\n SCX_UnixProcessStatisticalInformation_Class& inst, bool keysOnly,\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> processinst)\n{\n SCXLogHandle& log = SCXCore::g_ProcessProvider.GetLogHandle();\n\n // Add the key properties first.\n scxulong pid;\n if (processinst->GetPID(pid))\n {\n inst.Handle_value(StrToUTF8(StrFrom(pid)).c_str());\n }\n\n // Add keys of scoping operating system\n try {\n SCXCoreLib::NameResolver mi;\n inst.CSName_value(StrToMultibyte(mi.GetHostDomainname()).c_str());\n } catch (SCXException& e){\n SCX_LOGWARNING(log, StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n try {\n SCXSystemLib::SCXOSTypeInfo osinfo;\n inst.OSName_value(StrToMultibyte(osinfo.GetOSName(true)).c_str());\n } catch (SCXException& e){\n SCX_LOGWARNING(log, StrAppend(\n StrAppend(L\"Can't read OS name because \", e.What()),\n e.Where()));\n }\n\n inst.CSCreationClassName_value(\"SCX_ComputerSystem\");\n inst.OSCreationClassName_value(\"SCX_OperatingSystem\");\n inst.ProcessCreationClassName_value(\"SCX_UnixProcessStatisticalInformation\");\n\n std::string name;\n if (processinst->GetName(name))\n {\n inst.Name_value(name.c_str());\n }\n\n if (!keysOnly)\n {\n unsigned int uint = 0;\n scxulong ulong = 0;\n\n inst.Description_value(\"A snapshot of a current process\");\n inst.Caption_value(\"Unix process information\");\n\n if (processinst->GetRealData(ulong))\n {\n inst.RealData_value(ulong);\n }\n\n if (processinst->GetRealStack(ulong))\n {\n inst.RealStack_value(ulong);\n }\n\n if (processinst->GetVirtualText(ulong))\n {\n inst.VirtualText_value(ulong);\n }\n\n if (processinst->GetVirtualData(ulong))\n {\n inst.VirtualData_value(ulong);\n }\n\n if (processinst->GetVirtualStack(ulong))\n {\n inst.VirtualStack_value(ulong);\n }\n\n if (processinst->GetVirtualMemoryMappedFileSize(ulong))\n {\n inst.VirtualMemoryMappedFileSize_value(ulong);\n }\n\n if (processinst->GetVirtualSharedMemory(ulong))\n {\n inst.VirtualSharedMemory_value(ulong);\n }\n\n if (processinst->GetCpuTimeDeadChildren(ulong))\n {\n inst.CpuTimeDeadChildren_value(ulong);\n }\n\n if (processinst->GetSystemTimeDeadChildren(ulong))\n {\n inst.SystemTimeDeadChildren_value(ulong);\n }\n\n if (processinst->GetRealText(ulong))\n {\n inst.RealText_value(ulong);\n }\n\n if (processinst->GetCPUTime(uint))\n {\n inst.CPUTime_value(uint);\n }\n\n if (processinst->GetBlockWritesPerSecond(ulong))\n {\n inst.BlockWritesPerSecond_value(ulong);\n }\n\n if (processinst->GetBlockReadsPerSecond(ulong))\n {\n inst.BlockReadsPerSecond_value(ulong);\n }\n\n if (processinst->GetBlockTransfersPerSecond(ulong))\n {\n inst.BlockTransfersPerSecond_value(ulong);\n }\n\n if (processinst->GetPercentUserTime(ulong))\n {\n inst.PercentUserTime_value((unsigned char) ulong);\n }\n\n if (processinst->GetPercentPrivilegedTime(ulong))\n {\n inst.PercentPrivilegedTime_value((unsigned char) ulong);\n }\n\n if (processinst->GetUsedMemory(ulong))\n {\n inst.UsedMemory_value(ulong);\n }\n\n if (processinst->GetPercentUsedMemory(ulong))\n {\n inst.PercentUsedMemory_value((unsigned char) ulong);\n }\n\n if (processinst->GetPagesReadPerSec(ulong))\n {\n inst.PagesReadPerSec_value(ulong);\n }\n }\n context.Post(inst);\n}\n\nSCX_UnixProcessStatisticalInformation_Class_Provider::SCX_UnixProcessStatisticalInformation_Class_Provider(\n Module* module) :\n m_Module(module)\n{\n}\n\nSCX_UnixProcessStatisticalInformation_Class_Provider::~SCX_UnixProcessStatisticalInformation_Class_Provider()\n{\n}\n\nvoid SCX_UnixProcessStatisticalInformation_Class_Provider::Load(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n SCXCore::g_ProcessProvider.Load();\n\n // Notify that we don't wish to unload\n MI_Result r = context.RefuseUnload();\n if ( MI_RESULT_OK != r )\n {\n SCX_LOGWARNING(SCXCore::g_ProcessProvider.GetLogHandle(),\n SCXCoreLib::StrAppend(L\"SCX_UnixProcessStatisticalInformation_Class_Provider::Load() refuses to not unload, error = \", r));\n }\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcessStatisticalInformation_Class_Provider::Load\", SCXCore::g_ProcessProvider.GetLogHandle() );\n}\n\nvoid SCX_UnixProcessStatisticalInformation_Class_Provider::Unload(\n Context& context)\n{\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n SCXCore::g_ProcessProvider.Unload();\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcessStatisticalInformation_Class_Provider::Unload\", SCXCore::g_ProcessProvider.GetLogHandle() );\n}\n\nvoid SCX_UnixProcessStatisticalInformation_Class_Provider::EnumerateInstances(\n Context& context,\n const String& nameSpace,\n const PropertySet& propertySet,\n bool keysOnly,\n const MI_Filter* filter)\n{\n SCXLogHandle& log = SCXCore::g_ProcessProvider.GetLogHandle();\n SCX_LOGTRACE(log, L\"UnixProcessStat Provider EnumerateInstances begin\");\n\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n\n SCX_LOGTRACE(SCXCore::g_ProcessProvider.GetLogHandle(), L\"Process Provider EnumerateInstances\");\n\n SCXHandle<SCXSystemLib::ProcessEnumeration> processEnum = SCXCore::g_ProcessProvider.GetProcessEnumerator();\n\n string processID=\"\";\n\n if(filter) {\n char* exprStr[QLENGTH]={NULL};\n char* qtypeStr[QLENGTH]={NULL};\n\n const MI_Char** expr=(const MI_Char**)&exprStr;\n const MI_Char** qtype=(const MI_Char**)&qtypeStr;\n\n MI_Filter_GetExpression(filter, qtype, expr);\n SCX_LOGTRACE(log, SCXCoreLib::StrAppend(L\"Unix Process Statistical Provider Filter Set with Expression: \",*expr));\n\n std::wstring filterQuery(SCXCoreLib::StrFromUTF8(*expr));\n\n SCXCoreLib::SCXPatternFinder::SCXPatternCookie s_patternID = 0, id=0;\n SCXCoreLib::SCXPatternFinder::SCXPatternMatch param;\n std::wstring s_pattern(L\"select * from SCX_UnixProcessStatisticalInformation where Handle=%name\");\n\n SCXCoreLib::SCXPatternFinder patterenfinder;\n patterenfinder.RegisterPattern(s_patternID, s_pattern);\n\n bool status=patterenfinder.Match(filterQuery, id, param);\n\n if (status && id == s_patternID && param.end() != param.find(L\"name\"))\n {\n processID=StrToUTF8(param.find(L\"name\")->second);\n SCX_LOGTRACE(log, StrAppend(L\"Unix Process Statistical Provider Enum Requested for Process ID: \", param.find(L\"name\")->second));\n }\n }\n\n if ( processID != \"\" ) {\n stringstream ss(processID);\n int pid;\n ss >> pid;\n processEnum->UpdateSpecific(pid);\n }\n else\n processEnum->Update();\n\n SCX_LOGTRACE(log, StrAppend(L\"Number of Processes = \", processEnum->Size()));\n\n for(size_t i = 0; i < processEnum->Size(); i++)\n {\n if ( processID != \"\"){\n scxulong pid = 0;\n processEnum->GetInstance(i)->GetPID(pid);\n stringstream ss; ss<<pid;\n string spid;ss>>spid;\n if ( spid != processID) continue;\n }\n\n SCX_UnixProcessStatisticalInformation_Class proc;\n EnumerateOneInstance(context, proc, keysOnly, processEnum->GetInstance(i));\n if ( processID != \"\") break;\n }\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcessStatisticalInformation_Class_Provider::EnumerateInstances\", log );\n\n SCX_LOGTRACE(log, L\"UnixProcessStat Provider EnumerateInstances end\");\n}\n\nvoid SCX_UnixProcessStatisticalInformation_Class_Provider::GetInstance(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcessStatisticalInformation_Class& instanceName,\n const PropertySet& propertySet)\n{\n SCXLogHandle& log = SCXCore::g_ProcessProvider.GetLogHandle();\n\n SCX_PEX_BEGIN\n {\n // Global lock for ProcessProvider class\n SCXCoreLib::SCXThreadLock lock(SCXCoreLib::ThreadLockHandleGet(L\"SCXCore::ProcessProvider::Lock\"));\n\n // We have 7-part key:\n // [Key] Name=udevd\n // [Key] CSCreationClassName=SCX_ComputerSystem\n // [Key] CSName=jeffcof64-rhel6-01.scx.com\n // [Key] OSCreationClassName=SCX_OperatingSystem\n // [Key] OSName=Red Hat Distribution\n // [Key] Handle=54321\n // [Key] ProcessCreationClassName=SCX_UnixProcessStatisticalInformation\n\n if ( !instanceName.Handle_exists() ||\n !instanceName.Name_exists() || \n !instanceName.CSCreationClassName_exists() ||\n !instanceName.CSName_exists() ||\n !instanceName.OSCreationClassName_exists() ||\n !instanceName.OSName_exists() ||\n !instanceName.ProcessCreationClassName_exists() ) \n {\n context.Post(MI_RESULT_INVALID_PARAMETER);\n return;\n }\n\n SCXCoreLib::NameResolver mi;\n std::string csName;\n try {\n csName = StrToMultibyte(mi.GetHostDomainname()).c_str();\n } catch (SCXException& e){\n SCX_LOGWARNING(log, StrAppend(\n StrAppend(L\"Can't read host/domainname because \", e.What()),\n e.Where()));\n }\n\n SCXSystemLib::SCXOSTypeInfo osinfo;\n std::string osName;\n try {\n osName = StrToMultibyte(osinfo.GetOSName(true)).c_str();\n } catch (SCXException& e){\n SCX_LOGWARNING(log, StrAppend(\n StrAppend(L\"Can't read OS name because \", e.What()),\n e.Where()));\n }\n\n SCX_LOGTRACE(log, L\"Process Provider GetInstances\");\n SCXHandle<SCXSystemLib::ProcessEnumeration> processEnum = SCXCore::g_ProcessProvider.GetProcessEnumerator();\n processEnum->Update();\n\n SCXCoreLib::SCXHandle<SCXSystemLib::ProcessInstance> processInst =\n processEnum->GetInstance(StrFromMultibyte(instanceName.Handle_value().Str()));\n\n std::string name;\n if (processInst != NULL)\n {\n processInst->GetName(name);\n }\n\n if ( (processInst == NULL) || \n (0 != strcmp(name.c_str(), instanceName.Name_value().Str())) || \n (0 != strcmp(csName.c_str(), instanceName.CSName_value().Str())) || \n (0 != strcmp(osName.c_str(), instanceName.OSName_value().Str())) ||\n (0 != strcasecmp(\"SCX_ComputerSystem\", instanceName.CSCreationClassName_value().Str())) ||\n (0 != strcasecmp(\"SCX_OperatingSystem\", instanceName.OSCreationClassName_value().Str())) ||\n (0 != strcasecmp(\"SCX_UnixProcessStatisticalInformation\", instanceName.ProcessCreationClassName_value().Str())) )\n {\n // Didn't find a match.\n context.Post(MI_RESULT_NOT_FOUND);\n return;\n }\n\n // Found a Match. Enumerate the properties for the instance.\n SCX_UnixProcessStatisticalInformation_Class proc;\n EnumerateOneInstance(context, proc, false, processInst);\n\n context.Post(MI_RESULT_OK);\n }\n SCX_PEX_END( L\"SCX_UnixProcessStatisticalInformation_Class_Provider::GetInstances\", log );\n}\n\nvoid SCX_UnixProcessStatisticalInformation_Class_Provider::CreateInstance(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcessStatisticalInformation_Class& newInstance)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_UnixProcessStatisticalInformation_Class_Provider::ModifyInstance(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcessStatisticalInformation_Class& modifiedInstance,\n const PropertySet& propertySet)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\nvoid SCX_UnixProcessStatisticalInformation_Class_Provider::DeleteInstance(\n Context& context,\n const String& nameSpace,\n const SCX_UnixProcessStatisticalInformation_Class& instanceName)\n{\n context.Post(MI_RESULT_NOT_SUPPORTED);\n}\n\n\nMI_END_NAMESPACE\n" }, { "alpha_fraction": 0.617253303527832, "alphanum_fraction": 0.6292990446090698, "avg_line_length": 47.589019775390625, "blob_id": "db9a12fec0494e19f600e661d54932dac7307bf0", "content_id": "08eda4207303cc670d81107d1d74847a100e648e", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 89409, "license_type": "permissive", "max_line_length": 429, "num_lines": 1803, "path": "/test/code/providers/appserver_provider/jbossappserverinstance_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\r\n Copyright (c) Microsoft Corporation. All rights reserved.\r\n\r\n Created date 2011-05-18\r\n\r\n jboss appserver data colletion test class.\r\n\r\n*/\r\n/*----------------------------------------------------------------------------*/\r\n#include <scxcorelib/scxcmn.h>\r\n#include <scxcorelib/stringaid.h>\r\n#include <scxcorelib/scxfilesystem.h>\r\n#include <testutils/scxunit.h>\r\n#include <scxcorelib/scxprocess.h>\r\n\r\n#include <jbossappserverinstance.h>\r\n\r\n#include <cppunit/extensions/HelperMacros.h>\r\n\r\nusing namespace SCXCoreLib;\r\nusing namespace SCXSystemLib;\r\nusing namespace std;\r\n\r\n// Test dependencies used to get the XML content from string constants instead of from files\r\n// Also has the ability to control some aspects of the XML to supply, to simulate different problems\r\nclass JBossAppServerInstanceTestPALDependencies : public JBossAppServerInstancePALDependencies\r\n{\r\npublic:\r\n JBossAppServerInstanceTestPALDependencies() : \r\n m_xmlVersionFilename(L\"\"), m_xmlPortsFilename(L\"\"), m_httpBindingProperty(false), \r\n m_includeJbossJar(true), m_version5(true),m_hasJboss7File(true), m_hasBadJboss7File(false), m_version7(false), m_httpBinding(true), m_httpsBinding(true),\r\n m_noPortsFile(false), m_noVersionFile(false), m_noServiceFile(false), m_noServerFile(false), \r\n m_noBindingFile(false), m_emptyPortsFile(false), m_emptyVersionFile(false), m_emptyServiceFile(false), \r\n m_emptyServerFile(false), m_emptyBindingFile(false), m_badPortsXml(false), m_badVersionXml(false), \r\n m_badHttpPortValue(false), m_badPortOffsetValue(false), m_serviceBinding(true),\r\n m_noPortOffsetValue(false), m_badPortOffsetValueWithSocket(false), m_hasEnterpriseVersionFile(false),\r\n\t\tm_domainMode(false), m_domainPortOffset(false),\r\n\t\tm_portBindingName(\"${jboss.service.binding.set:ports-default}\")\r\n {}\r\n \r\n\t// Should the JBoss Instance be a Enterpise Application Server\r\n\tvoid SetHasEnterpriseVersionFile(bool hasEnterpriseVersionFile)\r\n\t{\r\n\t\tm_hasEnterpriseVersionFile = hasEnterpriseVersionFile;\r\n\t}\r\n\r\n\t// Should the JBoss Domain instance have a port offset (JBoss 7 + Wildfly)\r\n\tvoid SetDomainPortOffset(bool domainPortOffset)\r\n\t{\r\n\t\tm_domainPortOffset = domainPortOffset;\r\n\t}\r\n\r\n // Should the JBoss instance be running in Domain mode (JBoss 7 + Wildfly)\r\n void SetDomainMode(bool domainMode)\r\n {\r\n m_domainMode = domainMode;\r\n }\r\n\r\n // Should there be an Port Offset Value attribute in socket-binding-group tag (JBoss 7)\r\n void SetNoPortOffsetValue(bool noPortOffsetValue)\r\n {\r\n m_noPortOffsetValue = noPortOffsetValue;\r\n }\r\n\r\n // Should there be an invalid Port Offset Value attribute in socket-binding-group for secondary option i.e using jboss.socket (JBoss 7)\r\n void SetBadPortOffsetValueWithSocket(bool badPortOffsetValueWithSocket)\r\n {\r\n m_badPortOffsetValueWithSocket = badPortOffsetValueWithSocket;\r\n }\r\n\r\n // Should the XML contain a serviceBindingManager tag\r\n void SetServiceBinding(bool serviceBinding)\r\n {\r\n m_serviceBinding = serviceBinding;\r\n }\r\n\r\n // Should the XML contain a property tag with a name attribute with the value bindingName that contains the string HttpConnector\r\n void SetHttpBindingProperty(bool httpBindingProperty)\r\n {\r\n m_httpBindingProperty = httpBindingProperty;\r\n }\r\n\r\n // Should the XML contain a section describign the HTTPS binding\r\n void SetHttpsBinding(bool httpsBinding)\r\n {\r\n m_httpsBinding = httpsBinding;\r\n }\r\n\r\n // Should the XML contain a section describign the HTTP binding\r\n void SetHttpBinding(bool httpBinding)\r\n {\r\n m_httpBinding = httpBinding;\r\n }\r\n\r\n // Should the XML contain an entry for jboss.jar \r\n void SetIncludeJbossJar(bool includeJbossJar)\r\n {\r\n m_includeJbossJar = includeJbossJar;\r\n }\r\n\r\n // Should the XML contain version 5 or 4\r\n void SetVersion5(bool version5)\r\n {\r\n m_version5 = version5;\r\n }\r\n\r\n //should this File execute the standalone.sh script\r\n void SetHasJboss7File(bool hasJboss7File)\r\n {\r\n m_hasJboss7File = hasJboss7File;\r\n }\r\n\r\n // Should we use XML from JBoss 7 or JBoss 4 or 5\r\n void SetVersion7(bool version7)\r\n {\r\n m_version7 = version7;\r\n }\r\n\r\n //Should the Run command return something without the versoin\r\n void SetHasBadJboss7VersionFile(bool hasBadJboss7VersionFile)\r\n {\r\n m_hasBadJboss7File = hasBadJboss7VersionFile;\r\n }\r\n\r\n // Should the we throw an exception when opening the ports file\r\n void SetNoPortsFile(bool noPortsFile)\r\n {\r\n m_noPortsFile = noPortsFile;\r\n }\r\n\r\n // Should the we throw an exception when opening the version file\r\n void SetNoVersionFile(bool noVersionFile)\r\n {\r\n m_noVersionFile = noVersionFile;\r\n }\r\n\r\n // Should the we throw an exception when opening the service file\r\n void SetNoServiceFile(bool noServiceFile)\r\n {\r\n m_noServiceFile = noServiceFile;\r\n }\r\n\r\n // Should the we throw an exception when opening the server file\r\n void SetNoServerFile(bool noServerFile)\r\n {\r\n m_noServerFile = noServerFile;\r\n }\r\n\r\n // Should the we throw an exception when opening the binding file\r\n void SetNoBindingFile(bool noBindingFile)\r\n {\r\n m_noBindingFile = noBindingFile;\r\n }\r\n\r\n // Should the we return an empty string for the content of the ports file\r\n void SetEmptyPortsFile(bool emptyPortsFile)\r\n {\r\n m_emptyPortsFile = emptyPortsFile;\r\n }\r\n\r\n // Should the we return an empty string for the content of the version file\r\n void SetEmptyVersionFile(bool emptyVersionFile)\r\n {\r\n m_emptyVersionFile = emptyVersionFile;\r\n }\r\n\r\n // Should the we return an empty string for the content of the service file\r\n void SetEmptyServiceFile(bool emptyServiceFile)\r\n {\r\n m_emptyServiceFile = emptyServiceFile;\r\n }\r\n\r\n // Should the we return an empty string for the content of the server file\r\n void SetEmptyServerFile(bool emptyServerFile)\r\n {\r\n m_emptyServerFile = emptyServerFile;\r\n }\r\n\r\n // Should the we return an empty string for the content of the binding file\r\n void SetEmptyBindingFile(bool emptyBindingFile)\r\n {\r\n m_emptyBindingFile = emptyBindingFile;\r\n }\r\n\r\n // Should the we return invalid XML for the content of the ports file\r\n void SetBadPortsXml(bool badPortsXml)\r\n {\r\n m_badPortsXml = badPortsXml;\r\n }\r\n\r\n // Should the we return invalid XML for the content of the version file\r\n void SetBadVersionXml(bool badVersionXml)\r\n {\r\n m_badVersionXml = badVersionXml;\r\n }\r\n\r\n // Should the XML contain a non-numeric value for the HTTP port\r\n void SetBadHttpPortValue(bool badHttpPortValue)\r\n {\r\n m_badHttpPortValue = badHttpPortValue;\r\n }\r\n\r\n // Should the XML contain a non-numeric value for the port offset\r\n void SetBadPortOffsetValue(bool badPortOffsetValue)\r\n {\r\n m_badPortOffsetValue = badPortOffsetValue;\r\n }\r\n\r\n virtual SCXHandle<std::istream> OpenXmlVersionFile(wstring filename)\r\n {\r\n m_xmlVersionFilename = filename;\r\n\r\n SCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n if (m_noVersionFile)\r\n {\r\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\r\n }\r\n\r\n if (m_emptyVersionFile)\r\n {\r\n return xmlcontent;\r\n }\r\n\r\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\r\n *xmlcontent << \"<jar-versions>\" << endl;\r\n *xmlcontent << \"<jar name=\\\"FastInfoset.jar\\\" specVersion=\\\"1.0\\\" specVendor=\\\"JBoss (http://www.jboss.org/)\\\" specTitle=\\\"ITU-T Rec. X.891 | ISO/IEC 24824-1 (Fast Infoset)\\\" implVersion=\\\"1.2.2\\\" implVendor=\\\"Sun Microsystems, Inc.\\\" implTitle=\\\"Fast Infoset Implementation \\\" implVendorID=\\\"com.sun\\\" implURL=\\\"http://www.jboss.org/\\\" sealed=\\\"false\\\" md5Digest=\\\"aaa3ac05dbedcbd8c4d62e11e68a4b7e\\\"/>\" << endl;\r\n *xmlcontent << \"<jar name=\\\"activation.jar\\\" specVersion=\\\"1.1\\\" specVendor=\\\"Sun Microsystems, Inc.\\\" specTitle=\\\"JavaBeans(TM) Activation Framework Specification\\\" implVersion=\\\"1.1\\\" implVendor=\\\"Sun Microsystems, Inc.\\\" implTitle=\\\"Sun Java System Application Server\\\" implVendorID=\\\"com.sun\\\" implURL=\\\"http://www.jboss.org/\\\" sealed=\\\"false\\\" md5Digest=\\\"2dc066d4c6fda44c8e32ea95ad267b2a\\\"/>\" << endl;\r\n\r\n if (m_includeJbossJar)\r\n {\r\n if (m_version5)\r\n {\r\n *xmlcontent << \"<jar name=\\\"jboss.jar\\\" specVersion=\\\"5.1.0.GA\\\" specVendor=\\\"JBoss (http://www.jboss.org/)\\\" specTitle=\\\"JBoss\\\" implVersion=\\\"5.1.0.GA (build: SVNTag=JBoss_5_1_0_GA date=200905221634)\\\" implVendor=\\\"JBoss Inc.\\\" implTitle=\\\"JBoss [The Oracle]\\\" implVendorID=\\\"http://www.jboss.org/\\\" implURL=\\\"http://www.jboss.org/\\\" sealed=\\\"false\\\" md5Digest=\\\"4080a2cc0e907c386fb78247f97139de\\\"/>\" << endl;\r\n }\r\n else\r\n {\r\n *xmlcontent << \"<jar name=\\\"jboss.jar\\\" specVersion=\\\"4.2.1.GA\\\" specVendor=\\\"JBoss (http://www.jboss.org/)\\\" specTitle=\\\"JBoss\\\" implVersion=\\\"4.2.1.GA (build: SVNTag=JBoss_4_2_1_GA date=200707131605)\\\" implVendor=\\\"JBoss Inc.\\\" implTitle=\\\"JBoss [Trinity]\\\" implVendorID=\\\"http://www.jboss.org/\\\" implURL=\\\"http://www.jboss.org/\\\" sealed=\\\"false\\\" md5Digest=\\\"d52311010c99823da360b6c3db8bcdcd\\\"/>\" << endl;\r\n }\r\n }\r\n\r\n *xmlcontent << \"<jar name=\\\"xnio-nio.jar\\\" specVersion=\\\"1.2.1.GA\\\" specVendor=\\\"JBoss, a division of Red Hat, Inc.\\\" specTitle=\\\"XNIO NIO Implementation\\\" implVersion=\\\"1.2.1.GA\\\" implVendor=\\\"JBoss, a division of Red Hat, Inc.\\\" implTitle=\\\"XNIO NIO Implementation\\\" implVendorID=\\\"http://www.jboss.org/\\\" implURL=\\\"http://www.jboss.com/xnio\\\" sealed=\\\"false\\\" md5Digest=\\\"232167be18917246e62c64b75d7922fb\\\"/>\" << endl;\r\n\r\n if (!m_badVersionXml)\r\n {\r\n *xmlcontent << \"</jar-versions>\" << endl;\r\n }\r\n\r\n return xmlcontent;\r\n }\r\n\r\n\tvirtual SCXHandle<std::istream> OpenModuleXmlFile(wstring filename)\r\n\t{\r\n\t\tSCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n\t\tif(m_version7 && !m_hasEnterpriseVersionFile)\r\n\t\t{\r\n\t\t\t*xmlcontent << \"<module xmlns=\\\"urn:jboss:module:1.0\\\" name=\\\"org.jboss.as.server\\\">\"<<endl;\r\n\t\t\t*xmlcontent << \" <main-class name=\\\"org.jboss.as.server.DomainServerMain\\\"/>\"<<endl;\r\n\t\t\t*xmlcontent << \" <resources>\"<<endl;\r\n\t\t\t*xmlcontent << \" <resource-root path=\\\"jboss-as-server-7.0.0.Final.jar\\\"/>\"<<endl;\r\n\t\t\t*xmlcontent << \" </resources>\"<<endl;\r\n\t\t\t*xmlcontent << \"</module>\"<<endl;\r\n\t\t}\r\n\t\telse if(m_hasEnterpriseVersionFile)\r\n\t\t{\r\n\t\t\t*xmlcontent << \"<module xmlns=\\\"urn:jboss:module:1.1\\\" name=\\\"org.jboss.as.version\\\">\"<<endl;\r\n\t\t\t*xmlcontent << \" <main-class name=\\\"org.jboss.as.server.DomainServerMain\\\"/>\"<<endl;\r\n\t\t\t*xmlcontent << \" <resources>\"<<endl;\r\n\t\t\t*xmlcontent << \" <resource-root path=\\\"jboss-as-version-7.2.0.Final-redhat-8.jar\\\"/>\"<<endl;\r\n\t\t\t*xmlcontent << \" </resources>\"<<endl;\r\n\t\t\t*xmlcontent << \"</module>\"<<endl;\r\n\t\t}\r\n\t\treturn xmlcontent;\r\n\t}\r\n\r\n virtual bool versionJBossWildfly(SCXCoreLib::SCXFilePath filepath, jboss_version_type &version)\r\n {\r\n\t\tif(m_hasBadJboss7File)\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\telse if(m_hasEnterpriseVersionFile)\r\n\t\t{\r\n\t\t\tversion = jboss_version_8;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse if(m_hasJboss7File)\r\n\t\t{\r\n\t\t\tversion = jboss_version_7;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\telse\r\n\t\t\treturn false;\r\n }\r\n\r\n\tvirtual SCXHandle<std::istream> OpenDomainHostXmlFile(wstring filename)\r\n\t{\r\n\t\tSCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n *xmlcontent <<\"<host name=\\\"master\\\" xmlns=\\\"urn:jboss:domain:1.2\\\">\"<<endl;\r\n *xmlcontent <<\" <management/>\"<<endl;\r\n *xmlcontent <<\" <interfaces/>\"<<endl;\r\n *xmlcontent <<\" <servers>\"<<endl;\r\n *xmlcontent <<\" <server name=\\\"server-one\\\" group=\\\"main-server-group\\\">\"<<endl;\r\n\t\tif(m_domainPortOffset)\r\n {\r\n\t\t\t*xmlcontent <<\" <socket-bindings port-offset=\\\"100\\\"/>\"<<endl; \r\n }\r\n\t\t*xmlcontent <<\" <!-- Remote JPDA debugging for a specific server\"<<endl;\r\n *xmlcontent <<\" <jvm name=\\\"default\\\">\"<<endl;\r\n *xmlcontent <<\" <jvm-options>\"<<endl;\r\n *xmlcontent <<\" <option value=\\\"-Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n\\\"/>\"<<endl;\r\n *xmlcontent <<\" </jvm-options>\"<<endl;\r\n *xmlcontent <<\" </jvm>\"<<endl;\r\n *xmlcontent <<\" -->\"<<endl;\r\n\t\t*xmlcontent <<\" </server>\"<<endl;\r\n *xmlcontent <<\" <server name=\\\"server-two\\\" group=\\\"main-server-group\\\" auto-start=\\\"true\\\">\"<<endl;\r\n *xmlcontent <<\" <!-- server-two avoids port conflicts by incrementing the ports in\"<<endl;\r\n *xmlcontent <<\" the default socket-group declared in the server-group -->\"<<endl;\r\n\t\tif(m_domainPortOffset)\r\n {\r\n\t\t\t*xmlcontent <<\" <socket-bindings port-offset=\\\"200\\\"/>\"<<endl; \r\n }\r\n *xmlcontent <<\" </server>\"<<endl;\r\n *xmlcontent <<\" <server name=\\\"server-three\\\" group=\\\"other-server-group\\\" auto-start=\\\"false\\\">\"<<endl;\r\n *xmlcontent <<\" <!-- server-three avoids port conflicts by incrementing the ports in\"<<endl;\r\n *xmlcontent <<\" the default socket-group declared in the server-group -->\"<<endl;\r\n\t\tif(m_domainPortOffset)\r\n {\r\n\t\t\t*xmlcontent <<\" <socket-bindings port-offset=\\\"300\\\"/>\"<<endl; \r\n }\r\n *xmlcontent <<\" </server>\"<<endl;\r\n *xmlcontent <<\" </servers>\"<<endl;\r\n *xmlcontent <<\"</host>\"<<endl; \r\n\r\n\t\treturn xmlcontent;\r\n\t}\r\n\r\n\tvirtual SCXHandle<std::istream> OpenDomainXmlFile(wstring filename)\r\n\t{\r\n\t\tSCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n\t\t*xmlcontent<<\"<domain xmlns=\\\"urn:jboss:domain:2.1\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <extensions>\"<<endl;\r\n\t\t*xmlcontent<<\" </extensions>\"<<endl;\r\n\t\t*xmlcontent<<\" <system-properties>\"<<endl;\r\n\t\t*xmlcontent<<\" </system-properties>\"<<endl;\r\n\t\t*xmlcontent<<\" <management>\"<<endl;\r\n\t\t*xmlcontent<<\" </management>\"<<endl;\r\n\t\t*xmlcontent<<\" <profiles>\"<<endl;\r\n\t\t*xmlcontent<<\" </profiles>\"<<endl;\r\n\t\t*xmlcontent<<\" <interfaces>\"<<endl;\r\n\t\t*xmlcontent<<\" </interfaces>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding-groups>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding-group name=\\\"standard-sockets\\\" default-interface=\\\"public\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <!-- Needed for server groups using the 'default' profile -->\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"ajp\\\" port=\\\"${jboss.ajp.port:8009}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"http\\\" port=\\\"${jboss.http.port:8080}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"https\\\" port=\\\"${jboss.https.port:8443}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"txn-recovery-environment\\\" port=\\\"4712\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"txn-status-manager\\\" port=\\\"4713\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <outbound-socket-binding name=\\\"mail-smtp\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <remote-destination host=\\\"localhost\\\" port=\\\"25\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" </outbound-socket-binding>\"<<endl;\r\n\t\t*xmlcontent<<\" </socket-binding-group>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding-group name=\\\"ha-sockets\\\" default-interface=\\\"public\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <!-- Needed for server groups using the 'ha' profile -->\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"ajp\\\" port=\\\"${jboss.ajp.port:8009}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"http\\\" port=\\\"${jboss.http.port:8080}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"https\\\" port=\\\"${jboss.https.port:8443}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-mping\\\" port=\\\"0\\\" multicast-address=\\\"${jboss.default.multicast.address:230.0.0.4}\\\" multicast-port=\\\"45700\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-tcp\\\" port=\\\"7600\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-tcp-fd\\\" port=\\\"57600\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-udp\\\" port=\\\"55200\\\" multicast-address=\\\"${jboss.default.multicast.address:230.0.0.4}\\\" multicast-port=\\\"45688\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-udp-fd\\\" port=\\\"54200\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"modcluster\\\" port=\\\"0\\\" multicast-address=\\\"224.0.1.105\\\" multicast-port=\\\"23364\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"txn-recovery-environment\\\" port=\\\"4712\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"txn-status-manager\\\" port=\\\"4713\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <outbound-socket-binding name=\\\"mail-smtp\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <remote-destination host=\\\"localhost\\\" port=\\\"25\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" </outbound-socket-binding>\"<<endl;\r\n\t\t*xmlcontent<<\" </socket-binding-group>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding-group name=\\\"full-sockets\\\" default-interface=\\\"public\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <!-- Needed for server groups using the 'full' profile -->\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"ajp\\\" port=\\\"${jboss.ajp.port:8009}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"http\\\" port=\\\"${jboss.http.port:8080}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"https\\\" port=\\\"${jboss.https.port:8443}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jacorb\\\" interface=\\\"unsecure\\\" port=\\\"3528\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jacorb-ssl\\\" interface=\\\"unsecure\\\" port=\\\"3529\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"messaging-group\\\" port=\\\"0\\\" multicast-address=\\\"${jboss.messaging.group.address:231.7.7.7}\\\" multicast-port=\\\"${jboss.messaging.group.port:9876}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"txn-recovery-environment\\\" port=\\\"4712\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"txn-status-manager\\\" port=\\\"4713\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <outbound-socket-binding name=\\\"mail-smtp\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <remote-destination host=\\\"localhost\\\" port=\\\"25\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" </outbound-socket-binding>\"<<endl;\r\n\t\t*xmlcontent<<\" </socket-binding-group>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding-group name=\\\"full-ha-sockets\\\" default-interface=\\\"public\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <!-- Needed for server groups using the 'full-ha' profile -->\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"ajp\\\" port=\\\"${jboss.ajp.port:8009}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"http\\\" port=\\\"${jboss.http.port:8080}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"https\\\" port=\\\"${jboss.https.port:8443}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jacorb\\\" interface=\\\"unsecure\\\" port=\\\"3528\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jacorb-ssl\\\" interface=\\\"unsecure\\\" port=\\\"3529\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-mping\\\" port=\\\"0\\\" multicast-address=\\\"${jboss.default.multicast.address:230.0.0.4}\\\" multicast-port=\\\"45700\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-tcp\\\" port=\\\"7600\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-tcp-fd\\\" port=\\\"57600\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-udp\\\" port=\\\"55200\\\" multicast-address=\\\"${jboss.default.multicast.address:230.0.0.4}\\\" multicast-port=\\\"45688\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"jgroups-udp-fd\\\" port=\\\"54200\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"messaging-group\\\" port=\\\"0\\\" multicast-address=\\\"${jboss.messaging.group.address:231.7.7.7}\\\" multicast-port=\\\"${jboss.messaging.group.port:9876}\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"modcluster\\\" port=\\\"0\\\" multicast-address=\\\"224.0.1.105\\\" multicast-port=\\\"23364\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"txn-recovery-environment\\\" port=\\\"4712\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding name=\\\"txn-status-manager\\\" port=\\\"4713\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" <outbound-socket-binding name=\\\"mail-smtp\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <remote-destination host=\\\"localhost\\\" port=\\\"25\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" </outbound-socket-binding>\"<<endl;\r\n\t\t*xmlcontent<<\" </socket-binding-group>\"<<endl;\r\n\t\t*xmlcontent<<\" </socket-binding-groups>\"<<endl;\r\n\t\t*xmlcontent<<\" <server-groups>\"<<endl;\r\n\t\t*xmlcontent<<\" <server-group name=\\\"main-server-group\\\" profile=\\\"full\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <jvm name=\\\"default\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <heap size=\\\"64m\\\" max-size=\\\"512m\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" </jvm>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding-group ref=\\\"full-sockets\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" </server-group>\"<<endl;\r\n\t\t*xmlcontent<<\" <server-group name=\\\"other-server-group\\\" profile=\\\"full-ha\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <jvm name=\\\"default\\\">\"<<endl;\r\n\t\t*xmlcontent<<\" <heap size=\\\"64m\\\" max-size=\\\"512m\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" </jvm>\"<<endl;\r\n\t\t*xmlcontent<<\" <socket-binding-group ref=\\\"full-ha-sockets\\\"/>\"<<endl;\r\n\t\t*xmlcontent<<\" </server-group>\"<<endl;\r\n\t\t*xmlcontent<<\" </server-groups>\"<<endl;\r\n\t\t*xmlcontent<<\"</domain>\"<<endl;\r\n\r\n\t\treturn xmlcontent;\r\n\t}\r\n\r\n virtual SCXHandle<std::istream> OpenXmlPortsFile(wstring filename)\r\n {\r\n m_xmlPortsFilename = filename;\r\n\r\n SCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n if (m_noPortsFile)\r\n {\r\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\r\n }\r\n\r\n if (m_emptyPortsFile)\r\n {\r\n return xmlcontent;\r\n }\r\n \r\n\t\t// Standalone JBoss Version 7 and Wildfly 8\r\n if(!m_version5 && m_version7 && !m_domainMode)\r\n {\r\n *xmlcontent << \" <server xmlns=\\\"urn:jboss:domain:1.0\\\">\"<<endl;\r\n \r\n if(m_noPortOffsetValue)\r\n {\r\n *xmlcontent << \" <socket-binding-group name=\\\"standard-sockets\\\" default-interface=\\\"public\\\">\"<<endl;\r\n }\r\n else if(m_badPortOffsetValue)\r\n {\r\n *xmlcontent <<\" <socket-binding-group name=\\\"standard-sockets\\\" default-interface=\\\"public\\\" port-offset=\\\"xyz\\\">\"<<endl;\r\n }\r\n else if(m_badPortOffsetValueWithSocket)\r\n {\r\n *xmlcontent <<\" <socket-binding-group name=\\\"standard-sockets\\\" default-interface=\\\"public\\\" port-offset=\\\"${jboss.socket.binding.port-offset:xyz}\\\">\"<<endl;\r\n }\r\n else\r\n {\r\n *xmlcontent <<\" <socket-binding-group name=\\\"standard-sockets\\\" default-interface=\\\"public\\\">\"<<endl;\r\n }\r\n\r\n if(m_badHttpPortValue)\r\n {\r\n *xmlcontent <<\" <socket-binding name=\\\"http\\\" port=\\\"xyz\\\"/>\"<<endl; \r\n }\r\n else\r\n { \r\n *xmlcontent <<\" <socket-binding name=\\\"http\\\" port=\\\"8080\\\"/>\"<<endl;\r\n }\r\n\r\n *xmlcontent <<\" <socket-binding name=\\\"https\\\" port=\\\"8443\\\"/>\"<<endl;\r\n *xmlcontent <<\" <socket-binding name=\\\"jmx-connector-registry\\\" port=\\\"1090\\\"/>\"<<endl;\r\n *xmlcontent <<\" <socket-binding name=\\\"jmx-connector-server\\\" port=\\\"1091\\\"/>\"<<endl;\r\n *xmlcontent <<\" <socket-binding name=\\\"jndi\\\" port=\\\"1099\\\"/>\"<<endl;\r\n *xmlcontent <<\" <socket-binding name=\\\"osgi-http\\\" port=\\\"8090\\\"/>\"<<endl;\r\n *xmlcontent <<\" <socket-binding name=\\\"remoting\\\" port=\\\"4447\\\"/>\"<<endl;\r\n *xmlcontent <<\" <socket-binding name=\\\"txn-recovery-environment\\\" port=\\\"4712\\\"/>\"<<endl;\r\n *xmlcontent <<\" <socket-binding name=\\\"txn-status-manager\\\" port=\\\"4713\\\"/>\"<<endl;\r\n *xmlcontent <<\" </socket-binding-group>\"<<endl;\r\n *xmlcontent <<\" </server>\"<<endl;\r\n\r\n return xmlcontent;\r\n }\r\n \r\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\r\n *xmlcontent << \"<deployment kalle=\\\"urn:jboss:bean-deployer:2.0\\\">\" << endl;\r\n *xmlcontent << \" <bean name=\\\"ServiceBindingManager\\\" class=\\\"org.jboss.services.binding.ServiceBindingManager\\\">\" << endl;\r\n *xmlcontent << \" <annotation>@org.jboss.aop.microcontainer.aspects.jmx.JMX(name=\\\"jboss.system:service=ServiceBindingManager\\\", exposedInterface=org.jboss.services.binding.ServiceBindingManagerMBean.class, registerDirectly=true)</annotation>\" << endl;\r\n *xmlcontent << \" <constructor factoryMethod=\\\"getServiceBindingManager\\\">\" << endl;\r\n *xmlcontent << \" <factory bean=\\\"ServiceBindingManagementObject\\\"/>\" << endl;\r\n *xmlcontent << \" </constructor>\" << endl;\r\n *xmlcontent << \" </bean>\" << endl;\r\n *xmlcontent << \" <bean name=\\\"ServiceBindingManagementObject\\\" class=\\\"org.jboss.services.binding.managed.ServiceBindingManagementObject\\\">\" << endl;\r\n *xmlcontent << \" <constructor>\" << endl;\r\n *xmlcontent << \" <parameter>\" << m_portBindingName << \"</parameter>\" << endl;\r\n *xmlcontent << \" <parameter>\" << endl;\r\n *xmlcontent << \" <set>\" << endl;\r\n *xmlcontent << \" <inject bean=\\\"PortsDefaultBindings\\\"/>\" << endl;\r\n *xmlcontent << \" <inject bean=\\\"Ports01Bindings\\\"/>\" << endl;\r\n *xmlcontent << \" <inject bean=\\\"Ports02Bindings\\\"/>\" << endl;\r\n *xmlcontent << \" <inject bean=\\\"Ports03Bindings\\\"/>\" << endl;\r\n *xmlcontent << \" </set>\" << endl;\r\n *xmlcontent << \" </parameter>\" << endl;\r\n *xmlcontent << \" <parameter><inject bean=\\\"StandardBindings\\\"/></parameter> \" << endl;\r\n *xmlcontent << \" </constructor>\" << endl;\r\n *xmlcontent << \" </bean>\" << endl;\r\n *xmlcontent << \" <bean name=\\\"PortsDefaultBindings\\\" class=\\\"org.jboss.services.binding.impl.ServiceBindingSet\\\">\" << endl;\r\n *xmlcontent << \" <constructor>\" << endl;\r\n *xmlcontent << \" <parameter>ports-default</parameter>\" << endl;\r\n *xmlcontent << \" <parameter>${jboss.bind.address}</parameter>\" << endl;\r\n *xmlcontent << \" <parameter>0</parameter>\" << endl;\r\n *xmlcontent << \" <parameter><null/></parameter>\" << endl;\r\n *xmlcontent << \" </constructor>\" << endl;\r\n *xmlcontent << \" </bean>\" << endl;\r\n *xmlcontent << \" <bean name=\\\"Ports01Bindings\\\" class=\\\"org.jboss.services.binding.impl.ServiceBindingSet\\\">\" << endl;\r\n *xmlcontent << \" <constructor>\" << endl;\r\n *xmlcontent << \" <parameter>ports-01</parameter>\" << endl;\r\n *xmlcontent << \" <parameter>${jboss.bind.address}</parameter>\" << endl;\r\n\r\n if (m_badPortOffsetValue)\r\n {\r\n *xmlcontent << \" <parameter>xyz</parameter>\" << endl;\r\n }\r\n else\r\n {\r\n *xmlcontent << \" <parameter>100</parameter>\" << endl;\r\n }\r\n\r\n *xmlcontent << \" <parameter><null/></parameter>\" << endl;\r\n *xmlcontent << \" </constructor>\" << endl;\r\n *xmlcontent << \" </bean>\" << endl;\r\n *xmlcontent << \" <bean name=\\\"StandardBindings\\\" class=\\\"java.util.HashSet\\\">\" << endl;\r\n *xmlcontent << \" <constructor>\" << endl;\r\n *xmlcontent << \" <parameter class=\\\"java.util.Collection\\\">\" << endl;\r\n *xmlcontent << \" <set elementClass=\\\"org.jboss.services.binding.ServiceBindingMetadata\\\">\" << endl;\r\n\r\n if (m_httpBinding)\r\n {\r\n *xmlcontent << \" <bean class=\\\"org.jboss.services.binding.ServiceBindingMetadata\\\">\" << endl;\r\n *xmlcontent << \" <property name=\\\"serviceName\\\">jboss.web:service=WebServer</property>\" << endl;\r\n\r\n if (m_httpBindingProperty)\r\n {\r\n *xmlcontent << \" <property name=\\\"bindingName\\\">HttpConnector</property>\" << endl;\r\n }\r\n\r\n if (m_badHttpPortValue)\r\n {\r\n *xmlcontent << \" <property name=\\\"port\\\">xyz</property>\" << endl;\r\n }\r\n else\r\n {\r\n *xmlcontent << \" <property name=\\\"port\\\">8080</property>\" << endl;\r\n }\r\n\r\n *xmlcontent << \" <property name=\\\"description\\\">JBoss Web HTTP connector socket; also drives the values for the HTTPS and AJP sockets</property>\" << endl;\r\n *xmlcontent << \" <property name=\\\"serviceBindingValueSourceConfig\\\"><inject bean=\\\"JBossWebConnectorXSLTConfig\\\"/></property>\" << endl;\r\n *xmlcontent << \" </bean>\" << endl;\r\n }\r\n\r\n if (m_httpsBinding)\r\n {\r\n *xmlcontent << \" <bean class=\\\"org.jboss.services.binding.ServiceBindingMetadata\\\">\" << endl;\r\n *xmlcontent << \" <property name=\\\"serviceName\\\">jboss.web:service=WebServer</property>\" << endl;\r\n *xmlcontent << \" <property name=\\\"bindingName\\\">HttpsConnector</property>\" << endl;\r\n *xmlcontent << \" <property name=\\\"port\\\">8443</property>\" << endl;\r\n *xmlcontent << \" <property name=\\\"description\\\">JBoss Web HTTPS connector socket</property>\" << endl;\r\n *xmlcontent << \" </bean>\" << endl;\r\n }\r\n\r\n *xmlcontent << \" </set>\" << endl;\r\n *xmlcontent << \" </parameter>\" << endl;\r\n *xmlcontent << \" </constructor>\" << endl;\r\n *xmlcontent << \" </bean>\" << endl;\r\n\r\n if (!m_badPortsXml)\r\n {\r\n *xmlcontent << \"</deployment>\" << endl;\r\n }\r\n\r\n return xmlcontent; \r\n }\r\n\r\n virtual SCXHandle<std::istream> OpenXmlServiceFile(wstring filename)\r\n {\r\n m_xmlServiceFilename = filename;\r\n\r\n SCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n if (m_noServiceFile)\r\n {\r\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\r\n }\r\n\r\n if (m_emptyServiceFile)\r\n {\r\n return xmlcontent;\r\n }\r\n\r\n *xmlcontent << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\" << endl;\r\n *xmlcontent << \"<server>\" << endl;\r\n *xmlcontent << \" <classpath codebase=\\\"${jboss.server.lib.url:lib}\\\" archives=\\\"*\\\"/>\" << endl;\r\n *xmlcontent << \" <mbean code=\\\"org.jboss.system.pm.AttributePersistenceService\\\"\" << endl;\r\n *xmlcontent << \" name=\\\"jboss:service=AttributePersistenceService\\\"\" << endl;\r\n *xmlcontent << \" xmbean-dd=\\\"resource:xmdesc/AttributePersistenceService-xmbean.xml\\\">\" << endl;\r\n *xmlcontent << \" </mbean>\" << endl;\r\n\r\n if (m_serviceBinding)\r\n {\r\n *xmlcontent << \" <mbean code=\\\"org.jboss.services.binding.ServiceBindingManager\\\"\" << endl;\r\n *xmlcontent << \" name=\\\"jboss.system:service=ServiceBindingManager\\\">\" << endl;\r\n *xmlcontent << \" <attribute name=\\\"ServerName\\\">ports-01</attribute>\" << endl;\r\n *xmlcontent << \" <attribute name=\\\"StoreURL\\\">${jboss.home.url}/docs/examples/binding-manager/sample-bindings.xml</attribute>\" << endl;\r\n *xmlcontent << \" <attribute name=\\\"StoreFactoryClassName\\\">\" << endl;\r\n *xmlcontent << \" org.jboss.services.binding.XMLServicesStoreFactory\" << endl;\r\n *xmlcontent << \" </attribute>\" << endl;\r\n *xmlcontent << \" </mbean>\" << endl;\r\n }\r\n\r\n *xmlcontent << \" <mbean code=\\\"org.jnp.server.NamingBeanImpl\\\"\" << endl;\r\n *xmlcontent << \" name=\\\"jboss:service=NamingBeanImpl\\\"\" << endl;\r\n *xmlcontent << \" xmbean-dd=\\\"resource:xmdesc/NamingBean-xmbean.xml\\\">\" << endl;\r\n *xmlcontent << \" </mbean>\" << endl;\r\n *xmlcontent << \"</server>\" << endl;\r\n\r\n return xmlcontent;\r\n }\r\n\r\n virtual SCXHandle<std::istream> OpenXmlServerFile(wstring filename)\r\n {\r\n m_xmlServerFilename = filename;\r\n\r\n SCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n if (m_noServerFile)\r\n {\r\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\r\n }\r\n\r\n if (m_emptyServerFile)\r\n {\r\n return xmlcontent;\r\n }\r\n\r\n *xmlcontent << \"<Server>\" << endl;\r\n *xmlcontent << \" <Listener className=\\\"org.apache.catalina.core.AprLifecycleListener\\\" SSLEngine=\\\"on\\\" />\" << endl;\r\n *xmlcontent << \" <Listener className=\\\"org.apache.catalina.core.JasperListener\\\" />\" << endl;\r\n *xmlcontent << \" <Service name=\\\"jboss.web\\\">\" << endl;\r\n *xmlcontent << \" <Connector port=\\\"8080\\\" address=\\\"${jboss.bind.address}\\\"\" << endl;\r\n *xmlcontent << \" maxThreads=\\\"250\\\" maxHttpHeaderSize=\\\"8192\\\"\" << endl;\r\n *xmlcontent << \" emptySessionPath=\\\"true\\\" protocol=\\\"HTTP/1.1\\\"\" << endl;\r\n *xmlcontent << \" enableLookups=\\\"false\\\" redirectPort=\\\"8443\\\" acceptCount=\\\"100\\\"\" << endl;\r\n *xmlcontent << \" connectionTimeout=\\\"20000\\\" disableUploadTimeout=\\\"true\\\" />\" << endl;\r\n *xmlcontent << \" <Connector port=\\\"8443\\\" protocol=\\\"HTTP/1.1\\\" SSLEnabled=\\\"true\\\"\" << endl;\r\n *xmlcontent << \" maxThreads=\\\"150\\\" scheme=\\\"https\\\" secure=\\\"true\\\"\" << endl;\r\n *xmlcontent << \" clientAuth=\\\"false\\\" sslProtocol=\\\"TLS\\\" />\" << endl;\r\n *xmlcontent << \" <Connector port=\\\"8009\\\" address=\\\"${jboss.bind.address}\\\" protocol=\\\"AJP/1.3\\\"\" << endl;\r\n *xmlcontent << \" emptySessionPath=\\\"true\\\" enableLookups=\\\"false\\\" redirectPort=\\\"8443\\\" />\" << endl;\r\n *xmlcontent << \" <Engine name=\\\"jboss.web\\\" defaultHost=\\\"localhost\\\">\" << endl;\r\n *xmlcontent << \" <Realm className=\\\"org.jboss.web.tomcat.security.JBossSecurityMgrRealm\\\"\" << endl;\r\n *xmlcontent << \" certificatePrincipal=\\\"org.jboss.security.auth.certs.SubjectDNMapping\\\"\" << endl;\r\n *xmlcontent << \" allRolesMode=\\\"authOnly\\\"/>\" << endl;\r\n *xmlcontent << \" <Host name=\\\"localhost\\\"\" << endl;\r\n *xmlcontent << \" autoDeploy=\\\"false\\\" deployOnStartup=\\\"false\\\" deployXML=\\\"false\\\"\" << endl;\r\n *xmlcontent << \" configClass=\\\"org.jboss.web.tomcat.security.config.JBossContextConfig\\\">\" << endl;\r\n *xmlcontent << \" <Valve className=\\\"org.jboss.web.tomcat.service.jca.CachedConnectionValve\\\"\" << endl;\r\n *xmlcontent << \" cachedConnectionManagerObjectName=\\\"jboss.jca:service=CachedConnectionManager\\\"\" << endl;\r\n *xmlcontent << \" transactionManagerObjectName=\\\"jboss:service=TransactionManager\\\" />\" << endl;\r\n *xmlcontent << \" </Host>\" << endl;\r\n *xmlcontent << \" </Engine>\" << endl;\r\n *xmlcontent << \" </Service>\" << endl;\r\n *xmlcontent << \"</Server>\" << endl;\r\n\r\n return xmlcontent;\r\n }\r\n\r\n virtual SCXHandle<std::istream> OpenXmlBindingFile(wstring filename)\r\n {\r\n m_xmlBindingFilename = filename;\r\n\r\n SCXHandle<stringstream> xmlcontent( new stringstream );\r\n\r\n if (m_noBindingFile)\r\n {\r\n throw SCXFilePathNotFoundException(filename, SCXSRCLOCATION);\r\n }\r\n\r\n if (m_emptyBindingFile)\r\n {\r\n return xmlcontent;\r\n }\r\n\r\n *xmlcontent << \"<service-bindings>\" << endl;\r\n *xmlcontent << \" <server name=\\\"ports-default\\\">\" << endl;\r\n *xmlcontent << \" <service-config name=\\\"jboss.remoting:type=Connector,name=DefaultEjb3Connector,handler=ejb3\\\"\" << endl;\r\n *xmlcontent << \" delegateClass=\\\"org.jboss.services.binding.AttributeMappingDelegate\\\">\" << endl;\r\n *xmlcontent << \" <delegate-config>\" << endl;\r\n *xmlcontent << \" <attribute name=\\\"InvokerLocator\\\">socket://${jboss.bind.address}:3873</attribute>\" << endl;\r\n *xmlcontent << \" </delegate-config>\" << endl;\r\n *xmlcontent << \" <binding port=\\\"3873\\\"/>\" << endl;\r\n *xmlcontent << \" </service-config>\" << endl;\r\n *xmlcontent << \" <service-config name=\\\"jboss.web:service=WebServer\\\"\" << endl;\r\n *xmlcontent << \" delegateClass=\\\"org.jboss.services.binding.XSLTFileDelegate\\\">\" << endl;\r\n *xmlcontent << \" <delegate-config>\" << endl;\r\n *xmlcontent << \" </delegate-config>\" << endl;\r\n *xmlcontent << \" <binding port=\\\"8080\\\"/>\" << endl;\r\n *xmlcontent << \" </service-config>\" << endl;\r\n *xmlcontent << \" </server>\" << endl;\r\n *xmlcontent << \" <server name=\\\"ports-01\\\">\" << endl;\r\n *xmlcontent << \" <service-config name=\\\"jboss.remoting:type=Connector,name=DefaultEjb3Connector,handler=ejb3\\\"\" << endl;\r\n *xmlcontent << \" delegateClass=\\\"org.jboss.services.binding.AttributeMappingDelegate\\\">\" << endl;\r\n *xmlcontent << \" <delegate-config>\" << endl;\r\n *xmlcontent << \" <attribute name=\\\"InvokerLocator\\\">socket://${jboss.bind.address}:3973</attribute>\" << endl;\r\n *xmlcontent << \" </delegate-config>\" << endl;\r\n *xmlcontent << \" <binding port=\\\"3973\\\"/>\" << endl;\r\n *xmlcontent << \" </service-config>\" << endl;\r\n *xmlcontent << \" <service-config name=\\\"jboss.web:service=WebServer\\\"\" << endl;\r\n *xmlcontent << \" delegateClass=\\\"org.jboss.services.binding.XSLTFileDelegate\\\">\" << endl;\r\n *xmlcontent << \" <delegate-config>\" << endl;\r\n *xmlcontent << \" </delegate-config>\" << endl;\r\n *xmlcontent << \" <binding port=\\\"8180\\\"/>\" << endl;\r\n *xmlcontent << \" </service-config>\" << endl;\r\n *xmlcontent << \" </server>\" << endl;\r\n *xmlcontent << \"</service-bindings>\" << endl;\r\n\r\n return xmlcontent;\r\n }\r\n \r\n // Set the Port Binding configuration string\r\n void SetPortBindingName(string portBindingName)\r\n {\r\n m_portBindingName = portBindingName;\r\n }\r\n\r\n wstring m_xmlVersionFilename;\r\n wstring m_xmlPortsFilename;\r\n wstring m_xmlServiceFilename;\r\n wstring m_xmlServerFilename;\r\n wstring m_xmlBindingFilename;\r\n bool m_httpBindingProperty;\r\n bool m_includeJbossJar;\r\n bool m_version5;\r\n bool m_hasJboss7File;\r\n bool m_hasBadJboss7File;\r\n bool m_version7;\r\n bool m_httpBinding;\r\n bool m_httpsBinding;\r\n bool m_noPortsFile;\r\n bool m_noVersionFile;\r\n bool m_noServiceFile;\r\n bool m_noServerFile;\r\n bool m_noBindingFile;\r\n bool m_emptyPortsFile;\r\n bool m_emptyVersionFile;\r\n bool m_emptyServiceFile;\r\n bool m_emptyServerFile;\r\n bool m_emptyBindingFile;\r\n bool m_badPortsXml;\r\n bool m_badVersionXml;\r\n bool m_badHttpPortValue;\r\n bool m_badPortOffsetValue;\r\n bool m_serviceBinding;\r\n bool m_noPortOffsetValue;\r\n bool m_badPortOffsetValueWithSocket;\r\n\tbool m_hasEnterpriseVersionFile;\r\n bool m_domainMode;\r\n\tbool m_domainPortOffset;\r\n\r\n string m_portBindingName;\r\n};\r\n\r\nclass JBossAppServerInstance_Test : public CPPUNIT_NS::TestFixture\r\n{\r\n CPPUNIT_TEST_SUITE( JBossAppServerInstance_Test );\r\n\r\n CPPUNIT_TEST( testJBoss4WithBinding );\r\n CPPUNIT_TEST( testJBoss4WithoutBinding );\r\n CPPUNIT_TEST( testJBoss4NoServiceFile );\r\n CPPUNIT_TEST( testJBoss4EmptyServiceFile );\r\n CPPUNIT_TEST( testJBoss4NoServerFile );\r\n CPPUNIT_TEST( testJBoss4EmptyServerFile );\r\n CPPUNIT_TEST( testJBoss4NoBindingFile );\r\n CPPUNIT_TEST( testJBoss4EmptyBindingFile );\r\n CPPUNIT_TEST( testWithoutHttpBindingProperty );\r\n CPPUNIT_TEST( testWithHttpBindingProperty );\r\n CPPUNIT_TEST( testNoVersion );\r\n CPPUNIT_TEST( testWithNoHttps );\r\n CPPUNIT_TEST( testWithNoHttp );\r\n CPPUNIT_TEST( testNoPortsFile );\r\n CPPUNIT_TEST( testNoVersionFile );\r\n CPPUNIT_TEST( testEmptyPortsFile );\r\n CPPUNIT_TEST( testEmptyVersionFile );\r\n CPPUNIT_TEST( testBadPortsXml );\r\n CPPUNIT_TEST( testBadVersionXml );\r\n CPPUNIT_TEST( testBadHttpPortValue );\r\n CPPUNIT_TEST( testBadPortOffsetValue );\r\n CPPUNIT_TEST( testJBoss7WithNonDefaultConfig );\r\n CPPUNIT_TEST( testJBoss7WithCmdLinePortOffset );\r\n CPPUNIT_TEST( testJBoss7NoStandaloneConfigDir );\r\n CPPUNIT_TEST( testPort_XMLSetTo_Junk_CommandLineSetTo_ports01 );\r\n CPPUNIT_TEST( testPort_XMLSetTo_Port01_CommandLineSetTo_Junk );\r\n CPPUNIT_TEST( testPort_XMLSetTo_Junk_NoCommandLineBinding );\r\n CPPUNIT_TEST( testPort_XMLSetTo_Ports01 );\r\n CPPUNIT_TEST( testJBoss7WithBadVersionFile );\r\n CPPUNIT_TEST( testJBoss7WithBadHttpProperty );\r\n CPPUNIT_TEST( testJBoss7WithBadPortOffsetValue );\r\n CPPUNIT_TEST( testJBoss7WithBadPortOffsetValueSocketBindingValue );\r\n CPPUNIT_TEST( testJBossDomainModeGoodGroupServerName );\r\n\tCPPUNIT_TEST( testJBossDomainMultipleServers );\r\n\tCPPUNIT_TEST( testJBossDomainModePorts );\r\n\tCPPUNIT_TEST( testJBossEnterpriseVersion );\r\n \r\n CPPUNIT_TEST_SUITE_END();\r\n\r\n public:\r\n\r\n void setUp(void)\r\n {\r\n }\r\n\r\n void tearDown(void)\r\n {\r\n }\r\n \r\n\t// Test Enterprise Version Parsing when using the command line\r\n\tvoid testJBossEnterpriseVersion()\r\n\t{\r\n\t\tSCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n deps->SetHasEnterpriseVersionFile(true);\r\n deps->SetBadHttpPortValue(true);\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"id/standalone/configuration/\", L\"\", deps) );\r\n \r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"7.2.0.Final-redhat-8\", asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"7\", asInstance->GetMajorVersion());\r\n\t}\r\n\r\n\t// Test proper parsing for domain id and diskpath\r\n void testJBossDomainModeGoodGroupServerName()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n\t\tdeps->SetDomainMode(true);\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id\", L\"id/domain/servers/server-one/data\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n \r\n\t\t// We only want to verify that the ID and diskpath is being parsed properly from AppServer Instance\r\n CPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-one/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-one/\", asInstance->GetDiskPath());\r\n }\r\n\r\n\t// Test multiple functions for retrieving domain ports\r\n\tvoid testJBossDomainModePorts()\r\n\t{\r\n\t\tSCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n\r\n\t\tdeps->SetDomainMode(true);\r\n\t\tdeps->SetDomainPortOffset(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id\", L\"id/domain/servers/server-one/data\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-one/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-one/\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL( L\"8180\", asInstance->GetHttpPort());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"8543\", asInstance->GetHttpsPort());\r\n\t\tCPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"7.0.0.Final\",asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"7\",asInstance->GetMajorVersion());\r\n\t}\r\n\r\n\t// Test JBoss domain mode with multiple servers\r\n\tvoid testJBossDomainMultipleServers()\r\n\t{\r\n\t\tSCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n\r\n\t\tdeps->SetDomainMode(true);\r\n\t\tdeps->SetDomainPortOffset(true);\r\n\r\n\t\tSCXHandle<JBossAppServerInstance> serverOne( new JBossAppServerInstance(L\"id\", L\"id/domain/servers/server-one/data\", L\"\", deps) );\r\n\t\tSCXHandle<JBossAppServerInstance> serverTwo( new JBossAppServerInstance(L\"id\", L\"id/domain/servers/server-two/data\", L\"\", deps) );\r\n\t\tSCXHandle<JBossAppServerInstance> serverThree( new JBossAppServerInstance(L\"id\", L\"id/domain/servers/server-three/data\", L\"\", deps) );\r\n\r\n\t\tserverOne->Update();\r\n\t\t// Assertions for server-one of domain mode\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-one/\", serverOne->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-one/\", serverOne->GetDiskPath());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"8180\", serverOne->GetHttpPort());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"8543\", serverOne->GetHttpsPort());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"JBoss\", serverOne->GetType());\r\n\r\n\t\tserverTwo->Update();\r\n\t\t// Assertions for server-two of domain mode\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-two/\", serverTwo->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-two/\", serverTwo->GetDiskPath());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"8280\", serverTwo->GetHttpPort());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"8643\", serverTwo->GetHttpsPort());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"JBoss\", serverTwo->GetType());\r\n\t\t\r\n\t\tserverThree->Update();\r\n\t\t// Assertions for server-three of domain mode\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-three/\", serverThree->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/domain/servers/server-three/\", serverThree->GetDiskPath());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"8380\", serverThree->GetHttpPort());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"8743\", serverThree->GetHttpsPort());\r\n\t\tCPPUNIT_ASSERT_EQUAL( L\"JBoss\", serverThree->GetType());\r\n\t\t\r\n\t}\r\n\r\n // Test with command running a parse on a bad script\r\n void testJBoss7WithBadVersionFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n deps->SetHasBadJboss7VersionFile(true);\r\n deps->SetBadHttpPortValue(true);\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"id/standalone/configuration/\", L\"\", deps) );\r\n \r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"\", asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"\", asInstance->GetMajorVersion());\r\n // Doesnt know Jboss 7, therefore cannot get standalone\r\n CPPUNIT_ASSERT_EQUAL(L\"\", asInstance->GetHttpPort());\r\n CPPUNIT_ASSERT_EQUAL(L\"\", asInstance->GetHttpsPort());\r\n // Will be empty because cannot get version\r\n CPPUNIT_ASSERT_EQUAL(L\"\", deps->m_xmlPortsFilename);\r\n }\r\n \r\n // Test with XML containing bad HTTP port attribute\r\n void testJBoss7WithBadHttpProperty()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n \r\n deps->SetBadHttpPortValue(true);\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"id/standalone/configuration/\", L\"\", deps) );\r\n \r\n asInstance->Update();\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"7.0.0.Final\",asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"7\",asInstance->GetMajorVersion());\r\n // Http Ports will contain nonsense and return 0\r\n CPPUNIT_ASSERT_EQUAL(L\"\", asInstance->GetHttpPort());\r\n CPPUNIT_ASSERT_EQUAL(L\"8443\", asInstance->GetHttpsPort());\r\n\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone.xml\", deps->m_xmlPortsFilename);\r\n }\r\n\r\n // Test with XML containing bad port-offset attribute\r\n void testJBoss7WithBadPortOffsetValue()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n \r\n deps->SetBadPortOffsetValue(true);\r\n \r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"id/standalone/configuration/\", L\"\", deps) );\r\n \r\n asInstance->Update();\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"7.0.0.Final\",asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"7\",asInstance->GetMajorVersion());\r\n // port offset will contain junk and return 0\r\n CPPUNIT_ASSERT_EQUAL(L\"8080\", asInstance->GetHttpPort());\r\n CPPUNIT_ASSERT_EQUAL(L\"8443\", asInstance->GetHttpsPort());\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone.xml\", deps->m_xmlPortsFilename);\r\n }\r\n \r\n void testJBoss7WithNonDefaultConfig()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n \r\n deps->SetBadPortOffsetValue(false);\r\n \r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"id/standalone/configuration/standalone-full.xml\", L\"\", deps) );\r\n \r\n asInstance->Update();\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone-full.xml\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone-full.xml\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"7.0.0.Final\",asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"7\",asInstance->GetMajorVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"8080\", asInstance->GetHttpPort());\r\n CPPUNIT_ASSERT_EQUAL(L\"8443\", asInstance->GetHttpsPort());\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone-full.xml\", deps->m_xmlPortsFilename);\r\n }\r\n\r\n void testJBoss7WithCmdLinePortOffset()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n \r\n deps->SetBadPortOffsetValue(false);\r\n \r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"id/standalone/configuration/standalone-full.xml\", L\"1000\", deps) );\r\n \r\n asInstance->Update();\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone-full.xml:1000\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone-full.xml:1000\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"7.0.0.Final\",asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"7\",asInstance->GetMajorVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"9080\", asInstance->GetHttpPort());\r\n CPPUNIT_ASSERT_EQUAL(L\"9443\", asInstance->GetHttpsPort());\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone-full.xml\", deps->m_xmlPortsFilename);\r\n }\r\n\r\n void testJBoss7NoStandaloneConfigDir()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n \r\n deps->SetBadPortOffsetValue(false);\r\n \r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"id/instance0/configuration/\", L\"\", deps, L\"standalone\") );\r\n \r\n asInstance->Update();\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/instance0/configuration/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/instance0/configuration/\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"7.0.0.Final\",asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"7\",asInstance->GetMajorVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"8080\", asInstance->GetHttpPort());\r\n CPPUNIT_ASSERT_EQUAL(L\"8443\", asInstance->GetHttpsPort());\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/instance0/configuration/standalone.xml\", deps->m_xmlPortsFilename);\r\n }\r\n\r\n // Test with XML containing bad port-offset attribute in binding socket\r\n void testJBoss7WithBadPortOffsetValueSocketBindingValue()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetIncludeJbossJar(false);\r\n deps->SetHttpBinding(false);\r\n deps->SetHttpsBinding(false);\r\n deps->SetVersion7(true);\r\n deps->SetNoVersionFile(true);\r\n\r\n deps->SetBadPortOffsetValueWithSocket(true);\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"id/standalone/configuration/\", L\"\", deps) );\r\n \r\n asInstance->Update();\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetId());\r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/\", asInstance->GetDiskPath());\r\n CPPUNIT_ASSERT_EQUAL(L\"JBoss\", asInstance->GetType());\r\n CPPUNIT_ASSERT_EQUAL(L\"7.0.0.Final\",asInstance->GetVersion());\r\n CPPUNIT_ASSERT_EQUAL(L\"7\",asInstance->GetMajorVersion());\r\n // port offset will contain junk and return 0\r\n CPPUNIT_ASSERT_EQUAL(L\"8080\", asInstance->GetHttpPort());\r\n CPPUNIT_ASSERT_EQUAL(L\"8443\", asInstance->GetHttpsPort());\r\n \r\n CPPUNIT_ASSERT_EQUAL( L\"id/standalone/configuration/standalone.xml\", deps->m_xmlPortsFilename);\r\n }\r\n\r\n // Test with XML not containing the HTTPBinding property, but which do contain the HTTP section\r\n void testJBoss4WithBinding()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"4.2.1.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"4\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8180\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8543\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlServiceFilename == L\"id/server/myconfig/conf/jboss-service.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlBindingFilename == L\"id/docs/examples/binding-manager/sample-bindings.xml\");\r\n }\r\n\r\n // Test with XML not containing the HTTPBinding property, but which do contain the HTTP section\r\n void testJBoss4WithoutBinding()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n deps->SetVersion5(false);\r\n deps->SetServiceBinding(false);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"4.2.1.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"4\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlServiceFilename == L\"id/server/myconfig/conf/jboss-service.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/server/myconfig/deploy/jboss-web.deployer/server.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlBindingFilename == L\"\");\r\n }\r\n\r\n // Test with code that throw exception when we try to open the service file\r\n void testJBoss4NoServiceFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetNoServiceFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"4.2.1.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"4\");\r\n // Without a service file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlServiceFilename == L\"id/server/myconfig/conf/jboss-service.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlBindingFilename == L\"\");\r\n }\r\n\r\n // Test with code that returns an empty string from the service file\r\n void testJBoss4EmptyServiceFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetEmptyServiceFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"4.2.1.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"4\");\r\n // Without a service file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlServiceFilename == L\"id/server/myconfig/conf/jboss-service.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlBindingFilename == L\"\");\r\n }\r\n\r\n // Test with code that throw exception when we try to open the server file\r\n void testJBoss4NoServerFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetServiceBinding(false);\r\n deps->SetNoServerFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"4.2.1.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"4\");\r\n // Without a server file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlServiceFilename == L\"id/server/myconfig/conf/jboss-service.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/server/myconfig/deploy/jboss-web.deployer/server.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlBindingFilename == L\"\");\r\n }\r\n\r\n // Test with code that returns an empty string from the server file\r\n void testJBoss4EmptyServerFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetServiceBinding(false);\r\n deps->SetEmptyServerFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"4.2.1.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"4\");\r\n // Without a server file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlServiceFilename == L\"id/server/myconfig/conf/jboss-service.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"id/server/myconfig/deploy/jboss-web.deployer/server.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlBindingFilename == L\"\");\r\n }\r\n\r\n // Test with code that throw exception when we try to open the binding file\r\n void testJBoss4NoBindingFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetNoBindingFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"4.2.1.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"4\");\r\n // Without a binding file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlServiceFilename == L\"id/server/myconfig/conf/jboss-service.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlBindingFilename == L\"id/docs/examples/binding-manager/sample-bindings.xml\");\r\n }\r\n\r\n // Test with code that returns an empty string from the binding file\r\n void testJBoss4EmptyBindingFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetVersion5(false);\r\n deps->SetEmptyBindingFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"4.2.1.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"4\");\r\n // Without a binding file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlServiceFilename == L\"id/server/myconfig/conf/jboss-service.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlServerFilename == L\"\");\r\n CPPUNIT_ASSERT(deps->m_xmlBindingFilename == L\"id/docs/examples/binding-manager/sample-bindings.xml\");\r\n }\r\n\r\n // Test with XML not containing the HTTPBinding property, but which do contain the HTTP section\r\n void testWithoutHttpBindingProperty()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n \r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n // We should still find the HTTP port even without the HTTPBinding property\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8180\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8543\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with XML containing the HTTPBinding property in the HTTP section\r\n void testWithHttpBindingProperty()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetHttpBindingProperty(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n // We should ofcourse find the HTTP port witht the HTTPBinding property\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8180\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8543\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with XML not containing the HTTPS section \r\n void testWithNoHttps()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetHttpsBinding(false);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8180\");\r\n // No HTTPS section means no HTTPS port found\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with XML not containing the HTTP section \r\n void testWithNoHttp()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetHttpBinding(false);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n // No HTTP section means no HTTP port found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8543\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with XML not containing the section we get the version from \r\n void testNoVersion()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetIncludeJbossJar(false);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n // Without version, we don't know that this is a JBoss 5, and cannot get the ports\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n // Without version, we don't know that this is a JBoss 5, and don't try to open the ports file\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n }\r\n\r\n // Test with code that throw exception when we try to open the ports file\r\n void testNoPortsFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetNoPortsFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n // Without a ports file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with code that throw exception when we try to open the version file\r\n void testNoVersionFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetNoVersionFile(true);\r\n deps->SetHasJboss7File(false);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n // Without version, we don't know that this is a JBoss 5, and cannot get the ports\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n // Without version, we don't know that this is a JBoss 5, and don't try to open the ports file\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n }\r\n\r\n // Test with code that returns an empty string from the ports file\r\n void testEmptyPortsFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetEmptyPortsFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n // Without the content of the ports file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with code that returns an empty string from the version file\r\n void testEmptyVersionFile()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetEmptyVersionFile(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n // Without version, we don't know that this is a JBoss 5, and cannot get the ports\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n // Without version, we don't know that this is a JBoss 5, and don't try to open the ports file\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n }\r\n\r\n // Test with code that returns invalid XML from the ports file\r\n void testBadPortsXml()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetBadPortsXml(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n // Without good content from the ports file, no ports will be found\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with code that returns invalid XML from the version file\r\n void testBadVersionXml()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetBadVersionXml(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n // Without version, we don't know that this is a JBoss 5, and cannot get the ports\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n // Without version, we don't know that this is a JBoss 5, and don't try to open the ports file\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"\");\r\n }\r\n\r\n // Test with XML that has non-numeric value for the HTTP port\r\n void testBadHttpPortValue()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetBadHttpPortValue(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n // If we cannot convert the HTTP base port to an integer, we cannot calculate the port value\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8543\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with XML that has non-numeric value for the port offset\r\n void testBadPortOffsetValue()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetBadPortOffsetValue(true);\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n // If we cannot convert the port offset to an integer, we fall back to assuming offset 0 (ports-default)\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with no commandline binding and the default in the XML set to \"ports-01\".\r\n // As the BindingPort in the XML doc is valid the correct port base + offset should be returned\r\n void testPort_XMLSetTo_Ports01()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetPortBindingName(\"${jboss.service.binding.set:ports-01}\");\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8180\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8543\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with no commandline binding and the default in the XML set to be invalid.\r\n // As the BindingPort in the XML doc is invalid the default port base should be returned\r\n void testPort_XMLSetTo_Junk_NoCommandLineBinding()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetPortBindingName(\"${jboss.service.binding.set:junk}\");\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with an invalid commandline binding and the default in the XML set to ports-01.\r\n // The command line setting will take precedence over the BindingPort in the XML doc,\r\n // the command line setting will fail and the default port base should be returned.\r\n void testPort_XMLSetTo_Port01_CommandLineSetTo_Junk()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetPortBindingName(\"${jboss.service.binding.set:ports-01}\");\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"xxx\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8080\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8443\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n // Test with a valid commandline binding and the default in the XML set to junk.\r\n // The command line setting will take precedence over the BindingPort in the XML doc\r\n // and the correct port base + offset should be returned\r\n void testPort_XMLSetTo_Junk_CommandLineSetTo_ports01()\r\n {\r\n SCXHandle<JBossAppServerInstanceTestPALDependencies> deps(new JBossAppServerInstanceTestPALDependencies());\r\n\r\n deps->SetPortBindingName(\"${jboss.service.binding.set:junk}\");\r\n\r\n SCXHandle<JBossAppServerInstance> asInstance( new JBossAppServerInstance(L\"id/\", L\"myconfig\", L\"ports-01\", deps) );\r\n\r\n asInstance->Update();\r\n\r\n CPPUNIT_ASSERT(asInstance->GetId() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetDiskPath() == L\"id/server/myconfig/\");\r\n CPPUNIT_ASSERT(asInstance->GetType() == L\"JBoss\");\r\n CPPUNIT_ASSERT(asInstance->GetVersion() == L\"5.1.0.GA\");\r\n CPPUNIT_ASSERT(asInstance->GetMajorVersion() == L\"5\");\r\n\r\n CPPUNIT_ASSERT(asInstance->GetHttpPort() == L\"8180\");\r\n CPPUNIT_ASSERT(asInstance->GetHttpsPort() == L\"8543\");\r\n\r\n CPPUNIT_ASSERT(deps->m_xmlVersionFilename == L\"id/jar-versions.xml\");\r\n CPPUNIT_ASSERT(deps->m_xmlPortsFilename == L\"id/server/myconfig/conf/bindingservice.beans/META-INF/bindings-jboss-beans.xml\");\r\n }\r\n\r\n};\r\n\r\nCPPUNIT_TEST_SUITE_REGISTRATION( JBossAppServerInstance_Test );\r\n" }, { "alpha_fraction": 0.48209211230278015, "alphanum_fraction": 0.4891984164714813, "avg_line_length": 33.155338287353516, "blob_id": "d933b290a78050fe82db5930587f698a77d0aad4", "content_id": "8e688670861ca7235516e06a063c45bea492239c", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3518, "license_type": "permissive", "max_line_length": 149, "num_lines": 103, "path": "/test/code/shared/testutils/scxassert_cppunit.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n \n Created date 20070618 09:21:00\n\n Implements the assert failed method for unit tests.\n \n*/\n/*----------------------------------------------------------------------------*/\n\n#include <sstream>\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxassert.h>\n#include <testutils/scxassert_cppunit.h>\n#include <scxcorelib/stringaid.h>\n\nnamespace SCXCoreLib\n{\n //! Number of asserts failed since last reset.\n unsigned int SCXAssertCounter::nrAssertsFailed = 0;\n //! Message of last assert.\n std::wstring SCXAssertCounter::lastMessage = L\"\";\n\n /*----------------------------------------------------------------------------*/\n /**\n Reset assert counter.\n \n */\n void SCXAssertCounter::Reset() {\n nrAssertsFailed = 0;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get number of failed asserts since last reset.\n \\returns Asserts failed.\n */\n unsigned int SCXAssertCounter::GetFailedAsserts() {\n return nrAssertsFailed;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Get the message of the last assert with message.\n \\returns Message of last assert.\n */\n const std::wstring& SCXAssertCounter::GetLastMessage() {\n return lastMessage;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Add a new assert.\n \\param m Assert message.\n\n */\n void SCXAssertCounter::AssertFailed(const std::wstring& m) {\n lastMessage = m;\n ++nrAssertsFailed;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Report assertion failed suitable for unit tests.\n \n Parameters: c - The condition that failed (as a string).\n f - name of file where asserttion failed.\n l - line in file where assertion failed.\n m - extra log message. Ignored if 0.\n Retval: None.\n \n This method is called by the SCXASSERT macro when the assertion failes.\n For unit tests this macro does nothing more than increment the assertion\n failed counter.\n \n */\n void scx_assert_failed(const char* c, const char* f, const unsigned int l, const wchar_t* m /*= 0*/)\n {\n std::wstringstream ss;\n\n // this routine formats message for unit-test to display, so output should look like:\n // \n // 1) test: SCXRunAsProviderTest::testDoInvokeMethodPartParams (F) \n // Unexpected assertion failure\n // - SCXRunAsProviderTest::testDoInvokeMethodPartParams; Condiiton: ; File: /home/dp/dev/source/code/include/scxcorelib/scxexception.h: 373; \n // [/home/dp/dev/source/code/providers/runas_provider/runasprovider.cpp:234]Internal Error: missing arguments to ExecuteCommand method\n\n ss << \n L\"Conditon: \" <<\n SCXCoreLib::StrFromMultibyte(c ? c : \"\") << \n L\"; File: \" <<\n SCXCoreLib::StrFromMultibyte(f ? f : \"\") <<\n L\": \" <<\n l <<\n L\"; \" << \n (m ? m : L\"\");\n\n SCXAssertCounter::AssertFailed(ss.str());\n }\n} /* namespace SCXCoreLib */\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6126721501350403, "alphanum_fraction": 0.6146923899650574, "avg_line_length": 32.61111068725586, "blob_id": "3a2da54035cc0536314eeb7d8f0f67d3fda2576e", "content_id": "b3e566205eed94cbe61331d20cfe368643ab56a2", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5445, "license_type": "permissive", "max_line_length": 128, "num_lines": 162, "path": "/source/code/shared/tools/scx_admin/logconfigurator.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief scx configuration tool for SCX.\n\n \\date 8/22/2008\n\n*/\n#ifndef LOG_CONFIG_READER_H\n#define LOG_CONFIG_READER_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxlog.h>\n#include \"source/code/scxcorelib/util/log/scxlogconfigreader.h\"\n#include \"admin_api.h\"\n\n\n#include <iostream>\n\n/*----------------------------------------------------------------------------*/\n/**\n helper abstract class to store information about \n \"backend\" section in config file\n \n*/ \nclass BackendSection {\npublic:\n //! map to store module/severity information\n typedef std::map< std::wstring, SCXCoreLib::SCXLogSeverity > MapModules;\n\n virtual ~BackendSection(){}\n\n /** adds/updates severity for given module\n \\param[in] strModule - module name\n \\param[in] sev - new severity\n \\returns \"true\" if success, \"false\" if failed\n */ \n bool SetModuleSeverity( std::wstring strModule, SCXCoreLib::SCXLogSeverity sev ) {m_mapModules[strModule]=sev; return true;}\n\n /// removes all \"module\" entries from the section\n void Clear() {m_mapModules.clear();}\n\n /** updates special backend-specific property\n \\param[in] name - property name\n \\param[in] value - new value\n \\returns \"true\" if success, \"false\" if failed\n */ \n virtual bool SetProperty( std::wstring name, std::wstring value ) = 0;\n \n //! checks if backend section is initialized and all mandatory parameters were set\n //! \\returns \"true\" if backend section is initialized and all mandatory parameters were set\n virtual bool IsInitialized() const = 0;\n \n //! \\returns \"id\" of the section, compatible with command line argument\n virtual std::wstring GetID() const = 0;\n \n //! prints content of the section to the provided stream\n /// \\param[out] buf stream for configuration writing\n virtual void Print(std::wostringstream& buf) const = 0;\n\nprotected:\n void PrintModules(std::wostringstream& buf) const;\n \nprotected:\n // data\n MapModules m_mapModules; ///< module/severity map\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n helper class to store information about \"FILE backend\" section in config file\n \n*/ \nclass BackendSectionFile : public BackendSection {\npublic:\n virtual bool SetProperty( std::wstring name, std::wstring value )\n { \n if ( name == L\"PATH\" ){\n m_strPath = value;\n return true;\n }\n return false;\n }\n \n virtual bool IsInitialized() const { return !m_mapModules.empty() && !m_strPath.empty();}\n virtual std::wstring GetID() const {return std::wstring(L\"FILE.\") + m_strPath;}\n virtual void Print(std::wostringstream& buf) const;\nprotected:\n // data\n std::wstring m_strPath; ///< log file name from FILE backend\n};\n\n/*----------------------------------------------------------------------------*/\n/**\n helper class to store information about \"STDOUT backend\" section in config file\n \n*/ \nclass BackendSectionStdout : public BackendSection {\npublic:\n virtual bool SetProperty( std::wstring , std::wstring )\n { \n return false;\n }\n \n virtual bool IsInitialized() const { return !m_mapModules.empty();}\n virtual std::wstring GetID() const {return std::wstring(L\"STDOUT\");}\n virtual void Print(std::wostringstream& buf) const;\n};\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Implementation of admin-log API for scx core log configuration\n \n*/ \nclass SCX_LogConfigurator : public SCX_AdminLogAPI {\n \npublic:\n /// type to store all backends; maps backend id to backend pointer \n typedef std::map< std::wstring, SCXCoreLib::SCXHandle<BackendSection> > MapBackends;\n SCX_LogConfigurator();\n SCX_LogConfigurator(const SCXFilePath& oConfigFileName);\n ~SCX_LogConfigurator();\n\n virtual bool LogRotate();\n virtual bool Print(std::wostringstream& buf) const;\n virtual bool Reset();\n virtual bool Set(LogLevelEnum level);\n\n // \"provider-specific\" functions:\n void Set( const std::wstring& name, const std::wstring& value );\n void Reset( const std::wstring& name );\n void Remove( const std::wstring& name );\n\n // funcitons that are used by SCXLogConfigReader\n bool SetSeverityThreshold(SCXCoreLib::SCXHandle<BackendSection> backend,\n const std::wstring& module,\n SCXCoreLib::SCXLogSeverity newThreshold);\n SCXCoreLib::SCXHandle<BackendSection> Create(const std::wstring& name);\n void Add( SCXCoreLib::SCXHandle<BackendSection> backend );\n\nprivate:\n bool LoadAndValidate( bool bCreateImplicitEntries );\n bool Save();\n void GetEntryModuleID( \n const std::wstring& name, \n std::wstring& entryID, \n std::wstring& moduleID, \n SCXHandle<BackendSection> &new_backend );\n\n MapBackends m_mapConfig; ///< all sections\n SCXFilePath m_oConfigFileName; ///< file name to store configuration\n};\n\n#endif\n" }, { "alpha_fraction": 0.5677376389503479, "alphanum_fraction": 0.5797397494316101, "avg_line_length": 32.80610275268555, "blob_id": "0ddd0d4a578c00566806680527167636d25f0913", "content_id": "bf45d98ef5fc8b61b2426151766b25609919d3b0", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 37660, "license_type": "permissive", "max_line_length": 167, "num_lines": 1114, "path": "/source/code/shared/tools/scx_ssl_config/scxsslcert.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief Generates SSL certificates for the SCX Installer.\n\n \\date 1-17-2008\n\n Implementation of class SCXSSLCertificate.\n\n*/\n\n#include <scxcorelib/scxcmn.h>\n\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/strerror.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxglob.h>\n\n#include <openssl/bio.h>\n#include <openssl/evp.h>\n#include <openssl/conf.h>\n#include <openssl/err.h>\n#include <openssl/asn1.h>\n#include <openssl/x509.h>\n#include <openssl/x509v3.h>\n#include <openssl/objects.h>\n#include <openssl/pem.h>\n#include <openssl/bn.h>\n#include <openssl/rsa.h>\n#include <openssl/dsa.h>\n#include <openssl/engine.h>\n#include <openssl/conf.h>\n#include <openssl/opensslv.h>\n\n#include \"scxsslcert.h\"\n#include \"resourcehelper.h\"\n\n#include <cassert>\n#include <cstdio>\n#include <cstdlib>\n#include <time.h>\n#include <string.h>\n#include <iostream>\n#include <sstream>\n#include <string>\n#include <vector>\n#include <fcntl.h>\n#include <unistd.h>\n\n#include <dlfcn.h>\n#include <assert.h>\n#include <locale.h>\n#include <sys/utsname.h>\nusing std::wcout;\nusing std::wcerr;\nusing std::endl;\nusing std::ends;\nusing std::string;\nusing std::wstring;\n\nusing SCXCoreLib::SCXFile;\nusing SCXCoreLib::SCXNULLPointerException;\nusing SCXCoreLib::StrFromMultibyte;\nusing SCXCoreLib::StrToMultibyte;\n\n// Define constant strings for the IDN library name based on platform:\n// For UNIX: libidn.so\n// For Linux: libcidn.so\n// Take care that Universal Linux is counted as Linux\n\n#if defined(aix) || defined(hpux) || defined(sun)\nconst char *s_idnLibraryName = \"libidn.so\";\n#else\nconst char *s_idnLibraryName = \"libcidn.so\";\n#endif\n\n\n/******************************************************************************\n *\n * SCXSSLException Implementation\n *\n ******************************************************************************/\n\n/*----------------------------------------------------------------------------*/\n/* (overload)\n Format which pointer was NULL\n\n*/\nwstring SCXSSLException::What() const\n{\n return L\"Error generating SSL certificate. Use scxsslconfig to \"\n L\"generate a new certificate, specifying host and domain names if \"\n L\"necessary. The error was: '\" + m_Reason + L\"'\";\n }\n\n/******************************************************************************\n *\n * SCXSSLCertificate Implementation\n *\n ******************************************************************************/\n\n//------------------------------------------------------------------------------\n// Public Methods\n//------------------------------------------------------------------------------\n\n/*----------------------------------------------------------------------------*/\n/**\n Constructor - Instantiate a SCXSSLCertificate object.\n\n \\param[in] keyPath Full path to the key file.\n \\param[in] certPath Full path to the certificate file.\n \\param[in] startDays Days to offset valid start time with.\n \\param[in] endDays Days to offset valid end time with.\n \\param[in] hostname Hostname to use in the certificates.\n \\param[in] domainname Domainname to use in the certificates.\n \\param[in] bits Number of bits in key.\n \\param[in] clientCert generate certificate with clientAuth eku\n\n \\date 1-17-2008\n*/\nSCXSSLCertificate::SCXSSLCertificate(SCXCoreLib::SCXFilePath keyPath, SCXCoreLib::SCXFilePath certPath,\n int startDays, int endDays, const wstring & hostname,\n const wstring & domainname, int bits, bool clientCert /* = false */)\n : m_startDays(startDays),\n m_endDays(endDays),\n m_bits(bits),\n m_clientCert(clientCert),\n m_KeyPath(keyPath),\n m_CertPath(certPath),\n m_hostname(hostname),\n m_domainname(domainname)\n{\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Destructor\n\n \\throws SCXSSLException\n*/\nSCXSSLCertificate::~SCXSSLCertificate()\n{\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Tries to seed random from a file. Will never block.\n\n \\param file Path to file with radnom bytes.\n \\param num Number of bytes to read from file. Zero means complete file.\n \\returns Number of bytes actually read from random file.\n\n If the num parameter is zero the file is read until it blocks.\n*/\n\nsize_t SCXSSLCertificate::LoadRandomFromFile(const char* file, size_t num)\n{\n size_t remain = num;\n size_t result = 0;\n int fd = open(file, O_RDONLY);\n if (-1 == fd)\n goto cleanup;\n if (-1 == fcntl(fd, F_SETFL, O_NONBLOCK))\n goto cleanup;\n\n char buffer[1024];\n while (remain > 0 || 0 == num) {\n size_t r = read(fd, buffer, (remain>sizeof(buffer) || 0 == num)?sizeof(buffer):remain);\n if (static_cast<size_t>(-1) == r)\n goto cleanup;\n if (0 == r)\n break;\n result += r;\n RAND_seed(buffer, static_cast<int>(r));\n remain -= r;\n }\n\n cleanup:\n if (-1 != fd)\n close(fd);\n return result;\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Load the random number seed from a file.\n\n \\throws SCXResourceExhaustedException\n\n*/\nvoid SCXSSLCertificate::LoadRndNumber()\n{\n size_t nLoadedBytes = 0;\n const size_t randomNeeded = 1024;\n const size_t goodRandomNeeded = 256;\n\n nLoadedBytes = LoadRandomFromUserFile();\n\n // Even if we got a lot of good data from the user rnd file we add extra entropy\n // from /dev/random if we can to get an even better seed.\n // In the best case scenario this means we have 2048 bytes of random to seed with\n nLoadedBytes += LoadRandomFromDevRandom(randomNeeded);\n\n // we want to get at least 256 bytes good random data in total from either file or\n // 'random' (ideally both)\n // based on open-ssl man page, \"file\" is a \"good\" source of random data\n // in case if file is missing, we take it from \"random\" device,\n // which is blocking (on some platforms) if there is not enough entropy\n // in that case we log a warning to the user and try to read the rest from urandom device\n // that is not a \"good\" source.\n if ( nLoadedBytes < goodRandomNeeded )\n {\n DisplaySeedWarning(goodRandomNeeded);\n nLoadedBytes += LoadRandomFromDevUrandom(randomNeeded);\n // Should not fail, but making sure\n if ( nLoadedBytes < goodRandomNeeded )\n {\n throw SCXCoreLib::SCXResourceExhaustedException(L\"random data\", L\"Failed to get random data - not enough entropy\", SCXSRCLOCATION);\n }\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Save the random number seed to a file.\n\n \\throws SCXSSLException\n\n*/\nvoid SCXSSLCertificate::SaveRndNumber()\n{\n char buffer[200];\n const char* file = RAND_file_name(buffer, sizeof buffer);\n if (!RAND_write_file(file))\n {\n ; //TODO: Only log that no random file was found. DO NOT FAIL!\n }\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Generate the certificates.\n\n \\throws SCXCoreLib::SCXInvalidArgumentException\n\n \\date 1-17-2008\n\n \\note The certificates are generated using the hostname and domain name, which\n is collected automatically.\n\n*/\nvoid SCXSSLCertificate::Generate()\n{\n if (0 == m_KeyPath.Get().size())\n {\n throw SCXCoreLib::SCXInvalidArgumentException(L\"keyPath\",\n L\"Key path is not set.\", SCXSRCLOCATION);\n }\n if (0 == m_CertPath.Get().size())\n {\n throw SCXCoreLib::SCXInvalidArgumentException(L\"certPath\",\n L\"Certificate path is not set.\", SCXSRCLOCATION);\n }\n SCXCoreLib::SCXFileInfo keyInfo(m_KeyPath.GetDirectory());\n SCXCoreLib::SCXFileInfo certInfo(m_CertPath.GetDirectory());\n if( ! keyInfo.PathExists())\n {\n throw SCXCoreLib::SCXFilePathNotFoundException(m_KeyPath.GetDirectory(), SCXSRCLOCATION);\n }\n if( ! certInfo.PathExists())\n {\n throw SCXCoreLib::SCXFilePathNotFoundException(m_CertPath.GetDirectory(), SCXSRCLOCATION);\n }\n\n LoadRndNumber();\n DoGenerate();\n SaveRndNumber();\n}\n\n//------------------------------------------------------------------------------\n// Private Methods\n//------------------------------------------------------------------------------\n\n// Resource helper classes.\n\n/** Helper class to construct an ASN1_INTEGER */\nstruct LoadASN1 {\n X509V3_EXT_METHOD * m_Method; ///< method function pointer.\n const char * m_SerialNumber; ///< serial number\n\n /** CTOR\n \\param m Method function pointer.\n \\param s Serial number.\n */\n LoadASN1( X509V3_EXT_METHOD * m, const char * s) : m_Method(m), m_SerialNumber(s)\n {\n }\n\n /**\n Create an ASN1_INTEGER struct.\n \\returns A pointer to a newly created ASN1_INTEGER struct encoding the serial\n number with the given method.\n */\n ASN1_INTEGER * operator()()\n {\n return s2i_ASN1_INTEGER(m_Method, const_cast<char*>(m_SerialNumber));\n }\n};\n\n// Resource helper functions.\n\n/**\n Function to make a macro behave like a static function.\n\n OpenSSL_add_all_algorithms() is a macro so it could not be passed as a function pointer.\n*/\n#if OPENSSL_VERSION_NUMBER <= 0x100fffffL // SSL 1.0.x or lower?\nstatic void SSL_OpenSSL_add_all_algorithms()\n{\n // Call to a macro\n OpenSSL_add_all_algorithms();\n}\n#else\nvoid NoOp_Destructor(){}\n#endif\n\n/*----------------------------------------------------------------------------*/\n/**\n Generate the SSL Certificates.\n\n \\throws SCXSSLException\n \\throws SCXCoreLib::SCXNULLPointerException\n*/\nvoid SCXSSLCertificate::DoGenerate()\n{\n try\n {\n int newKeyLength = m_bits;\n\n // Arguments from the command line.\n string outfile(StrToMultibyte(m_CertPath));\n string keyout(StrToMultibyte(m_KeyPath));\n\n #if OPENSSL_VERSION_NUMBER <= 0x100fffffL // SSL 1.0.x or lower?\n ManagedResource res1(ERR_load_crypto_strings, ERR_free_strings);\n ManagedResource res2(SSL_OpenSSL_add_all_algorithms, EVP_cleanup);\n ManagedResource res3(ENGINE_load_builtin_engines, ENGINE_cleanup);\n #else\n ManagedResource res1(ENGINE_load_builtin_engines, NoOp_Destructor);\n #endif\n\n // Serial number is always set to \"1\".\n // This is a self-signed certificate. Serial number is unimportant.\n char one[] = \"1\";\n ManagedValueResource<ASN1_INTEGER> serial(LoadASN1(NULL, one)(), ASN1_INTEGER_free);\n if (0 == serial.Get())\n {\n throw SCXNULLPointerException(L\"Error generating serial number\", SCXSRCLOCATION);\n }\n\n ManagedValueResource<BIO> out(BIO_new(BIO_s_file()), BIO_free_all);\n if (0 == out.Get())\n {\n throw SCXSSLException(L\"Failed to open out file\", SCXSRCLOCATION);\n }\n\n // Allocate an empty private key structure.\n ManagedValueResource<EVP_PKEY> pkey(EVP_PKEY_new(), EVP_PKEY_free);\n if (pkey.Get() == 0)\n {\n throw SCXNULLPointerException(L\"Unable to allocate empty private key structure.\",\n SCXSRCLOCATION);\n }\n\n {\n int ret = 1;\n\n #if OPENSSL_VERSION_NUMBER < 0x0090800fL // SSL version lower than 0.9.8? It is needed for Solaris-10.\n RSA * rsa = RSA_generate_key(newKeyLength, 0x10001, 0, 0);\n\n if ( ! rsa )\n {\n throw SCXCoreLib::SCXNULLPointerException(L\"Error allocating RSA structure.\",\n SCXSRCLOCATION);\n }\n\n #else\n\n BIGNUM *bne = BN_new();\n\n ret = BN_set_word(bne,RSA_F4);\n\n if(ret !=1){\n throw SCXNULLPointerException(L\"Unable to set empty private key structure.\",\n SCXSRCLOCATION);\n }\n\n RSA * rsa = RSA_new();\n\n if ( ! rsa )\n {\n throw SCXCoreLib::SCXNULLPointerException(L\"Error allocating RSA structure.\",\n SCXSRCLOCATION);\n }\n\n ret = RSA_generate_key_ex(rsa, newKeyLength, bne, NULL);\n #endif\n\n if ( ret != 1 || ! EVP_PKEY_assign_RSA(pkey.Get(), rsa))\n {\n // Free rsa if the assign was unsuccessful. (If it was successful, then rsa\n // is owned by pkey.)\n RSA_free(rsa);\n throw SCXSSLException(L\"Error generating RSA key pair..\", SCXSRCLOCATION);\n }\n }\n\n if (BIO_write_filename(out.Get(),const_cast<char*>(keyout.c_str())) <= 0)\n {\n int e = errno;\n std::wstring errText = SCXCoreLib::StrFromUTF8(SCXCoreLib::strerror(e));\n std::wostringstream ss;\n ss << keyout.c_str() << L\": \";\n if ( ! errText.empty() )\n {\n ss << errText;\n }\n else\n {\n ss << L\"errno=\" << e;\n }\n throw SCXSSLException(ss.str(), SCXSRCLOCATION);\n }\n\n if ( ! PEM_write_bio_PrivateKey(out.Get(),pkey.Get(),NULL,NULL,0,NULL,NULL))\n {\n throw SCXSSLException(L\"Error writing private key file\", SCXSRCLOCATION);\n }\n\n // Allocate a new X509_REQ structure\n ManagedValueResource<X509_REQ> req(X509_REQ_new(), X509_REQ_free);\n if (0 == req.Get())\n {\n throw SCXNULLPointerException(L\"Unable to allocate memory for an X509_REQ struct.\",\n SCXSRCLOCATION);\n }\n\n // Set the properties in the req structure from the private key.\n SetX509Properties(req.Get(),pkey.Get());\n\n ManagedValueResource<X509> x509ss(X509_new(), X509_free);\n if (0 == x509ss.Get())\n {\n throw SCXNULLPointerException(L\"Error allocating X509 structure x509ss.\",\n SCXSRCLOCATION);\n }\n\n if (!X509_set_serialNumber(x509ss.Get(), serial.Get()))\n {\n throw SCXSSLException(L\"Unable to set certificate serial nubmer.\", SCXSRCLOCATION);\n }\n\n // Copy the issuer name from the request.\n if (!X509_set_issuer_name(x509ss.Get(), X509_REQ_get_subject_name(req.Get())))\n {\n throw SCXSSLException(L\"Unable to set issuer name.\", SCXSRCLOCATION);\n }\n\n // Ensure the time is not before the certificate time.\n if (!X509_gmtime_adj(X509_get_notBefore(x509ss.Get()),(long)60*60*24*m_startDays))\n {\n throw SCXSSLException(L\"Invalid time range.\", SCXSRCLOCATION);\n }\n\n // Ensure the time is not after the certificate time.\n if (!X509_gmtime_adj(X509_get_notAfter(x509ss.Get()), (long)60*60*24*m_endDays))\n {\n throw SCXSSLException(L\"Invalid time range\", SCXSRCLOCATION);\n }\n\n // Copy the subject name from the request.\n if (!X509_set_subject_name(x509ss.Get(), X509_REQ_get_subject_name(req.Get())))\n {\n throw SCXSSLException(L\"Unable to set subject name.\", SCXSRCLOCATION);\n }\n\n {\n // Get the public key from the request, and set it in our cert.\n ManagedValueResource<EVP_PKEY> tmppkey(X509_REQ_get_pubkey(req.Get()), EVP_PKEY_free);\n if (!tmppkey.Get() || !X509_set_pubkey(x509ss.Get(),tmppkey.Get()))\n {\n throw SCXSSLException(L\"Unable to set the public key in the certificate\", SCXSRCLOCATION);\n }\n }\n\n /* Set up V3 context struct */\n\n X509V3_CTX ext_ctx;\n X509V3_set_ctx(&ext_ctx, x509ss.Get(), x509ss.Get(), NULL, NULL, 0);\n\n // Add serverAuth extension ... this magic OID is defined in RFC 3280,\n // section 4.2.1.13 \"Extended Key Usage\", as \"1.3.6.1.5.5.7.3.1\"\n // We will access it the right way ...\n // There is no need to free the pointer returned here, no memory is allocated\n ASN1_OBJECT * authOBJ = NULL;\n if (m_clientCert)\n {\n \tauthOBJ = OBJ_nid2obj(NID_client_auth);\n }\n else\n {\n \tauthOBJ = OBJ_nid2obj(NID_server_auth);\n }\n if(authOBJ == NULL)\n {\n throw SCXSSLException(L\"Unable to get serverAuth/clientAuth ASN1_OBJECT pointer\", SCXSRCLOCATION);\n }\n\n // The oid is of known length, 17 bytes ... pad it a little ...\n char authOIDBuf[24] = {0};\n\n // The flag 1 denotes that the numeric form of the answer (not long or short name) will be used\n // The return is (apparently) the string length of the converted string (this is undocumented) ..\n if(OBJ_obj2txt(authOIDBuf, static_cast<int> (sizeof(authOIDBuf)/sizeof(*authOIDBuf)), authOBJ, 1) <= 0)\n {\n throw SCXSSLException(L\"Not able to convert OBJ_server_auth/OBJ_client_auth to text\", SCXSRCLOCATION);\n }\n\n X509_EXTENSION * ext = X509V3_EXT_conf_nid(NULL, &ext_ctx, (int)NID_ext_key_usage, authOIDBuf);\n if(!ext)\n {\n throw SCXSSLException(L\"Unable to get extension pointer for serverAuth/clientAuth extension\", SCXSRCLOCATION);\n }\n\n int ext_OK = X509_add_ext(x509ss.Get(), ext, -1);\n X509_EXTENSION_free(ext);\n if(!ext_OK)\n {\n throw SCXSSLException(L\"Unable to add serverAuth/clientAuth extension\", SCXSRCLOCATION);\n }\n\n // Sign the certificate\n const EVP_MD * digest = EVP_sha256();\n int i = X509_sign(x509ss.Get(),pkey.Get(),digest);\n if (! i)\n {\n throw SCXSSLException(L\"Error signing certificate.\", SCXSRCLOCATION);\n }\n\n // Write the new certificate to a file.\n if ( ! BIO_write_filename(out.Get(),const_cast<char*>(outfile.c_str())))\n {\n throw SCXCoreLib::SCXInternalErrorException(L\"Unable to open the cert file for writing.\", SCXSRCLOCATION);\n }\n\n if ( ! PEM_write_bio_X509(out.Get(),x509ss.Get()))\n {\n throw SCXCoreLib::SCXInternalErrorException(L\"Error writing the cert file.\", SCXSRCLOCATION);\n }\n\n // Cleanup the rest of the resources that may have been allocated internally.\n #if OPENSSL_VERSION_NUMBER <= 0x100fffffL // SSL 1.0.x or lower?\n OBJ_cleanup();\n #endif\n CONF_modules_unload(1);\n #if OPENSSL_VERSION_NUMBER <= 0x100fffffL // SSL 1.0.x or lower?\n CRYPTO_cleanup_all_ex_data();\n ERR_remove_state(0);\n #endif\n }\n catch (SCXCoreLib::SCXException & e)\n {\n // Blunt force resource release functions.\n #if OPENSSL_VERSION_NUMBER <= 0x100fffffL // SSL 1.0.x or lower?\n OBJ_cleanup();\n CONF_modules_free();\n CRYPTO_cleanup_all_ex_data();\n ERR_remove_state(0);\n #endif\n\n throw;\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Set the properties in the X509_REQ object.\n\n \\param req pointer to openSSL X509 request information object.\n \\param pkey pointer to PEM Private Key object.\n \\throws SCXSSLException if unsuccessful.\n\n The X509_REQ object replaces the need for a separate config file.\n\n*/\nvoid SCXSSLCertificate::SetX509Properties(X509_REQ *req, EVP_PKEY *pkey)\n{\n // Set the version in the request.\n if ( ! X509_REQ_set_version(req,0L))\n {\n throw SCXSSLException(L\"Unable to set the version number in the request.\", SCXSRCLOCATION);\n }\n\n // Get the subject from the request.\n X509_NAME *subj = X509_REQ_get_subject_name(req);\n\n char dcPart[] = \"DC\";\n wstring tmp = m_domainname;\n wstring::size_type pos;\n while( ! tmp.empty())\n {\n if(wstring::npos != (pos = tmp.find_last_of(L'.')))\n {\n // Add the domain part to the subject.\n if ( ! X509_NAME_add_entry_by_txt(subj, dcPart, MBSTRING_ASC,\n reinterpret_cast<unsigned char*>(const_cast<char*>(StrToMultibyte(tmp.substr(pos+1)).c_str())), -1, -1, 0))\n {\n throw SCXSSLException(L\"Unable to add the domain to the subject.\", SCXSRCLOCATION);\n }\n tmp.erase(pos);\n }\n else\n {\n // Add the domain part to the subject.\n if ( ! X509_NAME_add_entry_by_txt(subj, dcPart, MBSTRING_ASC,\n reinterpret_cast<unsigned char*>(const_cast<char*>(StrToMultibyte(tmp).c_str())), -1, -1, 0))\n {\n throw SCXSSLException(L\"Unable to add the domain to the subject.\", SCXSRCLOCATION);\n }\n tmp.erase();\n }\n }\n\n char cnPart[] = \"CN\";\n if ( ! X509_NAME_add_entry_by_txt(subj, cnPart, MBSTRING_ASC,\n reinterpret_cast<unsigned char*>(const_cast<char*>(StrToMultibyte(m_hostname).c_str())), -1, -1, 0))\n {\n throw SCXSSLException(L\"Unable to add hostname to the subject.\", SCXSRCLOCATION);\n }\n wstring cn(m_hostname);\n // avoid putting the \".\" if there is no domain.\n if ( ! m_domainname.empty())\n {\n cn = SCXCoreLib::StrAppend(m_hostname,SCXCoreLib::StrAppend(L\".\",m_domainname));\n }\n if ( ! X509_NAME_add_entry_by_txt(subj, cnPart, MBSTRING_ASC,\n reinterpret_cast<unsigned char*>(const_cast<char*>(StrToMultibyte(cn).c_str())), -1, -1, 0))\n {\n throw SCXSSLException(L\"Unable to add the domain name to the subject.\", SCXSRCLOCATION);\n }\n\n if ( ! X509_REQ_set_pubkey(req,pkey))\n {\n throw SCXSSLException(L\"Unable to set the public key in the request.\", SCXSRCLOCATION);\n }\n\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Load random data from /dev/random\n\n \\param randomNeeded Bytes of random data to read\n \\returns Number of bytes read\n\n*/\nsize_t SCXSSLCertificate::LoadRandomFromDevRandom(size_t randomNeeded)\n{\n return LoadRandomFromFile(\"/dev/random\", randomNeeded);\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Load random data from /dev/urandom\n\n \\param randomNeeded Bytes of random data to read\n \\returns Number of bytes read\n\n*/\nsize_t SCXSSLCertificate::LoadRandomFromDevUrandom(size_t randomNeeded)\n{\n return LoadRandomFromFile(\"/dev/urandom\", randomNeeded);\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Load random data from user rnd file\n\n \\returns Number of bytes read\n\n*/\nsize_t SCXSSLCertificate::LoadRandomFromUserFile()\n{\n char buffer[200];\n const char* file = RAND_file_name(buffer, sizeof buffer);\n if ( file != NULL )\n {\n // We load the entire user rnd file since:\n // 1. The default for OpenSSL is to create this file with 1024 bytes of data\n // 2. We will tell OpenSSL to replace this with new data when we are done\n return LoadRandomFromFile(file, 0);\n }\n return 0;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Display warning to the user that not enough good random data could be read\n\n \\param goodRandomNeeded Bytes of random data that was needed\n\n*/\nvoid SCXSSLCertificate::DisplaySeedWarning(size_t goodRandomNeeded)\n{\n wcout << endl << L\"WARNING!\" << endl;\n wcout << L\"Could not read \" << goodRandomNeeded << L\" bytes of random data from /dev/random. \";\n wcout << L\"Will revert to less secure /dev/urandom.\" << endl;\n wcout << L\"See the security guide for how to regenerate certificates at a later time when more random data might be available.\" << endl << endl;\n}\n\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Constructor - Instantiate a SCXSSLCertificateLocalizedDomain object.\n\n \\param[in] keyPath Full path to the key file.\n \\param[in] certPath Full path to the certificate file.\n \\param[in] startDays Days to offset valid start time with.\n \\param[in] endDays Days to offset valid end time with.\n \\param[in] hostname Hostname to use in the certificates.\n \\param[in] domainname Domainname to use in the certificates.\n \\param[in] bits Number of bits in key.\n \\param[in] clientCert generate certificate with clientAuth eku.\n\n Note that it passes an empty string for the domain to the parent. It is expected that\nthe user will call Generate() to create a punycode domain string after this is called.\n*/\nSCXSSLCertificateLocalizedDomain::SCXSSLCertificateLocalizedDomain(SCXCoreLib::SCXFilePath keyPath, SCXCoreLib::SCXFilePath certPath,\n int startDays, int endDays, const wstring & hostname,\n const wstring & domainname_raw, int bits, bool clientCert)\n :SCXSSLCertificate(keyPath, certPath, startDays, endDays, hostname, wstring(L\"\"), bits, clientCert), m_domainname_raw(domainname_raw)\n{\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n CleanupErrorOutput() - post processing of error strings returned by the system,\n which can contain problematic characters.\n\n \\param[in] sErr Returned by dlerror().\n \\param[in] verbage Stringstream for error output.\n\n*/\nvoid SCXSSLCertificateLocalizedDomain::CleanupErrorOutput(const char * sErr, std::ostringstream& verbage)\n{\n // AIX likes to return strings with an embedded linefeed, which is not convenient to us ....\n#if defined(aix)\n if(sErr)\n {\n string strRaw = std::string(sErr);\n // Strip out linefeeds\n for(size_t offset = strRaw.find('\\x0a'); offset != string::npos; offset = strRaw.find('\\x0a'))\n strRaw.replace(offset, 1, string(\" \"));\n\n // Collapse all the doubled up spaces too ...\n for(size_t offset = strRaw.find(\" \"); offset != string::npos; offset = strRaw.find(\" \"))\n strRaw.replace(offset, 2, string(\" \"));\n\n verbage << \", reason given: \\'\" << strRaw << \"\\'\";\n }\n#else\n if(sErr)\n verbage << \", reason given: \\'\" << sErr << \"\\'\";\n#endif\n verbage << \".\" << endl;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Generate() - Punycode-converts domain string, and calls base\n class Generate() to create certificates.\n\n \\param[in] verbage Stream to receive chatter when user chooses verbose output.\n\n*/\nvoid SCXSSLCertificateLocalizedDomain::Generate(std::ostringstream& verbage)\n{\n std::wstring domainname_processed;\n bool bConverted = false;\n const char * sErr = 0;\n\n // Get library handle if you can, but first clear errors\n dlerror();\n void * hLib = GetLibIDN();\n\n if(hLib)\n {\n AutoClose aclib(hLib);\n\n // Get function pointer if you can\n IDNFuncPtr pCvt = GetIDNAToASCII(hLib);\n\n if(pCvt)\n {\n verbage << \"Using punycode library for certificate generation\" << endl;\n\n std::string domainname_raw_skinny = SCXCoreLib::StrToMultibyte(m_domainname_raw, true);\n\n // Now we can convert, or try to ...\n // Get locale, OK if it returns null\n const char * sLoc = setlocale(LC_CTYPE, \"\");\n\n char * pout = 0;\n int nSuccess = pCvt(domainname_raw_skinny.c_str(), &pout, 0);\n\n // Restore locale, harmless if sLoc is null\n setlocale(LC_CTYPE, sLoc);\n\n // Zero means it worked ... a 7 bit string will pass through unchanged\n if(nSuccess == 0)\n {\n verbage << \"Conversion succeeded\" << endl;\n\n domainname_processed = SCXCoreLib::StrFromMultibyte(pout, true);\n bConverted = true;\n }\n else\n {\n verbage << \"Found library and function, but not able to convert string, returned value is \" << nSuccess << endl;\n if(nSuccess == 1)\n verbage << \"Return code of 1 indicates a problem with locale. Consider using the LC_CTYPE environment variable to adjust locale settings.\" << endl;\n }\n }\n else\n {\n sErr = dlerror();\n verbage << \"Not using punycode because library does not have conversion function\" << endl;\n CleanupErrorOutput(sErr, verbage);\n }\n // Library closes automagically through AutoClose\n }\n else\n {\n sErr = dlerror();\n verbage << \"Not using punycode because library not found\";\n CleanupErrorOutput(sErr, verbage);\n }\n\n if(!bConverted)\n {\n // This in theory can produce an SCXCoreLib::SCXStringConversionException,\n // which will have to be handled in client code. We can do nothing\n // about converting this string if this fails\n verbage << \"Converting string in raw form, \\'\" << SCXCoreLib::StrToMultibyte(m_domainname_raw, true) << \"\\'.\" << endl;\n domainname_processed = m_domainname_raw;\n }\n\n // Store processed domain name, ::Generate() will use it\n // Do not trap exception because we do not expect ever to see it .. if domainname were\n // unconvertible we would know it by now\n m_domainname = domainname_processed;\n verbage << \"Domain name, after processing:\" << SCXCoreLib::StrToMultibyte(m_domainname, true) << endl;\n\n try\n {\n SCXSSLCertificate::Generate();\n verbage << \"Generated certificate\" << endl;\n }\n catch(SCXCoreLib::SCXStringConversionException)\n {\n verbage << \"Caught an exception from base::Generate() \" << endl;\n }\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Loads and returns handle to libcidn library, if it is installed.\n\n \\return Opaque library handle, or null.\n*/\nvoid * SCXSSLCertificateLocalizedDomain::GetLibIDN(void)\n{\n void * pLib = NULL;\n\n // Use dlopen() to look in the usual places ... this will\n // work if libcidn.so is a softlink chaining to a binary,\n // which will be the case if the idn devel library is installed.\n pLib = dlopen(s_idnLibraryName, RTLD_LOCAL|RTLD_LAZY);\n if(pLib)\n return pLib;\n\n // Above did not work, look in directories for libcidn.so.<N>,\n // taking the largest <N> preferentially.\n const char * sDir = NULL;\n\n#if PF_WIDTH == 64\n sDir = \"/lib64/\";\n#else\n sDir = \"/lib/\";\n#endif\n\n pLib = GetLibIDNByDirectory(sDir);\n if(pLib)\n return pLib;\n\n // Some systems (Ubuntu) put libraries into a directory of the form /lib/x86_64-linux-gnu.\n // The leading part of the subdirectory is uname-derived, being obviously just the machine\n // type. Rather than guess how it puts together the rest of the name, we will pass in a wild\n // card and let glob() figure it out.\n struct utsname uts;\n if(uname(&uts) == 0)\n {\n std::stringstream sDirMachine;\n sDirMachine << \"/lib/\" << uts.machine << \"*/\";\n pLib = GetLibIDNByDirectory(sDirMachine.str().c_str());\n if(pLib)\n return pLib;\n }\n // Fail ...\n return NULL;\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Searches directory for libcidn.so.* library file, and loads library if it is found.\n Sorts on suffix as integer, preferring (for instance) libcidn.so.2 over libcidn.so.1.\n This is to ensure getting the latest library.\n\n \\param sDir Name of directory in which to search, e.g. /usr/lib/ . Assumed\n to be non-null and to end with a '/' char.\n \\return Handle to library returned by dlopen().\n*/\nvoid * SCXSSLCertificateLocalizedDomain::GetLibIDNByDirectory(const char * sDir)\n{\n SCXCoreLib::SCXFilePath file_path;\n\n // Note that this is safe only because we know the dirs passed in will have no Unicode chars\n file_path.SetDirectory(SCXCoreLib::StrFromMultibyte(sDir));\n\n // It is tempting to get clever with globbing here but _caveat programmer_ :\n // glob strings are not regular expressions and it is not trivial to write\n // one that will trap any positive integer of any length and exclude all\n // non-digits. So this is done the old fashioned way, with a trailing '*' and a\n // validation routine.\n std::wstring idnName(SCXCoreLib::StrFromUTF8(s_idnLibraryName));\n idnName += L\".*\";\n file_path.SetFilename(idnName);\n\n SCXCoreLib::SCXGlob glob(file_path.Get());\n SCXCoreLib::SCXFilePath path;\n\n glob.DoGlob();\n glob.Next();\n\n // Sorts by trailing integer\n SuffixSortedFileSet file_set;\n\n do\n {\n path = glob.Current();\n\n // Validate for nice file names ..\n if(IntegerSuffixComparator::IsGoodFileName(path))\n file_set.insert(new SCXCoreLib::SCXFilePath(path));\n\n } while(glob.Next());\n\n void * pLib;\n SuffixSortedFileSet::iterator si;\n\n // Fetch top file name, should have biggest suffix value\n si = file_set.begin();\n if(si == file_set.end())\n pLib = NULL;\n else\n {\n pLib = dlopen(SCXCoreLib::StrToMultibyte((*si)->Get()).c_str(), RTLD_LOCAL|RTLD_LAZY);\n // Free alloc'd pointers here ...\n for(si = file_set.begin(); si != file_set.end(); ++si)\n delete (*si);\n }\n\n // Clean up struct ...\n file_set.clear();\n\n return pLib;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Validates file path is of the form /dir/subdir/file.ext.<N>, with <N> being\n a decimal integer.\n This function does input validation for the convenience of\n operator(), which is fussy about input by design.\n\n \\param path Path to file.\n \\return True/false for is/is not in correct form.\n*/\nbool IntegerSuffixComparator::IsGoodFileName(const SCXCoreLib::SCXFilePath& path)\n{\n std::wstring str_path = path.Get();\n\n if(str_path.length() == 0)\n return false;\n\n size_t offset;\n\n offset = str_path.find_last_of('.');\n\n // No dots, not a nice path\n if(offset == std::wstring::npos)\n return false;\n\n // Do not want dot at end of name\n if(offset == str_path.length() - 1)\n return false;\n\n // Must be all digits after the last dot\n static const wchar_t * sDigits = L\"0123456789\";\n if(str_path.find_first_not_of(sDigits, offset + 1) != std::wstring::npos)\n return false;\n\n return true;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Sort on integer file name suffix, e.g. libcidn.so.3 sorts before libcidn.so.2 .\n\n \\param pa, pb are pointers to SCXFilePath's that are pre-groomed and have nice\n file names with trailing integer suffixes.\n \\return True/false to sort by descending order of suffixes.\n*/\nbool IntegerSuffixComparator::operator()(const SCXCoreLib::SCXFilePath * pa, const SCXCoreLib::SCXFilePath * pb) const\n{\n // No checking is done for pa and pb because functor is called by set::insert() and they are known good\n // before insertion.\n // Also note that the file names are assumed to be OK because they passed through\n // IntegerSuffixComparator::IsGoodFileName() to get here.\n // Could do input validation here but this functor could be called many times during sorts / inserts\n // so it is more efficient to do it before insertion.\n\n std::wstring file_a, file_b; // file names\n file_a = pa->Get();\n file_b = pb->Get();\n\n scxlong sfx_a, sfx_b; // file name suffixes in integer form\n size_t offset_a, offset_b;\n\n // Validation routine verified that the strings contain a '.' before insertion.\n // We will not be seeing npos here .... no check.\n offset_a = file_a.find_last_of('.');\n offset_b = file_b.find_last_of('.');\n\n // Do not handle exceptions, we won't be getting any ... file and directory names are clean 7-bit strings.\n // We also already know that offsets do not point to last char in string ...\n sfx_a = SCXCoreLib::StrToLong(file_a.substr(offset_a + 1).c_str());\n sfx_b = SCXCoreLib::StrToLong(file_b.substr(offset_b + 1).c_str());\n return sfx_a > sfx_b;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Closes handle returned by GetLibIDN().\n\n \\param hLib Handle returned by GetLibIDN().\n \\return Does not return.\n*/\nvoid SCXSSLCertificateLocalizedDomain::CloseLibIDN(void * hLib)\n{\n assert(hLib);\n dlclose(hLib);\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n Gets pointer to punycode string conversion function from libcidna library.\n\n \\param hLib Handle to libcidn library returned by GetLibIDN().\n \\return Pointer to function idna_to_ascii_lz(), or null.\n*/\nIDNFuncPtr SCXSSLCertificateLocalizedDomain::GetIDNAToASCII(void * hLib)\n{\n void * p = dlsym(hLib, \"idna_to_ascii_lz\");\n if(!p)\n return NULL;\n\n// compilers on some platforms do not support the __extension__ keyword;\n// others require it.\n#if defined(sun) || defined(hpux)\n return (IDNFuncPtr)p;\n#else\n return __extension__(IDNFuncPtr)p;\n#endif\n}\n\n/** Autoclose destructor **/\nSCXSSLCertificateLocalizedDomain::AutoClose::~AutoClose()\n{\n if(m_hLib != 0)\n {\n CloseLibIDN(m_hLib);\n }\n}\n\n/*--------------------------E-N-D---O-F---F-I-L-E----------------------------*/\n" }, { "alpha_fraction": 0.6416396498680115, "alphanum_fraction": 0.647490918636322, "avg_line_length": 43.227848052978516, "blob_id": "65fc7a5c1f15c57fcbd9db3b2ae63ddcf5805398", "content_id": "a4452ac0b24d4ca8aec6d5fe18b377dc4d2c24d9", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 31446, "license_type": "permissive", "max_line_length": 124, "num_lines": 711, "path": "/test/code/providers/runas_provider/runasprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the runas provider\n\n \\date 2008-05-07 12:02\n\n Only tests the functionality of the provider class.\n The actual data gathering is tested by a separate class.\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxdirectoryinfo.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/strerror.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxprocess.h>\n#include <scxsystemlib/scxsysteminfo.h>\n#include <util/Base64Helper.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n#include \"support/scxrunasconfigurator.h\"\n#include \"support/runasprovider.h\"\n#include <list>\n#include <unistd.h>\n#include <sstream>\n#include \"SCX_OperatingSystem_Class_Provider.h\"\n\nusing namespace SCXCoreLib;\n\n// If you want to see extra information from executed commands/scripts\n// set \"c_EnableDebugOutput\" to 1.\nconst int c_EnableDebugOutput = 0;\n\nclass SCXRunAsProviderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXRunAsProviderTest );\n CPPUNIT_TEST( TestDoInvokeMethodNoParams );\n CPPUNIT_TEST( TestDoInvokeMethodPartParams );\n CPPUNIT_TEST( TestDoInvokeMethodCommandOK );\n CPPUNIT_TEST( TestDoInvokeMethodCommandOKWithEmptyElevationType );\n CPPUNIT_TEST( TestDoInvokeMethodCommandOKWithElevationType );\n CPPUNIT_TEST( TestDoInvokeMethodCommandOKWithUppercaseElevationType );\n CPPUNIT_TEST( TestDoInvokeMethodCommandOKWithInvalidElevationType );\n CPPUNIT_TEST( TestDoInvokeMethodCommandFailed );\n CPPUNIT_TEST( TestDoInvokeMethodShellCommandOK );\n CPPUNIT_TEST( TestDoInvokeMethodShellCommandOKWithBase64 );\n CPPUNIT_TEST( TestDoInvokeMethodShellCommandOKWithSudoElevationType );\n CPPUNIT_TEST( TestDoInvokeMethodShellCommandOKWithEmptyElevationType );\n CPPUNIT_TEST( TestDoInvokeMethodShellCommandOKWithInvalidElevationType );\n CPPUNIT_TEST( TestDoInvokeMethodScriptOK );\n CPPUNIT_TEST( TestDoInvokeMethodScriptOKWithBase64 );\n CPPUNIT_TEST( TestDoInvokeMethodScriptOKWithSudoElevation );\n CPPUNIT_TEST( TestDoInvokeMethodScriptOKWithUpperCaseSudoElevation );\n CPPUNIT_TEST( TestDoInvokeMethodScriptOKWithEmptyElevation );\n CPPUNIT_TEST( TestDoInvokeMethodScriptFailed );\n CPPUNIT_TEST( TestDoInvokeMethodScriptNonSH );\n CPPUNIT_TEST( TestDoInvokeMethodScriptNoHashBang );\n CPPUNIT_TEST( TestDoInvokeMethodScriptTmpDir );\n CPPUNIT_TEST( TestDoInvokeMethodScriptDefaultTmpDir );\n CPPUNIT_TEST( TestDoInvokeMethodScriptNonDefaultTmpDir );\n CPPUNIT_TEST( TestChRoot );\n CPPUNIT_TEST( TestCWD );\n\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodCommandOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodCommandOKWithEmptyElevationType, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodCommandOKWithElevationType, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodCommandOKWithUppercaseElevationType, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodCommandOKWithInvalidElevationType, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodCommandFailed, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodShellCommandOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodShellCommandOKWithBase64, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodShellCommandOKWithSudoElevationType, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodShellCommandOKWithEmptyElevationType, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodShellCommandOKWithInvalidElevationType, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodScriptOK, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodScriptOKWithBase64, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodScriptOKWithSudoElevation, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodScriptOKWithUpperCaseSudoElevation, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodScriptOKWithEmptyElevation, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodScriptFailed, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodScriptNonSH, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestDoInvokeMethodScriptNoHashBang, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestChRoot, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(TestCWD, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\npublic:\n \n void RunCommand(std::wstring command, std::wstring caller)\n {\n \tstd::istringstream input;\n \tstd::ostringstream output, error;\n \tint code = SCXCoreLib::SCXProcess::Run(command, input, output, error);\n \tif(code !=0 || error.str().length() > 0) {\n \t\tstd::stringstream ss;\n \t\tss<<\"Failure running command: \"<<StrToUTF8(command)<<std::endl;\n \t\tss<<\"Called by Method: \"<<StrToUTF8(caller)<<std::endl;\n \t\tif(code != 0) {\n \t\t\tss<<\"Exit code: \"<<code<<std::endl;\n \t\t}\n \t\tif(error.str().length() > 0) {\n \t\t\tss<<\"Error: \"<<error.str()<<std::endl;\n \t\t}\n \t\tCPPUNIT_ASSERT_EQUAL_MESSAGE(ss.str(), std::string(\"\"), error.str());\n \t\tCPPUNIT_ASSERT_EQUAL_MESSAGE(ss.str(), 0, code);\n \t}\n }\n \n void setUp(void)\n {\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_OperatingSystem_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n\n // The default CWD may not exist so we use the current instead.\n SCXCoreLib::SCXHandle<SCXCore::RunAsConfigurator> configurator(new SCXCore::RunAsConfigurator());\n configurator->SetCWD(SCXCoreLib::SCXFilePath(L\"./\"));\n if (0 == geteuid() && ! configurator->GetAllowRoot())\n {\n configurator->SetAllowRoot(true);\n }\n SCXCore::g_RunAsProvider.SetConfigurator(configurator);\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_OperatingSystem_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n RunCommand(L\"rm -rf testChRoot\", L\"tearDown\");\n RunCommand(L\"rm -rf testCWD\", L\"tearDown\");\n RunCommand(L\"rm -rf testTmpDir\", L\"tearDown\");\n }\n\n struct InvokeReturnData\n {\n MI_Sint32 returnCode;\n std::wstring stdOut;\n std::wstring stdErr;\n InvokeReturnData(): returnCode(-55555555){}\n };\n\n void VerifyInvokeResult(TestableContext &context, MI_Result result, InvokeReturnData &returnData,\n std::wstring errMsg)\n {\n if (c_EnableDebugOutput)\n {\n context.Print();\n }\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, result, context.GetResult());\n if (context.GetResult() == MI_RESULT_OK)\n {\n // We expect one instance to be returned.\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 1u, context.Size());\n bool miRet = context[0].GetProperty(\"MIReturn\",\n CALL_LOCATION(errMsg)).GetValue_MIBoolean(CALL_LOCATION(errMsg));\n returnData.returnCode = context[0].GetProperty(L\"ReturnCode\", CALL_LOCATION(errMsg)).\n GetValue_MISint32(CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, miRet, (returnData.returnCode == 0));\n \n returnData.stdOut = context[0].GetProperty(L\"StdOut\", CALL_LOCATION(errMsg)).\n GetValue_MIString(CALL_LOCATION(errMsg));\n returnData.stdErr = context[0].GetProperty(L\"StdErr\", CALL_LOCATION(errMsg)).\n GetValue_MIString(CALL_LOCATION(errMsg));\n \n // Some common sense basic tests.\n if (!miRet)\n {\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, returnData.stdOut.empty());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, returnData.stdErr.empty());\n }\n }\n }\n \n void ExecuteCommand(mi::SCX_OperatingSystem_ExecuteCommand_Class &param, MI_Result result, InvokeReturnData &returnData,\n std::wstring errMsg)\n {\n TestableContext context;\n mi::SCX_OperatingSystem_Class instanceName;\n mi::Module Module;\n mi::SCX_OperatingSystem_Class_Provider agent(&Module);\n agent.Invoke_ExecuteCommand(context, NULL, instanceName, param);\n context.WaitForResult();\n VerifyInvokeResult(context, result, returnData, CALL_LOCATION(errMsg));\n }\n\n void ExecuteShellCommand(mi::SCX_OperatingSystem_ExecuteShellCommand_Class &param, MI_Result result,\n InvokeReturnData &returnData, std::wstring errMsg)\n {\n TestableContext context;\n mi::SCX_OperatingSystem_Class instanceName;\n mi::Module Module;\n mi::SCX_OperatingSystem_Class_Provider agent(&Module);\n agent.Invoke_ExecuteShellCommand(context, NULL, instanceName, param);\n context.WaitForResult();\n VerifyInvokeResult(context, result, returnData, CALL_LOCATION(errMsg));\n }\n\n void ExecuteScript(mi::SCX_OperatingSystem_ExecuteScript_Class &param, MI_Result result, InvokeReturnData &returnData,\n std::wstring errMsg)\n {\n TestableContext context;\n mi::SCX_OperatingSystem_Class instanceName;\n mi::Module Module;\n mi::SCX_OperatingSystem_Class_Provider agent(&Module);\n agent.Invoke_ExecuteScript(context, NULL, instanceName, param);\n context.WaitForResult();\n VerifyInvokeResult(context, result, returnData, CALL_LOCATION(errMsg));\n }\n\n void TestDoInvokeMethodNoParams()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_INVALID_PARAMETER, returnData, CALL_LOCATION(errMsg));\n // Failure expected, nothing to be tested after this.\n }\n \n void TestDoInvokeMethodPartParams()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"ls\");\n // Don't specify timeout in parameter list.\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_INVALID_PARAMETER, returnData, CALL_LOCATION(errMsg));\n // Failure expected, nothing to be tested after this.\n }\n \n void TestDoInvokeMethodCommandOK()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"echo Testing\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Testing\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodCommandOKWithEmptyElevationType()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"echo Testing\");\n param.timeout_value(0);\n param.ElevationType_value(\"\");\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Testing\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodCommandOKWithElevationType()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"echo Testing\");\n param.timeout_value(0);\n param.ElevationType_value(\"sudo\");\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Testing\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodCommandOKWithUppercaseElevationType()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"echo Testing\");\n param.timeout_value(0);\n param.ElevationType_value(\"SUdo\");\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Testing\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodCommandOKWithInvalidElevationType()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"echo Testing\");\n param.timeout_value(0);\n param.ElevationType_value(\"aaaaaa\");\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_INVALID_PARAMETER, returnData, CALL_LOCATION(errMsg));\n // Failure expected, nothing to be tested after this.\n }\n\n void TestDoInvokeMethodCommandFailed()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"/non-existing-directory/non-existing-command\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_MESSAGE(ERROR_MESSAGE, 0 != returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, returnData.stdOut.empty());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, returnData.stdErr.empty());\n }\n\n void TestDoInvokeMethodShellCommandOK()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteShellCommand_Class param;\n param.Command_value(\"echo 'a\\nb\\nc' | grep b\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteShellCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"b\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n\n void TestDoInvokeMethodShellCommandOKWithBase64()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteShellCommand_Class param;\n // Command is: \"echo 'Howdy&There<Partner'\" (without quotes)\n param.Command_value(\"ZWNobyAnSG93ZHkmVGhlcmU8UGFydG5lcic=\");\n param.timeout_value(0);\n param.b64encoded_value(true);\n InvokeReturnData returnData;\n ExecuteShellCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, std::wstring(L\"Howdy&There<Partner\\n\"), returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, std::wstring(L\"\"), returnData.stdErr);\n }\n\n void TestDoInvokeMethodShellCommandOKWithSudoElevationType()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteShellCommand_Class param;\n param.Command_value(\"echo 'a\\nb\\nc' | grep b\");\n param.timeout_value(0);\n param.ElevationType_value(\"sudo\");\n InvokeReturnData returnData;\n ExecuteShellCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"b\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodShellCommandOKWithEmptyElevationType()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteShellCommand_Class param;\n param.Command_value(\"echo 'a\\nb\\nc' | grep b\");\n param.timeout_value(0);\n param.ElevationType_value(\"\");\n InvokeReturnData returnData;\n ExecuteShellCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"b\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodShellCommandOKWithInvalidElevationType()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteShellCommand_Class param;\n param.Command_value(\"echo 'a\\nb\\nc' | grep b\");\n param.timeout_value(0);\n param.ElevationType_value(\"aaaaaa\");\n InvokeReturnData returnData;\n ExecuteShellCommand(param, MI_RESULT_INVALID_PARAMETER, returnData, CALL_LOCATION(errMsg));\n // Failure expected, nothing to be tested after this.\n }\n\n const char* GetScript()\n {\n return\n \"#!/bin/sh\\n\"\n \"# write something to stdout stream\\n\"\n \"echo \\\"$3-$2-$1\\\"\\n\"\n \"# and now create stderr output\\n\"\n \"echo \\\"-$2-\\\">&2\\n\"\n \"exit 0\\n\";\n }\n\n void TestDoInvokeMethodScriptOK()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(GetScript());\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"run-test-unit\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"-test-\\n\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodScriptOKWithBase64()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n std::string command(GetScript());\n util::Base64Helper::Encode(command, command);\n param.Script_value(command.c_str());\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n param.b64encoded_value(true);\n InvokeReturnData returnData;\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"run-test-unit\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"-test-\\n\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodScriptOKWithSudoElevation()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(GetScript());\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n param.ElevationType_value(\"sudo\");\n InvokeReturnData returnData;\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"run-test-unit\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"-test-\\n\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodScriptOKWithUpperCaseSudoElevation()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(GetScript());\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n param.ElevationType_value(\"SUDO\");\n InvokeReturnData returnData;\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"run-test-unit\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"-test-\\n\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodScriptOKWithEmptyElevation()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(GetScript());\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n param.ElevationType_value(\"\");\n InvokeReturnData returnData;\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"run-test-unit\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"-test-\\n\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodScriptFailed()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(\"#!/bin/sh\\n\"\n \"no_exisiting_command_echo \\\"$3-$2-$1\\\"\\n\"\n \"# generate error code we can check later\\n\"\n \"exit 7\\n\");\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 7, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, returnData.stdOut.empty());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, returnData.stdErr.empty());\n }\n\n void TestDoInvokeMethodScriptNonSH()\n {\n std::wstring errMsg;\n\n // Try to find bash.\n std::list<std::wstring> bashPaths;\n bashPaths.push_back(L\"/bin/bash\");\n bashPaths.push_back(L\"/usr/bin/bash\");\n bashPaths.push_back(L\"/usr/local/bin/bash\");\n std::wstring bash = L\"\";\n for (std::list<std::wstring>::const_iterator iter = bashPaths.begin();\n iter != bashPaths.end();\n ++iter)\n {\n if (SCXFile::Exists(*iter))\n {\n bash = *iter;\n bash.append(L\"\\n\");\n }\n }\n\n CPPUNIT_ASSERT(L\"\" != bash);\n\n // This script will return what shell it is run in.\n std::string script = SCXCoreLib::StrToMultibyte(std::wstring(L\"#!\").append(bash).append(L\"echo $BASH\\n\"));\n\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(script.c_str());\n param.Arguments_value(\"\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, bash.c_str(), returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n void TestDoInvokeMethodScriptNoHashBang()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(\n \"# write something to stdout stream\\n\"\n \"echo \\\"$3-$2-$1\\\"\\n\"\n \"# and now create stderr output\\n\"\n \"echo \\\"-$2-\\\">&2\\n\"\n \"exit 0\\n\");\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"run-test-unit\\n\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"-test-\\n\", returnData.stdErr);\n }\n \n void TestDoInvokeMethodScriptTmpDir()\n {\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(\n \t\t \"#!/bin/sh\\n\"\n \t\t \"# Get location pointed by tmpdir\\n\"\n \t\t\t\t\"DIR=`dirname $0`\\n\"\n \t\t \"echo $DIR\\n\"\n \t\t \"exit 0\\n\");\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n SCXCore::g_RunAsProvider.SetTemporaryDirectory(L\"/some/random/directory/\");\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"/tmp\\n\", returnData.stdOut);\n }\n \n void TestDoInvokeMethodScriptDefaultTmpDir()\n {\n \tstd::wstring errMsg;\n \tmi::SCX_OperatingSystem_ExecuteScript_Class param;\n param.Script_value(\n \t\t \"#!/bin/sh\\n\"\n \t\t \"# Get location pointed by tmpdir\\n\"\n \t\t\t\"DIR=`dirname $0`\\n\"\n \t\t \"echo $DIR\\n\"\n \t\t \"exit 0\\n\");\n param.Arguments_value(\"unit test run\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n SCXCore::g_RunAsProvider.SetTemporaryDirectory(L\"/tmp/\");\n ExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"/tmp\\n\", returnData.stdOut);\n }\n \n void TestDoInvokeMethodScriptNonDefaultTmpDir()\n {\n \tstd::wstring errMsg;\n \tmi::SCX_OperatingSystem_ExecuteScript_Class param;\n \tparam.Script_value(\n \t \"#!/bin/sh\\n\"\n \t \t\"# Get location pointed by tmpdir\\n\"\n \t \t\"DIR=`dirname $0`\\n\"\n \t \t\"echo $DIR\\n\"\n \t \t\"exit 0\\n\");\n \tparam.Arguments_value(\"unit test run\");\n \tparam.timeout_value(0);\n \tInvokeReturnData returnData;\n \t\n \t// As readlink is not available on all plaforms testing this with a non default\n \t// directory\n \tSCXDirectory::CreateDirectory(L\"testTmpDir/\");\n \tSCXCore::g_RunAsProvider.SetTemporaryDirectory(L\"./testTmpDir/\");\n \t\n \tExecuteScript(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n \tCPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n \tCPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"./testTmpDir\\n\", returnData.stdOut);\n }\n\n void TestChRoot()\n {\n RunCommand(L\"rm -rf testChRoot\", L\"TestChRoot\");\n SCXDirectory::CreateDirectory(L\"testChRoot/\");\n\n // Write our script out\n {\n std::ofstream ofs(\"testChRoot/setup.sh\");\n ofs << \"BASE=testChRoot\" << std::endl;\n ofs << \"FILESET=\\\"\\\\\" << std::endl;\n ofs << \" /bin/touch \\\\\" << std::endl;\n ofs << \" /lib64/ld-linux-x86-64.so.2 \\\\\" << std::endl;\n ofs << \" /lib64/ld64.so.2 \\\\\" << std::endl;\n ofs << \" /lib64/libc.so.6 \\\\\" << std::endl;\n ofs << \" /lib64/libpthread.so.0 \\\\\" << std::endl;\n ofs << \" /lib64/librt.so.1 \\\\\" << std::endl;\n ofs << \" /lib64/tls/libc.so.6 \\\\\" << std::endl;\n ofs << \" /lib/ld-linux.so.2 \\\\\" << std::endl;\n ofs << \" /lib/libc.so.6 \\\\\" << std::endl;\n ofs << \" /lib/libpthread.so.0 \\\\\" << std::endl;\n ofs << \" /lib/librt.so.1 \\\\\" << std::endl;\n ofs << \" /usr/lib/dld.sl \\\\\" << std::endl;\n ofs << \" /usr/lib/hpux32/dld.so \\\\\" << std::endl;\n ofs << \" /usr/lib/hpux32/libc.so.1 \\\\\" << std::endl;\n ofs << \" /usr/lib/hpux32/libdl.so.1 \\\\\" << std::endl;\n ofs << \" /usr/lib/hpux32/uld.so \\\\\" << std::endl;\n ofs << \" /usr/lib/ld.so.1 \\\\\" << std::endl;\n ofs << \" /usr/lib/libc.2 \\\\\" << std::endl;\n ofs << \" /usr/lib/libc.a \\\\\" << std::endl;\n ofs << \" /usr/lib/libcmd.so.1 \\\\\" << std::endl;\n ofs << \" /usr/lib/libcrypt.a \\\\\" << std::endl;\n ofs << \" /usr/lib/libc.so.1 \\\\\" << std::endl;\n ofs << \" /usr/lib/libdld.2 \\\\\" << std::endl;\n ofs << \" /usr/lib/libdl.so.1 \\\\\" << std::endl;\n#if !defined(aix)\n // AIX doesn't reliably know the 'uname -i' command ...\n ofs << \" /lib/`uname -i`-linux-gnu/libc.so.6 \\\\\" << std::endl;\n ofs << \" /lib/`uname -i`-linux-gnu/librt.so.1 \\\\\" << std::endl;\n ofs << \" /lib/`uname -i`-linux-gnu/libpthread.so.0 \\\\\" << std::endl;\n#endif\n ofs << \" \\\"\" << std::endl;\n ofs << \"\" << std::endl;\n ofs << \"\" << std::endl;\n ofs << \"rm -rf ${BASE} >/dev/null 2>&1\" << std::endl;\n ofs << \"for f in ${FILESET} ; do\" << std::endl;\n ofs << \" test -r $f && mkdir -p ${BASE}/$(dirname $f) && cp -p $f ${BASE}/$f\" << std::endl;\n ofs << \"done\" << std::endl;\n ofs << \"exit 0\" << std::endl;\n }\n\n RunCommand(L\"chmod u+x testChRoot/setup.sh\", L\"TestChRoot\");\n RunCommand(L\"bash -c ./testChRoot/setup.sh\", L\"TestChRoot\");\n\n SCXCoreLib::SCXHandle<SCXCore::RunAsConfigurator> configurator(new SCXCore::RunAsConfigurator());\n configurator->SetChRootPath(SCXCoreLib::SCXFilePath(L\"./testChRoot\"));\n configurator->SetCWD(SCXCoreLib::SCXFilePath(L\"./\"));\n if (0 == geteuid() && ! configurator->GetAllowRoot())\n {\n configurator->SetAllowRoot(true);\n }\n SCXCore::g_RunAsProvider.SetConfigurator(configurator);\n\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"/bin/touch /ExecuteCommandWasHere\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT( SCXFile::Exists(L\"testChRoot/ExecuteCommandWasHere\") );\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n }\n\n void TestCWD()\n {\n RunCommand(L\"rm -rf testCWD\", L\"TestCWD\");\n SCXDirectory::CreateDirectory(L\"testCWD/\");\n\n SCXCoreLib::SCXHandle<SCXCore::RunAsConfigurator> configurator(new SCXCore::RunAsConfigurator());\n configurator->SetCWD(SCXCoreLib::SCXFilePath(L\"./testCWD/\"));\n if (0 == geteuid() && ! configurator->GetAllowRoot())\n {\n configurator->SetAllowRoot(true);\n }\n SCXCore::g_RunAsProvider.SetConfigurator(configurator);\n\n std::wstring errMsg;\n mi::SCX_OperatingSystem_ExecuteCommand_Class param;\n param.Command_value(\"/bin/touch ./ExecuteCommandWasHere\");\n param.timeout_value(0);\n InvokeReturnData returnData;\n ExecuteCommand(param, MI_RESULT_OK, returnData, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT( SCXFile::Exists(L\"testCWD/ExecuteCommandWasHere\") );\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 0, returnData.returnCode);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdOut);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", returnData.stdErr);\n } \n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXRunAsProviderTest );\n" }, { "alpha_fraction": 0.6506965756416321, "alphanum_fraction": 0.6534149050712585, "avg_line_length": 72.55000305175781, "blob_id": "14c79b67751c7368519746fce8841f8b271bbc80", "content_id": "017ee0ff89db7f0fcefbbd6cc32d2cfa7a3fa596", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 2943, "license_type": "permissive", "max_line_length": 194, "num_lines": 40, "path": "/build/Makefile.scxadmintests", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n# \n# Definition of all unit tests for SCXAdmin\n#\n#--------------------------------------------------------------------------------\n\n#--------------------------------------------------------------------------------\n# All tests for scxadmin\nPOSIX_UNITTESTS_SCXADMIN_SRCFILES = \\\n\t$(SCX_SHARED_TEST_ROOT)/tools/scx_admin/cimconfigurator_test.cpp \\\n\t$(SCX_SHARED_TEST_ROOT)/tools/scx_admin/logconfigurator_test.cpp \\\n\t$(SCX_SHARED_TEST_ROOT)/tools/scx_admin/cmdparser_test.cpp \\\n\t$(SCX_SHARED_TEST_ROOT)/tools/scx_admin/service_control_test.cpp \\\n\n# For a full build, also include these\nifneq ($(SCX_STACK_ONLY),true)\nPOSIX_UNITTESTS_SCXADMIN_SRCFILES += \\\n\t$(SCX_SHARED_TEST_ROOT)/tools/scx_admin/runasadminprovider_test.cpp \\\n\nendif\n\n# Extra include dirs for certain include files\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/cimconfigurator_test.d: INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/cimconfigurator_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/service_control_test.d: INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/service_control_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/logconfigurator_test.d: INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/logconfigurator_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/cmdparser_test.d: INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/cmdparser_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/runasadminprovider_test.d: INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin -I$(PROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/runasadminprovider_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin -I$(PROVIDER_SUPPORT_DIR)\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/runasconfigurator_test.d: INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin -I$(SCX_SRC_ROOT)/providers/runas_provider\n$(INTERMEDIATE_DIR)/test/code/shared/tools/scx_admin/runasconfigurator_test.$(PF_OBJ_FILE_SUFFIX): INCLUDES += -I$(SCX_SRC_ROOT)/shared/tools/scx_admin -I$(SCX_SRC_ROOT)/providers/runas_provider\n\n#-------------------------------- End of File -----------------------------------\n\n" }, { "alpha_fraction": 0.5299714803695679, "alphanum_fraction": 0.5328258872032166, "avg_line_length": 25.607595443725586, "blob_id": "7ed7debd3e023e86c6096d5c0a25736c883ac607", "content_id": "dbe204e9bbf429983b956903c8d08fafe5a52f17", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2102, "license_type": "permissive", "max_line_length": 108, "num_lines": 79, "path": "/source/code/providers/support/metaprovider.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n * \n * */\n /**\n \\file metaprovider.h\n\n \\brief Meta provider (SCX_Agent)\n\n \\date 04-01-03\n*/\n/*----------------------------------------------------------------------------*/\n\n#ifndef METAPROVIDER_H\n#define METAPROVIDER_H\n\n#include <scxcorelib/scxcmn.h>\n\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/scxtime.h>\n\n#include <MI.h>\n\nnamespace SCXCore\n{\n /*----------------------------------------------------------------------------*/\n /**\n Meta provider\n\n Provide base system information to the SCX_Agent provider.\n */\n class MetaProvider\n {\n public:\n MetaProvider()\n : m_buildTimeOK(false),\n m_readInstallInfoFile(false)\n { }\n virtual ~MetaProvider() { };\n\n virtual const std::wstring DumpString() const\n {\n return L\"MetaProvider\";\n }\n\n void Load();\n void Unload();\n bool GetInstallInfoData(std::string& installVersion, MI_Datetime& installTime);\n bool GetBuildTime(std::string& buildTime);\n\n SCXCoreLib::SCXLogHandle& GetLogHandle()\n {\n return m_log;\n }\n\n private:\n void ReadInstallInfoFile();\n void GetReleaseDate();\n\n //! Set to true if build time could be parsed OK\n bool m_buildTimeOK;\n //! build time set at compile time\n SCXCoreLib::SCXCalendarTime m_buildTime;\n\n //! Set to true if all info could be read from the install info file\n bool m_readInstallInfoFile;\n //! Install time read from install info file\n SCXCoreLib::SCXCalendarTime m_installTime;\n //! Install version read from install info file\n std::wstring m_installVersion;\n\n SCXCoreLib::SCXLogHandle m_log;\n static int ms_loadCount;\n };\n\n extern SCXCore::MetaProvider g_MetaProvider;\n}\n\n#endif // #ifndef METAPROVIDER_H\n" }, { "alpha_fraction": 0.6991822719573975, "alphanum_fraction": 0.702102780342102, "avg_line_length": 39.761905670166016, "blob_id": "1c223c09e68eee9477eabee8e936600b9acf03ab", "content_id": "01152e4beb0dd7b511269ddb2846bf9a94366567", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1712, "license_type": "permissive", "max_line_length": 117, "num_lines": 42, "path": "/test/code/shared/testutils/createEnv.sh", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\n# We need to set up some environment for the testrunner; do so here\n\nENV_FILE=`dirname $0`/env.sh\n\necho \"#!/bin/sh\" > $ENV_FILE\necho >> $ENV_FILE\n\n# Use the en_US locale for tests sensitive to date/time formatting\n[ -z \"$LANG\" ] && LANG=en_US.UTF-8\necho \"LANG=\\\"$LANG\\\"; export LANG\" >> $ENV_FILE\n\n# This is normally run from target directory. Include target directory in\n# LD_LIBRARY_PATH to pick up OMI libraries for the testrunner.\n#\n# The only other way was to have the 'make test' process pass a parameter to\n# us with the appropriate path, but this was easier and works fine.\nif [ \"`uname`\" = \"SunOS\" ]; then\n\techo \"LD_LIBRARY_PATH=/usr/local/ssl/lib:`pwd`; export LD_LIBRARY_PATH\" >> $ENV_FILE\nelif [ -n \"$LD_LIBRARY_PATH\" ] ; then\n\techo \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`pwd`\" >> $ENV_FILE\nelse\n\techo \"export LD_LIBRARY_PATH=`pwd`\" >> $ENV_FILE\nfi\n\n# Export a variable solely so that we can see we're running under test\n# This is currently used by the logfile provider\n#\n# Also, add logfilereader executable location to path (use '' to evaluate in child)\n# This avoids failing unit tests by having variable paths on invocation line\necho \"SCX_TESTRUN_ACTIVE=1; export SCX_TESTRUN_ACTIVE\" >> $ENV_FILE\necho 'PATH=$1:/usr/sbin:$PATH; export PATH' >> $ENV_FILE\n\n# Testrunner arguments are sent using environment variables...\n[ -n \"$SCX_TESTRUN_NAMES\" ] && echo \"SCX_TESTRUN_NAMES=\\\"$SCX_TESTRUN_NAMES\\\"; export SCX_TESTRUN_NAMES\" >> $ENV_FILE\n[ -n \"$SCX_TESTRUN_ATTRS\" ] && echo \"SCX_TESTRUN_ATTRS=\\\"$SCX_TESTRUN_ATTRS\\\"; export SCX_TESTRUN_ATTRS\" >> $ENV_FILE\n\n# Code coverage (BullsEye) environment\n[ -n \"$COVFILE\" ] && echo \"COVFILE=\\\"$COVFILE\\\"; export COVFILE\" >> $ENV_FILE\n\nexit 0;\n" }, { "alpha_fraction": 0.6144343018531799, "alphanum_fraction": 0.6345903873443604, "avg_line_length": 24.848739624023438, "blob_id": "73965f6be66291bf200f16485464981b371db39a", "content_id": "8eb7d06418a54959d481e38d1d889f436cca2387", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 3076, "license_type": "permissive", "max_line_length": 196, "num_lines": 119, "path": "/test/util/artifacts/runas-memleak/testleak.sh", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#! /bin/bash\n\n# Note: /bin/bash is required for mathmatical computions in workflow below.\n\nProvide_ExShell_Load()\n{\n # Run the ExecuteShellCommand RunAs provider 350 times, printing a \".\" after 25 iterations\n # (We want to give some indication we're running, but not flood the screen)\n\n I=0\n while [ $I -lt 350 ]; do\n R=$(($I % 25))\n [ $R -eq 0 ] && echo -n \".\"\n /opt/omi/bin/omicli iv root/scx { SCX_OperatingSystem } ExecuteShellCommand { command \"$FULLPATH\" timeout 0 } > /dev/null\n I=$(( $I + 1 ))\n done\n\n echo\n}\n\nProvide_ExScript_Load()\n{\n # Run the ExecuteScript RunAs provider 350 times, printing a \".\" after 25 iterations\n # (We want to give some indication we're running, but not flood the screen)\n #\n # The simple shell script:\n #\n # echo \"\"\n # echo \"Hello\"\n # echo \"Goodbye\"\n #\n # will yield ZWNobyAiIg0KZWNobyAiSGVsbG8iDQplY2hvICJHb29kYnllIg== when converted to Base64. As a result, the following is a simple invocation of the ExecuteScript \n\n\n I=0\n while [ $I -lt 350 ]; do\n R=$(($I % 25))\n [ $R -eq 0 ] && echo -n \".\"\n /opt/omi/bin/omicli iv root/scx { SCX_OperatingSystem } ExecuteScript { Script \"ZWNobyAiIg0KZWNobyAiSGVsbG8iDQplY2hvICJHb29kYnllIg==\" Arguments \"\" timeout 0 b64encoded \"true\" } > /dev/null\n I=$(( $I + 1 ))\n done\n\n echo\n}\n\nProvide_ExCommand_Load()\n{\n # Run the ExecuteCommand RunAs provider 350 times, printing a \".\" after 25 iterations\n # (We want to give some indication we're running, but not flood the screen)\n\n I=0\n while [ $I -lt 350 ]; do\n R=$(($I % 25))\n [ $R -eq 0 ] && echo -n \".\"\n /opt/omi/bin/omicli iv root/scx { SCX_OperatingSystem } ExecuteCommand { command hostname timeout 0 } > /dev/null\n I=$(( $I + 1 ))\n done\n\n echo\n}\n\n# Find out where we live ...\n# Can't use something like 'readlink -e $0' because that doesn't work everywhere\n\ncase $0 in\n /*|~*)\n SCRIPT_INDIRECT=\"`dirname $0`\"\n ;;\n *)\n PWD=\"`pwd`\"\n SCRIPT_INDIRECT=\"`dirname $PWD/$0`\"\n ;;\nesac\n\nBASEDIR=\"`(cd \\\"$SCRIPT_INDIRECT\\\"; pwd -P)`\"\nFULLPATH=$BASEDIR/measureleak.sh\nARRAY=( Provide_ExShell_Load Provide_ExScript_Load Provide_ExCommand_Load )\n\n# Don't allow errors to be ignored\nset -e\n\necho \"Invoking RunAs provider (to insure it's running) ...\"\n/opt/omi/bin/omicli iv root/scx { SCX_OperatingSystem } ExecuteShellCommand { command \"echo Hello World\" timeout 0 }\n\necho\necho \"Starting values for omiagent process:\"\n$FULLPATH\n\n# First run\n\nfor i in \"${ARRAY[@]}\"\ndo\n echo\n echo \"Will now exercise $i RunAs provider under load:\"\n $i\n\n echo\n echo \"Intermediate values for $i RunAs provider:\"\n $FULLPATH\ndone\n\n# Second Run\n\nfor i in \"${ARRAY[@]}\"\ndo\n echo\n echo \"Will exercise $i RunAs provider again under load:\"\n $i\n\n echo\n echo \"Current values for $i RunAs provider:\"\n $FULLPATH\ndone\n\necho\necho \"Note: These values should be very close to intermediate values!\"\necho \" If they are not very close, this must be investigated.\"\n\nexit 0\n" }, { "alpha_fraction": 0.33728981018066406, "alphanum_fraction": 0.36102867126464844, "avg_line_length": 23.923076629638672, "blob_id": "b245f7977ba256a0024da5ec138eb13a3904de0e", "content_id": "ce4cd1dec31411b64f90339428bce6db7cb30358", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1011, "license_type": "permissive", "max_line_length": 95, "num_lines": 39, "path": "/docs/int/template_files/template_impl_file.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\r\n Copyright (c) Microsoft Corporation. All rights reserved. \r\n \r\n*/\r\n/**\r\n \\file \r\n\r\n \\brief < Brief description of purpose of the file > \r\n \r\n \\date 07-07-13 11:23:02\r\n\r\n < Optional detailed description of file purpose >\r\n \r\n*/\r\n/*----------------------------------------------------------------------------*/\r\n\r\n#include <scxcorelib/scxcmn.h>\r\n\r\n\r\n/*----------------------------------------------------------------------------*/\r\n/**\r\n < Brief description of FUNCTION/METHOD here >\r\n \r\n \\param < One for each actual param >\r\n \\returns < Description >\r\n \\throws < One for each exception from this function >\r\n \r\n \\date 07-05-06 23:44:46 [if created long after class created]\r\n \r\n < Detailed description >\r\n \r\n*/\r\n\r\n\r\n\r\n\r\n\r\n\r\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\r\n" }, { "alpha_fraction": 0.5832547545433044, "alphanum_fraction": 0.5962662696838379, "avg_line_length": 34.35333251953125, "blob_id": "71b2990225ca62d1407dd99282d9cbe4d8da1f99", "content_id": "e3f0538ecdd9afb71d9aa6137f4b04f4520a903f", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 5303, "license_type": "permissive", "max_line_length": 170, "num_lines": 150, "path": "/build/Makefile.pf.AIX", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2008-02-27\n# \n# Platform-specific makefile for AIX\n# \n#--------------------------------------------------------------------------------\n\n# Define flags. (These will be submitted to all commands that use the preprocesor)\nDEFINES+=-Daix -DPF_MAJOR=$(PF_MAJOR) -DPF_MINOR=$(PF_MINOR) \n\nifeq ($(SCX_STACK_ONLY), true)\n\tDEFINES += -DSCX_STACK_ONLY\nendif\n\n# Compiler flags that regulates warning level.\n# Suppress warning 1540-2864: Only the last two digits of year are given by 'x' conversion in some locales.\nCXX_WARN_FLAGS=-qwarn64 -qformat -qhalt=w -qflag=w -qsuppress=1540-2864\nC_WARN_FLAGS=-qformat -qhalt=w -qflag=w:w -qsuppress=1540-2864\n\n# Common compiler flags (sent to compile command and link commands)\n# (-qthreaded is implied by using the _r version of xlc++)\n#64bit: COMMONFLAGS=-q64 -qlanglvl=stdc99 -qrtti -qpic\n#\n# Note: We used to use -qextchk , but this doesn't work well\n# with OMI. Defaul;t is off, and documentation says:\n# Generates bind-time type-checking information and\n# checks for compile-time consistency.\n# Since it's not clear if this ever helped us, is gone for now\n\nCOMMONFLAGS=-q64 -qlanglvl=stdc99 -qrtti -qpic\n\n\n# CXX Compiler flags \nCXXFLAGS=$(COMMONFLAGS) -qlonglong $(DEFINES) $(CXX_WARN_FLAGS)\nCFLAGS=$(COMMONFLAGS) $(DEFINES) $(C_WARN_FLAGS)\n\n# CXX Debug flags for debug builds\nifeq ($(BUILD_TYPE),Debug)\n\tCOMMONFLAGS += -g -qcheck \n# \tCOMMONFLAGS += -qheapdebug Currently disabled, see WI11161\n\tDEFINES += -D_DEBUG\nelse\n\tCOMMONFLAGS += -g -O2 -qcompact\n\tDEFINES += -DNDEBUG\nendif\n\n# Linker flags\nLINK_OUTFLAG=-o $@\nLINK_STATLIB_OUTFLAG=$@\n\n# Add profiling flags to compile/link command, if requested.\nifeq ($(BUILD_PROFILING), prof)\n COMMONFLAGS += -p\nendif\nifeq ($(BUILD_PROFILING), gprof)\n COMMONFLAGS += -pg\nendif\n\n#--------------------------------------------------------------------------------\n# Tools for this platform\n\n# Compiler for CPP files\nCXX=xlC_r\n\n# Link command for executables\n# Link an executable\nLINK=$(CXX) $(COMMONFLAGS) -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR) -L$(SCXOMI_LIBS)\n\n# Link command for static libraries (archives)\n#64bit: LINK_STATLIB=ar -rc -X 64\nLINK_STATLIB=ar -rc -X 64\n\n# Link a dynamic lib (\"create a shared library that uses runtime linking\")\nLINK_DYNLIB = $(CXX) -G $(COMMONFLAGS) -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR) -bernotok -blibpath:/usr/lib:/lib:/opt/microsoft/scx/lib\n\n# Include paths\nINCLUDES=-I$(SCX_SHARED_INCLUDE_DIR) -I$(INT_INCLUDE_DIR) -I$(SCXPAL_INT_INCLUDE_DIR) -I$(SCX_BRD) -I$(SCXPAL_DIR) -I$(SCX_SHARED_TST_EXT_INCLUDE_DIR) -I$(SCXOMI_INCLUDE)\nUNITTEST_EXTRA_INCLUDES=-I$(SCXPAL_TEST_ROOT)/include -I$(SCX_SHARED_SRC_ROOT)\n\n# No operation, i.e. suppressing a command\nNOOP=@echo Step suppressed \n\n# Command for making dependecies\n# Note the we need a special rule that redirects the output with -MF rather that '>'\nMKDEP=xlc++_r -E -qmakedep=gcc \n\n#--------------------------------------------------------------------------------\n# File type suffixes\n\nPF_OBJ_FILE_SUFFIX=o\nPF_STAT_LIB_FILE_SUFFIX=a\nPF_DYN_LIB_FILE_SUFFIX=so\nPF_EXE_FILE_SUFFIX=\nPF_KIT_FILE_SUFFIX=tar\n\n#--------------------------------------------------------------------------------\n# Paths\n#--------------------------------------------------------------------------------\n\n# Path to where the CPPUNIT libraries are checked in \nCPPUNIT_LIB_PATH=$(SCX_SHARED_TST_EXT_LIB_DIR)/aix/$(ARCH)/cppunit_64bit\n#64bit: CPPUNIT_LIB_PATH=$(SCX_SHARED_TST_EXT_LIB_DIR)/aix/$(ARCH)/cppunit_64bit\n\n#--------------------------------------------------------------------------------\n# Link switches for this platform, per target\n#--------------------------------------------------------------------------------\n\n\tLDFLAGS_DYNLIB =\n\tLDFLAGS_EXECUTABLE =\n\n# The Core Provider Module links with these \nLDFLAGS_COREPROVIDERMODULE = $(LDFLAGS_DYNLIB) -lperfstat -lodm -lcfg -llvm\n\n# The Test Provider Module links with these\nLDFLAGS_TESTPROVIDERMODULE = $(LDFLAGS_DYNLIB) -lodm -lcfg -llvm\n\n# The scx-admin tool links with these\nLDFLAGS_SCX_ADMIN_TOOL = -lperfstat -lodm -lcfg -llvm\n\n# Transforms a list of symbols that should be exposed to the correct link flags\nget_ld_flags_for_retaining_symbols=$(addprefix -u, $(1))\n\n# The testrunner links with these\n#\n# Need the -brtl flag on testrunner to resolve against libmicxx.so (from OMI)\n# Otherwise, the testrunner only links against static libraries, and libmicxx.so\n# isn't available that way.\nLDFLAGS_TESTRUNNER = $(LDFLAGS_EXECUTABLE) -brtl -lperfstat -lodm -lcfg -llvm -lm\n\nSSL_LIBS = -lssl -lcrypto\n\n#--------------------------------------------------------------------------------\n# InstallBuilder datafile determination\n#--------------------------------------------------------------------------------\n\nPF_DEPENDENT_DATAFILES = AIX.data\nifeq ($(PF_MAJOR), 7)\nPF_DEPENDENT_DATAFILES += AIX_7.data\nendif\nifeq ($(PF_MAJOR), 6)\nPF_DEPENDENT_DATAFILES += AIX_6.data\nendif\nifeq ($(PF_MAJOR), 5)\nPF_DEPENDENT_DATAFILES += AIX_5.data\nendif\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.6395228505134583, "alphanum_fraction": 0.6444501876831055, "avg_line_length": 40.021278381347656, "blob_id": "4778e7cc931b12830c953209247c02d491a58082", "content_id": "6df0977e767f4e13b8084ab39c4940e35c3866d9", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3856, "license_type": "permissive", "max_line_length": 187, "num_lines": 94, "path": "/source/code/providers/support/appserver/jbossappserverinstance.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file jbossappserverinstance.h\n\n \\brief PAL representation of a JBoss Application Server\n\n \\date 11-05-18 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef JBOSSAPPSERVERINSTANCE_H\n#define JBOSSAPPSERVERINSTANCE_H\n\n#include <string>\n\n#include \"appserverinstance.h\"\n\nnamespace SCXSystemLib\n{\n /*----------------------------------------------------------------------------*/\n /**\n Class representing all external dependencies from the AppServer PAL.\n\n */\n\ttypedef enum {\n\t\tjboss_version_7,\n\t\tjboss_version_8\n\t} jboss_version_type;\n class JBossAppServerInstancePALDependencies\n {\n public:\n virtual SCXCoreLib::SCXHandle<std::istream> OpenXmlVersionFile(std::wstring filename);\n virtual SCXCoreLib::SCXHandle<std::istream> OpenXmlPortsFile(std::wstring filename);\n virtual SCXCoreLib::SCXHandle<std::istream> OpenXmlServiceFile(std::wstring filename);\n virtual SCXCoreLib::SCXHandle<std::istream> OpenXmlServerFile(std::wstring filename);\n virtual SCXCoreLib::SCXHandle<std::istream> OpenXmlBindingFile(std::wstring filename);\n\t\tvirtual SCXCoreLib::SCXHandle<std::istream> OpenDomainHostXmlFile(std::wstring filename);\n\t\tvirtual SCXCoreLib::SCXHandle<std::istream> OpenDomainXmlFile(std::wstring filename);\n\t\tvirtual SCXCoreLib::SCXHandle<std::istream> OpenModuleXmlFile (std::wstring filename);\n\t\tvirtual bool versionJBossWildfly(SCXCoreLib::SCXFilePath filepath, jboss_version_type &version);\n virtual ~JBossAppServerInstancePALDependencies() {};\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Class that represents an instances.\n\n Concrete implementation of an instance of a JBoss Application Server\n\n */\n class JBossAppServerInstance : public AppServerInstance\n {\n friend class AppServerEnumeration;\n\n\tpublic:\n JBossAppServerInstance(\n std::wstring id, \n std::wstring config,\n std::wstring portsBinding,\n SCXCoreLib::SCXHandle<JBossAppServerInstancePALDependencies> deps = SCXCoreLib::SCXHandle<JBossAppServerInstancePALDependencies>(new JBossAppServerInstancePALDependencies()),\n std::wstring deployment = L\"\");\n JBossAppServerInstance(\n std::wstring diskPath,\n SCXCoreLib::SCXHandle<JBossAppServerInstancePALDependencies> deps = SCXCoreLib::SCXHandle<JBossAppServerInstancePALDependencies>(new JBossAppServerInstancePALDependencies()));\n virtual ~JBossAppServerInstance();\n\n virtual void Update();\n virtual bool IsStillInstalled();\n\n private:\n void UpdateVersion();\n void UpdateJBoss4PortsFromServiceBinding(std::wstring filename, std::string servername);\n void UpdateJBoss4PortsFromServerConfiguration();\n void UpdateJBoss4Ports();\n void UpdateJBoss5Ports();\n void UpdateJBoss7Ports();\n void GetStringFromStream(SCXCoreLib::SCXHandle<std::istream> mystream, std::string& content);\n void TryReadInteger(unsigned int& result, bool& found, const std::wstring& value, const std::wstring& errorText);\n\t\t\n\t\tstd::vector<std::wstring> GetJBossWildflyServerHostXmlInformation();\n std::wstring m_config;\n std::wstring m_serverName;\n std::wstring m_basePath;\n std::wstring m_portsBinding;\n std::wstring m_jbossStandaloneConfigFile;\n\n SCXCoreLib::SCXHandle<JBossAppServerInstancePALDependencies> m_deps;\n };\n\n}\n\n#endif /* JBOSSAPPSERVERINSTANCE_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5571591258049011, "alphanum_fraction": 0.5609570741653442, "avg_line_length": 21.117647171020508, "blob_id": "3bf95b1e9b4b3fa6754dccf5b0dfbe844c4a0262", "content_id": "ca25a40b966b0735b453bf902ebbb5e77a421d8a", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2633, "license_type": "permissive", "max_line_length": 100, "num_lines": 119, "path": "/source/code/shared/tools/scx_ssl_config/resourcehelper.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief Resource helper classes.\n\n \\date 2-12-2008\n\n These classes provide automated resource control.\n\n*/\n\n#ifndef RESOURCEHELPER_H\n#define RESOURCEHELPER_H\n\n#include <iosfwd>\n#include <cassert>\n\nextern \"C\"\n{\n typedef void (*fnptr)(); ///< Define a resource alloc/dealloc function pointer type.\n}\n\n/**\n Helper class to perform resouce management.\n\n Resources are allocated by a void (*fn)(void) call and deallocated the same way.\n*/\nclass ManagedResource {\nprivate:\n fnptr m_ReleaseFcn; ///< Release resource function pointer.\n\npublic:\n /** CTOR\n \\param[in] load Resource load function pointer.\n \\param[in] release Resource release function pointer.\n\n Create a resource control object and load the resource.\n */\n ManagedResource(fnptr load, fnptr release) : m_ReleaseFcn(release)\n {\n assert(m_ReleaseFcn);\n if (0 != load)\n {\n (*load)();\n }\n }\n\n /** DTOR\n Release the loaded resource.\n */\n ~ManagedResource()\n {\n (*m_ReleaseFcn)();\n }\n};\n\n\n/**\n Helper class to manage pointer resources.\n\n The class maintains a pointer to a resource. It must be provided methods to\n load the pointer and to free the pointer when the resource is to be released.\n\n*/\ntemplate<typename T> struct ManagedValueResource {\n typedef void (*releaseptr)(T *); ///< Resource release function prototype.\n\n T * m_Value; ///< Value pointer.\n releaseptr m_ReleaseFcn; ///< Release function pointer.\n\n /**\n CTOR\n Create a resource control object with a given initial value.\n \\param[in] init The initial value of the pointer.\n \\param[in] rp A release function pointer.\n */\n ManagedValueResource(T *init, releaseptr rp) :\n m_ReleaseFcn(rp)\n {\n m_Value = init;\n }\n\n /**\n DTOR\n Release the managed value.\n */\n ~ManagedValueResource()\n {\n (*m_ReleaseFcn)(m_Value);\n m_Value = 0;\n }\n\n /**\n Get the value.\n \\returns The value pointer.\n */\n T * Get()\n {\n return m_Value;\n }\n\n /**\n Check for assigned value.\n \\returns true if the value is unassigned.\n */\n bool operator !()\n {\n return 0 == m_Value;\n }\n};\n\n\n#endif /* RESOURCEHELPER_H */\n\n\n/*--------------------------E-N-D---O-F---F-I-L-E----------------------------*/\n\n" }, { "alpha_fraction": 0.5305646061897278, "alphanum_fraction": 0.5347643494606018, "avg_line_length": 31.96923065185547, "blob_id": "faba6209ea3e851fec9cc689a6e5cb7c7da92ad7", "content_id": "4407e4236f0252509656189bd1910c7e67817375", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2143, "license_type": "permissive", "max_line_length": 108, "num_lines": 65, "path": "/source/code/providers/support/filesystemprovider.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n * \n * */\n /**\n \\file filesystemprovider.cpp\n\n \\brief FileSystem provider implementation\n\n \\date 08-30-13 \n*/\n/*----------------------------------------------------------------------------*/\n\n#include \"filesystemprovider.h\"\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXCore\n{\n void FileSystemProvider::Load()\n {\n if ( 1 == ++ms_loadCount )\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.providers.filesystemprovider\");\n LogStartup();\n SCX_LOGTRACE(m_log, L\"FileSystemProvider::Load\");\n\n // Set up the dependencies;\n m_staticLogicaldeps = new DiskDependDefault();\n m_statisticalLogicaldeps = new DiskDependDefault();\n\n // Create the enumeration objects\n m_statisticalLogicalDisks = new StatisticalLogicalDiskEnumeration(m_statisticalLogicaldeps);\n m_statisticalLogicalDisks->Init();\n\n m_staticLogicalDisks = new StaticLogicalDiskEnumeration(m_staticLogicaldeps);\n m_staticLogicalDisks->Init();\n }\n }\n\n void FileSystemProvider::UnLoad()\n {\n SCX_LOGTRACE(m_log, L\"FileSystemProvider::Unload()\");\n if (0 == --ms_loadCount)\n {\n if (m_statisticalLogicalDisks != NULL)\n {\n m_statisticalLogicalDisks->CleanUp();\n m_statisticalLogicalDisks = NULL;\n }\n\n if (m_staticLogicalDisks != NULL)\n {\n m_staticLogicalDisks->CleanUp();\n m_staticLogicalDisks = NULL;\n }\n }\n }\n\n // Only construct FileSystemProvider class once - installation date/version never changes!\n SCXCore::FileSystemProvider g_FileSystemProvider;\n int SCXCore::FileSystemProvider::ms_loadCount = 0;\n}\n\n /*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.582770586013794, "alphanum_fraction": 0.5850216746330261, "avg_line_length": 28.389312744140625, "blob_id": "cb3e5c8c1f1e6932e28ee8961f22d74ef1058f56", "content_id": "29d890bc5f07106d1eaff0a398330fa199caaf1f", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 11550, "license_type": "permissive", "max_line_length": 177, "num_lines": 393, "path": "/source/code/shared/tools/scx_admin/logconfigurator.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file\n\n \\brief scx configuration tool for SCX.\n\n \\date 8/22/2008\n\n*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxstream.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxlogpolicy.h>\n#if !defined(SCX_STACK_ONLY)\n#include <scxsystemlib/processenumeration.h>\n#endif\n#include <scxcorelib/scxlogpolicy.h>\n\n#include <signal.h>\n\n#include <iostream>\n\n#include \"logconfigurator.h\"\n\nusing namespace SCXCoreLib;\nusing namespace std;\n\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Default Log policy factory\n\n \\returns The default log policy object.\n*/\nSCXHandle<SCXLogPolicy> DefaultLogPolicyFactory()\n{\n return SCXHandle<SCXLogPolicy>(new SCXLogPolicy());\n}\n\n//! internal helper function\n/// \\param[in,out] buf stream for configuration writing\nvoid BackendSection::PrintModules(std::wostringstream& buf) const\n{\n for ( MapModules::const_iterator it = m_mapModules.begin(); it != m_mapModules.end(); it++ ){\n buf << L\"MODULE: \" << it->first << L\" \" << SCXLogConfigReader_SeverityToString(it->second) << L\"\\n\";\n }\n}\n\nvoid BackendSectionFile::Print(std::wostringstream& buf) const\n{\n buf << L\"FILE (\\n\"\n L\"PATH: \" << m_strPath << L\"\\n\";\n\n BackendSection::PrintModules(buf);\n \n buf << L\")\\n\";\n}\n\nvoid BackendSectionStdout::Print(std::wostringstream& buf) const\n{\n buf << L\"STDOUT (\\n\";\n\n BackendSection::PrintModules(buf);\n \n buf << L\")\\n\";\n}\n\n///////////////////////////////////////////////////////////////////////////////////////\n\n/// default ctor with dependency injection\nSCX_LogConfigurator::SCX_LogConfigurator():\n m_oConfigFileName( DefaultLogPolicyFactory()->GetConfigFileName() )\n{\n LoadAndValidate( true );\n}\n\n/// ctor with dependency injection\n/// \\param[in] oConfigFileName - name of the file with configuration\nSCX_LogConfigurator::SCX_LogConfigurator(const SCXFilePath& oConfigFileName):\n m_oConfigFileName( oConfigFileName )\n{\n LoadAndValidate( true );\n\n}\n\n\nSCX_LogConfigurator::~SCX_LogConfigurator()\n{\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n helper function to load config file\n\n \\param[in] bCreateImplicitEntries - if bCreateImplicitEntries is set, it emulates core functionality to create a default FILE backend if no config/invalid config is provided\n\n*/ \nbool SCX_LogConfigurator::LoadAndValidate( bool bCreateImplicitEntries )\n{\n SCXLogConfigReader<BackendSection, SCX_LogConfigurator> oConfigReader;\n \n bool validConfig = oConfigReader.ParseConfigFile(\n m_oConfigFileName, this);\n\n if ( !validConfig && bCreateImplicitEntries ) {\n SCXHandle<BackendSection> defaultBackend(\n new BackendSectionFile() );\n \n defaultBackend->SetProperty( L\"PATH\", DefaultLogPolicyFactory()->GetDefaultLogFileName() );\n\n SetSeverityThreshold(defaultBackend, L\"\", DefaultLogPolicyFactory()->GetDefaultSeverityThreshold() );\n Add( defaultBackend );\n }\n\n return validConfig;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n sets given severity to the given module/section\n \\param[in] backend - backend to update\n \\param[in] module - module to update\n \\param[in] newThreshold - new severity\n*/ \nbool SCX_LogConfigurator::SetSeverityThreshold(SCXHandle<BackendSection> backend,\n const std::wstring& module,\n SCXLogSeverity newThreshold)\n{\n return backend->SetModuleSeverity( module, newThreshold);\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n creates a new backend section of required type (FILE/STDOUT)\n \\param[in] name - name of backend section from config file\n*/ \nSCXHandle<BackendSection> SCX_LogConfigurator::Create(const std::wstring& name)\n{\n SCXHandle<BackendSection> backend(0);\n if (L\"FILE (\" == name)\n {\n backend = new BackendSectionFile();\n }\n if (L\"STDOUT (\" == name)\n {\n backend = new BackendSectionStdout();\n }\n\n if ( backend != NULL )\n SetSeverityThreshold(backend, L\"\", DefaultLogPolicyFactory()->GetDefaultSeverityThreshold());\n \n return backend;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n adds a new backend, after \"reader\" verifies that it's initialized properly\n \\param[in] backend - new backend to add\n*/ \nvoid SCX_LogConfigurator::Add( SCXHandle<BackendSection> backend )\n{\n m_mapConfig[backend->GetID()] = backend;\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n saves the changes; may throw exception in case of error\n \\returns true if ok\n throws SCXAdminException in case of error\n \n*/ \nbool SCX_LogConfigurator::Save()\n{\n std::wostringstream buf;\n Print( buf );\n\n try {\n SCXHandle<std::fstream> fs = SCXFile::OpenFstream(m_oConfigFileName, std::ios_base::out);\n\n (*fs) << StrToMultibyte(buf.str());\n } catch ( SCXException& e ) {\n throw SCXAdminException(L\"unable to update file;\\n\" + e.What(), SCXSRCLOCATION);\n }\n\n return true;\n}\n\nbool SCX_LogConfigurator::LogRotate()\n{\n#if !defined(SCX_STACK_ONLY) \n SCXSystemLib::ProcessEnumeration::SendSignalByName( L\"omiagent\", SIGCONT);\n#else\n#if defined(linux)\n system(\"ps -A -o pid,comm | awk '$2~/omiagent/{print $1}' | xargs -r kill -s SIGCONT\");\n#else\n system(\"ps -A -o pid,comm | awk '$2~/omiagent/{print $1}' | xargs kill -s SIGCONT\");\n#endif\n#endif\n return true;\n}\n\nbool SCX_LogConfigurator::Print(std::wostringstream& buf) const\n{\n // print all entries\n for ( MapBackends::const_iterator it = m_mapConfig.begin(); it != m_mapConfig.end(); it++ ){\n it->second->Print( buf );\n buf << L\"\\n\";\n }\n\n return true;\n}\n\nbool SCX_LogConfigurator::Reset()\n{\n for ( MapBackends::iterator it = m_mapConfig.begin(); it != m_mapConfig.end(); it++ ){\n it->second->Clear();\n }\n\n Save();\n return true;\n}\n\n\n/*----------------------------------------------------------------------------*/\n/**\n Maps the admin-API logLevel to logfile-native level and saves file\n \n \\param [in] logLevel - The level to set, defined in the admin API \n \\returns true if success, false if not supported\n\n Implementation of method in the Admin API.\n \n*/\nbool SCX_LogConfigurator::Set(LogLevelEnum logLevel)\n{\n for ( MapBackends::iterator it = m_mapConfig.begin(); it != m_mapConfig.end(); it++ ){\n it->second->Clear();\n it->second->SetModuleSeverity( L\"\", \n logLevel == eLogLevel_Errors ? eWarning :\n logLevel == eLogLevel_Intermediate ? eInfo :\n logLevel == eLogLevel_Verbose ? eTrace : eWarning );\n }\n\n Save();\n return true;\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n helper function to parse section/module names encoded in command line parameter\n and creates a new backend section\n \\param[in] name - encoded name, like FILE:/var/myfile:core.pal\n \\param[out] entryID - backend entry id\n \\param[out] moduleID - module id\n \\param[out] new_backend - newly created section\n throws SCXAdminException in case of error\n*/ \nvoid SCX_LogConfigurator::GetEntryModuleID( \n const std::wstring& name, \n std::wstring& entryID, \n std::wstring& moduleID, \n SCXHandle<BackendSection> &new_backend )\n{\n vector < wstring > tokens;\n StrTokenizeStr(name, tokens, L\":\", true);\n\n if ( tokens.size() < 1 || tokens.size() > 3 )\n throw SCXAdminException( wstring(L\"invalid entry id \") + name, SCXSRCLOCATION );\n\n tokens[0] = StrToUpper(tokens[0]);\n\n if ( tokens[0] == L\"FILE\" ){\n if ( tokens.size() < 2 )\n throw SCXAdminException( wstring(L\"missing parameter for FILE entry id: path is expected \"), SCXSRCLOCATION );\n\n entryID = wstring(L\"FILE.\") + tokens[1];\n \n if ( tokens.size() > 2 )\n moduleID = tokens[2];\n\n new_backend = Create(L\"FILE (\");\n new_backend->SetProperty( L\"PATH\", tokens[1] );\n \n } else if ( tokens[0] == L\"STDOUT\" ){\n entryID = tokens[0];\n \n if ( tokens.size() > 1 )\n moduleID = tokens[1];\n\n new_backend = Create(L\"STDOUT (\");\n } else {\n throw SCXAdminException( wstring(L\"unknown entry id \") + name, SCXSRCLOCATION );\n }\n \n}\n\n/*----------------------------------------------------------------------------*/\n/**\n sets given severity to the given module/section\n \\param[in] name - property name\n \\param[in] value - property value\n*/ \nvoid SCX_LogConfigurator::Set( const std::wstring& name, const std::wstring& value )\n{\n m_mapConfig.clear();\n\n LoadAndValidate(false); // do not create the default \n \n // parse the name to get backen/module pair:\n wstring entryID, moduleID;\n SCXHandle<BackendSection> new_backend;\n\n GetEntryModuleID( name, entryID, moduleID, new_backend );\n \n MapBackends::iterator it = m_mapConfig.find( entryID );\n if ( it != m_mapConfig.end() )\n new_backend = it->second;\n else\n m_mapConfig[entryID] = new_backend;\n\n SCXLogSeverity severity = SCXLogConfigReader_TranslateSeverityString( StrToUpper(value) );\n if (severity == eNotSet)\n {\n throw SCXAdminException( L\"invalid severity string: \" + value, SCXSRCLOCATION );\n }\n\n SetSeverityThreshold(new_backend, moduleID, severity );\n\n Save();\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n resets given section to default level (info)\n\n \\param[in] name - property name\n\n*/ \nvoid SCX_LogConfigurator::Reset( const std::wstring& name )\n{\n LoadAndValidate(true); // create the default one if needed\n \n // parse the name to get backen/module pair:\n wstring entryID, moduleID;\n SCXHandle<BackendSection> new_backend;\n GetEntryModuleID( name, entryID, moduleID, new_backend );\n \n MapBackends::iterator it = m_mapConfig.find( entryID );\n if ( it != m_mapConfig.end() )\n new_backend = it->second;\n else\n throw SCXAdminException(wstring(L\" entry \") + name + L\" was not found\", SCXSRCLOCATION );\n\n new_backend->Clear();\n\n Save();\n\n}\n\n/*----------------------------------------------------------------------------*/\n/**\n removes section from config file\n \\param[in] name - property name\n*/ \nvoid SCX_LogConfigurator::Remove( const std::wstring& name )\n{\n LoadAndValidate(true); // create the default one if needed\n \n // parse the name to get backen/module pair:\n wstring entryID, moduleID;\n SCXHandle<BackendSection> new_backend;\n\n GetEntryModuleID( name, entryID, moduleID, new_backend );\n \n MapBackends::iterator it = m_mapConfig.find( entryID );\n if ( it == m_mapConfig.end() )\n throw SCXAdminException(wstring(L\" entry \") + name + L\" was not found\", SCXSRCLOCATION );\n\n m_mapConfig.erase( it );\n\n Save();\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5202311873435974, "alphanum_fraction": 0.5202311873435974, "avg_line_length": 17.210525512695312, "blob_id": "ea88d0b6033019c2e36e6694d498d3951db77771", "content_id": "31d6343790b462d166d6915ce8ce503e0efe08aa", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 346, "license_type": "permissive", "max_line_length": 80, "num_lines": 19, "path": "/test/util/testapp/diskinfo.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n */\n#pragma once\n\n#include <string>\n\nusing namespace std;\n\nclass DiskInfo\n{\npublic:\n string name;\n string physical;\n unsigned int free_kb;\n unsigned int size_kb;\n unsigned int usage;\n};\n" }, { "alpha_fraction": 0.6499999761581421, "alphanum_fraction": 0.6499999761581421, "avg_line_length": 7.5, "blob_id": "f569ef1173ae4fc8b49d7d59f71327eb2d31dce8", "content_id": "af191304dfd1ca963903db80d5fe5158a32bd7cb", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 120, "license_type": "permissive", "max_line_length": 19, "num_lines": 14, "path": "/source/code/providers/module.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#include <MI.h>\n#include \"module.h\"\n\nMI_BEGIN_NAMESPACE\n\nModule::Module()\n{\n}\n\nModule::~Module()\n{\n}\n\nMI_END_NAMESPACE\n\n" }, { "alpha_fraction": 0.5700172781944275, "alphanum_fraction": 0.5779204964637756, "avg_line_length": 31.65322494506836, "blob_id": "831225cc8da100749191844e66d5f0f98b34999d", "content_id": "27c924b6c63e94d09b44a7eb3a0bef29828be045", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4049, "license_type": "permissive", "max_line_length": 109, "num_lines": 124, "path": "/source/code/providers/support/appserver/appserverconstants.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*-----------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file appserverconstants.h\n\n \\brief Constants associated with the various application servers\n\n \\date 11-08-19 12:00:00\n*/\n/*-----------------------------------------------------------------------*/\n#ifndef APPSERVERCONSTANTS_H\n#define APPSERVERCONSTANTS_H\n\n#include <string>\n\nnamespace SCXSystemLib {\n /*-------------------------------------------------------------------*/\n //\n // Generic Provider Constants\n //\n /*-------------------------------------------------------------------*/\n\n const static std::wstring PROTOCOL_HTTP = L\"HTTP\";\n\n const static std::wstring PROTOCOL_HTTPS = L\"HTTPS\";\n\n const static std::wstring APP_SERVER_TYPE_JBOSS = L\"JBoss\";\n\n const static std::wstring APP_SERVER_TYPE_TOMCAT = L\"Tomcat\";\n\n const static std::wstring APP_SERVER_TYPE_WEBLOGIC = L\"WebLogic\";\n\n const static std::wstring APP_SERVER_TYPE_WEBSPHERE = L\"WebSphere\";\n\n /*-------------------------------------------------------------------*/\n //\n // Generic File Reading Constants\n //\n /*-------------------------------------------------------------------*/\n\n const static std::wstring EMPTY_STRING = L\"\";\n\n const static std::string INI_COMMENT = \"#\";\n\n const static std::string INI_DELIMITER = \"=\";\n\n const static std::wstring TRUE_TEXT = L\"true\";\n\n /*-------------------------------------------------------------------*/\n //\n // WebLogic Constants\n //\n /*-------------------------------------------------------------------*/\n\n const static std::wstring DEFAULT_WEBLOGIC_HTTP_PORT = L\"7001\";\n\n const static std::wstring DEFAULT_WEBLOGIC_HTTPS_PORT = L\"7002\";\n\n const static std::string WEBLOGIC_ADMIN_SERVER_NAME = \"AdminServer\";\n\n const static std::string WEBLOGIC_ADMIN_SERVER_XML_NODE = \"admin-server-name\"; \n\n const static std::wstring WEBLOGIC_BRANDED_VERSION_10 = L\"10\";\n\n const static std::wstring WEBLOGIC_BRANDED_VERSION_11 = L\"11\";\n\n const static std::wstring WEBLOGIC_CONFIG_DIRECTORY = L\"config/\";\n\n const static std::wstring WEBLOGIC_CONFIG_FILENAME = L\"config.xml\";\n\n const static std::string WEBLOGIC_DOMAIN_ADMIN_SERVER_NAME = \"domain-admin-server-name\";\n\n const static std::wstring WEBLOGIC_DOMAIN_REGISTRY_XML_FILENAME = L\"domain-registry.xml\";\n\n const static std::string WEBLOGIC_DOMAIN_REGISTRY_XML_NODE = \"domain-registry\";\n\n const static std::string WEBLOGIC_DOMAIN_XML_NODE = \"domain\";\n\n const static std::string WEBLOGIC_DOMAIN_VERSION_XML_NODE = \"domain-version\";\n\n const static std::string WEBLOGIC_LISTEN_PORT_XML_NODE = \"listen-port\";\n\n const static std::string WEBLOGIC_LOCATION_XML_ATTRIBUTE = \"location\";\n\n const static std::string WEBLOGIC_NAME_XML_NODE = \"name\";\n\n const static std::wstring WEBLOGIC_NODEMANAGER_DOMAINS_DIRECTORY = L\"/wlserver_10.3/common/nodemanager/\";\n\n const static std::wstring WEBLOGIC_NODEMANAGER_DOMAINS_FILENAME = L\"nodemanager.domains\";\n\n const static std::wstring WEBLOGIC_SERVERS_DIRECTORY = L\"servers\";\n\n const static std::wstring WEBLOGIC_SERVER_TYPE_ADMIN = L\"Admin\";\n\n const static std::wstring WEBLOGIC_SERVER_TYPE_MANAGED = L\"Managed\";\n\n const static std::string WEBLOGIC_SERVER_XML_NODE = \"server\";\n\n const static std::string WEBLOGIC_SSL_XML_NODE = \"ssl\";\n\n const static std::string WEBLOGIC_SSL_ENABLED_XML_NODE = \"enabled\";\n\n const static std::string WEBLOGIC_VERSION_XML_NODE = \"domain-version\";\n\n const static unsigned int WEBLOGIC_VERSION_MINOR = 3;\n\n /*\n * This class should not be used, it exists so the constants\n * file will compile properly.\n */\n class AppServerConstants\n {\n public:\n\n AppServerConstants() {};\n\n virtual ~AppServerConstants() {};\n };\n\n}\n\n#endif /* APPSERVERCONSTANTS_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6857842803001404, "alphanum_fraction": 0.7141650319099426, "avg_line_length": 48.329166412353516, "blob_id": "0a68c2829e87c1f1d7d9ca3bc81ed139453e77e4", "content_id": "fcb8d2d07b149762a17456ed041051af063c52da", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 11839, "license_type": "permissive", "max_line_length": 242, "num_lines": 240, "path": "/build/Makefile.sslconfig", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*- \n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n\n#================================================================================\n# Static Libraries\n#================================================================================\n\n#================================================================================\n# Installation Tools\n#================================================================================\n\nSCXSSLCONFIG_DIR=$(SCX_SHARED_SRC_ROOT)/tools/scx_ssl_config\n\n# Static lib files for ssl tool\nSTATIC_SCXSSLCONFIG_SRCFILES = \\\n\t$(SCXSSLCONFIG_DIR)/scxsslcert.cpp\n\nSTATIC_SCXSSLCONFIG_OBJFILES = $(call src_to_obj,$(STATIC_SCXSSLCONFIG_SRCFILES))\n\nSCXSSLCONFIG_SRCFILES=\\\n\t$(SCXSSLCONFIG_DIR)/scx_ssl_config.cpp\n\nifneq ($(COMBINED_PACKAGES),1)\n\n$(INTERMEDIATE_DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES)\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\nSCXSSLCONFIG_OBJFILES = $(call src_to_obj,$(SCXSSLCONFIG_SRCFILES))\n\nSCXSSLCONFIG_DEPFILES=$(SCXSSLCONFIG_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d) $(STATIC_SCXSSLCONFIG_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d)\n\nelse\n\n# If universal agent, make two sets of binaries\n# Build paths to static object output for each version of OpenSSL\n\nSTATIC_SCXSSLCONFIG_OBJFILES_DIR=$(dir $(STATIC_SCXSSLCONFIG_OBJFILES))\nSTATIC_SCXSSLCONFIG_OBJFILES_NOTDIR=$(notdir $(STATIC_SCXSSLCONFIG_OBJFILES))\nSTATIC_SCXSSLCONFIG_OBJFILES_OPENSSL098 = $(STATIC_SCXSSLCONFIG_OBJFILES_DIR)$(OPENSSL098DIR)/$(STATIC_SCXSSLCONFIG_OBJFILES_NOTDIR)\nSTATIC_SCXSSLCONFIG_OBJFILES_OPENSSL100 = $(STATIC_SCXSSLCONFIG_OBJFILES_DIR)$(OPENSSL100DIR)/$(STATIC_SCXSSLCONFIG_OBJFILES_NOTDIR)\nifeq ($(PF_ARCH),x64)\n STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL110 = $(STATIC_SCXSSLCONFIG_OBJFILES_DIR)$(OPENSSL110DIR)/$(STATIC_SCXSSLCONFIG_OBJFILES_NOTDIR)\n STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL300 = $(STATIC_SCXSSLCONFIG_OBJFILES_DIR)$(OPENSSL300DIR)/$(STATIC_SCXSSLCONFIG_OBJFILES_NOTDIR)\nendif\n\n# Build paths to object output for each version of OpenSSL\nSCXSSLCONFIG_OBJFILES_DIR = $(dir $(call src_to_obj,$(SCXSSLCONFIG_SRCFILES)))\nSCXSSLCONFIG_OBJFILES_NOTDIR = $(notdir $(call src_to_obj,$(SCXSSLCONFIG_SRCFILES)))\nSCXSSLCONFIG_OBJFILES_OPENSSL098 = $(SCXSSLCONFIG_OBJFILES_DIR)$(OPENSSL098DIR)/$(SCXSSLCONFIG_OBJFILES_NOTDIR)\nSCXSSLCONFIG_OBJFILES_OPENSSL100 = $(SCXSSLCONFIG_OBJFILES_DIR)$(OPENSSL100DIR)/$(SCXSSLCONFIG_OBJFILES_NOTDIR)\nifeq ($(PF_ARCH),x64)\n SCXSSLCONFIG_OBJFILES_OPENSSL110 = $(SCXSSLCONFIG_OBJFILES_DIR)$(OPENSSL110DIR)/$(SCXSSLCONFIG_OBJFILES_NOTDIR)\n SCXSSLCONFIG_OBJFILES_OPENSSL300 = $(SCXSSLCONFIG_OBJFILES_DIR)$(OPENSSL300DIR)/$(SCXSSLCONFIG_OBJFILES_NOTDIR)\nendif\n\nendif\n\n# Static dependencies on POSIX platforms\n\nifneq ($(COMBINED_PACKAGES),1)\n\n#\n# Not Universal SSL Build\n#\n\nSCXSSLCONFIG_STATICLIB_DEPS = \\\n\tscxsslconfig\n\n# Foreach XYZ in the list above, build $(INTERMEDIATE_DIR)/libXYZ.a\nSCXSSLCONFIG_STATICLIB_DEPFILES = $(addprefix $(INTERMEDIATE_DIR)/lib, $(addsuffix .$(PF_STAT_LIB_FILE_SUFFIX), $(SCXSSLCONFIG_STATICLIB_DEPS)))\n\n$(INTERMEDIATE_DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX): \\\n\t$(SCXSSLCONFIG_OBJFILES) $(INTERMEDIATE_DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) $(SCXSSLCONFIG_DEPFILES) $(SCXSSLCONFIG_STATICLIB_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\t$(PROFILING) $(LINK) $(LINK_OUTFLAG) $(SCXSSLCONFIG_OBJFILES) $(SCXSSLCONFIG_STATICLIB_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES) $(SSL_LIBS) $(LDFLAGS_COREPROVIDERMODULE) $(LDFLAGS_EXECUTABLE)\n\nelse\n\n#\n# Universal SSL Build\n#\n\nSCXSSLCONFIG_STATICLIB_DEPS_OPENSSL = \\\n\tscxsslconfig \n\n# Foreach XYZ in the list above, build $(INTERMEDIATE_DIR)/libXYZ.a\nSCXSSLCONFIG_DEPFILES=$(SCXSSLCONFIG_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d) $(STATIC_SCXSSLCONFIG_OBJFILES:.$(PF_OBJ_FILE_SUFFIX)=.d)\n\n# Need three targets, one for each flavor of OpenSSL\nifeq ($(PF_ARCH),x64)\nscxsslconfig_both_targets: \\\n\t$(INTERMEDIATE_DIR)/$(OPENSSL098DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX) \\\n\t$(INTERMEDIATE_DIR)/$(OPENSSL100DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX) \\\n\t$(INTERMEDIATE_DIR)/$(OPENSSL110DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX) \\\n\t$(INTERMEDIATE_DIR)/$(OPENSSL300DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX)\nelse\nscxsslconfig_both_targets: \\\n\t$(INTERMEDIATE_DIR)/$(OPENSSL098DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX) \\\n\t$(INTERMEDIATE_DIR)/$(OPENSSL100DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX)\n\nendif\n\n# These targets override those in the Makefile.rules file\n# They build code and everything downstream to order for each version of OpenSSL\n# Non-universal Linux builds handle these steps implicitly through suffix rules.\n\nifeq ($(PF_ARCH),x64)\n$(INTERMEDIATE_DIR)/source/code/shared/tools/scx_ssl_config/$(OPENSSL300DIR)/%.$(PF_OBJ_FILE_SUFFIX) : $(SCXSSLCONFIG_DIR)/%.cpp\n\t$(MKPATH) $(@D)\n\t$(PROFILING) $(CXX) -c $(CXXFLAGS) -Wno-long-long $(OPENSSL300_CFLAGS) $(INCLUDES) -I$(<D) -o $@ $<\n$(INTERMEDIATE_DIR)/source/code/shared/tools/scx_ssl_config/$(OPENSSL110DIR)/%.$(PF_OBJ_FILE_SUFFIX) : $(SCXSSLCONFIG_DIR)/%.cpp\n\t$(MKPATH) $(@D)\n\t$(PROFILING) $(CXX) -c $(CXXFLAGS) -Wno-long-long $(OPENSSL110_CFLAGS) $(INCLUDES) -I$(<D) -o $@ $<\nendif\n\n$(INTERMEDIATE_DIR)/source/code/shared/tools/scx_ssl_config/$(OPENSSL100DIR)/%.$(PF_OBJ_FILE_SUFFIX) : $(SCXSSLCONFIG_DIR)/%.cpp\n\t$(MKPATH) $(@D)\n\t$(PROFILING) $(CXX) -c $(CXXFLAGS) -Wno-long-long $(OPENSSL100_CFLAGS) $(INCLUDES) -I$(<D) -o $@ $<\n\n$(INTERMEDIATE_DIR)/source/code/shared/tools/scx_ssl_config/$(OPENSSL098DIR)/%.$(PF_OBJ_FILE_SUFFIX) : $(SCXSSLCONFIG_DIR)/%.cpp\n\t$(MKPATH) $(@D)\n\t$(PROFILING) $(CXX) -c $(CXXFLAGS) -Wno-long-long $(OPENSSL098_CFLAGS) $(INCLUDES) -I$(<D) -o $@ $<\n\n$(INTERMEDIATE_DIR)/$(OPENSSL098DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL098)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL098DIR)\n\n\t# Set parameters to point pkg-config to different OpenSSL versions\n\texport PKG_CONFIG_PATH=$(PKG_CONFIG_PATH_OPENSSL098); \\\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH_OPENSSL098); \\\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\n$(INTERMEDIATE_DIR)/$(OPENSSL100DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL100)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL100DIR)\n\n\t# Use appropriate environment variable to set pkg-config paths.\n\texport PKG_CONFIG_PATH=$(PKG_CONFIG_PATH_OPENSSL100); \\\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH_OPENSSL100); \\\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\nifeq ($(PF_ARCH),x64)\n$(INTERMEDIATE_DIR)/$(OPENSSL110DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL110)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL110DIR)\n\n\t# Use appropriate environment variable to set pkg-config paths.\n\texport PKG_CONFIG_PATH=$(PKG_CONFIG_PATH_OPENSSL110); \\\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH_OPENSSL110); \\\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n$(INTERMEDIATE_DIR)/$(OPENSSL300DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL300)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL300DIR)\n\n\t# Use appropriate environment variable to set pkg-config paths.\n\texport PKG_CONFIG_PATH=$(PKG_CONFIG_PATH_OPENSSL300); \\\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH_OPENSSL300); \\\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\nendif\n\n$(INTERMEDIATE_DIR)/$(OPENSSL098DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX): $(SCXSSLCONFIG_OBJFILES_OPENSSL098) $(INTERMEDIATE_DIR)/$(OPENSSL098DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) $(SCXSSLCONFIG_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL098DIR)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\n\t# Use appropriate pkg-config environment variable to set library and header paths\n\texport PKG_CONFIG_PATH=$(PKG_CONFIG_PATH_OPENSSL098); \\\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH_OPENSSL098); \\\n\t$(PROFILING) $(LINK_OPENSSL098) $(LINK_OUTFLAG) $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL098) $(SCXSSLCONFIG_OBJFILES_OPENSSL098) $(SCXPAL_STATICLIB_DEPFILES) $(SSL_LIBS) $(LDFLAGS_EXECUTABLE)\n\n$(INTERMEDIATE_DIR)/$(OPENSSL100DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX): $(SCXSSLCONFIG_OBJFILES_OPENSSL100) $(INTERMEDIATE_DIR)/$(OPENSSL100DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) $(SCXSSLCONFIG_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES) \n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL100DIR)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\n\t# Use appropriate pkg-config environment variable to set library and header paths\n\texport PKG_CONFIG_PATH=$(PKG_CONFIG_PATH_OPENSSL100); \\\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH_OPENSSL100); \\\n\t$(PROFILING) $(LINK_OPENSSL100) $(LINK_OUTFLAG) $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL100) $(SCXSSLCONFIG_OBJFILES_OPENSSL100) $(SCXPAL_STATICLIB_DEPFILES) $(SSL_LIBS) $(LDFLAGS_EXECUTABLE)\n\nifeq ($(PF_ARCH),x64)\n$(INTERMEDIATE_DIR)/$(OPENSSL110DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX): $(SCXSSLCONFIG_OBJFILES_OPENSSL110) $(INTERMEDIATE_DIR)/$(OPENSSL110DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) $(SCXSSLCONFIG_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL110DIR)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\n\t# Use appropriate pkg-config environment variable to set library and header paths\n\texport PKG_CONFIG_PATH=$(PKG_CONFIG_PATH_OPENSSL110); \\\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH_OPENSSL110); \\\n\t$(PROFILING) $(LINK_OPENSSL110) $(LINK_OUTFLAG) $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL110) $(SCXSSLCONFIG_OBJFILES_OPENSSL110) $(SCXPAL_STATICLIB_DEPFILES) $(SSL_LIBS) $(LDFLAGS_EXECUTABLE)\n$(INTERMEDIATE_DIR)/$(OPENSSL300DIR)/scxsslconfig$(PF_EXE_FILE_SUFFIX): $(SCXSSLCONFIG_OBJFILES_OPENSSL300) $(INTERMEDIATE_DIR)/$(OPENSSL300DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) $(SCXSSLCONFIG_DEPFILES) $(SCXPAL_STATICLIB_DEPFILES)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL300DIR)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/tools\n\n\t# Use appropriate pkg-config environment variable to set library and header paths\n\texport PKG_CONFIG_PATH=$(PKG_CONFIG_PATH_OPENSSL300); \\\n\texport LD_LIBRARY_PATH=$(LD_LIBRARY_PATH_OPENSSL300); \\\n\t$(PROFILING) $(LINK_OPENSSL300) $(LINK_OUTFLAG) $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL300) $(SCXSSLCONFIG_OBJFILES_OPENSSL300) $(SCXPAL_STATICLIB_DEPFILES) $(SSL_LIBS) $(LDFLAGS_EXECUTABLE)\nendif\n\n# Test builds require this to produce test kits built with system version of openssl.\n\nifeq ($(OPENSSL_SYSTEM_VERSION),\"0.9.8\")\n\n# System kit is openssl 0.9.8\n$(INTERMEDIATE_DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL098)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL098DIR)\n\t@echo Building with system openssl kit, version 0.9.8....\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\nelse\nifeq ($(OPENSSL_SYSTEM_VERSION),\"1.0.0\")\n\n# System kit is 1.0.0\t\n$(INTERMEDIATE_DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL100)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL100DIR)\n\t@echo Building with system openssl kit, version 1.0.0 ....\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\nelse\nifeq ($(OPENSSL_SYSTEM_VERSION),\"1.1.0\")\nifeq ($(PF_ARCH),x64)\n\n# System kit is 1.1.0\n$(INTERMEDIATE_DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL110)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL110DIR)\n\t@echo Building with system openssl kit, version 1.1.0 ....\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\n\nelse\nifeq ($(OPENSSL_SYSTEM_VERSION),\"3.0.0\")\nifeq ($(PF_ARCH),x64)\n\n# System kit is 3.0.0\n$(INTERMEDIATE_DIR)/libscxsslconfig.$(PF_STAT_LIB_FILE_SUFFIX) : $(STATIC_SCXSSLCONFIG_OBJFILES_OPENSSL300)\n\t-$(MKPATH) $(INTERMEDIATE_DIR)/$(OPENSSL300DIR)\n\t@echo Building with system openssl kit, version 3.0.0 ....\n\t$(LINK_STATLIB) $(LINK_STATLIB_OUTFLAG) $^\nendif\nendif\nendif\nendif\nendif\nendif\nendif\n" }, { "alpha_fraction": 0.6190248727798462, "alphanum_fraction": 0.6210962533950806, "avg_line_length": 41.4054069519043, "blob_id": "30b618b76f0cafbbc6feef125c109465341de965", "content_id": "2f180e0d8f95ebd8b4c21fa95bb89083ad26f211", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6276, "license_type": "permissive", "max_line_length": 115, "num_lines": 148, "path": "/installer/generate_scxcore_scripts.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "import sys\nimport os\n\ndef Get_sh_path(PF):\n if PF == \"SunOS\" or PF == \"HPUX\":\n return '#!/usr/bin/sh'\n else:\n return '#!/bin/sh'\n\ndef GenerateSetupScriptFile():\n shfile = open(os.path.join(outputDir, 'scx_setup.sh'), 'w')\n shfile.write('# Copyright (c) Microsoft Corporation. All rights reserved.\\n')\n # Configure script to not complain if environment variable isn't currently set\n shfile.write('set +u\\n')\n if Variables[\"PF\"] == 'MacOS':\n shfile.write('PATH=/usr/libexec/omi/bin:$PATH' + '\\n')\n else:\n shfile.write('PATH=/opt/omi/bin:$PATH' + '\\n')\n shfile.write('export PATH' + '\\n')\n if Variables[\"PF\"] == 'MacOS':\n shfile.write('DYLD_LIBRARY_PATH=/usr/libexec/microsoft/scx/lib:$DYLD_LIBRARY_PATH' + '\\n')\n shfile.write('export DYLD_LIBRARY_PATH' + '\\n')\n elif Variables[\"PF\"] == 'HPUX' and Variables[\"PFARCH\"] == \"pa-risc\":\n shfile.write('SHLIB_PATH=/opt/omi/lib:$SHLIB_PATH' + '\\n')\n shfile.write('export SHLIB_PATH' + '\\n')\n elif Variables[\"PF\"] == \"SunOS\" and int(Variables[\"PFMAJOR\"]) == 5 and int(Variables[\"PFMINOR\"]) <= 9:\n shfile.write('LD_LIBRARY_PATH=/opt/omi/lib:/usr/local/ssl/lib:/usr/local/lib:$LD_LIBRARY_PATH' + '\\n')\n shfile.write('export LD_LIBRARY_PATH' + '\\n')\n elif Variables[\"PF\"] == \"AIX\":\n shfile.write('LIBPATH=/opt/omi/lib:$LIBPATH\\n')\n shfile.write('export LIBPATH\\n')\n # Since AIX searches LIBPATH first, it is questionable whether we need to define LD_LIBRARY_PATH also, but \n # in the interests of avoiding side effects of code that looks for it, we will set it here.\n shfile.write('LD_LIBRARY_PATH=/opt/omi/lib:$LD_LIBRARY_PATH\\n')\n shfile.write('export LD_LIBRARY_PATH\\n')\n else:\n shfile.write('LD_LIBRARY_PATH=/opt/omi/lib:$LD_LIBRARY_PATH\\n')\n shfile.write('export LD_LIBRARY_PATH' + '\\n')\n if Variables[\"BT\"] == 'Bullseye':\n shfile.write('COVFILE=/var/opt/microsoft/scx/log/OpsMgr.cov' + '\\n')\n shfile.write('export COVFILE' + '\\n')\n shfile.close()\n\ndef GenerateToolsSetupScriptFile():\n shfile = open(os.path.join(outputDir, 'scx_setup_tools.sh'), 'w')\n shfile.write('# Copyright (c) Microsoft Corporation. All rights reserved.\\n')\n # Configure script to not complain if environment variable isn't currently set\n shfile.write('set +u\\n')\n if Variables[\"PF\"] == 'MacOS':\n shfile.write('PATH=/usr/libexec/omi/bin/tools:$PATH' + '\\n')\n else:\n shfile.write('PATH=/opt/omi/bin:/opt/microsoft/scx/bin/tools:$PATH' + '\\n')\n shfile.write('export PATH' + '\\n')\n if Variables[\"PF\"] == 'MacOS':\n shfile.write('DYLD_LIBRARY_PATH=/usr/libexec/microsoft/scx/lib:$DYLD_LIBRARY_PATH' + '\\n')\n shfile.write('export DYLD_LIBRARY_PATH' + '\\n')\n elif Variables[\"PF\"] == 'HPUX' and Variables[\"PFARCH\"] == \"pa-risc\":\n shfile.write('SHLIB_PATH=/opt/omi/lib:$SHLIB_PATH' + '\\n')\n shfile.write('export SHLIB_PATH' + '\\n')\n elif Variables[\"PF\"] == \"SunOS\" and int(Variables[\"PFMAJOR\"]) == 5 and int(Variables[\"PFMINOR\"]) <= 9:\n shfile.write('LD_LIBRARY_PATH=/opt/omi/lib:/usr/local/ssl/lib:/usr/local/lib:$LD_LIBRARY_PATH' + '\\n')\n shfile.write('export LD_LIBRARY_PATH' + '\\n')\n elif Variables[\"PF\"] == 'AIX':\n shfile.write('LIBPATH=/opt/omi/lib:$LIBPATH\\n')\n shfile.write('export LIBPATH' + '\\n')\n # Since AIX searches LIBPATH first, it is questionable whether we need to define LD_LIBRARY_PATH also, but \n # in the interests of avoiding side effects of code that looks for it, we will set it here.\n shfile.write('LD_LIBRARY_PATH=/opt/omi/lib:$LD_LIBRARY_PATH\\n')\n shfile.write('export LD_LIBRARY_PATH\\n')\n else:\n shfile.write('LD_LIBRARY_PATH=/opt/omi/lib:$LD_LIBRARY_PATH' + '\\n')\n shfile.write('export LD_LIBRARY_PATH' + '\\n')\n if Variables[\"BT\"] == 'Bullseye':\n shfile.write('COVFILE=/var/opt/microsoft/scx/log/OpsMgr.cov' + '\\n')\n shfile.write('export COVFILE' + '\\n')\n shfile.close()\n\ndef GenerateAdminToolScriptFile():\n shfile = open(os.path.join(outputDir, 'scxadmin.sh'), 'w')\n shfile.write( Get_sh_path(Variables[\"PF\"]) )\n shfile.write( '\\n\\n' );\n shfile.write('# Copyright (c) Microsoft Corporation. All rights reserved.\\n\\n')\n\n if Variables[\"PF\"] == 'MacOS':\n scxpath = \"/usr/libexec\"\n else:\n scxpath = \"/opt\"\n\n shfile.write('. ' + scxpath + '/microsoft/scx/bin/tools/setup.sh\\n')\n\n # On older (pre-systemd) systems, with non-latin locale set, scxadmin can get\n # 'Exception: Multibyte string conversion failed' errors when trying to convert\n # strings from SCXProcess::Run with output like:\n #\n # Shutting down Open Group OMI Server: [ <non-ASCII characters> ]\n # Starting Open Group OMI Server: [ <non-ASCII characters> ]\n #\n # Just set the C locale (which exists on all systems) to resolve this issue.\n\n shfile.write('LANG=C; export LANG\\n')\n\n shfile.write('exec ' + scxpath + '/microsoft/scx/bin/tools/.scxadmin \"$@\"\\n')\n shfile.close()\n\ndef GenerateSSLToolScriptFile():\n shfile = open(os.path.join(outputDir, 'scxsslconfig.sh'), 'w')\n shfile.write( Get_sh_path(Variables[\"PF\"]) );\n shfile.write( '\\n\\n' );\n shfile.write('# Copyright (c) Microsoft Corporation. All rights reserved.\\n\\n')\n\n if Variables[\"PF\"] == 'MacOS':\n scxpath = \"/usr/libexec\"\n else:\n scxpath = \"/opt\"\n\n shfile.write('. ' + scxpath + '/microsoft/scx/bin/tools/setup.sh\\n')\n shfile.write('exec ' + scxpath + '/microsoft/scx/bin/tools/.scxsslconfig \"$@\"\\n')\n shfile.close()\n\ndef GenerateScripts():\n GenerateSetupScriptFile()\n GenerateToolsSetupScriptFile()\n GenerateAdminToolScriptFile()\n GenerateSSLToolScriptFile()\n\n\nVariables = dict()\n\n# Parse command line arguments\nargs = []\noptlist = []\nfor arg in sys.argv[1:]:\n if len(arg) < 2:\n # Must be a file\n args.append(arg)\n continue\n \n if arg[0:2] == \"--\":\n tokens = arg[2:].split(\"=\",1)\n if len(tokens) == 1:\n tokens.append(\"\")\n Variables[tokens[0]] = tokens[1]\n else:\n args.append(arg)\n\noutputDir = Variables[\"OUTPUT_DIR\"]\n\nGenerateScripts()\n" }, { "alpha_fraction": 0.29597702622413635, "alphanum_fraction": 0.30747127532958984, "avg_line_length": 42.4375, "blob_id": "1cbceddad28defa36fd2eba03885eb1bb0cfbfc2", "content_id": "33c11d65aeb099914141e6bbd55fcc8c64bb17c8", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 696, "license_type": "permissive", "max_line_length": 81, "num_lines": 16, "path": "/build/Makefile.sslconfigtests", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n# \n# Definition of all unit tests for sslconfig\n#\n#--------------------------------------------------------------------------------\n\n#--------------------------------------------------------------------------------\n# All tests for sslconfig\nPOSIX_UNITTESTS_SSLCONFIG_SRCFILES = \\\n\t$(SCX_SHARED_TEST_ROOT)/tools/scx_ssl_config/scxsslcert_test.cpp \\\n\n#-------------------------------- End of File -----------------------------------\n\n" }, { "alpha_fraction": 0.5200772285461426, "alphanum_fraction": 0.5247104167938232, "avg_line_length": 28.77011489868164, "blob_id": "1267c1a3f1fa7452c343857617dfaa5e045be562", "content_id": "b1186315a2cf7c12bb8aa8f6787f82ef80aed586", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2590, "license_type": "permissive", "max_line_length": 102, "num_lines": 87, "path": "/source/code/providers/support/appserver/removenonexistentappserverinstances.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file removenonexistentappserverinstances.cpp\n\n \\brief Means of removing non-existent application server instances \n from an array if the instances are no longer on disk\n\n \\date 11-05-27 12:00:00\n\n */\n/*-----------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n\n#include <algorithm>\n#include <functional>\n#include <string>\n#include <vector>\n\n#include <scxcorelib/stringaid.h>\n\n#include \"appserverinstance.h\"\n#include \"removenonexistentappserverinstances.h\"\n\nusing namespace std;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXSystemLib\n{\n\n /*-----------------------------------------------------------------*/\n /**\n Constructor (no arg)\n */\n RemoveNonexistentAppServerInstances::RemoveNonexistentAppServerInstances()\n {\n }\n\n /*-----------------------------------------------------------------*/\n /**\n Destructor\n */\n RemoveNonexistentAppServerInstances::~RemoveNonexistentAppServerInstances()\n {\n }\n\n /*--------------------------------------------------------*/\n /**\n Given a list of instances, remove the instances that are\n can no longer be found on disk\n \n \\param[in/out] instances - vector of Application Server Instances \n to be manipulated\n \n */\n void RemoveNonexistentAppServerInstances::RemoveNonexistentInstances(\n vector<SCXHandle<AppServerInstance> >& instances)\n {\n vector<SCXHandle<AppServerInstance> >::iterator \n tmp = remove_if(\n instances.begin(), \n instances.end(), \n RemoveNonExistentInstanceHelper);\n instances.resize(tmp-instances.begin());\n }\n\n /*--------------------------------------------------------*/\n /**\n Predicate Helper method for deciding which instances to remove\n \n \\param[in] instance - Application Server Instance to check\n \\return - true if the file does NOT exist on disk (i.e. should the \n file be removed)\n \n */\n bool RemoveNonexistentAppServerInstances::RemoveNonExistentInstanceHelper(\n SCXHandle<AppServerInstance> instance)\n {\n return !instance->IsStillInstalled();\n }\n\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6554502844810486, "alphanum_fraction": 0.6670613884925842, "avg_line_length": 41.2823371887207, "blob_id": "1f2f80ef63df203dafc4be944bfc9e98a569730f", "content_id": "820982a1a84b5fd1cd91402717a570775d166e3c", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 30402, "license_type": "permissive", "max_line_length": 229, "num_lines": 719, "path": "/build/Makefile.kits", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": " -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#--------------------------------------------------------------------------------\n\nSEPOLICY_SRC_DIR=$(SCX_BRD)/installer/selinux\nSEPOLICY_DIR=$(INTERMEDIATE_DIR)/selinux\nSEPOLICY_DIR_EL6=$(INTERMEDIATE_DIR)/selinux.el6\n\nOUTPUT_PACKAGE_PREFIX=\nOUTPUT_BUNDLE_PREFIX=\nOUTPUT_PACKAGE_SPECIFICATION_FIRST=\nOUTPUT_PACKAGE_SPECIFICATION_SECOND=\nWITH_SYMBOLS=withsymbols\nPACKAGE_FILENAME=package_filename\nSTRIPPED=stripped\nIS_OPENSSL_100=$(shell openssl version | grep 1.0 | wc -l)\n\nifeq ($(ENABLE_SCX_SECURITY_HARDENING),1)\n SECURITY_FLAG=.s\nelse\n SECURITY_FLAG=\nendif\n\nEXCLUDE_SECURITY_FLAG=.s\n\nifeq ($(PF_ARCH),x64)\n IS_OPENSSL_110=$(shell openssl version | grep 1.1 | wc -l)\n IS_OPENSSL_300=$(shell openssl version | grep 3.0 | wc -l)\nendif\n\nifneq ($(COMBINED_PACKAGES),1)\n DATAFILES = Base_SCXCore.data $(PF_DEPENDENT_DATAFILES)\n ifeq ($(PF_ARCH),ppc)\n ifeq ($(PF_DISTRO),REDHAT)\n SCX_PREFIX=scx\n OUTPUT_PACKAGE_PREFIX=$(SCX_PREFIX)-$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH)-$(SCX_BUILDVERSION_BUILDNR).rhel.$(PF_MAJOR).$(PF_ARCH)\n OUTPUT_PACKAGE_SPECIFICATION_FIRST=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n OUTPUT_PACKAGE_SPECIFICATION_SECOND=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n else\n ifeq ($(PF_DISTRO),SUSE)\n SCX_PREFIX=scx\n OUTPUT_PACKAGE_PREFIX=$(SCX_PREFIX)-$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH)-$(SCX_BUILDVERSION_BUILDNR).sles.$(PF_MAJOR).$(PF_ARCH)\n OUTPUT_PACKAGE_SPECIFICATION_FIRST=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n OUTPUT_PACKAGE_SPECIFICATION_SECOND=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n endif\n endif\n endif\n ifeq ($(PF),SunOS)\n SCX_PREFIX=scx\n OUTPUT_PACKAGE_PREFIX=$(SCX_PREFIX)-$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH)-$(SCX_BUILDVERSION_BUILDNR).solaris.$(PF_MINOR).$(PF_ARCH)\n OUTPUT_PACKAGE_SPECIFICATION_FIRST=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n OUTPUT_PACKAGE_SPECIFICATION_SECOND=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n endif\n ifeq ($(PF),AIX)\n SCX_PREFIX=scx\n OUTPUT_PACKAGE_PREFIX=$(SCX_PREFIX)-$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH)-$(SCX_BUILDVERSION_BUILDNR).aix.$(PF_MAJOR).$(PF_ARCH)\n OUTPUT_PACKAGE_SPECIFICATION_FIRST=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n OUTPUT_PACKAGE_SPECIFICATION_SECOND=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n endif\nelse\n DATAFILES = Base_SCXCore.data Linux.data\n DATAFILES_R = Linux_RPM.data\n DATAFILES_D = Linux_DPKG.data\n\n ifneq ($(DISABLE_LISTENER),0)\n DISABLE_PORT=--DISABLE_PORT=true\n SCX_PREFIX=scx-cimprov\n else\n DISABLE_PORT=\n SCX_PREFIX=scx\n\n # Currently, if we have an active listener, we want OSS bits.\n # If this ever changes, we'll likely need a setting in configure script.\n ifneq ($(PF),SunOS)\n ifeq ($(PF_ARCH),x86)\n OSS_KITS:=$(shell cd $(SCX_BRD)/../opsmgr-kits; ls *-oss-test.sh *.i686.sh)\n else\n ifeq ($(PF_ARCH),x64)\n OSS_KITS:=$(shell cd $(SCX_BRD)/../opsmgr-kits; ls *-oss-test.sh *.x86_64.sh)\n endif\n endif\n endif\n endif\n\n OUTPUT_PACKAGE_PREFIX=$(SCX_PREFIX)-$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH)-$(SCX_BUILDVERSION_BUILDNR).universal$(SECURITY_FLAG).$(PF_ARCH)\n OUTPUT_PACKAGE_SPECIFICATION_FIRST=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\n OUTPUT_PACKAGE_SPECIFICATION_SECOND=--OUTPUTFILE=$(OUTPUT_PACKAGE_PREFIX)\nendif\nifeq ($(BUILD_TYPE),Release)\n ifneq ($(OUTPUT_PACKAGE_PREFIX),)\n OUTPUT_BUNDLE_PREFIX=$(OUTPUT_PACKAGE_PREFIX).$(WITH_SYMBOLS)\n else\n OUTPUT_PACKAGE_PREFIX=scx-$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH)-$(SCX_BUILDVERSION_BUILDNR).native.$(PF_MAJOR).$(PF_ARCH)\n OUTPUT_BUNDLE_PREFIX=$(OUTPUT_PACKAGE_PREFIX)\n endif\n ifneq ($(OUTPUT_PACKAGE_SPECIFICATION_FIRST),)\n OUTPUT_PACKAGE_SPECIFICATION_FIRST:=$(OUTPUT_PACKAGE_SPECIFICATION_FIRST).$(WITH_SYMBOLS)\n endif\nelse\n OUTPUT_BUNDLE_PREFIX=$(OUTPUT_PACKAGE_PREFIX)\nendif\n\nDISTRO_TYPE = $(PF)\nifeq (\"$(wildcard /usr/bin/dpkg-deb)\",\"\")\nDPKG_LOCATION=\"--DPKG_LOCATION=$(SCXPAL_DIR)/installer/InstallBuilder/tools/bin/dpkg-deb-$(PF_ARCH)\"\nelse\nDPKG_LOCATION=\nendif\n\nifeq ($(PF),Linux)\n STRIP_PATH=strip\nelse\n ifeq ($(PF),AIX)\n STRIP_PATH=/usr/ccs/bin/strip -X64\n else\n STRIP_PATH=/usr/ccs/bin/strip\n endif\nendif\n\ninstallerOnly: bundle\n\nSTAGING_DIR = $(SCX_BRD)/installer/intermediate/staging\n\n# Easy way to just run installer (if you know all targets are built properly)\nkit : GetLinuxOS scx_scripts sepolicy\n\t$(ECHO) \"========================= Performing make installer\"\n\t$(ECHO) PF=$(PF) > $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)/pf_file.sh\n\t$(ECHO) PF_DISTRO=$(PF_DISTRO) >> $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)/pf_file.sh\n\t$(ECHO) PF_MAJOR=$(PF_MAJOR) >> $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)/pf_file.sh\n\t$(ECHO) PF_MINOR=$(PF_MINOR) >> $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)/pf_file.sh\n\t$(ECHO) PF_ARCH=$(PF_ARCH) >> $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)/pf_file.sh\n # The options passed to the installbuilder are inserted into the Variables list. They will override whatever variables are specified in the datafiles.\n\nifneq ($(COMBINED_PACKAGES),1)\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR) \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX= \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES)\n\n\tsudo rm -rf $(STAGING_DIR)\nifeq ($(BUILD_TYPE),Release)\n\t# copy symbol binaries to release folder\n\tmkdir -p $(INTERMEDIATE_DIR)_$(STRIPPED)\n\tcp -R $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)/* $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)_$(STRIPPED)\n\t# strip binaries\n\t$(STRIP_PATH) $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)_$(STRIPPED)/* > /dev/null 2>&1|true\n\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED) \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX= \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES)\nendif\n\nelse\n\n\t# Build for COMBINED_PACKAGES (.rpm and .deb living together, mass hysteria)\n\t# First comes RPM symbol packages\n\tsudo rm -rf $(STAGING_DIR)\n\trm -rf $(INTERMEDIATE_DIR)/{098,100}\n\tmkdir -p $(INTERMEDIATE_DIR)/{098,100}\n\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)/098 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_0.9.8 $(DISABLE_PORT) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES) $(DATAFILES_R)\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)/100 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_1.0.0 $(DISABLE_PORT) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES) $(DATAFILES_R)\n\tsudo rm -rf $(STAGING_DIR)\nifeq ($(PF_ARCH),x64)\n\trm -rf $(INTERMEDIATE_DIR)/110\n\tmkdir -p $(INTERMEDIATE_DIR)/110\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)/110 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_1.1.0 $(DISABLE_PORT) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES) $(DATAFILES_R)\n\tsudo rm -rf $(STAGING_DIR)\n\trm -rf $(INTERMEDIATE_DIR)/300\n\tmkdir -p $(INTERMEDIATE_DIR)/300\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)/300 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_3.0.0 $(DISABLE_PORT) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES) $(DATAFILES_R)\nendif\n\n\t# Next comes DEB symbol packages\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)/098 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_0.9.8 $(DISABLE_PORT) \\\n\t\t$(DPKG_LOCATION) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES) $(DATAFILES_D)\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)/100 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_1.0.0 $(DISABLE_PORT) \\\n\t\t$(DPKG_LOCATION) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES) $(DATAFILES_D)\n\tsudo rm -rf $(STAGING_DIR)\nifeq ($(PF_ARCH),x64)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)/110 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_1.1.0 $(DISABLE_PORT) \\\n\t\t$(DPKG_LOCATION) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES) $(DATAFILES_D)\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)/300 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_3.0.0 $(DISABLE_PORT) \\\n\t\t$(DPKG_LOCATION) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_FIRST) \\\n\t\t$(DATAFILES) $(DATAFILES_D)\n\tsudo rm -rf $(STAGING_DIR)\nendif\n\nifeq ($(BUILD_TYPE),Release)\n\t# copy symbol binaries to symbol folder\n\tmkdir -p $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)_$(STRIPPED)\n\tcp -R $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)/* $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)_$(STRIPPED)\n\t# strip binaries\n\t$(STRIP_PATH) $(SCX_BRD)/intermediate/$(BUILD_CONFIGURATION)_$(STRIPPED)/* > /dev/null 2>&1|true\n\n\t# Next comes RPM release packages\n\trm -rf $(INTERMEDIATE_DIR)_$(STRIPPED)/{098,100}\n\tmkdir -p $(INTERMEDIATE_DIR)_$(STRIPPED)/{098,100}\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED)/098 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_0.9.8 $(DISABLE_PORT) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES) $(DATAFILES_R)\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED)/100 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_1.0.0 $(DISABLE_PORT) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES) $(DATAFILES_R)\n\tsudo rm -rf $(STAGING_DIR)\nifeq ($(PF_ARCH),x64)\n\trm -rf $(INTERMEDIATE_DIR)_$(STRIPPED)/110\n\tmkdir -p $(INTERMEDIATE_DIR)_$(STRIPPED)/110\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED)/110 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_1.1.0 $(DISABLE_PORT) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES) $(DATAFILES_R)\n\tsudo rm -rf $(STAGING_DIR)\n\trm -rf $(INTERMEDIATE_DIR)_$(STRIPPED)/300\n\tmkdir -p $(INTERMEDIATE_DIR)_$(STRIPPED)/300\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED)/300 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_3.0.0 $(DISABLE_PORT) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES) $(DATAFILES_R)\nendif\n\n\t# Next comes DEB release packages\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED)/098 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_0.9.8 $(DISABLE_PORT) \\\n\t\t$(DPKG_LOCATION) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES) $(DATAFILES_D)\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED)/100 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_1.0.0 $(DISABLE_PORT) \\\n\t\t$(DPKG_LOCATION) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES) $(DATAFILES_D)\n\tsudo rm -rf $(STAGING_DIR)\nifeq ($(PF_ARCH),x64)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED)/110 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_1.1.0 $(DISABLE_PORT) \\\n\t\t$(DPKG_LOCATION) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES) $(DATAFILES_D)\n\tsudo rm -rf $(STAGING_DIR)\n\tpython $(SCXPAL_DIR)/installer/InstallBuilder/installbuilder.py \\\n\t\t--BASE_DIR=$(SCX_BRD) \\\n\t\t--TARGET_DIR=$(INTERMEDIATE_DIR)_$(STRIPPED)/300 \\\n\t\t--INTERMEDIATE_DIR=$(SCX_BRD)/installer/intermediate \\\n\t\t--STAGING_DIR=$(STAGING_DIR) \\\n\t\t--OMI_DIR=$(SCXOMI_DIR) \\\n\t\t--BUILD_TYPE=$(BUILD_TYPE) \\\n\t\t--BUILD_CONFIGURATION=$(BUILD_CONFIGURATION)_$(STRIPPED) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--VERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH) \\\n\t\t--RELEASE=$(SCX_BUILDVERSION_BUILDNR) \\\n\t\t--ULINUX_POSTFIX=/openssl_3.0.0 $(DISABLE_PORT) \\\n\t\t$(DPKG_LOCATION) \\\n\t\t--DATAFILE_PATH=$(SCX_BRD)/installer/datafiles \\\n\t\t$(OUTPUT_PACKAGE_SPECIFICATION_SECOND) \\\n\t\t$(DATAFILES) $(DATAFILES_D)\nendif\n\nendif # ifeq ($(BUILD_TYPE),Release)\n\nendif # ifneq ($(COMBINED_PACKAGES),1)\n\nifeq ($(BUILD_TYPE),Release)\ncallgenbundle2: INTERMEDIATE_DIR:=$(INTERMEDIATE_DIR)_$(STRIPPED)\ncallgenbundle2: OUTPUT_BUNDLE_PREFIX:=$(OUTPUT_PACKAGE_PREFIX)\ncallgenbundle2: PACKAGE_FILENAME:=stripped_package_filename\ncallgenbundle2: genbundle2\n\t# Done generate the second bundle\n\nbundle: kit genbundle1 callgenbundle2\n\t# Done bundle\n\ngenbundle1 genbundle2:\nelse\nbundle: kit\n # Done bundle\nendif\n\tmkdir -p $(TARGET_DIR)\n\nifneq ($(OSS_KITS),)\n\t# Copy OSS kit files to target directory if Linux or ULINUX\n\tcd $(SCX_BRD)/../opsmgr-kits; cp $(OSS_KITS) $(INTERMEDIATE_DIR); cd $(INTERMEDIATE_DIR); chmod u+wx $(OSS_KITS);\nendif\n\n\t# Copy remaining kit files to target directory\nifneq ($(COMBINED_PACKAGES),1)\n\t# (Copying for non-combined packages)\n\trm -f $(INTERMEDIATE_DIR)/omi-*.$(PACKAGE_SUFFIX)\n ifeq ($(PF),SunOS)\n\tcp `find $(OMIKITS_DIR) -name omi-*solaris.$(PF_MINOR).$(PF_ARCH).pkg.Z` $(INTERMEDIATE_DIR)/\n\tcd $(INTERMEDIATE_DIR); uncompress `ls omi-*.Z`\n endif\n\n ifeq ($(PF_ARCH),ppc)\n ifeq ($(PF),AIX)\n\tcp `find $(OMIKITS_DIR) -name omi-*aix.$(PF_MAJOR).$(PF_ARCH).lpp` $(INTERMEDIATE_DIR)/\n else\n ifeq ($(PF_DISTRO),SUSE)\n\tcp `find $(OMIKITS_DIR) -name omi-*suse.$(PF_MAJOR).$(PF_ARCH).rpm` $(INTERMEDIATE_DIR)/\n else\n\tcp `find $(OMIKITS_DIR) -name omi-*rhel.$(PF_MAJOR).$(PF_ARCH).rpm` $(INTERMEDIATE_DIR)/\n endif\n endif\n endif\n\n ifeq ($(PF),HPUX)\n\tcp `find $(OMIKITS_DIR) -name omi-*hpux.$(PF_MAJOR)*.$(PF_ARCH).depot.Z` $(INTERMEDIATE_DIR)/\n\tcd $(INTERMEDIATE_DIR); uncompress `ls omi-*.Z`\n endif\n\n # Handle Linux builds when combined packages not enabled\n ifeq ($(PF),Linux)\n ifneq ($(PF_ARCH),ppc)\n\t# Copy omi kit depending on openssl version\n ifeq ($(IS_OPENSSL_110),1)\n\tcp `find $(OMIKITS_DIR) -name omi-*ssl_110.ulinux$(SECURITY_FLAG).$(PF_ARCH).$(PACKAGE_SUFFIX)` $(INTERMEDIATE_DIR)/\n else\n ifeq ($(IS_OPENSSL_300),1)\n\t cp `find $(OMIKITS_DIR) -name omi-*ssl_300.ulinux$(SECURITY_FLAG).$(PF_ARCH).$(PACKAGE_SUFFIX)` $(INTERMEDIATE_DIR)/\n else\n ifeq ($(IS_OPENSSL_100),1)\n\t cp `find $(OMIKITS_DIR) -name omi-*ssl_100.ulinux$(SECURITY_FLAG).$(PF_ARCH).$(PACKAGE_SUFFIX)` $(INTERMEDIATE_DIR)/\n endif\n endif\n endif\n endif\n endif\n ifeq ($(PF),Linux)\n ifeq ($(ENABLE_SCX_SECURITY_HARDENING),1)\n\tcd $(INTERMEDIATE_DIR); echo `ls omi-*$(SECURITY_FLAG).$(PF_ARCH).$(PACKAGE_SUFFIX)` > omi_package_filename\n else\n\tcd $(INTERMEDIATE_DIR); echo `ls omi-*.$(PF_ARCH).$(PACKAGE_SUFFIX)|grep -v \"$(EXCLUDE_SECURITY_FLAG).$(PF_ARCH)\"` > omi_package_filename\n endif\n else\n\tcd $(INTERMEDIATE_DIR); echo `ls omi-*.$(PACKAGE_SUFFIX)` > omi_package_filename\n endif\n # Handle Redhat on PPC\n ifeq ($(PF_ARCH),ppc)\n ifeq ($(DISTRO_TYPE),Linux)\n\tcd $(INTERMEDIATE_DIR); tar cvf $(OUTPUT_BUNDLE_PREFIX).tar `cat $(INTERMEDIATE_DIR)/package_filename` `cat $(INTERMEDIATE_DIR)/omi_package_filename` $(OSS_KITS)\n ifeq ($(PF_DISTRO),REDHAT)\n\t ../installer/bundle/create_bundle.sh 'PPC-RHEL' $(INTERMEDIATE_DIR) $(OUTPUT_BUNDLE_PREFIX).tar $(OUTPUT_BUNDLE_PREFIX) `cat $(INTERMEDIATE_DIR)/omi_package_filename` $(DISABLE_LISTENER)\n else\n\t ../installer/bundle/create_bundle.sh 'PPC-SUSE' $(INTERMEDIATE_DIR) $(OUTPUT_BUNDLE_PREFIX).tar $(OUTPUT_BUNDLE_PREFIX) `cat $(INTERMEDIATE_DIR)/omi_package_filename` $(DISABLE_LISTENER)\n endif \n\t# Copy the shell bundle to the target directory\n\tcp $(INTERMEDIATE_DIR)/$(OUTPUT_BUNDLE_PREFIX).sh $(TARGET_DIR)\n endif # ifeq ($(DISTRO_TYPE),Linux)\n endif # ifeq ($(PF_ARCH),ppc)\n\n # We only build shell bundles for Linux (combined packages) or non-Linux platforms\n ifneq ($(DISTRO_TYPE),Linux)\n\tcd $(INTERMEDIATE_DIR); tar cvf `cat $(INTERMEDIATE_DIR)/package_filename`.tar `cat $(INTERMEDIATE_DIR)/package_filename` `cat $(INTERMEDIATE_DIR)/omi_package_filename` $(OSS_KITS)\n\t../installer/bundle/create_bundle.sh $(DISTRO_TYPE) $(INTERMEDIATE_DIR) `cat $(INTERMEDIATE_DIR)/package_filename`.tar `cat $(INTERMEDIATE_DIR)/package_filename` `cat $(INTERMEDIATE_DIR)/omi_package_filename` $(DISABLE_LISTENER)\n\t# Remove package extension from `package_filename` file (AIX: .lpp, HP: .depot, Sun: .pkg)\n\tcd $(INTERMEDIATE_DIR); sed -e 's/.lpp$$//' -e 's/.depot$$//' -e 's/.pkg$$//' package_filename > package_filename.tmp; mv package_filename.tmp package_filename\n ifeq ($(BUILD_TYPE),Release)\n\t # Generate the symbol shell bundle\n\t test \"${PACKAGE_FILENAME}\" = \"stripped_package_filename\" && echo -n `cat $(INTERMEDIATE_DIR)/package_filename` > $(INTERMEDIATE_DIR)/stripped_package_filename || true\n\t test \"${PACKAGE_FILENAME}\" = \"stripped_package_filename\" && mv $(INTERMEDIATE_DIR)/`cat $(INTERMEDIATE_DIR)/package_filename`.sh $(INTERMEDIATE_DIR)/`cat $(INTERMEDIATE_DIR)/stripped_package_filename`.sh || true\n endif\n\t# Copy the shell bundle to the target directory\n\tcd $(INTERMEDIATE_DIR); cp `cat $(INTERMEDIATE_DIR)/$(PACKAGE_FILENAME)`.sh $(TARGET_DIR)\n endif # ifneq ($(DISTRO_TYPE),Linux)\n\nelse # ifneq ($(COMBINED_PACKAGES),1)\n\n\t# (Copying for combined packages)\n ifeq ($(DISABLE_LISTENER),0)\n\t # Grab the OMI bits\n ifeq ($(ENABLE_SCX_SECURITY_HARDENING),1)\n\t cd $(INTERMEDIATE_DIR); cp $(OMIKITS_DIR)/omi-*ssl_100*$(SECURITY_FLAG).$(PF_ARCH).{rpm,deb} 100\n ifeq ($(PF_ARCH),x64)\n\t cd $(INTERMEDIATE_DIR); cp $(OMIKITS_DIR)/omi-*ssl_110*$(SECURITY_FLAG).$(PF_ARCH).{rpm,deb} 110\n\t cd $(INTERMEDIATE_DIR); cp $(OMIKITS_DIR)/omi-*ssl_300*$(SECURITY_FLAG).$(PF_ARCH).{rpm,deb} 300\n endif\n else\n\t cd $(INTERMEDIATE_DIR); cp `ls $(OMIKITS_DIR)/omi-*ssl_100*.$(PF_ARCH).{rpm,deb}|grep -v \"$(EXCLUDE_SECURITY_FLAG).$(PF_ARCH)\"` 100\n ifeq ($(PF_ARCH),x64)\n\t cd $(INTERMEDIATE_DIR); cp `ls $(OMIKITS_DIR)/omi-*ssl_110*.$(PF_ARCH).{rpm,deb}|grep -v \"$(EXCLUDE_SECURITY_FLAG).$(PF_ARCH)\"` 110\n\t\tcd $(INTERMEDIATE_DIR); cp `ls $(OMIKITS_DIR)/omi-*ssl_300*.$(PF_ARCH).{rpm,deb}|grep -v \"$(EXCLUDE_SECURITY_FLAG).$(PF_ARCH)\"` 300\n endif\n endif\n\n # Remove ssl_098, ssl_100 and ssl_110 from omi filename\n\t cd $(INTERMEDIATE_DIR)/100; mv omi-*.deb `ls omi-*.deb | sed \"s/\\.ssl_100\\./\\./g\"`\n\t cd $(INTERMEDIATE_DIR)/100; mv omi-*.rpm `ls omi-*.rpm | sed \"s/\\.ssl_100\\./\\./g\"`\n ifeq ($(PF_ARCH),x64)\n\t cd $(INTERMEDIATE_DIR)/110; mv omi-*.deb `ls omi-*.deb | sed \"s/\\.ssl_110\\./\\./g\"`\n\t cd $(INTERMEDIATE_DIR)/110; mv omi-*.rpm `ls omi-*.rpm | sed \"s/\\.ssl_110\\./\\./g\"`\n\t cd $(INTERMEDIATE_DIR)/300; mv omi-*.deb `ls omi-*.deb | sed \"s/\\.ssl_300\\./\\./g\"`\n\t cd $(INTERMEDIATE_DIR)/300; mv omi-*.rpm `ls omi-*.rpm | sed \"s/\\.ssl_300\\./\\./g\"`\n endif\n\t cd $(INTERMEDIATE_DIR)/100; echo `ls omi-*.deb` > omi_package_filename\n endif\n ifeq ($(PF_ARCH),x64)\n\t cd $(INTERMEDIATE_DIR); tar cvf $(OUTPUT_BUNDLE_PREFIX).tar 100/*.{rpm,deb} 110/*.{rpm,deb} 300/*.{rpm,deb} $(OSS_KITS)\n else\n\t cd $(INTERMEDIATE_DIR); tar cvf $(OUTPUT_BUNDLE_PREFIX).tar 100/*.{rpm,deb} $(OSS_KITS)\n endif\n\t../installer/bundle/create_bundle.sh $(DISTRO_TYPE) $(INTERMEDIATE_DIR) $(OUTPUT_BUNDLE_PREFIX).tar $(OUTPUT_BUNDLE_PREFIX) `cat $(INTERMEDIATE_DIR)/100/omi_package_filename` $(DISABLE_LISTENER)\n\tcp $(INTERMEDIATE_DIR)/$(OUTPUT_BUNDLE_PREFIX).sh $(TARGET_DIR)\n\nendif # ifneq ($(COMBINED_PACKAGES),1)\n\n# Generate scripts that are consumed by SCXCore\nscx_scripts:\n\tpython $(SCX_BRD)/installer/generate_scxcore_scripts.py \\\n\t\t--OUTPUT_DIR=$(INTERMEDIATE_DIR) \\\n\t\t--PF=$(PF) \\\n\t\t--PFARCH=$(PF_ARCH) \\\n\t\t--PFMAJOR=$(PF_MAJOR) \\\n\t\t--PFMINOR=$(PF_MINOR) \\\n\t\t--BT=$(BUILD_TYPE)\n\ninstallerPackage: \\\n\tscxcore-status $(INTERMEDIATE_DIR)/libSCXCoreProviderModule.$(PF_DYN_LIB_FILE_SUFFIX) \\\n\tscx-tools-status scx-tools installerOnly\n\nssl-tool-status:\n\t$(ECHO) \"========================= Performing make ssl-tool\"\n\nscx-tools-status:\n\t$(ECHO) \"========================= Performing make scx-tools\"\n\nscxcore-status:\n\t$(ECHO) \"========================= Performing make OpsMgr\"\n\nifeq ($(PF),Linux)\nGetLinuxOS: $(INTERMEDIATE_DIR)/GetLinuxOS.sh\n\n$(INTERMEDIATE_DIR)/GetLinuxOS.sh: $(SCXPAL_TARGET_DIR)/GetLinuxOS.sh\n\tsed \"s@<RelDir>@/etc/opt/microsoft/scx/conf@\" $(SCXPAL_TARGET_DIR)/GetLinuxOS.sh > $(INTERMEDIATE_DIR)/GetLinuxOS.sh\n\tchmod +x $(INTERMEDIATE_DIR)/GetLinuxOS.sh\nelse\nGetLinuxOS:\nendif\n\n# Build SELinux policy modules for scxagent-logrotate\nifeq ($(PF),Linux)\n sepolicy: $(SEPOLICY_DIR)/scxagent-logrotate.pp $(SEPOLICY_DIR_EL6)/scxagent-logrotate.pp\nelse\n sepolicy:\nendif\n\n$(SEPOLICY_DIR)/scxagent-logrotate.pp : $(SEPOLICY_SRC_DIR)/scxagent-logrotate.te $(SEPOLICY_SRC_DIR)/scxagent-logrotate.fc\n\t@echo \"========================= Building selinux policy module for scxagent-logrotate\"\n\t$(MKPATH) $(SEPOLICY_DIR)\n\t$(COPY) $(SEPOLICY_SRC_DIR)/scxagent-logrotate.te $(SEPOLICY_SRC_DIR)/scxagent-logrotate.fc $(SEPOLICY_DIR)\n\tcd $(SEPOLICY_DIR); make -f /usr/share/selinux/devel/Makefile\n\n$(SEPOLICY_DIR_EL6)/scxagent-logrotate.pp : $(SEPOLICY_SRC_DIR)/scxagent-logrotate.el6.te $(SEPOLICY_SRC_DIR)/scxagent-logrotate.fc\n\t@echo \"========================= Building EL6 selinux policy module for scxagent-logrotate\"\n\t$(MKPATH) $(SEPOLICY_DIR_EL6)\n\t$(COPY) $(SEPOLICY_SRC_DIR)/scxagent-logrotate.el6.te $(SEPOLICY_DIR_EL6)/scxagent-logrotate.te\n\t$(COPY) $(SEPOLICY_SRC_DIR)/scxagent-logrotate.fc $(SEPOLICY_DIR_EL6)\n\tcd $(SEPOLICY_DIR_EL6); make -f /usr/share/selinux/devel/Makefile\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.6217028498649597, "alphanum_fraction": 0.6319857835769653, "avg_line_length": 43.90813064575195, "blob_id": "121dc73490e32f05dbef4435cd35c6b47688732c", "content_id": "8a61fba15ad9c25d472bbe43cd3daf1c127f1a05", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 55241, "license_type": "permissive", "max_line_length": 208, "num_lines": 1230, "path": "/test/code/providers/logfile_provider/logfileprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "ISO-8859-1", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the logfile provider\n\n \\date 2008-08-26 13:19:10\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxprocess.h>\n#include <scxcorelib/stringaid.h>\n#include \"source/code/scxcorelib/util/persist/scxfilepersistmedia.h\"\n\n#include <support/logfileprovider.h>\n#include <support/logfileutils.h>\n\n#include <cppunit/extensions/HelperMacros.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n#include <testutils/scxtestutils.h>\n\n#include <stdio.h> // For fopen() in test testLocale8859_1\n#include <sys/wait.h>\n#if defined(aix)\n#include <unistd.h>\n#endif\n\n#include \"SCX_LogFile_Class_Provider.h\"\n\n// dynamic_cast fix - wi 11220\n#ifdef dynamic_cast\n#undef dynamic_cast\n#endif\n\nusing namespace SCXCore;\nusing namespace SCXCoreLib;\n\nclass TestableLogfileProvider : public LogFileProvider\n{\npublic:\n TestableLogfileProvider(SCXCoreLib::SCXHandle<LogFileReader> pLogFileReader) :\n LogFileProvider(pLogFileReader)\n {\n m_pLogFileReader = pLogFileReader;\n }\n\n void TestSetPersistMedia(SCXCoreLib::SCXHandle<SCXCoreLib::SCXPersistMedia> persistMedia) \n {\n m_pLogFileReader->SetPersistMedia(persistMedia);\n }\n\nprivate:\n // No implementation; do not use default constructor for unit tests!\n TestableLogfileProvider();\n\n SCXCoreLib::SCXHandle<LogFileReader> m_pLogFileReader;\n};\n\nconst std::wstring testlocalefilename = L\"./testfiles/scxlogfilereader-locale\";\nconst std::wstring testlogfilename = L\"./logfileproviderTest.log\";\nconst std::wstring testQID = L\"TestQID\";\nconst std::wstring testQID2 = L\"AnotherTestQID\";\n\nclass LogFileProviderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( LogFileProviderTest );\n CPPUNIT_TEST( callDumpStringForCoverage );\n CPPUNIT_TEST( testLogFilePositionRecordCreateNewRecord );\n CPPUNIT_TEST( testLogFilePositionRecordPersistable );\n CPPUNIT_TEST( testLogFilePositionRecordUnpersist );\n CPPUNIT_TEST( testLogFilePositionRecordConflictingPaths );\n CPPUNIT_TEST( testLogFileStreamPositionerOpenNew );\n CPPUNIT_TEST( testLogFileStreamPositionerReOpen );\n // testTellgBehavior() exists to investigate WI 15418, and eventually WI 16772\n //CPPUNIT_TEST( testTellgBehavior );\n CPPUNIT_TEST( testLogFileStreamPersistSmallerFile );\n CPPUNIT_TEST( testLogFileStreamPositionerNoFile );\n CPPUNIT_TEST( testLogFileStreamPositionerFileRotateSize );\n CPPUNIT_TEST( testLogFileStreamPositionerFileRotateInode );\n CPPUNIT_TEST( testLogFileStreamPositionerFileDisappearsAndReappears );\n CPPUNIT_TEST( testDoInvokeMethod );\n CPPUNIT_TEST( testDoInvokeMethodWithNonexistantLogfile );\n CPPUNIT_TEST( testInvokeResetStateFile );\n CPPUNIT_TEST( testInvokeResetStateFileWithResetFlag );\n CPPUNIT_TEST( testInvokeResetAllStateFiles );\n CPPUNIT_TEST( testInvokeResetAllStateFilesWithResetFlag );\n CPPUNIT_TEST( testLocale8859_1 );\n\n SCXUNIT_TEST_ATTRIBUTE(testLogFilePositionRecordPersistable, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testLogFilePositionRecordUnpersist, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testDoInvokeMethod, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testDoInvokeMethodWithNonexistantLogfile, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testInvokeResetStateFile, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testInvokeResetStateFileWithResetFlag, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testInvokeResetAllStateFiles, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testInvokeResetAllStateFilesWithResetFlag, SLOW);\n SCXUNIT_TEST_ATTRIBUTE(testLocale8859_1, SLOW);\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n SCXHandle<SCXPersistMedia> m_pmedia;\n SCXCoreLib::SCXHandle<TestableLogfileProvider> m_logFileProv;\n SCXCoreLib::SCXHandle<LogFileReader> m_pReader;\n\npublic:\n LogFileProviderTest() : m_pReader(new LogFileReader()) { }\n\n void setUp(void)\n {\n m_pmedia = GetPersistMedia();\n SCXFilePersistMedia* m = dynamic_cast<SCXFilePersistMedia*> (m_pmedia.GetData());\n CPPUNIT_ASSERT(m != 0);\n m->SetBasePath(L\"./\");\n\n SCXHandle<LogFileReader::LogFilePositionRecord> r( \n new LogFileReader::LogFilePositionRecord(testlogfilename, testQID, m_pmedia) );\n r->UnPersist();\n SCXHandle<LogFileReader::LogFilePositionRecord> r2(\n new LogFileReader::LogFilePositionRecord(testlogfilename, testQID2, m_pmedia) );\n r2->UnPersist();\n\n m_logFileProv = new TestableLogfileProvider(m_pReader);\n m_logFileProv->TestSetPersistMedia(m_pmedia);\n\n std::wstring errMsg;\n TestableContext context;\n SetUpAgent<mi::SCX_LogFile_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n\n // Delete the locale file if it exists\n SCXCoreLib::SelfDeletingFilePath localeFile( testlocalefilename );\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_LogFile_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n\n m_logFileProv = 0;\n SCXHandle<LogFileReader::LogFilePositionRecord> r(\n new LogFileReader::LogFilePositionRecord(testlogfilename, testQID, m_pmedia) );\n r->UnPersist();\n SCXFile::Delete(testlogfilename);\n SCXHandle<LogFileReader::LogFilePositionRecord> r2( \n new LogFileReader::LogFilePositionRecord(testlogfilename, testQID2, m_pmedia) );\n r2->UnPersist();\n\n // Delete the locale file if it exists\n SCXCoreLib::SelfDeletingFilePath localeFile( testlocalefilename );\n }\n\n void callDumpStringForCoverage()\n {\n CPPUNIT_ASSERT(m_logFileProv->DumpString().find(L\"LogFileProvider\") != std::wstring::npos);\n }\n\n void testLogFilePositionRecordCreateNewRecord()\n {\n LogFileReader::LogFilePositionRecord r(L\"/This/is/a/file/path.log\", testQID);\n CPPUNIT_ASSERT(0 == r.GetPos());\n CPPUNIT_ASSERT(0 == r.GetStatStIno());\n CPPUNIT_ASSERT(0 == r.GetStatStSize());\n }\n\n void testLogFilePositionRecordPersistable()\n {\n pid_t pid = fork();\n CPPUNIT_ASSERT(-1 != pid);\n if (0 == pid)\n {\n // Child process will do the writing.\n LogFileReader::LogFilePositionRecord r(L\"/This/is/a/file/path.log\", testQID, m_pmedia);\n r.SetPos(1337);\n r.SetStatStIno(17);\n r.SetStatStSize(4711);\n CPPUNIT_ASSERT_NO_THROW(r.Persist());\n exit(0);\n }\n\n // Parent process will do the reading after child has finished.\n waitpid(pid, 0, 0);\n\n LogFileReader::LogFilePositionRecord r(L\"/This/is/a/file/path.log\", testQID, m_pmedia);\n CPPUNIT_ASSERT(r.Recover());\n CPPUNIT_ASSERT(1337 == r.GetPos());\n CPPUNIT_ASSERT(17 == r.GetStatStIno());\n CPPUNIT_ASSERT(4711 == r.GetStatStSize());\n \n CPPUNIT_ASSERT(r.UnPersist());\n }\n\n void testLogFilePositionRecordUnpersist()\n {\n LogFileReader::LogFilePositionRecord r(L\"/This/is/a/file/path.log\", testQID, m_pmedia);\n CPPUNIT_ASSERT( ! r.Recover() );\n CPPUNIT_ASSERT( ! r.UnPersist() );\n CPPUNIT_ASSERT_NO_THROW(r.Persist());\n CPPUNIT_ASSERT( r.Recover() );\n CPPUNIT_ASSERT( r.UnPersist() );\n CPPUNIT_ASSERT( ! r.Recover() );\n }\n\n void testLogFilePositionRecordConflictingPaths()\n {\n {\n LogFileReader::LogFilePositionRecord r1(L\"/This/is/a/file_path.log\", testQID, m_pmedia);\n LogFileReader::LogFilePositionRecord r2(L\"/This_is/a_file/path.log\", testQID, m_pmedia);\n\n r1.SetPos(1337);\n r1.SetStatStIno(17);\n r1.SetStatStSize(4711);\n CPPUNIT_ASSERT_NO_THROW(r1.Persist());\n\n r2.SetPos(1338);\n r2.SetStatStIno(18);\n r2.SetStatStSize(4712);\n CPPUNIT_ASSERT_NO_THROW(r2.Persist());\n }\n \n LogFileReader::LogFilePositionRecord r1(L\"/This/is/a/file_path.log\", testQID, m_pmedia);\n LogFileReader::LogFilePositionRecord r2(L\"/This_is/a_file/path.log\", testQID, m_pmedia);\n\n CPPUNIT_ASSERT_NO_THROW(r1.Recover());\n CPPUNIT_ASSERT(1337 == r1.GetPos());\n CPPUNIT_ASSERT(17 == r1.GetStatStIno());\n CPPUNIT_ASSERT(4711 == r1.GetStatStSize());\n\n CPPUNIT_ASSERT_NO_THROW(r2.Recover());\n CPPUNIT_ASSERT(1338 == r2.GetPos());\n CPPUNIT_ASSERT(18 == r2.GetStatStIno());\n CPPUNIT_ASSERT(4712 == r2.GetStatStSize());\n\n CPPUNIT_ASSERT(r1.UnPersist());\n CPPUNIT_ASSERT(r2.UnPersist());\n }\n\n void testLogFileStreamPositionerOpenNew()\n {\n std::wstring firstRow(L\"This is the first row.\");\n std::wstring secondRow(L\"This is the second row.\");\n {\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n \n *stream << firstRow << std::endl\n << secondRow << std::endl;\n }\n\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n\n // Fist time the file is opened, the position should be at the end of the file.\n SCXHandle<std::wfstream> stream = p.GetStream();\n CPPUNIT_ASSERT( (scxulong) (stream->tellg()) > (scxulong) (firstRow.size() + secondRow.size()) );\n CPPUNIT_ASSERT( ! SCXStream::IsGood(*stream));\n }\n \n void testLogFileStreamPositionerReOpen()\n {\n std::wstring firstRow(L\"This is the first row.\");\n std::wstring secondRow(L\"This is the second row.\");\n\n SCXHandle<std::wfstream> outstream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *outstream << firstRow << std::endl;\n \n {\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n p.PersistState();\n }\n\n // Write some more to the file.\n *outstream << secondRow << std::endl;\n \n\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n std::wstring line;\n getline(*stream, line);\n CPPUNIT_ASSERT(secondRow == line);\n }\n\n void testTellgBehavior()\n {\n std::wstring firstRow(L\"This is the first row.\"); // 23 bytes\n std::wstring secondRow(L\"This is the second row.\"); // 24 bytes\n\n // Write the file\n\n {\n SCXHandle<std::wfstream> outstream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *outstream << firstRow << std::endl;\n }\n\n // Read it in a separate stream\n\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n p.PersistState();\n\n // Verify that we're at EOF\n\n CPPUNIT_ASSERT(!SCXStream::IsGood(*stream));\n std::cout << std::endl;\n std::cout << \"stream->tellg(): \" << stream->tellg() << std::endl;\n\n // Now append some data to the file (in a separate process)\n\n pid_t pid = fork();\n CPPUNIT_ASSERT(-1 != pid);\n if (0 == pid)\n {\n // Child process will do the appending.\n SCXHandle<std::wfstream> outstream = SCXFile::OpenWFstream(testlogfilename,\n std::ios_base::out | std::ios_base::app);\n *outstream << secondRow << std::endl;\n exit(0);\n }\n\n // Parent process will do the reading after child has finished.\n waitpid(pid, 0, 0);\n\n CPPUNIT_ASSERT(!SCXStream::IsGood(*stream));\n std::cout << \"stream->tellg(): \" << stream->tellg() << std::endl;\n }\n\n void testLogFileStreamPersistSmallerFile()\n {\n std::wstring firstRow(L\"This is the first row.\"); // 23 bytes\n std::wstring secondRow(L\"This is the second row.\"); // 24 bytes\n\n // Write the file (23 + 24 bytes = 47 bytes)\n\n {\n SCXHandle<std::wfstream> outstream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *outstream << firstRow << std::endl << secondRow << std::endl;\n }\n \n // Persist the size and state information\n\n {\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n p.PersistState();\n }\n\n // Verify the persisted size and state information\n\n {\n LogFileReader::LogFilePositionRecord r(testlogfilename, testQID, m_pmedia);\n CPPUNIT_ASSERT(r.Recover());\n CPPUNIT_ASSERT(47 == r.GetPos());\n CPPUNIT_ASSERT(0 != r.GetStatStIno());\n CPPUNIT_ASSERT(47 == r.GetStatStSize());\n }\n\n // Rewrite the file now to a smaller size (23 bytes)\n\n {\n SCXHandle<std::wfstream> outstream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *outstream << firstRow << std::endl;\n }\n\n // Reread the file twice:\n // First time, we should get the new data\n // Second time, we should not\n //\n // NOTE: We must use SCXStream::ReadLine() to read the stream. This is\n // how the \"real\" provider does it, and we leave the stream in a\n // \"bad\" state otherwise. Always test if the stream is \"good\"\n // prior to trying to read it.\n\n {\n std::wstring line;\n SCXStream::NLF nlf;\n\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n\n CPPUNIT_ASSERT(SCXStream::IsGood(*stream));\n SCXStream::ReadLine(*stream, line, nlf);\n CPPUNIT_ASSERT(firstRow == line);\n\n // Be sure we're now at EOF (no more lines in the file)\n CPPUNIT_ASSERT(!SCXStream::IsGood(*stream));\n\n p.PersistState();\n }\n\n {\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n\n // Be sure that there's nothing further in the stream\n CPPUNIT_ASSERT(!SCXStream::IsGood(*stream));\n }\n }\n\n void testLogFileStreamPositionerNoFile()\n {\n CPPUNIT_ASSERT_THROW(LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia), SCXFilePathNotFoundException);\n }\n\n void testLogFileStreamPositionerFileRotateSize()\n {\n std::wstring firstRow(L\"This is the first row.\");\n std::wstring secondRow(L\"This is the second row.\");\n {\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << firstRow << std::endl\n << secondRow << std::endl;\n }\n\n {\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n p.PersistState();\n }\n\n // Rewrite the file. This should make it a new file\n {\n SCXFile::Delete(testlogfilename);\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << firstRow << std::endl;\n }\n\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n // This time we should be positioned at the top of the file.\n CPPUNIT_ASSERT( 0 == stream->tellg() );\n \n std::wstring line;\n getline(*stream, line);\n CPPUNIT_ASSERT(firstRow == line);\n }\n\n void testLogFileStreamPositionerFileRotateInode()\n {\n std::wstring firstRow(L\"This is the first row.\");\n std::wstring secondRow(L\"This is the second row.\");\n {\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << firstRow << std::endl\n << secondRow << std::endl;\n }\n\n {\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n p.PersistState();\n // If we move the file while it is open it should retain its inode number.\n SCXFile::Move(testlogfilename, L\"./logfileproviderTest2.log\");\n }\n\n // Rewrite the file. This should generate a new inode number.\n {\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << firstRow << std::endl\n << secondRow << std::endl;\n }\n\n SCXFile::Delete(L\"./logfileproviderTest2.log\"); // clean up.\n\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n // This time we should be positioned at the top of the file.\n CPPUNIT_ASSERT( 0 == stream->tellg() );\n \n std::wstring line;\n getline(*stream, line);\n CPPUNIT_ASSERT(firstRow == line);\n getline(*stream, line);\n CPPUNIT_ASSERT(secondRow == line);\n }\n\n void testLogFileStreamPositionerFileDisappearsAndReappears()\n {\n std::wstring firstRow(L\"This is the first row.\");\n std::wstring secondRow(L\"This is the second row.\");\n {\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << firstRow << std::endl\n << secondRow << std::endl;\n }\n\n {\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n p.PersistState();\n }\n\n // Delete the file\n SCXFile::Delete(testlogfilename);\n\n CPPUNIT_ASSERT_THROW(LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia), SCXFilePathNotFoundException);\n\n // Rewrite the file. This should make it a new file\n {\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << firstRow << std::endl;\n }\n\n LogFileReader::LogFileStreamPositioner p(testlogfilename, testQID, m_pmedia);\n SCXHandle<std::wfstream> stream = p.GetStream();\n // This time we should be positioned at the top of the file.\n CPPUNIT_ASSERT( 0 == stream->tellg() );\n \n std::wstring line;\n getline(*stream, line);\n CPPUNIT_ASSERT(firstRow == line);\n }\n\n std::string DumpProperty_MIStringA(const TestableInstance::PropertyInfo &property, std::wstring errMsg)\n {\n std::wstringstream ret;\n if (property.exists)\n {\n std::vector<std::wstring> rows = property.GetValue_MIStringA(CALL_LOCATION(errMsg));\n ret << L\" Size: \" << rows.size() << std::endl;\n size_t i;\n for(i = 0; i < rows.size(); i++)\n {\n ret << L\" \" << i << L\": \" << rows[i] << std::endl;\n }\n }\n else\n {\n ret << L\" Property not set\" << std::endl;\n }\n return SCXCoreLib::StrToMultibyte(ret.str());\n }\n\n void testDoInvokeMethod ()\n {\n // This test is a little convoluted, but it's a very useful test, so it remains.\n //\n // First, to make this fly:\n // 1. setUp() function (for all tests) resets the environment (clears\n // the state files) and sets the state file path. Note that the\n // state path only happens in the context of this process.\n //\n // 2. logfileprovider (DoInvokeMethod()) ultimately calls code that is\n // sensitive to if the testrunner is currently running (when tests\n // are run, createEnv.sh runs, and that sets SCX_TESTRUN_ACTIVE in\n // the environment). If running in the context of testrunner, it\n // invokes the scxlogfilereader CLI program from the build path\n // (rather than the installed path) AND it passes a special flag,\n // -t (for test).\n //\n // 3. When run, scxlogfilereader will note if -t is passed and, if so,\n // it will set the state path to the current default directory.\n //\n // All these things work in concert to allow this test to work properly.\n //\n // Ultimately, this set is an end-to-end functional test of the logfile\n // provider (as such, it will actually invoke the scxlogfilereader CLI\n // program multiple times). It tests that new log files never have lines\n // returned, and that as log files grow, additional lines are returned.\n // Finally, it tests for proper handling of invalid regular expressions.\n\n const std::wstring invalidRegexpStr = L\"InvalidRegexp;0\";\n const std::wstring OKRegexpStr = L\"1;\";\n const std::wstring moreRowsStr = L\"MoreRowsAvailable;true\";\n\n std::wstring errMsg;\n TestableContext context;\n mi::SCX_LogFile_Class instanceName;\n mi::StringA regexps;\n regexps.PushBack(\"[a\");// Invalid regular expression.\n regexps.PushBack(\".*\");\n mi::Module Module;\n mi::SCX_LogFile_Class_Provider agent(&Module);\n \n // Call with missing filename.\n mi::SCX_LogFile_GetMatchedRows_Class paramNoFilename;\n paramNoFilename.regexps_value(regexps);\n paramNoFilename.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, paramNoFilename);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_INVALID_PARAMETER, context.GetResult());\n \n // Call with missing regular expression.\n mi::SCX_LogFile_GetMatchedRows_Class paramNoRegEx;\n paramNoRegEx.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n paramNoRegEx.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, paramNoRegEx);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_INVALID_PARAMETER, context.GetResult());\n \n // Call with missing qid.\n mi::SCX_LogFile_GetMatchedRows_Class paramNoQid;\n paramNoQid.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n paramNoQid.regexps_value(regexps);\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, paramNoQid);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_INVALID_PARAMETER, context.GetResult());\n\n // Create a log file with one row in it.\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << L\"This is the first row.\" << std::endl;\n\n mi::SCX_LogFile_GetMatchedRows_Class param;\n param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n param.regexps_value(regexps);\n param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // First call should return only one status row.\n CPPUNIT_ASSERT_EQUAL(1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n CPPUNIT_ASSERT_EQUAL(invalidRegexpStr,\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[0]);\n\n mi::SCX_LogFile_GetMatchedRows_Class param2;\n param2.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n param2.regexps_value(regexps);\n param2.qid_value(SCXCoreLib::StrToMultibyte(testQID2).c_str());\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param2);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // First call with new QID should return only one status row.\n CPPUNIT_ASSERT_EQUAL_MESSAGE(DumpProperty_MIStringA(context[0].GetProperty(\n \"rows\", CALL_LOCATION(errMsg)), CALL_LOCATION(errMsg)),\n 1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n CPPUNIT_ASSERT_EQUAL(invalidRegexpStr,\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[0]);\n\n // Add another row to the log file.\n const std::wstring secondRow(L\"This is the second row.\");\n *stream << secondRow << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should get 1 new row and one status row.\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n CPPUNIT_ASSERT_EQUAL(invalidRegexpStr,\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[0]);\n CPPUNIT_ASSERT_EQUAL(StrAppend(OKRegexpStr, secondRow),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[1]);\n\n // Add yet another row to the log file.\n const std::wstring thirdRow(L\"This is the third row.\");\n *stream << thirdRow << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param2);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Using new QID should get two new rows and one status row.\n CPPUNIT_ASSERT_EQUAL(3u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n CPPUNIT_ASSERT_EQUAL(invalidRegexpStr,\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[0]);\n CPPUNIT_ASSERT_EQUAL(StrAppend(OKRegexpStr, secondRow),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[1]);\n CPPUNIT_ASSERT_EQUAL(StrAppend(OKRegexpStr, thirdRow),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[2]);\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should get one new row and one status row.\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n CPPUNIT_ASSERT_EQUAL(invalidRegexpStr,\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[0]);\n CPPUNIT_ASSERT_EQUAL(StrAppend(OKRegexpStr, thirdRow),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[1]);\n\n // Add another 800 rows to the log file.\n for (int i=0; i<800; i++)\n {\n *stream << L\"This is another row.\" << std::endl;\n }\n\n size_t rowCnt = 0;\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n rowCnt = context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg)).size();\n // Should get first 500 rows and two status rows.\n CPPUNIT_ASSERT_EQUAL(502u, rowCnt);\n CPPUNIT_ASSERT_EQUAL(moreRowsStr,\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[rowCnt - 1]);\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n rowCnt = context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg)).size();\n // Should get next 300 rows and one status row.\n CPPUNIT_ASSERT_EQUAL(301u, rowCnt);\n CPPUNIT_ASSERT(moreRowsStr !=\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[rowCnt - 1]);\n\n\n mi::StringA regexps2;\n regexps2.PushBack(\"warning\");\n regexps2.PushBack(\"error\");\n mi::SCX_LogFile_GetMatchedRows_Class param3;\n param3.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n param3.regexps_value(regexps2);\n param3.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n\n const std::wstring normalRow = L\"Just a normal row with no problem\";\n const std::wstring warningRow = L\"A row with a warning in it\";\n const std::wstring errorRow = L\"A row with an error in it\";\n const std::wstring errandwarnRow = L\"A row with both a warning and an error in it\";\n\n *stream << normalRow << std::endl\n << normalRow << std::endl\n << warningRow << std::endl\n << normalRow << std::endl\n << errorRow << std::endl\n << normalRow << std::endl\n << normalRow << std::endl\n << errandwarnRow << std::endl\n << normalRow << std::endl\n << warningRow << std::endl\n << normalRow << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param3);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should match 4 rows and no status row.\n CPPUNIT_ASSERT_EQUAL_MESSAGE(DumpProperty_MIStringA(context[0].GetProperty(\n \"rows\", CALL_LOCATION(errMsg)), CALL_LOCATION(errMsg)),\n 4u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n CPPUNIT_ASSERT_EQUAL(StrAppend(L\"0;\", warningRow),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[0]);\n CPPUNIT_ASSERT_EQUAL(StrAppend(L\"1;\", errorRow),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[1]);\n CPPUNIT_ASSERT_EQUAL(StrAppend(L\"0 1;\", errandwarnRow),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[2]);\n CPPUNIT_ASSERT_EQUAL(StrAppend(L\"0;\", warningRow),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[3]);\n }\n\n void testDoInvokeMethodWithNonexistantLogfile()\n {\n std::wstring errMsg;\n TestableContext context;\n mi::SCX_LogFile_Class instanceName;\n mi::SCX_LogFile_GetMatchedRows_Class param;\n param.filename_value(\".wyzzy.nosuchfile\");\n mi::StringA regexps;\n regexps.PushBack(\".*\");\n param.regexps_value(regexps);\n param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n\n mi::Module Module;\n mi::SCX_LogFile_Class_Provider agent(&Module);\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // No status rows since the log file doesn't exist.\n CPPUNIT_ASSERT_EQUAL(0u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n }\n\n void testInvokeResetStateFile()\n {\n std::wstring errMsg;\n TestableContext context;\n mi::SCX_LogFile_Class instanceName;\n mi::StringA regexps;\n regexps.PushBack(\".*\");\n mi::Module Module;\n mi::SCX_LogFile_Class_Provider agent(&Module);\n\n // Create a log file with one row in it.\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << L\"This is the first row.\" << std::endl;\n\n mi::SCX_LogFile_GetMatchedRows_Class gmr_param;\n gmr_param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n gmr_param.regexps_value(regexps);\n gmr_param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // First call should return no status rows (treated as new file)\n CPPUNIT_ASSERT_EQUAL(0u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Add another row to the log file.\n *stream << L\"This is the second row.\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should get 1 new row\n CPPUNIT_ASSERT_EQUAL(1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Add another row to the log file.\n *stream << L\"This is the third row.\" << std::endl;\n\n // Invoke ResetStateFile (without resetOnRead)\n mi::SCX_LogFile_ResetStateFile_Class rsf_param;\n rsf_param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n rsf_param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n context.Reset();\n agent.Invoke_ResetStateFile(context, NULL, instanceName, rsf_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(0u, context.Size());\n\n // Finally, add one last row to the log file.\n *stream << L\"This is the forth row\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should now get 1 new row (first time read since we initialized)\n CPPUNIT_ASSERT_EQUAL_MESSAGE(DumpProperty_MIStringA(context[0].GetProperty(\n \"rows\", CALL_LOCATION(errMsg)), CALL_LOCATION(errMsg)),\n 1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n }\n\n void testInvokeResetStateFileWithResetFlag()\n {\n std::wstring errMsg;\n TestableContext context;\n mi::SCX_LogFile_Class instanceName;\n mi::StringA regexps;\n regexps.PushBack(\".*\");\n mi::Module Module;\n mi::SCX_LogFile_Class_Provider agent(&Module);\n\n // Create a log file with one row in it.\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << L\"This is the first row.\" << std::endl;\n\n mi::SCX_LogFile_GetMatchedRows_Class gmr_param;\n gmr_param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n gmr_param.regexps_value(regexps);\n gmr_param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // First call should return no status rows (treated as new file)\n CPPUNIT_ASSERT_EQUAL(0u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Add another row to the log file.\n *stream << L\"This is the second row.\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should get 1 new row\n CPPUNIT_ASSERT_EQUAL(1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Add another row to the log file.\n *stream << L\"This is the third row.\" << std::endl;\n\n // Invoke ResetStateFile (with resetOnRead)\n mi::SCX_LogFile_ResetStateFile_Class rsf_param;\n rsf_param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n rsf_param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n rsf_param.resetOnRead_value(true);\n context.Reset();\n agent.Invoke_ResetStateFile(context, NULL, instanceName, rsf_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(0u, context.Size());\n\n // Add another row to the log file.\n *stream << L\"This is the forth row\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should not get any rows due to resetOnRead flag\n CPPUNIT_ASSERT_EQUAL(0u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Finally, add one last row to the log file.\n *stream << L\"This is the fifth row\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should now get 1 new row (first time read since we initialized)\n CPPUNIT_ASSERT_EQUAL_MESSAGE(DumpProperty_MIStringA(context[0].GetProperty(\n \"rows\", CALL_LOCATION(errMsg)), CALL_LOCATION(errMsg)),\n 1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n }\n\n void InvokeProcess_scxlogfilereader(const std::wstring parameters)\n {\n std::stringstream processInput;\n std::stringstream processOutput;\n std::stringstream processError;\n\n // Test to see if we're running under testrunner. This makes it easy\n // to know where to launch our test program, allowing unit tests to\n // test all the way through to the CLI.\n\n std::wstring programName = L\"testfiles/scxlogfilereader-test \" + parameters;\n\n int returnCode;\n returnCode = SCXProcess::Run(\n programName,\n processInput, processOutput, processError);\n CPPUNIT_ASSERT_EQUAL(\"\", processOutput.str());\n CPPUNIT_ASSERT_EQUAL(\"\", processError.str());\n CPPUNIT_ASSERT_EQUAL(0, returnCode);\n }\n\n void testInvokeResetAllStateFiles()\n {\n // ResetStateFile() resets a specific file while ResetAllStateFiles()\n // resets all state files that exist in the user directory. We can have\n // something super sophisticated that has multiple state files and\n // validates each of them, but given the code implementation, verifying\n // one state file is good enough, and test team will do further testing.\n\n std::wstring errMsg;\n TestableContext context;\n mi::SCX_LogFile_Class instanceName;\n mi::StringA regexps;\n regexps.PushBack(\".*\");\n mi::Module Module;\n mi::SCX_LogFile_Class_Provider agent(&Module);\n\n // Create a log file with one row in it.\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << L\"This is the first row.\" << std::endl;\n\n mi::SCX_LogFile_GetMatchedRows_Class gmr_param;\n gmr_param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n gmr_param.regexps_value(regexps);\n gmr_param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // First call should return no status rows (treated as new file)\n CPPUNIT_ASSERT_EQUAL(0u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Add another row to the log file.\n *stream << L\"This is the second row.\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should get 1 new row\n CPPUNIT_ASSERT_EQUAL(1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Add another row to the log file.\n *stream << L\"This is the third row.\" << std::endl;\n\n // Reset the log files (without resetOnRead)\n InvokeProcess_scxlogfilereader(L\"-t -g 0\");\n\n // Finally, add one last row to the log file.\n *stream << L\"This is the forth row\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should now get 1 new row (first time read since we initialized)\n CPPUNIT_ASSERT_EQUAL_MESSAGE(DumpProperty_MIStringA(context[0].GetProperty(\n \"rows\", CALL_LOCATION(errMsg)), CALL_LOCATION(errMsg)),\n 1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n }\n\n void testInvokeResetAllStateFilesWithResetFlag()\n {\n std::wstring errMsg;\n TestableContext context;\n mi::SCX_LogFile_Class instanceName;\n mi::StringA regexps;\n regexps.PushBack(\".*\");\n mi::Module Module;\n mi::SCX_LogFile_Class_Provider agent(&Module);\n\n // Create a log file with one row in it.\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << L\"This is the first row.\" << std::endl;\n\n mi::SCX_LogFile_GetMatchedRows_Class gmr_param;\n gmr_param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n gmr_param.regexps_value(regexps);\n gmr_param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // First call should return no status rows (treated as new file)\n CPPUNIT_ASSERT_EQUAL(0u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Add another row to the log file.\n *stream << L\"This is the second row.\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should get 1 new row\n CPPUNIT_ASSERT_EQUAL(1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Add another row to the log file.\n *stream << L\"This is the third row.\" << std::endl;\n\n // Reset the log files (with resetOnRead)\n InvokeProcess_scxlogfilereader(L\"-t -g 1\");\n\n // Add another row to the log file.\n *stream << L\"This is the forth row\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should not get any rows due to resetOnRead flag\n CPPUNIT_ASSERT_EQUAL(0u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Finally, add one last row to the log file.\n *stream << L\"This is the fifth row\" << std::endl;\n\n context.Reset();\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, gmr_param);\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Should now get 1 new row (first time read since we initialized)\n CPPUNIT_ASSERT_EQUAL_MESSAGE(DumpProperty_MIStringA(context[0].GetProperty(\n \"rows\", CALL_LOCATION(errMsg)), CALL_LOCATION(errMsg)),\n 1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n }\n\n void testLocale8859_1()\n {\n const std::wstring regexpStr = L\"0;\";\n#if defined(aix) || defined(sun)\n const char *localeString = \"en_US.ISO8859-1\";\n#else\n const char *localeString = \"en_US.iso88591\";\n#endif\n\n // See if we have the locale that we need\n try {\n std::locale newLocale(localeString);\n }\n catch (...)\n {\n std::wstring warnText;\n warnText = L\"Unable to run LogFileProviderTest::testLocale8859_1 since locale \"\n + SCXCoreLib::StrFromUTF8(localeString) + L\" is not installed\";\n SCXUNIT_WARNING(warnText);\n return;\n }\n\n // Tell scxlogfilereader to deal with en_US.iso88591 locale\n {\n std::fstream localeFile( SCXCoreLib::StrToMultibyte(testlocalefilename).c_str(), std::fstream::out );\n localeFile << localeString;\n }\n\n std::wstring errMsg;\n TestableContext context;\n mi::SCX_LogFile_Class instanceName;\n mi::StringA regexps;\n regexps.PushBack(\".*\");\n mi::Module Module;\n mi::SCX_LogFile_Class_Provider agent(&Module);\n\n // Create a log file with one row in it.\n SCXHandle<std::wfstream> stream = SCXFile::OpenWFstream(testlogfilename, std::ios_base::out);\n *stream << L\"This is the first row.\" << std::endl;\n\n {\n mi::SCX_LogFile_GetMatchedRows_Class param;\n param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n param.regexps_value(regexps);\n param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n }\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // First call should not return any rows of data (no state file)\n CPPUNIT_ASSERT_EQUAL(0u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n\n // Verify a second row just to insure the state file exists and everything is working\n std::wstring second_row(L\"This is the second row.\");\n *stream << second_row << std::endl;\n stream->close(); // Don't need this stream anymore\n\n context.Reset();\n {\n mi::SCX_LogFile_GetMatchedRows_Class param;\n param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n param.regexps_value(regexps);\n param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n }\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // Second call should return the second row of data\n CPPUNIT_ASSERT_EQUAL(1u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n CPPUNIT_ASSERT_EQUAL(SCXCoreLib::StrAppend(regexpStr, second_row),\n context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg))[0]);\n\n // Append a utf8859-1 line to the file\n //\n // It's a little tricky to do this for two reasons:\n //\n // 1. The compiler doesn't like some of the bytes. So build a string\n // using '~' as iso8859-1 bytes, and then substitute them after we\n // have remainder of string constructed.\n //\n // The actual string we want to test against is:\n // \"16.04.2013 14.20.08.766 INFO TransactionInterceptor.invoke() - Betriebsbezeichnung 'Ges.f.Betoninstandsetzung u. Straßenunterhaltung GmbH & Co. KG' ist ungültig (name1)\"\n //\n // 2. We specifically want to test with an en_US.iso88591 format file.\n // Thus, we can't use wide streams (or SCX functions). So we use\n // 8-bit (not wstring) characters and use stdio.\n\n std::string iso8859_1_Row(\"16.04.2013 14.20.08.766 INFO TransactionInterceptor.invoke() - Betriebsbezeichnung 'Ges.f.Betoninstandsetzung u. Stra~enunterhaltung GmbH & Co. KG' ist ung~ltig (name1)\");\n CPPUNIT_ASSERT_EQUAL('~', iso8859_1_Row[119]);\n iso8859_1_Row[119] = (char) 0xDF; // ß\n CPPUNIT_ASSERT_EQUAL('~', iso8859_1_Row[157]);\n iso8859_1_Row[157] = (char) 0xFC; // ü\n\n std::string addl_Row(\"This is a fourth row of data\");\n\n // Write out the file using stdio\n FILE *f = fopen( SCXCoreLib::StrToMultibyte(testlogfilename).c_str(), \"a\" );\n CPPUNIT_ASSERT( f != NULL );\n CPPUNIT_ASSERT_EQUAL( 1u, fwrite(iso8859_1_Row.c_str(), iso8859_1_Row.size(), 1u, f) );\n CPPUNIT_ASSERT_EQUAL( 1u, fwrite(\"\\n\", 1u, 1u, f) ); // Write a \\n at the end of our file\n CPPUNIT_ASSERT_EQUAL( 1u, fwrite(addl_Row.c_str(), addl_Row.size(), 1u, f) );\n CPPUNIT_ASSERT_EQUAL( 1u, fwrite(\"\\n\", 1u, 1u, f) ); // Write a \\n at the end of our file\n CPPUNIT_ASSERT_EQUAL( 0, fclose(f) );\n\n context.Reset();\n {\n mi::SCX_LogFile_GetMatchedRows_Class param;\n param.filename_value(SCXCoreLib::StrToMultibyte(testlogfilename).c_str());\n param.regexps_value(regexps);\n param.qid_value(SCXCoreLib::StrToMultibyte(testQID).c_str());\n agent.Invoke_GetMatchedRows(context, NULL, instanceName, param);\n // context.Print();\n }\n CPPUNIT_ASSERT_EQUAL(MI_RESULT_OK, context.GetResult());\n CPPUNIT_ASSERT_EQUAL(1u, context.Size());\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetNumberOfProperties());\n // This call should return the iso8859-1 data we just wrote, but in UTF-8 format (and not garbled)\n CPPUNIT_ASSERT_EQUAL(2u, context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).\n GetValue_MIStringA(CALL_LOCATION(errMsg)).size());\n std::vector<std::wstring> rows = context[0].GetProperty(\"rows\", CALL_LOCATION(errMsg)).GetValue_MIStringA(CALL_LOCATION(errMsg));\n // Note that OMI always returns data in UTF-8 format. So convert our 8859-1 line to UTF-8 (as a wstring).\n // Note that StrFromMultibyte is locale-sensitive. So set our locale and then convert using that.\n const char *sLoc = setlocale(LC_CTYPE, localeString);\n\n std::wstring wide_utf32_Row( SCXCoreLib::StrFromMultibyte(iso8859_1_Row, false) );\n\n // Reset locale. \n setlocale(LC_CTYPE, sLoc);\n\n // Compare the lines we got back with the lines we expect\n CPPUNIT_ASSERT_EQUAL(SCXCoreLib::StrAppend(regexpStr, wide_utf32_Row), rows[0]);\n CPPUNIT_ASSERT_EQUAL(SCXCoreLib::StrAppend(regexpStr, SCXCoreLib::StrFromMultibyte(addl_Row)), rows[1]);\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( LogFileProviderTest );\n" }, { "alpha_fraction": 0.6837060451507568, "alphanum_fraction": 0.6980830430984497, "avg_line_length": 27.454545974731445, "blob_id": "8d4d2ce9bf4d122790ff5cdd134df1206e72ce9d", "content_id": "e673d972497b207c737754510141b53ae3c5ad86", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 626, "license_type": "permissive", "max_line_length": 59, "num_lines": 22, "path": "/test/code/shared/testutils/testrun_wrapper", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/sh \n\nif [ -z \"$1\" ]; then\n echo \"$0 must be run with at least one parameter\"\n exit 1\nfi\n\n# There might be an environment shell script created by \n# \"somebody else\" in the current directory, if so run\n# the tests using those variables\nENV_FILE=`dirname $0`/env.sh\nSOURCE_ENV=\"\"\nif [ -f $ENV_FILE ]; then SOURCE_ENV=\". $ENV_FILE $1;\"; fi\n\n# Execute the testrunner with root privileges\nsudo sh -c \"$SOURCE_ENV $1/testrunner $2 $3\"\n# Preserve exit status\nexit_status=$?\n# Make sure any files created during testrun can be removed\nsudo chown -R $USER $1/*\n# Return with exit status from the test run\nexit $exit_status\n" }, { "alpha_fraction": 0.6211538314819336, "alphanum_fraction": 0.6301282048225403, "avg_line_length": 28.433961868286133, "blob_id": "81e56e0164050245b04888c0e6c61b6effd3415a", "content_id": "9593a04209d38e5b081de96e6bff545122716d8f", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1560, "license_type": "permissive", "max_line_length": 100, "num_lines": 53, "path": "/source/code/shared/tools/scx_prune_repository/moffilerepository.py", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#\n# Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n#\n##\n# Contains the MofFileRepository class\n#\n# Date: 2008-10-28 16:18:10\n#\n\nimport os\nfrom moffile import MofFile\n\n##\n# This class recursively enumerates all mof files\n# in a certain directory. From this enumeration you can\n# then retrieve which file defines a speciffic cim class.\n#\nclass MofFileRepository:\n ##\n # Constructor.\n # Enumerates all mof files in path and creates\n # MofFile objects out of them.\n # Saves the MofFile objects in a dictionary for\n # later access.\n #\n def __init__(self, path):\n self.moffiles = []\n self.classToFileDict = {}\n for root, dirs, files in os.walk(path):\n for filename in files:\n if filename.endswith('.mof'):\n moffile = MofFile(os.path.join(root, filename))\n self.moffiles.append(moffile)\n for cimclass in moffile.GetDefinedClasses():\n self.classToFileDict[cimclass] = moffile\n \n ##\n # Retrueves all mof files enumerated as a\n # list of MofFile objects.\n #\n def GetAllMofFiles(self):\n return self.moffiles\n\n ##\n # Retrieve the moffile that contains the definition\n # of cimclass and return it as a MofFile object.\n # Returns None if no file defines cimclass.\n #\n def GetFileDefiningClass(self, cimclass):\n try:\n return self.classToFileDict[cimclass]\n except KeyError:\n return None\n" }, { "alpha_fraction": 0.5529859066009521, "alphanum_fraction": 0.5876762270927429, "avg_line_length": 35.703487396240234, "blob_id": "4d274c39c3a0e022c0d0ad23bb06bc9143c7e7fa", "content_id": "983c06e8288bd06a4de93bca897aec40fce0f89b", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 6315, "license_type": "permissive", "max_line_length": 112, "num_lines": 172, "path": "/build/Makefile.pf.Linux", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#\n# Platform-specific overrides to the general POSIX platform file\n#\n#--------------------------------------------------------------------------------\n\nifeq ($(COMBINED_PACKAGES),1)\n\t# Reassign SCXOMI directories to any OMI output directory (generic non-SSL use)\n\tSCXOMI_DEV_ROOT := $(SCXOMI_DIR)/output_openssl_1.0.0\n\tSCXOMI_INCLUDE := $(SCXOMI_DEV_ROOT)/include\n\tSCXOMI_LIBS := $(SCXOMI_DEV_ROOT)/lib\nendif\n\n# Catchall\nifeq (,$(PF_DISTRO))\n\tVERSTRING=UNKNOWN\n\tPF_DISTRO=UNKNOWN\n\tPF_MAJOR=UNKNOWN\n\tPF_MINOR=UNKNOWN\n\t$(warning \"Unmatched version string\")\nendif\n\ninclude Makefile.gcc4\n\n#================================================================================\n# OpenSSL\n# For ULINUX, on x64 platfomrs we need to build against three versions of OpenSSL: 0.9.8, 1.0.0,1.1.0 and 3.0.0.\n# on x86 platforms we need to build against two versions of OpenSSL: 0.9.8, 1.0.0.\n#================================================================================\nifeq ($(COMBINED_PACKAGES),1)\n\n# Let's figure out the system version of SSL installed (for unit test purposes)\n\nOPENSSL_SYSTEM_VERSION_FULL=$(shell openssl version | awk '{print $$2}')\nOPENSSL_SYSTEM_VERSION_098=$(shell echo $(OPENSSL_SYSTEM_VERSION_FULL) | grep -Eq '^0.9.8'; echo $$?)\nOPENSSL_SYSTEM_VERSION_100=$(shell echo $(OPENSSL_SYSTEM_VERSION_FULL) | grep -Eq '^1.0.'; echo $$?)\nOPENSSL_SYSTEM_VERSION_110=$(shell echo $(OPENSSL_SYSTEM_VERSION_FULL) | grep -Eq '^1.1.'; echo $$?)\nOPENSSL_SYSTEM_VERSION_300=$(shell echo $(OPENSSL_SYSTEM_VERSION_FULL) | grep -Eq '^3.0.'; echo $$?)\n\nifeq ($(OPENSSL_SYSTEM_VERSION_098), 0)\nexport OPENSSL_SYSTEM_VERSION=\"0.9.8\"\nelse\nifeq ($(OPENSSL_SYSTEM_VERSION_100), 0)\nexport OPENSSL_SYSTEM_VERSION=\"1.0.0\"\nelse\nifeq ($(OPENSSL_SYSTEM_VERSION_110), 0)\nexport OPENSSL_SYSTEM_VERSION=\"1.1.0\"\nelse\nifeq ($(OPENSSL_SYSTEM_VERSION_300), 0)\nexport OPENSSL_SYSTEM_VERSION=\"3.0.0\"\nelse\n$(error Unable to determine SSL system version installed!)\nendif\nendif\nendif\nendif\n\ndisplaySSLversion:\n\t@echo \"OpenSSL system full version: $(OPENSSL_SYSTEM_VERSION_FULL)\"\n\t@echo \"OpenSSL system full version 098: $(OPENSSL_SYSTEM_VERSION_098)\"\n\t@echo \"OpenSSL system full version 100: $(OPENSSL_SYSTEM_VERSION_100)\"\n\t@echo \"OpenSSL system full version 110: $(OPENSSL_SYSTEM_VERSION_110)\"\n\t@echo \"OpenSSL system full version 300: $(OPENSSL_SYSTEM_VERSION_300)\"\n\t@echo \"OpenSSL system version: $(OPENSSL_SYSTEM_VERSION)\"\n\n# Now define other SSL variables for expansion/directory purposes\n\nexport OPENSSL098DIR=openssl_0.9.8\nexport OPENSSL100DIR=openssl_1.0.0\nexport OPENSSL110DIR=openssl_1.1.0\nexport OPENSSL300DIR=openssl_3.0.0\n\nLINK_OPENSSL098=$(LINK) -L$(INTERMEDIATE_DIR)/$(OPENSSL098DIR) -L$(SCXPAL_TARGET_DIR)\nLINK_OPENSSL100=$(LINK) -L$(INTERMEDIATE_DIR)/$(OPENSSL100DIR) -L$(SCXPAL_TARGET_DIR)\nLINK_OPENSSL110=$(LINK) -L$(INTERMEDIATE_DIR)/$(OPENSSL110DIR) -L$(SCXPAL_TARGET_DIR)\nLINK_OPENSSL300=$(LINK) -L$(INTERMEDIATE_DIR)/$(OPENSSL300DIR) -L$(SCXPAL_TARGET_DIR)\n\nLD_LIBRARY_PATH_OPENSSL098=$(OPENSSL098_LIBDIR)\nPKG_CONFIG_PATH_OPENSSL098=$(OPENSSL098_LIBDIR)/pkgconfig\nLD_LIBRARY_PATH_OPENSSL100=$(OPENSSL100_LIBDIR)\nPKG_CONFIG_PATH_OPENSSL100=$(OPENSSL100_LIBDIR)/pkgconfig\nLD_LIBRARY_PATH_OPENSSL110=$(OPENSSL110_LIBDIR)\nPKG_CONFIG_PATH_OPENSSL110=$(OPENSSL110_LIBDIR)/pkgconfig\nLD_LIBRARY_PATH_OPENSSL300=$(OPENSSL300_LIBDIR)\nPKG_CONFIG_PATH_OPENSSL300=$(OPENSSL300_LIBDIR)/pkgconfig\n\nendif\n\n#--------------------------------------------------------------------------------\n# Paths\n#--------------------------------------------------------------------------------\n\n# Path to where the CPPUNIT libraries are checked in\nCPPUNIT_LIB_PATH=$(SCX_SHARED_TST_EXT_LIB_DIR)/linux/$(ARCH)/cppunit\n\n#--------------------------------------------------------------------------------\n# Tools on this platform\n#--------------------------------------------------------------------------------\n\n# Link a dynamic lib\nLINK_DYNLIB=g++ -shared -Wl,-rpath=/opt/microsoft/scx/lib -Wl,-rpath=/opt/omi/lib\nifeq ($(PF_ARCH),x86)\n\tLINK_DYNLIB+= -m32\nelse\n\tLINK_DYNLIB+= -m64\nendif\nLINK_DYNLIB+= -L$(INTERMEDIATE_DIR) -L$(SCXPAL_TARGET_DIR)\n\n#--------------------------------------------------------------------------------\n# Link switches for this platform, per target\n#--------------------------------------------------------------------------------\n\nLDFLAGS_RPM = -lrpm -lpopt\nLDFLAGS_DYNLIB = -ldl -lpthread -lcrypt -lrt\nLDFLAGS_EXECUTABLE = -ldl -lpthread -lrt\n\nifneq ($(COMBINED_PACKAGES),1)\nLDFLAGS_DYNLIB += $(LDFLAGS_RPM)\nLDFLAGS_EXECUTABLE += $(LDFLAGS_RPM)\nendif\n\nifeq ($(PF_DISTRO),SUSE)\n\tifeq ($(PF_MAJOR),9)\n\telse\n\t\tLDFLAGS_EXECUTABLE += -pie\n\tendif\nendif\n\n# The Core Provider Module links with these\nLDFLAGS_COREPROVIDERMODULE = $(LDFLAGS_DYNLIB)\n\n# The Test Provider Module links with these\nLDFLAGS_TESTPROVIDERMODULE = $(LDFLAGS_DYNLIB)\n\n# Test Provider specific link flags. Used to hide symbols\nTESTPROVIDERMODULE_EXTRA_LINKFLAGS=-Wl,--version-script=$(INTERMEDIATE_DIR)/testprovider.map\n\n# The testrunner links with these\nLDFLAGS_TESTRUNNER = $(LDFLAGS_EXECUTABLE)\n\n# Transforms a list of symbols that should be exposed to the correct link flags\nget_ld_flags_for_retaining_symbols=$(addprefix -u, $(1))\n\n# Run pkg-config to get ssl library switches for this platform\nSSL_LIBS = `pkg-config --libs openssl`\n\n#--------------------------------------------------------------------------------\n# Compiler switch tweaks\n#--------------------------------------------------------------------------------\n\n# C++ 11 for IBM atomic support\nifeq ($(ARCH),ppc)\n\tCXXFLAGS += -std=c++11 -D=linux\nendif\n\n#--------------------------------------------------------------------------------\n# InstallBuilder datafile determination\n#--------------------------------------------------------------------------------\n\nPF_DEPENDENT_DATAFILES = Linux.data\n\nifeq (\"$(wildcard /usr/bin/dpkg-deb)\",\"\")\n PF_DEPENDENT_DATAFILES += Linux_RPM.data\nelse\n PF_DEPENDENT_DATAFILES += Linux_DPKG.data\nendif\n\n#-------------------------------- End of File -----------------------------------\n" }, { "alpha_fraction": 0.5911034941673279, "alphanum_fraction": 0.5979469418525696, "avg_line_length": 19.15517234802246, "blob_id": "58feaafe1e13d63c9f5aaecdd0ac5eb4fce22ede", "content_id": "8d0ffde58ea024bbe70a5db57428cf005b7818ba", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1169, "license_type": "permissive", "max_line_length": 70, "num_lines": 58, "path": "/test/util/artifacts/runas-memleak/measureleak.sh", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "#!/bin/bash \n\nos=`uname`\ncase $os in\n'AIX')\n\tme=`whoami`\n\tpid=`ps -ef |grep omiagent |grep $me |grep -v grep |awk '{print $2}'`\n\ttc=`ps -o thcount -p $pid | grep -v THCNT`\n\tfdc=`lsof -p $pid |wc -l`\n\techo \"PID $pid\"\n\techo \"Thread count $tc\"\n\techo \"FD count $fdc\"\n\n\techo \"Memstats:\"\n\tps u $pid\n\t;;\n'HP-UX')\n\tme=`whoami`\n\tpid=`ps -ef |grep omiagent |grep $me |grep -v grep |awk '{print $2}'`\n\tfdc=`lsof -p $pid |wc -l`\n\techo \"PID $pid\"\n\techo \"Thread count N/A\"\n\techo \"FD count $fdc\"\n\n\techo \"Memstats:\"\n\tUNIX95= ps -C omiagent -o pid,sz,vsz,comm\n\t;;\n'Linux')\n\tme=`whoami`\n\tpid=`ps aux |grep omiagent |grep $me |grep -v grep |awk '{print $2}'`\n\ttc=`ps huH p $pid | wc -l`\n\tfdc=`lsof -p $pid |wc -l`\n\techo \"PID $pid\"\n\techo \"Thread count $tc\"\n\techo \"FD count $fdc\"\n\n\techo \"Memstats:\"\n\tps p $pid o pid,rss,vsz,comm\n\t;;\n'SunOS')\n\tme=`/opt/sfw/bin/whoami`\n\tpid=`ps -ef |grep omiagent |grep $me |grep -v grep |awk '{print $2}'`\n\ttc=`ps -eLf | grep omiagent | grep -v grep | wc -l`\n\tfdc=`lsof -p $pid |wc -l`\n\techo \"PID $pid\"\n\techo \"Thread count $tc\"\n\techo \"FD count $fdc\"\n\n\techo \"Memstats:\"\n\tps -p $pid -o pid,rss,vsz,comm\n\t;;\n*)\n\techo \"Unsupported OS\"\n\texit 1\n\t;;\nesac\n\nexit 0\n" }, { "alpha_fraction": 0.3738977015018463, "alphanum_fraction": 0.3985890746116638, "avg_line_length": 32.35293960571289, "blob_id": "33b8785803136d46c7ce405fb47c084a100d5893", "content_id": "6d6ab4aec75bee184db60ad73fe7638c36e7c06a", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 567, "license_type": "permissive", "max_line_length": 102, "num_lines": 17, "path": "/source/code/providers/support/logpolicy.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n \n*/\n/**\n \\file logpolicy.cpp\n\n \\brief Includes the default implementation of the log policy factory.\n\n \\date 2008-08-07 09:40:12\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxdefaultlogpolicyfactory.h>\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5501744747161865, "alphanum_fraction": 0.5513374209403992, "avg_line_length": 36.618751525878906, "blob_id": "0519932c2cf702760141efd4a37576935f86eb26", "content_id": "e84e658169ee923d9e066f9b099cb31029408f1f", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 12038, "license_type": "permissive", "max_line_length": 125, "num_lines": 320, "path": "/source/code/providers/support/appserver/persistappserverinstances.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file persistappserverinstances.cpp\n\n \\brief Means of persisting application server instances to disk\n\n \\date 11-05-18 12:00:00\n*/\n/*-----------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n\n#include <algorithm>\n#include <functional>\n#include <string>\n#include <vector>\n\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/stringaid.h>\n\n#include \"appserverconstants.h\"\n#include \"appserverinstance.h\"\n#include \"weblogicappserverinstance.h\"\n#include \"websphereappserverinstance.h\"\n#include \"tomcatappserverinstance.h\"\n#include \"jbossappserverinstance.h\"\n#include \"persistappserverinstances.h\"\n\n#include \"source/code/scxcorelib/util/persist/scxfilepersistdatareader.h\"\n#include \"source/code/scxcorelib/util/persist/scxfilepersistdatawriter.h\"\n#include \"source/code/scxcorelib/util/persist/scxfilepersistmedia.h\"\n\nusing namespace std;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nnamespace SCXSystemLib\n{\n\n /*-----------------------------------------------------------------*/\n /**\n Constructor (no arg)\n */\n PersistAppServerInstances::PersistAppServerInstances()\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.common.pal.system.appserver.persistappserverinstances\");\n m_pmedia = GetPersistMedia();\n\n SCX_LOGTRACE(m_log, wstring(L\"PersistAppServerInstances default constructor\"));\n }\n\n /*-----------------------------------------------------------------*/\n /**\n Destructor\n */\n PersistAppServerInstances::~PersistAppServerInstances()\n {\n SCX_LOGTRACE(m_log, wstring(L\"PersistAppServerInstances destructor\"));\n }\n\n /*-----------------------------------------------------------------*/\n /**\n Erase all application server instances from disk.\n */\n void PersistAppServerInstances::EraseFromDisk(void)\n {\n try\n {\n m_pmedia->UnPersist(APP_SERVER_PROVIDER);\n }\n catch(PersistDataNotFoundException& pdnfe)\n {\n SCX_LOGTRACE(m_log, pdnfe.What());\n }\n }\n\n /*-----------------------------------------------------------------*/\n /**\n Read a list of application server instances from disk.\n\n \\param[out] instances - vector of Application Server Instances \n to insert the values read from disk into \n \n */\n void PersistAppServerInstances::ReadFromDisk(\n vector<SCXHandle<AppServerInstance> >& instances)\n {\n try\n {\n SCXHandle<SCXPersistDataReader> preader = \n m_pmedia->CreateReader(APP_SERVER_PROVIDER);\n\n preader->ConsumeStartGroup(APP_SERVER_METADATA, true);\n wstring sizeFromCache = preader->ConsumeValue(APP_SERVER_NUMBER);\n preader->ConsumeEndGroup(true); // Closing APP_SERVER_NUMBER\n\n unsigned int size = StrToUInt(sizeFromCache);\n \n while(ReadFromDiskHelper(preader, instances))\n {\n }\n\n // If the size read does not match the actual number\n // of instances read (for instance, some has truncated\n // the cache), then the cache probably has been corrupted.\n // For this case, throw away all the cache information.\n if (instances.size() != size)\n {\n instances.clear();\n }\n\n RemoveNonExistentInstances(instances);\n }\n // Could have gotten here is the cache does not\n // exist or is corrupt. If it does not exist, then\n // the exception is thrown when doing the first read\n // and nothing has been added to the array. In this case,\n // the goal is to not surface the error.\n //\n // If corruption has occurred, then the cache should be \n // deleted (which should happen when we re-persist the current\n // state.\n catch(SCXNotSupportedException& snse)\n {\n SCX_LOGTRACE(m_log, snse.What());\n instances.clear();\n }\n catch(PersistDataNotFoundException& pdnfe)\n {\n SCX_LOGTRACE(m_log, pdnfe.What());\n instances.clear();\n }\n catch(PersistUnexpectedDataException& pude)\n {\n SCX_LOGTRACE(m_log, pude.What());\n instances.clear();\n }\n }\n\n /*--------------------------------------------------------*/\n /**\n Helper method for reading instances from disk\n \n \\param[in] preader - handle to the physical media reader\n \\param[out] instances - vector of Application Server Instances \n to insert the values read from disk into \n\n */\n bool PersistAppServerInstances::ReadFromDiskHelper(\n SCXHandle<SCXPersistDataReader>& preader,\n vector<SCXHandle<AppServerInstance> >& instances)\n {\n \n bool isThereAnElement = preader->ConsumeStartGroup(APP_SERVER_INSTANCE, false);\n \n if (isThereAnElement)\n {\n wstring id, diskPath, httpPort, httpsPort, protocol, isDeepMonitored, type, version, profile, cell, node, server;\n diskPath = preader->ConsumeValue(APP_SERVER_DISK_PATH);\n try\n {\n id = preader->ConsumeValue(APP_SERVER_ID);\n }\n catch(PersistUnexpectedDataException)\n {\n // To be backward compatible, we default to disk path if id is not in the persited data\n id = diskPath;\n SCX_LOGTRACE(m_log, L\"Id not found in persited data, defaulting to disk path\");\n }\n httpPort = preader->ConsumeValue(APP_SERVER_HTTP_PORT);\n httpsPort = preader->ConsumeValue(APP_SERVER_HTTPS_PORT);\n try\n {\n protocol = preader->ConsumeValue(APP_SERVER_PROTOCOL);\n }\n catch(PersistUnexpectedDataException)\n {\n // To be backward compatible, we default to HTTP if protocol is not in the persited data\n protocol = PROTOCOL_HTTP;\n SCX_LOGTRACE(m_log, L\"Protocol not found in persited data, defaulting to HTTP\");\n }\n isDeepMonitored = preader->ConsumeValue(APP_SERVER_IS_DEEP_MONITORED);\n type = preader->ConsumeValue(APP_SERVER_TYPE);\n version = preader->ConsumeValue(APP_SERVER_VERSION);\n try\n {\n profile = preader->ConsumeValue(APP_SERVER_PROFILE);\n cell = preader->ConsumeValue(APP_SERVER_CELL);\n node = preader->ConsumeValue(APP_SERVER_NODE);\n server = preader->ConsumeValue(APP_SERVER_SERVER);\n }\n catch(PersistUnexpectedDataException)\n {\n // To be backward compatible, we default profile, cell, node & server to \n // empty strings if they are not in the persited data\n profile = L\"\";\n cell = L\"\";\n node = L\"\";\n server = L\"\";\n SCX_LOGTRACE(m_log, L\"WebSphere properties not found in persited data, defaulting to empty strings\");\n }\n preader->ConsumeEndGroup(true);\n\n SCXHandle<AppServerInstance> instance;\n\n bool badType = false;\n\n if (APP_SERVER_TYPE_JBOSS == type)\n {\n instance = new JBossAppServerInstance(diskPath);\n } \n else if (APP_SERVER_TYPE_TOMCAT == type)\n {\n instance = new TomcatAppServerInstance(diskPath, diskPath);\n }\n else if (APP_SERVER_TYPE_WEBLOGIC == type)\n {\n instance = new WebLogicAppServerInstance(diskPath);\n instance->SetServer(server);\n }\n else if (APP_SERVER_TYPE_WEBSPHERE == type)\n {\n instance = new WebSphereAppServerInstance(diskPath, cell, node, profile, server);\n }\n else\n {\n SCX_LOGWARNING(m_log, wstring(L\"Unknown application server type read from cache: \").append(type));\n badType = true;\n }\n\n if (!badType)\n {\n instance->SetHttpPort(httpPort);\n instance->SetHttpsPort(httpsPort);\n \n // This value is a bool, but when written to disk it is \n // serialized as an integer.\n instance->SetIsDeepMonitored(L\"1\" == isDeepMonitored, protocol);\n \n // If read from cache, then by default this representation\n // of the instance is not running\n instance->SetIsRunning(false);\n instance->SetVersion(version);\n instances.push_back(instance);\n }\n }\n \n return isThereAnElement;\n }\n\n /*--------------------------------------------------------*/\n /**\n Given a list of instances, remove the instances that are\n can no longer be found on disk\n \n \\param[in/out] instances - vector of Application Server Instances \n to be manipulated\n \\param[in] remover - predicate object for removing non-existent\n application server instances. \n\n */\n void PersistAppServerInstances::RemoveNonExistentInstances(\n vector<SCXHandle<AppServerInstance> >& instances,\n RemoveNonexistentAppServerInstances remover )\n {\n remover.RemoveNonexistentInstances(instances);\n }\n\n \n /*-----------------------------------------------------------------*/\n /**\n Write the given list of application server instances to disk.\n \n \\param[in] instances - vector of Application Server Instances \n to write to disk\n \n */\n void PersistAppServerInstances::WriteToDisk(\n vector<SCXHandle<AppServerInstance> >& instances)\n {\n SCXHandle<SCXPersistDataWriter> pwriter= \n m_pmedia->CreateWriter(APP_SERVER_PROVIDER);\n\n pwriter->WriteStartGroup(APP_SERVER_METADATA);\n pwriter->WriteValue(APP_SERVER_NUMBER, \n StrFrom(instances.size()));\n pwriter->WriteEndGroup(); // Closing APP_METADATA\n\n int index = 0; \n for(\n vector<SCXHandle<AppServerInstance> >::iterator instance = instances.begin();\n instance != instances.end();\n ++instance, ++index)\n {\n pwriter->WriteStartGroup(APP_SERVER_INSTANCE);\n\n pwriter->WriteValue(APP_SERVER_DISK_PATH, (*instance)->GetDiskPath());\n pwriter->WriteValue(APP_SERVER_ID, (*instance)->GetId());\n pwriter->WriteValue(APP_SERVER_HTTP_PORT, (*instance)->GetHttpPort());\n pwriter->WriteValue(APP_SERVER_HTTPS_PORT, (*instance)->GetHttpsPort());\n pwriter->WriteValue(APP_SERVER_PROTOCOL, (*instance)->GetProtocol());\n pwriter->WriteValue(APP_SERVER_IS_DEEP_MONITORED, \n StrFrom((*instance)->GetIsDeepMonitored()));\n pwriter->WriteValue(APP_SERVER_TYPE, (*instance)->GetType());\n pwriter->WriteValue(APP_SERVER_VERSION, (*instance)->GetVersion());\n pwriter->WriteValue(APP_SERVER_PROFILE, (*instance)->GetProfile());\n pwriter->WriteValue(APP_SERVER_CELL, (*instance)->GetCell());\n pwriter->WriteValue(APP_SERVER_NODE, (*instance)->GetNode());\n pwriter->WriteValue(APP_SERVER_SERVER, (*instance)->GetServer());\n\n pwriter->WriteEndGroup(); // Closing this instance\n }\n \n pwriter->DoneWriting();\n }\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5178467035293579, "alphanum_fraction": 0.520772397518158, "avg_line_length": 22.73611068725586, "blob_id": "185ce171ab98532472af6303cee7fe5f859d1be0", "content_id": "4d1f912fb7f2d4163fb4a67cdf1e5447e3dbd3ae", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3418, "license_type": "permissive", "max_line_length": 114, "num_lines": 144, "path": "/source/code/shared/tools/regex_test/regex_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n\n*/\n\n// Simple program to test native C-style regular expressions\n//\n// Compile with something like:\n//\n// make regex_test\n\n#include <iostream>\n#include <string>\n#include <fstream>\n#include <unistd.h>\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxregex.h>\n#include <scxcorelib/stringaid.h>\n\n#include <scxcorelib/scxdefaultlogpolicyfactory.h> // Using the default log policy.\n\nusing namespace std;\nusing namespace SCXCoreLib;\n\nvoid usage(const char* program)\n{\n cerr << \"usage: \" << program << \" {-p pattern | -f pattern-file} [filename ...]\" << endl;\n exit(1);\n}\n\nwstring ReadPatternFromFile(const wstring& filename)\n{\n vector<wstring> lines;\n SCXStream::NLFs nlfs;\n\n SCXFile::ReadAllLines(SCXFilePath(filename), lines, nlfs);\n\n for (size_t i = 0; i < lines.size(); i++)\n {\n // Trim leading and trailing whitespace\n\n wstring line = StrTrim(lines[i]);\n\n if (line.length())\n {\n return line;\n }\n }\n\n wcerr << L\"no pattern found in [\" << filename << L\"]: exiting\" << endl;\n exit(2);\n\n return L\"\"; // Never reached; pacify compiler\n}\n\nvoid ReadLinesFromFile(SCXHandle<SCXRegex>& re, wistream& ifs)\n{\n vector<wstring> lines;\n SCXStream::NLFs nlfs;\n\n SCXStream::ReadAllLines(ifs, lines, nlfs);\n\n for (size_t i = 0; i < lines.size(); i++)\n {\n wstring line = lines[i];\n\n if (re->IsMatch(line))\n {\n wcout << L\"***\";\n }\n wcout << L\"\\t\" << line << endl;\n }\n}\n\nint main(int argc, char *argv[])\n{\n int exitStatus = 0;\n bool p_flag = false;\n bool f_flag = false;\n wstring pattern;\n wstring patternFilename;\n int c;\n\n while((c = getopt(argc, argv, \"p:f:\")) != -1) {\n switch(c) {\n case 'p':\n p_flag = true;\n pattern = StrFromMultibyte(optarg);\n break;\n case 'f':\n f_flag = true;\n patternFilename = StrFromMultibyte(optarg);\n break;\n default:\n usage(argv[0]);\n /*NOTREACHED*/\n break;\n }\n }\n\n if (!p_flag && !f_flag) {\n usage(argv[0]);\n /*NOTREACHED*/\n }\n\n if (f_flag) {\n pattern = ReadPatternFromFile(patternFilename);\n }\n\n SCXHandle<SCXRegex> re;\n try\n {\n re = new SCXRegex(pattern);\n }\n catch (SCXException& e)\n {\n wcerr << L\"Fatal error: \" << e.What() << endl;\n exit(3);\n }\n\n if (optind == argc) {\n // read from stdin\n ReadLinesFromFile(re, wcin);\n } else {\n // read each of the files named\n for(int index = optind; index < argc; index++) {\n wifstream ifs(argv[index], ifstream::in);\n if (!ifs.fail())\n {\n ReadLinesFromFile(re, ifs);\n }\n else\n {\n wcerr << L\"Filename \\\"\" << StrFromMultibyte(argv[index]) << L\"\\\" empty or does not exist\" << endl;\n exitStatus = 4; // One or more of the filenames couldn't be opened\n }\n }\n }\n\n exit(exitStatus);\n}\n" }, { "alpha_fraction": 0.6337831616401672, "alphanum_fraction": 0.6358771324157715, "avg_line_length": 37.35714340209961, "blob_id": "236eb727c7304c1d0de9b58023fd763f24c68b6e", "content_id": "bdd79c5630ab748b02181d2241e6f2806704d03b", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 4298, "license_type": "permissive", "max_line_length": 192, "num_lines": 112, "path": "/build/Makefile.macros", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "# -*- mode: Makefile; -*-\n#--------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n#--------------------------------------------------------------------------------\n# 2007-08-23\n#--------------------------------------------------------------------------------\n\n# Roots to common areas in $/ScxCore/scx_core (and $/ScxCore/shared_main)\nSCX_TEST_ROOT=$(SCX_BRD)/test\n\n#--- Begin differences shared_main vs. scx_core ---\n# Depending on which tree this file is located exactly one of these sections should \n# be in effect\n\n# Roots to functionality areas in $/ScxCore/scx_core\nSCX_SRC_ROOT=$(SCX_BRD)/source/code\n\n# Roots for shared code in $/ScxCore/scx_core\nSCX_SHARED_SRC_ROOT=$(SCX_SRC_ROOT)/shared\nSCX_SHARED_TEST_ROOT=$(SCX_BRD)/test/code/shared\nSCX_SHARED_INCLUDE_DIR=$(SCXPAL_DIR)/source/code/include\nSCX_SHARED_EXT_LIB_DIR=$(SCX_BRD)/source/ext/lib\nSCX_SHARED_TST_EXT_INCLUDE_DIR=$(SCXPAL_DIR)/test/ext/include\n\nSCXPAL_TEST_ROOT=$(SCXPAL_DIR)/test/code\nSCX_SHARED_TST_EXT_LIB_DIR=$(SCXPAL_DIR)/test/ext/lib\n\n# Only of interest for $/ScxCore/scx_core\nSCX_UNITTEST_ROOT=$(SCX_BRD)/test/code\n\n# Intermediate include dir. Contains header files generated during build.\nINT_INCLUDE_DIR=$(INTERMEDIATE_DIR)/include\n\n# Locations in common SCXPal project\nSCXPAL_SRC_ROOT=$(SCXPAL_DIR)/source/code\nSCXPAL_INT_INCLUDE_DIR=$(SCXPAL_INTERMEDIATE_DIR)/include\n\nMOF_PATH=$(SCX_SRC_ROOT)/mof\n\n#--------------------------------------------------------------------------------\n# Configuration cahce info, controlled from cmdline or Makefile.config_cache\n# \n\nBUILD_TYPE?=Release\n\nBUILD_PROFILING?=false\n\nUNITTESTS_SUBSET?=\n\n# Root directory of the build process output.\n# Individual developers may redirect the output of their local build \n# by defining the variable in the environment.\n\nSCX_BUILD_OUTPUT_DIR?=$(SCX_BRD)\n\n# Output of temporary build files on this platform, with current config \nINTERMEDIATE_DIR=$(SCX_BUILD_OUTPUT_DIR)/intermediate/$(BUILD_CONFIGURATION)\n# Output of all build targets (to be delivered\nTARGET_DIR=$(SCX_BUILD_OUTPUT_DIR)/target/$(BUILD_CONFIGURATION)\n\n# Composite string for build version. \nSCX_BUILDVERSION=$(SCX_BUILDVERSION_MAJOR).$(SCX_BUILDVERSION_MINOR).$(SCX_BUILDVERSION_PATCH)-$(SCX_BUILDVERSION_BUILDNR)\n\n#--------------------------------------------------------------------------------\n# Doxygen output \nDOXYGEN_OUTPUT_DIR=$(SCX_BUILD_OUTPUT_DIR)/target\n\n#-------------------------------------------------------------------------------- \n# List of symbols which shall be exposed by the libSCXCoreProviderModule\nCOREPROVIDERMODULE_EXPOSED_SYMS= \\\n\tSCX_MetaProvider_Create_InstanceMI \\\n\tSCX_MetaProvider_Create_MethodMI \\\n\nifneq ($(SCX_STACK_ONLY), true)\nCOREPROVIDERMODULE_EXPOSED_SYMS += \\\n\tSCX_ASProvider_Create_InstanceMI \\\n\tSCX_ASProvider_Create_MethodMI \\\n\tSCX_NetworkProvider_Create_InstanceMI \\\n\tSCX_NetworkProvider_Create_MethodMI \\\n\tSCX_CPUProvider_Create_InstanceMI \\\n\tSCX_CPUProvider_Create_MethodMI \\\n\tSCX_MemoryProvider_Create_InstanceMI \\\n\tSCX_MemoryProvider_Create_MethodMI \\\n\tSCX_OSProvider_Create_InstanceMI \\\n\tSCX_OSProvider_Create_MethodMI \\\n\tSCX_DiskProvider_Create_InstanceMI \\\n\tSCX_DiskProvider_Create_MethodMI \\\n\tSCX_ProcessProvider_Create_InstanceMI \\\n\tSCX_ProcessProvider_Create_MethodMI \\\n\tSCX_RunAsProvider_Create_InstanceMI \\\n\tSCX_RunAsProvider_Create_MethodMI \\\n\tSCX_LogFileProvider_Create_InstanceMI \\\n\tSCX_LogFileProvider_Create_MethodMI \\\n\nendif\n\n# List of symbols which shall be exposed by the libSCXTestProviderModule\nTESTPROVIDERMODULE_EXPOSED_SYMS= \\\n\tSCX_TestProvider_Create_InstanceMI \\\n\tSCX_TestProvider_Create_MethodMI \\\n\n\n#================================================================================\n# Internal functions\n#================================================================================\n\n# Convert a list of src files with absolute paths under SCX_BRD to corresponding\n# object files under intermediate directory \n# src_to_obj(list_of_cppfiles)\nsrc_to_obj = $(patsubst $(SCX_BRD)%, $(INTERMEDIATE_DIR)%, $(patsubst %.s, %.$(PF_OBJ_FILE_SUFFIX), $(patsubst %.c, %.$(PF_OBJ_FILE_SUFFIX), $(patsubst %.cpp, %.$(PF_OBJ_FILE_SUFFIX), $(1)))))\n\n#-------------------------------- End of File -----------------------------------\n\n\n" }, { "alpha_fraction": 0.4813384711742401, "alphanum_fraction": 0.496782511472702, "avg_line_length": 31.375, "blob_id": "a20b5cac5d9a671c3610c6bee838242dbb4e0139", "content_id": "4ef5b2e3eb902d75d89e218bb3dc9de52bd7afec", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 777, "license_type": "permissive", "max_line_length": 102, "num_lines": 24, "path": "/source/code/providers/support/startuplog.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file startuplog.h\n\n \\brief Declaration of the \"log once\" functionality for startup logging\n\n \\date 08-10-21 17:56:06\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef INITLOG_H\n#define INITLOG_H\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxfilepath.h>\n\nnamespace SCXCore {\n static const SCXCoreLib::SCXFilePath SCXConfFile(L\"/etc/opt/microsoft/scx/conf/scxconfig.conf\");\n void LogStartup(void);\n}\n\n#endif /* INITLOG_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.47576436400413513, "alphanum_fraction": 0.4806114733219147, "avg_line_length": 31.31325340270996, "blob_id": "af8882ec565092b1c4dda5723a6e3b3a67ada5d7", "content_id": "b9ce1b462cd71daed6bbf73d66bb30173f0c6532", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2682, "license_type": "permissive", "max_line_length": 100, "num_lines": 83, "path": "/source/code/providers/support/appserver/removenonexistentappserverinstances.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file removenonexistentappserverinstances.h\n\n \\brief Remove AppServerInstances from an array if they are no \n longer on disk\n\n \\date 11-05-27 12:00:00\n\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef REMOVENONEXISTENTAPPSERVERINSTANCES_H\n#define REMOVENONEXISTENTAPPSERVERINSTANCES_H\n\n#include <string>\n#include <scxcorelib/scxcmn.h>\n\nnamespace SCXSystemLib\n{\n /*--------------------------------------------------------*/\n /**\n Class that represents an how to persist application server instances \n */\n class IRemoveNonexistentAppServerInstances\n {\n public:\n virtual ~IRemoveNonexistentAppServerInstances() {};\n\n \n /*--------------------------------------------------------*/\n /**\n Given a list of instances, remove the instances that are\n can no longer be found on disk\n */\n virtual void RemoveNonexistentInstances(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& instances) = 0;\n\n };\n\n /*--------------------------------------------------------*/\n /**\n Class that represents an how to persist application server instances \n */\n class RemoveNonexistentAppServerInstances :\n public IRemoveNonexistentAppServerInstances\n {\n\n public:\n \n /*\n * Default no-arg constructor, uses the\n * default/production values\n */\n RemoveNonexistentAppServerInstances();\n\n /*\n * Destructor\n */\n virtual ~RemoveNonexistentAppServerInstances();\n\n /*--------------------------------------------------------*/\n /**\n Given a list of instances, remove the instances that are\n can no longer be found on disk\n */\n virtual void RemoveNonexistentInstances(\n std::vector<SCXCoreLib::SCXHandle<AppServerInstance> >& instances);\n\n private:\n /*--------------------------------------------------------*/\n /**\n Predicate Helper method for deciding which instances to remove\n */\n static bool RemoveNonExistentInstanceHelper(\n SCXCoreLib::SCXHandle<AppServerInstance>);\n };\n\n}\n\n#endif /* REMOVENONEXISTENTAPPSERVERINSTANCES_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5495092868804932, "alphanum_fraction": 0.5537732839584351, "avg_line_length": 37.17829513549805, "blob_id": "3801a328075bb2afd342bc5f75b25a69b805dbb6", "content_id": "e6af66092dea95bde2e59f99be79d1477716e3b0", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14775, "license_type": "permissive", "max_line_length": 170, "num_lines": 387, "path": "/source/code/providers/support/appserver/websphereappserverinstance.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file websphereappserverinstance.cpp\n\n \\brief PAL representation of a WebSphere application server\n\n \\date 11-08-20 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n\n#include <string>\n\n#include <scxcorelib/stringaid.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxdirectoryinfo.h>\n#include <scxcorelib/scxregex.h>\n#include <util/XElement.h>\n\n#include \"appserverconstants.h\"\n#include \"websphereappserverinstance.h\"\n\nusing namespace std;\nusing namespace SCXCoreLib;\nusing namespace SCX::Util::Xml;\n\nnamespace SCXSystemLib\n{\n\n /**\n Returns a stream for reading from server.xml\n\n \\param[in] filename Name of file to open\n */\n SCXHandle<istream> WebSphereAppServerInstancePALDependencies::OpenXmlServerFile(const wstring& filename)\n {\n return SCXFile::OpenFstream(filename, ios::in);\n }\n\n /**\n Returns a stream for reading from profile.version\n\n \\param[in] filename Name of file to open\n */\n SCXHandle<istream> WebSphereAppServerInstancePALDependencies::OpenXmlVersionFile(const wstring& filename)\n {\n return SCXFile::OpenFstream(filename, ios::in);\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Constructor\n\n \\param[in] cell The WebSphere Cell Name\n \\param[in] node The WebSphere Node Name\n \\param[in] profile The WebSphete Profile Name\n \\param[in] installDir The folder where WebSphere is installed\n \\param[in] server The WebSphere Server Name\n \\param[in] deps Dependency instance to use\n */\n WebSphereAppServerInstance::WebSphereAppServerInstance(\n wstring installDir, wstring cell, wstring node, wstring profile, wstring server,\n SCXHandle<WebSphereAppServerInstancePALDependencies> deps) : \n AppServerInstance(installDir, APP_SERVER_TYPE_WEBSPHERE), m_deps(deps)\n {\n SCXFilePath installPath;\n\n installPath.SetDirectory(installDir);\n\n m_diskPath = installPath.Get();\n \n m_cell = cell;\n m_node = node;\n m_profile = profile;\n m_server = server;\n\n wstring id = profile;\n SetId(id.append(L\"-\").append(cell).append(L\"-\").append(node).append(L\"-\").append(server));\n\n SCX_LOGTRACE(m_log, wstring(L\"WebSphereAppServerInstance default constructor - \").append(GetId()));\n }\n\n\n /*----------------------------------------------------------------------------*/\n /**\n Destructor\n */\n WebSphereAppServerInstance::~WebSphereAppServerInstance()\n {\n SCX_LOGTRACE(m_log, wstring(L\"WebSphereAppServerInstance destructor - \").append(GetId()));\n }\n\n \n /*----------------------------------------------------------------------------*/\n /**\n Get port from a specialEndpoints tag from the serverindex.xml file\n \n \\param[in] node specialEndpoint node to get port from\n \\param[out] found Set to true if successfully read port\n \\param[out] port Return the port if found\n */\n void WebSphereAppServerInstance::GetPortFromXml(const XElementPtr& node, bool& found, wstring& port)\n {\n const string cEndPointNodeName(\"endPoint\");\n const string cPortAttributeName(\"port\");\n\n XElementPtr endPoint;\n if (node->GetChild(cEndPointNodeName, endPoint))\n {\n string portstr;\n if (endPoint->GetAttributeValue(cPortAttributeName, portstr))\n {\n port = StrFromUTF8(portstr);\n found = true;\n }\n }\n }\n /*----------------------------------------------------------------------------*/\n /**\n function that returns the profileDiskPath instead of the full server disk path\n profile Disk Path ex:/opt/IBM/WebSphere/AppServer/profiles/AppSrv01\n server Disk Path ec:/opt/IBM/WebSphere/AppServer/profiles/AppSrv01/servers/server1\n\n to check if we have the already have the profile diskPath we check if the 2nd to last entry is\n const string \"profiles\"\n */\n wstring returnProfileDiskPath(wstring m_diskPath)\n {\n SCXRegex re(L\"(.*)/(.*)/(.*)/(.*)/(.*)\");\n vector<wstring> v_profileDiskPath;\n if (re.ReturnMatch(m_diskPath,v_profileDiskPath,0))\n {\n //v_profileDiskPath[1] will include disk path until profile name <../../../../profiles>\n //v_profileDiskPath[2] will include profile name <AppSrv01>\n if(v_profileDiskPath[3].compare(L\"servers\") == 0)\n {\n return v_profileDiskPath[1].append(L\"/\").append(v_profileDiskPath[2]).append(L\"/\");\n }\n }\n return m_diskPath;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Update ports for WebSphere\n\n Load XML file <disk path>/config/cells/<Cell Name>/nodes/<Node Name>/serverindex.xml\n \n Ger serverIndex/serverEntries node where serverName attribute is the name of the server\n For HTTP port get specialEndpoints node where endPointName is WC_defaulthost and \n get port attribute from endPoint node\n For HTTPS port get specialEndpoints node where endPointName is WC_defaulthost_secure and \n get port attribute from endPoint node\n */\n void WebSphereAppServerInstance::UpdatePorts()\n {\n const string cServerIndexNodeName(\"serverindex:ServerIndex\");\n const string cServerEntriesNodeName(\"serverEntries\");\n const string cServerNameAttributeName(\"serverName\");\n const string cSpecialEndpointsNodeName(\"specialEndpoints\");\n const string cEndPointNameAttributeName(\"endPointName\");\n const string cWCdefaultHostName(\"WC_defaulthost\");\n const string cWCdefaultHostSecureName(\"WC_defaulthost_secure\");\n const string cEndPointNodeName(\"endPoint\");\n const string cPortAttributeName(\"port\");\n \n string xmlcontent;\n SCXFilePath filename(returnProfileDiskPath(m_diskPath)); \n\n filename.AppendDirectory(L\"config\");\n filename.AppendDirectory(L\"cells\");\n filename.AppendDirectory(m_cell);\n filename.AppendDirectory(L\"nodes\");\n filename.AppendDirectory(m_node);\n filename.SetFilename(L\"serverindex.xml\");\n\n try {\n SCXHandle<istream> mystream = m_deps->OpenXmlServerFile(filename.Get());\n GetStringFromStream(mystream, xmlcontent);\n\n // Load the XML, but don't honor namespaces\n XElementPtr serverIndexNode;\n XElement::Load(xmlcontent, serverIndexNode, false);\n\n if (serverIndexNode->GetName() == cServerIndexNodeName)\n {\n XElementList serverEntriesNodes;\n bool foundServer = false;\n\n serverIndexNode->GetChildren(serverEntriesNodes);\n\n for (size_t idx = 0; !foundServer && idx < serverEntriesNodes.size(); ++idx)\n {\n string name;\n if (serverEntriesNodes[idx]->GetName() == cServerEntriesNodeName && \n serverEntriesNodes[idx]->GetAttributeValue(cServerNameAttributeName, name) && \n m_server == StrFromUTF8(name))\n {\n XElementList childNodes;\n bool foundHTTPnode = false;\n bool foundHTTPSnode = false;\n foundServer = true;\n\n serverEntriesNodes[idx]->GetChildren(childNodes);\n\n for (size_t idx2 = 0; !(foundHTTPnode && foundHTTPSnode) && idx2 < childNodes.size(); ++idx2)\n {\n if (childNodes[idx2]->GetName() == cSpecialEndpointsNodeName && \n childNodes[idx2]->GetAttributeValue(cEndPointNameAttributeName, name))\n { \n if (cWCdefaultHostName == name)\n {\n GetPortFromXml(childNodes[idx2], foundHTTPnode, m_httpPort);\n }\n else if (cWCdefaultHostSecureName == name)\n {\n GetPortFromXml(childNodes[idx2], foundHTTPSnode, m_httpsPort);\n }\n }\n }\n }\n }\n }\n }\n catch (SCXFilePathNotFoundException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"WebSphereAppServerInstance::UpdatePorts() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\n }\n catch (SCXUnauthorizedFileSystemAccessException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"WebSphereAppServerInstance::UpdatePorts() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\n }\n catch (XmlException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"WebSphereAppServerInstance::UpdatePorts() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Update version\n \n Load XML file <disk path>\\properties\\version\\profile.version\n\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <profile>\n <id>default</id>\n <version>7.0.0.0</version>\n <build-info date=\"8/31/08\" level=\"r0835.03\"/>\n </profile>\n \n */\n void WebSphereAppServerInstance::UpdateVersion()\n {\n const string cProfileNodeName(\"profile\");\n const string cVersionNodeName(\"version\");\n \n string xmlcontent;\n SCXFilePath filename(GetProfileVersionXml());\n\n try {\n SCXHandle<istream> mystream = m_deps->OpenXmlVersionFile(filename.Get());\n GetStringFromStream(mystream, xmlcontent);\n\n XElementPtr profileNode;\n XElement::Load(xmlcontent, profileNode);\n\n if (profileNode->GetName() == cProfileNodeName)\n {\n XElementPtr versionNode;\n if (profileNode->GetChild(cVersionNodeName, versionNode))\n {\n wstring version;\n versionNode->GetContent(version);\n SetVersion(version);\n }\n }\n }\n catch (SCXFilePathNotFoundException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"WebSphereAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - Could not find file: \").append(filename));\n }\n catch (SCXUnauthorizedFileSystemAccessException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"WebSphereAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - not authorized to open file: \").append(filename));\n }\n catch (XmlException&)\n {\n SCX_LOGERROR(m_log, wstring(L\"WebSphereAppServerInstance::UpdateVersion() - \").append(GetId()).append(L\" - Could not load XML from file: \").append(filename));\n }\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Return a file path to the profile.version XML file\n\n */\n SCXFilePath WebSphereAppServerInstance::GetProfileVersionXml() const\n {\n SCXFilePath filename(returnProfileDiskPath(m_diskPath));\n \n filename.AppendDirectory(L\"properties\");\n filename.AppendDirectory(L\"version\");\n filename.SetFilename(L\"profile.version\");\n \n return filename;\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Update values\n\n */\n void WebSphereAppServerInstance::Update()\n {\n SCX_LOGTRACE(m_log, wstring(L\"WebSphereAppServerInstance::Update() - \").append(GetId()));\n\n UpdateVersion();\n UpdatePorts();\n }\n\n /*----------------------------------------------------------------------------*/\n /**\n Read all lines from a stream and save in a string\n\n \\param[in] mystream Stream to read from\n \\param[out] content String to return content in\n */\n void WebSphereAppServerInstance::GetStringFromStream(SCXHandle<istream> mystream, string& content)\n {\n content = \"\";\n while (SCXStream::IsGood(*mystream))\n {\n string tmp;\n getline(*mystream, tmp);\n content.append(tmp);\n content.append(\"\\n\");\n }\n }\n\n /*--------------------------------------------------------------------*/\n /**\n Check if the application server is still installed.\n \n This overrides the default logic\n\n */\n bool WebSphereAppServerInstance::IsStillInstalled()\n {\n // Check to see if servers directory is present\n // If the directory is present then this means that the installation is a Network Deployment installation\n // If Network Deployment installation go all the way to root diskPath + \"servers/server1/configuration\"\n // This directory contains wsBundleMetadata file that we can check to make sure exists\n SCXCoreLib::SCXFilePath profileDiskPath(returnProfileDiskPath(m_diskPath));\n profileDiskPath.AppendDirectory(L\"servers\");\n \n if (SCXDirectory::Exists(profileDiskPath))\n {\n // Atleast on Websphere 8.5 wsBundleMetadata is a directory.\n // Hence adding check for presence of the directory along with the file.\n SCXCoreLib::SCXFilePath serverDiskPath(m_diskPath);\n serverDiskPath.AppendDirectory(L\"configuration\");\n SCXCoreLib::SCXFilePath metadataDiskPath(serverDiskPath);\n serverDiskPath.Append(L\"wsBundleMetadata\");\n metadataDiskPath.AppendDirectory(L\"wsBundleMetadata\");\n \n if (SCXFile::Exists(serverDiskPath.Get()) || SCXDirectory::Exists(metadataDiskPath))\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n else\n {\n return SCXFile::Exists(GetProfileVersionXml());\n }\n }\n}\n\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.5963375568389893, "alphanum_fraction": 0.6011146306991577, "avg_line_length": 33.88888931274414, "blob_id": "bb00605876664722b02aced8b1b9981e51b26c39", "content_id": "1c433c061058597f5a7fdd5f9585d91c80ac7073", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2512, "license_type": "permissive", "max_line_length": 199, "num_lines": 72, "path": "/source/code/providers/support/appserver/websphereappserverinstance.h", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file websphereappserverinstance.h\n\n \\brief PAL representation of a WebSphere Application Server\n\n \\date 11-05-18 12:00:00\n*/\n/*----------------------------------------------------------------------------*/\n#ifndef WEBSPHEREAPPSERVERINSTANCE_H\n#define WEBSPHEREAPPSERVERINSTANCE_H\n\n#include <string>\n#include <util/XElement.h>\n\n#include \"appserverinstance.h\"\n\nnamespace SCXSystemLib\n{\n /*----------------------------------------------------------------------------*/\n /**\n Class representing all external dependencies from the AppServer PAL.\n\n */\n class WebSphereAppServerInstancePALDependencies\n {\n public:\n virtual SCXCoreLib::SCXHandle<std::istream> OpenXmlServerFile(const std::wstring& filename);\n virtual SCXCoreLib::SCXHandle<std::istream> OpenXmlVersionFile(const std::wstring& filename);\n virtual ~WebSphereAppServerInstancePALDependencies() {};\n };\n\n /*----------------------------------------------------------------------------*/\n /**\n Class that represents an instances.\n\n Concrete implementation of an instance of a WebSphere Application Server\n\n */\n class WebSphereAppServerInstance : public AppServerInstance\n {\n friend class AppServerEnumeration;\n\n public:\n\n WebSphereAppServerInstance(\n std::wstring cell, std::wstring node, std::wstring profile, std::wstring installDir, std::wstring server,\n SCXCoreLib::SCXHandle<WebSphereAppServerInstancePALDependencies> deps = SCXCoreLib::SCXHandle<WebSphereAppServerInstancePALDependencies>(new WebSphereAppServerInstancePALDependencies()));\n virtual ~WebSphereAppServerInstance();\n\n virtual bool IsStillInstalled();\n\n virtual void Update();\n\n private:\n\n void UpdateVersion();\n void UpdatePorts();\n void GetStringFromStream(SCXCoreLib::SCXHandle<std::istream> mystream, std::string& content);\n void GetPortFromXml(const SCX::Util::Xml::XElementPtr& node, bool& found, std::wstring& port);\n\n SCXCoreLib::SCXFilePath GetProfileVersionXml() const;\n\n SCXCoreLib::SCXHandle<WebSphereAppServerInstancePALDependencies> m_deps;\n };\n\n}\n\n#endif /* WEBSPHEREAPPSERVERINSTANCE_H */\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.489073783159256, "alphanum_fraction": 0.4932176470756531, "avg_line_length": 38.00126266479492, "blob_id": "70350a3ac9c61a24b66c64feadf457ca95031d63", "content_id": "5aed76cfb7914a9fa160ad55faa62f12f8d60b21", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 30889, "license_type": "permissive", "max_line_length": 125, "num_lines": 792, "path": "/source/code/providers/support/appserver/weblogicappserverenumeration.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*----------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved. See license.txt for license information.\n*/\n/**\n \\file weblogicappserverenumeration.cpp\n\n \\brief Enumerator of WebLogic Application Server\n\n \\date 11-08-18 12:00:00\n*/\n/*----------------------------------------------------------------------*/\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include <scxcorelib/scxcmn.h>\n#include <scxcorelib/scxcondition.h>\n#include <scxcorelib/scxdirectoryinfo.h>\n#include <scxcorelib/scxexception.h>\n#include <scxcorelib/scxfile.h>\n#include <scxcorelib/scxfilepath.h>\n#include <scxcorelib/scxlog.h>\n#include <scxcorelib/stringaid.h>\n#include <util/XElement.h>\n\n#include \"appserverconstants.h\"\n#include \"weblogicappserverenumeration.h\"\n#include \"weblogicappserverinstance.h\"\n\nusing namespace std;\nusing namespace SCXCoreLib;\nusing namespace SCX::Util::Xml;\nusing namespace SCXSystemLib;\n\nnamespace SCXSystemLib {\n /*------------------------------------------------------------------*/\n /**\n Constructor for a file-system abstraction\n Note: this function exists for the purpose of unit-testing\n \n */\n WebLogicFileReader::WebLogicFileReader() : IWebLogicFileReader() {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.common.pal.system.appserver.weblogicfilereader\");\n SCX_LOGTRACE(m_log, L\"WebLogicFileReader Constructor\");\n }\n\n /*------------------------------------------------------------------*/\n /**\n Wrapper to the filesystem check if the given file exists.\n Note: this function exists for the purpose of unit-testing\n \n \\param[in] path Full filepath to the XML file containing\n the domain's servers's configuration\n \n */\n bool WebLogicFileReader::DoesConfigXmlExist(\n const SCXFilePath& path)\n {\n return SCXFile::Exists(path);\n }\n\n /*------------------------------------------------------------------*/\n /**\n Wrapper to the filesystem check if the given file exists.\n Note: this function exists for the purpose of unit-testing\n \n \\param[in] path Full filepath to the XML file containing\n the domains for a WebLogic 11g install\n \n */\n bool WebLogicFileReader::DoesDomainRegistryXmlExist(\n const SCXFilePath& path)\n {\n return SCXFile::Exists(path);\n }\n\n /*------------------------------------------------------------------*/\n /**\n Wrapper to the filesystem check if the given file exists.\n Note: this function exists for the purpose of unit-testing\n \n \\param[in] path Full filepath to the INI file containing\n the domains for a WebLogic 10g install\n\n */\n bool WebLogicFileReader::DoesNodemanagerDomainsExist(\n const SCXFilePath& path)\n {\n return SCXFile::Exists(path);\n }\n\n /*------------------------------------------------------------------*/\n /**\n Wrapper to the filesystem check if the given file exists.\n \n In addition to abstracting the file-system access, this check is\n used to determine if a WebLogic managed server is available on\n this particular system.\n \n In a cluster environment, all of the managed servers are present in\n the XML file. Aparently, the directory will only exist on disk\n if the managed server has been run at least once. This check is\n necessary to prevent instance being discovered on the wrong box\n in a clustered environment.\n \n \\param[in] path Full filepath to the directory that contains\n the working content of the server's files.\n\n */\n bool WebLogicFileReader::DoesServerDirectoryExist(\n const SCXFilePath& path)\n {\n return SCXDirectory::Exists(path);\n }\n\n /*------------------------------------------------------------------*/\n /**\n From the necessary file, read the domains and return a unique list\n of potential domains.\n \n */\n vector<SCXFilePath> WebLogicFileReader::GetDomains()\n {\n SCX_LOGTRACE(m_log, L\"WebLogicFileReader::GetDomains\");\n\n vector<SCXFilePath> domains;\n\n // Logic necessary for reading WebLogic 11g domains\n SCXFilePath domainRegistryXml;\n domainRegistryXml.SetDirectory(m_installationPath);\n domainRegistryXml.SetFilename(\n WEBLOGIC_DOMAIN_REGISTRY_XML_FILENAME);\n \n if (DoesDomainRegistryXmlExist(domainRegistryXml))\n {\n ReadDomainRegistryXml(domainRegistryXml, domains);\n }\n\n // Logic necessary for reading WebLogic 10g domains\n SCXFilePath nodemanagerDomains;\n nodemanagerDomains.SetDirectory(m_installationPath);\n nodemanagerDomains.AppendDirectory(WEBLOGIC_NODEMANAGER_DOMAINS_DIRECTORY);\n nodemanagerDomains.SetFilename(WEBLOGIC_NODEMANAGER_DOMAINS_FILENAME);\n\n if (DoesNodemanagerDomainsExist(nodemanagerDomains))\n {\n ReadNodemanagerDomains(nodemanagerDomains, domains);\n }\n \n // There may be duplicates in the list, it is necessary to\n // sort the list of domains and return only the unique instances.\n sort(domains.begin(), domains.end(), SortPath());\n vector<SCXFilePath>::iterator tmp = \n unique(domains.begin(), domains.end());\n domains.resize(tmp-domains.begin());\n \n SCX_LOGTRACE(m_log, \n wstring(L\"WebLogicFileReader::GetDomains() - \").\n append(L\"Found \").append(StrFrom(domains.size())).append(L\" domain(s)\"));\n\n return domains;\n }\n \n /*------------------------------------------------------------------*/\n /**\n From the necessary XML configuration file, read information about\n the known instances.\n \n The file should be:\n ${Install}/${Domain}/config/config.xml\n\n \\param[in] domains List of domains to find instances for\n\n \\param[out] instances vector to add instances to\n \n */ \n void WebLogicFileReader::GetInstances(\n const SCXFilePath& domain,\n vector<SCXHandle<AppServerInstance> >& instances)\n {\n SCXFilePath configXml;\n configXml.SetDirectory(domain.Get());\n configXml.AppendDirectory(WEBLOGIC_CONFIG_DIRECTORY);\n configXml.Append(WEBLOGIC_CONFIG_FILENAME);\n \n if (DoesConfigXmlExist(configXml)) \n {\n SCX_LOGTRACE(m_log, \n wstring(L\"WebLogicFileReader::GetInstances() - \").\n append(L\"Reading \").append(configXml.Get()));\n ReadConfigXml(domain, configXml, instances);\n }\n else\n {\n SCX_LOGTRACE(m_log, \n wstring(L\"WebLogicFileReader::GetInstances() - \").\n append(L\"Expected configuration file '\").\n append(configXml.Get()).append(L\"' does not exist.\"));\n }\n }\n\n /*------------------------------------------------------------------*/\n /**\n Returns a stream for reading the domain's config/config.xml file.\n This configuration file contains info for the Admin Server and all\n Managed Servers known to the domain.\n\n \\param[in] filename Name of file to open\n */\n SCXHandle<istream> WebLogicFileReader::OpenConfigXml(\n const wstring& filename)\n {\n return SCXFile::OpenFstream(filename, ios::in);\n }\n \n /*------------------------------------------------------------------*/\n /**\n Returns a stream for reading the domain-registry.xml file.\n This is a simple XML file containing directories to the domains\n known to the installation.\n\n \\param[in] filename Name of file to open\n */\n SCXHandle<istream> WebLogicFileReader::OpenDomainRegistryXml(\n const wstring& filename)\n {\n return SCXFile::OpenFstream(filename, ios::in);\n }\n\n /*------------------------------------------------------------------*/\n /**\n Returns a stream for reading the nodemanger.domains file.\n This is a simple text file containing directories to the domains\n known to the installation.\n\n \\param[in] filename Name of file to open\n */\n SCXHandle<istream> WebLogicFileReader::OpenNodemanagerDomains(\n const wstring& filename)\n {\n return SCXFile::OpenFstream(filename, ios::in);\n }\n\n /*------------------------------------------------------------------*/\n /**\n Read a simple XML file to find the locations of the both \n the Admin and Managed servers for a WebLogic 11g R1 installation.\n \n Example:\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <domain ...>\n <name>base_domain</name>\n <domain-version>10.3.2.0</domain-version>\n <security-configuration ...>\n ...\n </security-configuration>\n <server>\n <name>AdminServer</name>\n <ssl>\n <name>AdminServer</name>\n <enabled>true</enabled>\n <listen-port>7012</listen-port>\n </ssl>\n <machine>new_UnixMachine_1</machine>\n <listen-port>7011</listen-port>\n <listen-address/>\n </server>\n <server>\n <name>new_ManagedServer_1</name>\n <ssl>\n <name>new_ManagedServer_1</name>\n <enabled>true</enabled>\n <listen-port>7513</listen-port>\n </ssl>\n <machine>new_UnixMachine_1</machine>\n <listen-port>7013</listen-port>\n <listen-address/>\n </server>\n <embedded-ldap>\n <name>base_domain</name>\n <credential-encrypted>{AES}RVX+Cadq8XJ5EvV7/1Ta2qGZrJlxve6t5CEa2A9euGUkYOMDTAwAqytymqDBS00Q</credential-encrypted>\n </embedded-ldap>\n <configuration-version>10.3.2.0</configuration-version>\n <machine xsi:type=\"unix-machineType\">\n <name>new_UnixMachine_1</name>\n <node-manager>\n <name>new_UnixMachine_1</name>\n <listen-address>localhost</listen-address>\n <listen-port>5566</listen-port>\n </node-manager>\n </machine>\n <admin-server-name>AdminServer</admin-server-name>\n </domain>\n\n \\param[in] domainDir Directory of the domain (needed\n for build the path to the server\n \n \\param[in] configXml File object of the XML file\n to open.\n \n \\param[out] instances vector that will contain the\n list of server instances for the\n given domain.\n \n */\n void WebLogicFileReader::ReadConfigXml(\n const SCXFilePath& domainDir,\n const SCXFilePath& configXml,\n vector<SCXHandle<AppServerInstance> >& instances)\n {\n SCX_LOGTRACE(m_log, L\"WebLogicFileReader::ReadConfigXml\");\n SCX_LOGTRACE(m_log, \n wstring(L\"WebLogicFileReader::ReadConfigXml() - \").\n append(L\"Reading the file: \").append(configXml.Get()));\n string xml;\n\n try {\n SCXHandle<istream> reader = \n OpenConfigXml(configXml.Get());\n GetStringFromStream(reader, xml);\n\n XElementPtr domainNode;\n XElement::Load(xml, domainNode);\n \n if (domainNode->GetName() == WEBLOGIC_DOMAIN_XML_NODE)\n {\n string version;\n ReadConfigXmlForVersion(domainNode, version);\n \n string adminServerName;\n ReadConfigXmlForAdminServerName(domainNode, adminServerName);\n \n XElementList serverNodes;\n domainNode->GetChildren(serverNodes);\n for (size_t index = 0; index < serverNodes.size(); ++index)\n {\n if (serverNodes[index]->GetName() == WEBLOGIC_SERVER_XML_NODE)\n {\n bool isAdminServer = false;\n bool isSslEnabled = false;\n string name = \"\";\n string httpPort = \"\";\n string httpsPort = \"\";\n\n XElementList childNodes;\n serverNodes[index]->GetChildren(childNodes);\n for (size_t j = 0; j < childNodes.size(); ++j)\n {\n /*\n * <server>\n * <name>new_ManagedServer_1</name>\n * <ssl>\n * <name>new_ManagedServer_1</name>\n * <enabled>true</enabled>\n * <listen-port>7513</listen-port>\n * </ssl>\n * <machine>new_UnixMachine_1</machine>\n * <listen-port>7013</listen-port>\n * <listen-address/>\n * </server>\n * \n */\n if (childNodes[j]->GetName() == WEBLOGIC_NAME_XML_NODE)\n {\n childNodes[j]->GetContent(name);\n isAdminServer = adminServerName == name; \n } \n else if (childNodes[j]->GetName() == WEBLOGIC_SSL_XML_NODE)\n {\n ReadConfigXmlForSslInformation(\n childNodes[j],\n isSslEnabled,\n httpsPort);\n } \n else if (childNodes[j]->GetName() == WEBLOGIC_LISTEN_PORT_XML_NODE)\n {\n childNodes[j]->GetContent(httpPort);\n } \n }\n /*\n * Having found the server node, \n * read the children\n */\n wstring wideName = StrFromUTF8(name);\n SCXFilePath pathOnDisk;\n pathOnDisk.SetDirectory(domainDir.Get());\n pathOnDisk.AppendDirectory(WEBLOGIC_SERVERS_DIRECTORY);\n pathOnDisk.AppendDirectory(wideName);\n\n if (DoesServerDirectoryExist(pathOnDisk))\n {\n SCX_LOGTRACE(m_log, \n wstring(L\"WebLogicFileReader::ReadConfigXml() - \").\n append(L\"Adding instance for ID='\").append(pathOnDisk.Get()).\n append(L\"'\"));\n // when the HTTP port is not set for the AdminServer,\n // default to the default weblogic HTTP port (i.e. 7001)\n wstring wideHttpPort = StrFromUTF8(httpPort);\n if(isAdminServer && L\"\" == wideHttpPort)\n {\n wideHttpPort = DEFAULT_WEBLOGIC_HTTP_PORT;\n }\n\n // when the HTTPS port is not set, default to\n // the default HTTPS port (i.e. 7002)\n wstring wideHttpsPort = StrFromUTF8(httpsPort);\n if(L\"\" == wideHttpsPort)\n {\n wideHttpsPort = DEFAULT_WEBLOGIC_HTTPS_PORT;\n }\n \n wstring wideVersion = StrFromUTF8(version);\n \n SCXHandle<AppServerInstance> instance(\n new WebLogicAppServerInstance (\n pathOnDisk.GetDirectory()));\n \n instance->SetHttpPort(wideHttpPort);\n instance->SetHttpsPort(wideHttpsPort);\n instance->SetIsDeepMonitored(false, PROTOCOL_HTTPS);\n instance->SetIsRunning(false);\n instance->SetVersion(wideVersion);\n \n instance->SetServer(\n isAdminServer ?\n WEBLOGIC_SERVER_TYPE_ADMIN :\n WEBLOGIC_SERVER_TYPE_MANAGED);\n \n instances.push_back(instance);\n }\n else\n {\n SCX_LOGTRACE(m_log, \n wstring(L\"WebLogicFileReader::ReadConfigXml() - \").\n append(L\"The directory (\").append(pathOnDisk.Get()).\n append(L\") does not exist on disk, ignoring this instance\"));\n }\n }\n }\n }\n }\n catch (SCXFilePathNotFoundException&)\n {\n SCX_LOGERROR(m_log, \n wstring(L\"WebLogicFileReader::ReadConfigXml() - \").\n append(m_installationPath).append(L\" - Could not find file: \").\n append(configXml.Get()));\n }\n catch (SCXUnauthorizedFileSystemAccessException&)\n {\n SCX_LOGERROR(m_log, \n wstring(L\"WebLogicFileReader::ReadConfigXml() - \").\n append(m_installationPath).append(L\" - not authorized to open file: \").\n append(configXml.Get()));\n }\n catch (XmlException& x)\n {\n SCX_LOGERROR(m_log, \n wstring(L\"WebLogicFileReader::ReadConfigXml() - \").\n append(m_installationPath).append(L\" - Could not load XML from file: \").\n append(configXml.Get()));\n }\n }\n\n /*------------------------------------------------------------------*/\n /**\n Read the Admin Server Name \n \n \\param[in] domainNode domain node to read\n\n \\param[out] adminServerName discovered/parsed name\n */\n void WebLogicFileReader::ReadConfigXmlForAdminServerName(\n const XElementPtr& domainNode,\n string& adminServerName)\n {\n XElementList adminNodes;\n domainNode->GetChildren(adminNodes);\n for (size_t index = 0; index < adminNodes.size(); ++index)\n {\n if (adminNodes[index]->GetName() == WEBLOGIC_ADMIN_SERVER_XML_NODE)\n {\n adminNodes[index]->GetContent(adminServerName);\n }\n } \n }\n \n /*------------------------------------------------------------------*/\n /**\n Read the SSL information from the config.xml \n \n \\param[in] sslNode SSL node to read.\n\n \\param[out] sslEnabled is SSL enabled\n \n \\param[out] httpsPort HTTPS Port discovered\n */\n void WebLogicFileReader::ReadConfigXmlForSslInformation(\n const XElementPtr& sslNode,\n bool& sslEnabled,\n string& httpsPort)\n {\n sslEnabled =false;\n httpsPort = \"\";\n \n XElementList sslChildrenNodes;\n sslNode->GetChildren(sslChildrenNodes);\n for (size_t index = 0; index < sslChildrenNodes.size(); ++index)\n {\n if (sslChildrenNodes[index]->GetName() == WEBLOGIC_SSL_ENABLED_XML_NODE)\n {\n wstring wide;\n sslChildrenNodes[index]->GetContent(wide);\n wide = StrToLower(wide);\n sslEnabled = TRUE_TEXT == wide;\n }\n else if (sslChildrenNodes[index]->GetName() == WEBLOGIC_LISTEN_PORT_XML_NODE)\n {\n sslChildrenNodes[index]->GetContent(httpsPort);\n }\n } \n }\n\n /*------------------------------------------------------------------*/\n /**\n Read the Admin Server Name \n \n \\param[in] domainNode domain node to read\n\n \\param[out] version discovered/parsed version\n */\n void WebLogicFileReader::ReadConfigXmlForVersion(\n const XElementPtr& domainNode,\n string& version)\n {\n XElementList versionNodes;\n domainNode->GetChildren(versionNodes);\n for (size_t index = 0; index < versionNodes.size(); ++index)\n {\n if (versionNodes[index]->GetName() == WEBLOGIC_VERSION_XML_NODE)\n {\n versionNodes[index]->GetContent(version);\n }\n } \n }\n \n /*------------------------------------------------------------------*/\n /**\n Read a simple XML file to find the locations of the domains for\n this WebLogic 11g R1 installation.\n \n Example:\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <domain-registry xmlns=\"http://xmlns.oracle.com/weblogic/domain-registry\">\n <domain location=\"/opt/Oracle/Middleware/user_projects/domains/base_domain\"/>\n </domain-registry> \n \n \\param[in] domainRegistryXml File object of the XML file\n to open.\n \n \\param[out] domains vector that will contain the\n list of discovered domains.\n */\n void WebLogicFileReader::ReadDomainRegistryXml(\n const SCXFilePath& domainRegistryXml,\n vector<SCXFilePath>& domains)\n {\n string xml;\n\n try {\n SCXHandle<istream> reader = \n OpenDomainRegistryXml(domainRegistryXml.Get());\n GetStringFromStream(reader, xml);\n\n XElementPtr domainRegistryNode;\n XElement::Load(xml, domainRegistryNode);\n if (domainRegistryNode->GetName() == WEBLOGIC_DOMAIN_REGISTRY_XML_NODE)\n {\n XElementList domainNodes;\n domainRegistryNode->GetChildren(domainNodes);\n for (size_t index = 0; index < domainNodes.size(); ++index)\n {\n string location;\n if (domainNodes[index]->GetName() == WEBLOGIC_DOMAIN_XML_NODE && \n domainNodes[index]->GetAttributeValue(WEBLOGIC_LOCATION_XML_ATTRIBUTE, location))\n {\n wstring wideLocation = StrFromUTF8(location);\n SCXFilePath domainPath;\n domainPath.SetDirectory(wideLocation); \n domains.push_back(domainPath);\n }\n }\n }\n }\n catch (SCXFilePathNotFoundException&)\n {\n SCX_LOGERROR(m_log, \n wstring(L\"WebLogicFileReader::ReadDomainRegistryXml() - \").\n append(m_installationPath).append(L\" - Could not find file: \").\n append(domainRegistryXml.Get()));\n }\n catch (SCXUnauthorizedFileSystemAccessException&)\n {\n SCX_LOGERROR(m_log, \n wstring(L\"WebLogicFileReader::ReadDomainRegistryXml() - \").\n append(m_installationPath).append(L\" - not authorized to open file: \").\n append(domainRegistryXml.Get()));\n }\n catch (XmlException&)\n {\n SCX_LOGERROR(m_log, \n wstring(L\"WebLogicFileReader::ReadDomainRegistryXml() - \").\n append(m_installationPath).append(L\" - Could not load XML from file: \").\n append(domainRegistryXml.Get()));\n }\n }\n\n /*------------------------------------------------------------------*/\n /**\n Read the nodemanager.domains file to get a list of the\n WebLogic 10g domains associated with the installation.\n \n Note: this file is located up the tree in a 'well-known' location.\n i.e. /opt/Oracle/Middleware/wlserver_10.3/common/nodemanager/nodemanager.domains\n \n Example:\n #Domains and directories created by Configuration Wizard\n #Tue Apr 12 15:23:12 PDT 2011\n base_domain=/opt/Oracle/Middleware/user_projects/domains/base_domain \n \n \\param[in] nodemanagerDomains File object of the text file\n to open.\n \n \\param[out] domains vector that will be populated with\n list of discovered domains.\n \n */\n void WebLogicFileReader::ReadNodemanagerDomains(\n const SCXFilePath& nodemanagerDomains,\n vector<SCXFilePath>& domains)\n {\n string content;\n\n try {\n \n /*\n * Parse the INI file. \n * \n * After a '#', assume the rest of the line is a comment.\n * The file should consist of name/value pairs seperated\n * by an '='. \n */\n SCXHandle<istream> reader = \n OpenNodemanagerDomains(nodemanagerDomains.Get());\n \n while (SCXStream::IsGood(*reader))\n {\n string buffer;\n getline(*reader, buffer);\n \n size_t delimiterLocation = buffer.find(INI_DELIMITER);\n if (string::npos != delimiterLocation)\n {\n string narrowPath = buffer.substr(delimiterLocation + 1);\n wstring widePath = StrFromUTF8(narrowPath);\n SCXFilePath domainPath;\n domainPath.SetDirectory(widePath);\n domains.push_back(domainPath);\n }\n }\n }\n catch (SCXFilePathNotFoundException&)\n {\n SCX_LOGERROR(m_log, \n wstring(L\"WebLogicFileReader::ReadNodemanagerDomains() - \").\n append(m_installationPath).append(L\" - Could not find file: \").\n append(nodemanagerDomains.Get()));\n }\n catch (SCXUnauthorizedFileSystemAccessException&)\n {\n SCX_LOGERROR(m_log, \n wstring(L\"WebLogicFileReader::ReadNodemanagerDomains() - \").\n append(m_installationPath).append(L\" - not authorized to open file: \").\n append(nodemanagerDomains.Get()));\n }\n }\n \n /*------------------------------------------------------------------*/\n /**\n Read all lines from a stream and save in a string\n\n \\param[in] reader Stream to read from\n \\param[out] content String to return content in\n */\n void WebLogicFileReader::GetStringFromStream(\n SCXHandle<istream> reader, \n string& content)\n {\n content = \"\";\n while (SCXStream::IsGood(*reader))\n {\n string buffer;\n getline(*reader, buffer);\n content.append(buffer);\n content.append(\"\\n\");\n }\n }\n\n /*------------------------------------------------------------------*/\n /**\n Read all lines from a stream and save in a string\n\n \\param[in] path Full Path to an installation home \n */\n void WebLogicFileReader::SetPath(const wstring& path)\n {\n m_installationPath = path;\n }\n \n /*------------------------------------------------------------------*/\n /**\n Constructor\n\n */ \n WebLogicAppServerEnumeration::WebLogicAppServerEnumeration(\n SCXHandle<IWebLogicFileReader> reader)\n {\n m_log = SCXLogHandleFactory::GetLogHandle(L\"scx.core.common.pal.system.appserver.weblogicappserverenumeration\");\n SCX_LOGTRACE(m_log, L\"WebLogicAppServerEnumeration Constructor\");\n\n m_reader = reader;\n }\n\n /*------------------------------------------------------------------*/\n /**\n Destructor\n\n */\n WebLogicAppServerEnumeration::~WebLogicAppServerEnumeration()\n {\n SCX_LOGTRACE(m_log, L\"WebLogicAppServerEnumeration destructor\");\n }\n\n /*------------------------------------------------------------------*/\n /**\n GetInstances\n\n \\param[in] installations List of directories containing\n installs of WebLogic\n \\param[out] result output list of WebLogic application\n server instances\n\n */\n void WebLogicAppServerEnumeration::GetInstances(\n vector<wstring>& installations,\n vector<SCXHandle<AppServerInstance> >& result)\n {\n SCX_LOGTRACE(m_log, L\"WebLogicAppServerEnumeration::GetInstances()\");\n\n // the given list of installations has no guranteed ordering. Use the\n // STL to sort the incoming vector and find the unique instances.\n sort(installations.begin(), installations.end());\n vector<wstring>::iterator uniqueEnd = unique(installations.begin(), installations.end());\n installations.resize(uniqueEnd-installations.begin());\n\n // for each installation, add all discovered instances associated with that\n // installation and domain to the result set.\n result.clear();\n\n for (vector<wstring>::iterator installation = installations.begin();\n installation != installations.end();\n ++installation)\n {\n m_reader->SetPath(*installation);\n vector<SCXFilePath> domains = m_reader->GetDomains();\n \n for (vector<SCXFilePath>::iterator domain = domains.begin();\n domain != domains.end();\n ++domain)\n {\n SCX_LOGTRACE(m_log, \n wstring(L\"WebLogicAppServerEnumeration::GetInstances() - \").\n append(L\"Searching for servers in the domain '\").\n append((*domain).Get()).append(L\"'\"));\n\n m_reader->GetInstances(*domain, result);\n }\n }\n }\n}\n/*----------------------------E-N-D---O-F---F-I-L-E---------------------------*/\n" }, { "alpha_fraction": 0.6670745015144348, "alphanum_fraction": 0.6780861616134644, "avg_line_length": 46.05757522583008, "blob_id": "b265f65f4be9fb7cfa2b88aef242554a26b12c97", "content_id": "72b2c6069294c1257f4df2d844602c92f4cf70c9", "detected_licenses": [ "MS-PL" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 15529, "license_type": "permissive", "max_line_length": 123, "num_lines": 330, "path": "/test/code/providers/appserver_provider/appserverprovider_test.cpp", "repo_name": "microsoft/SCXcore", "src_encoding": "UTF-8", "text": "/*--------------------------------------------------------------------------------\n Copyright (c) Microsoft Corporation. All rights reserved.\n\n*/\n/**\n \\file\n\n \\brief Tests for the appserver provider\n\n \\date 2011-05-05\n\n*/\n/*----------------------------------------------------------------------------*/\n\n#include <scxcorelib/scxcmn.h>\n#include <scxsystemlib/scxostypeinfo.h>\n#include <testutils/scxunit.h>\n#include <testutils/providertestutils.h>\n#include \"appserver/appserverenumeration.h\"\n#include \"appserver/websphereappserverinstance.h\"\n#include \"appserver/appserverprovider.h\"\n#include \"SCX_Application_Server_Class_Provider.h\"\n\nusing namespace SCXCore;\nusing namespace SCXCoreLib;\nusing namespace SCXSystemLib;\n\nclass AppServerTestEnumeration : public AppServerEnumeration\n{\npublic:\n AppServerTestEnumeration() {};\n ~AppServerTestEnumeration() {};\n\n virtual void Init()\n {\n Update(false);\n };\n\n virtual void Update(bool /*updateInstances*/)\n {\n if (Size() == 0)\n {\n SCXHandle<AppServerInstance> inst = SCXHandle<AppServerInstance>(\n new AppServerInstance(L\"/opt/jboss-5.1.0.GA/\", L\"JBoss\"));\n\n inst->SetHttpPort(L\"8280\");\n inst->SetHttpsPort(L\"8643\");\n inst->SetVersion(L\"5.1.0.GA\");\n\n AddInstance(inst);\n\n SCXHandle<WebSphereAppServerInstance> inst2 = SCXHandle<WebSphereAppServerInstance>(\n new WebSphereAppServerInstance(L\"/opt/websphere/AppServer/profiles/AppSrv01/\",\n L\"Node01Cell\", L\"Node01\", L\"AppSrv01\", L\"server1\"));\n\n inst2->SetHttpPort(L\"9080\");\n inst2->SetHttpsPort(L\"9443\");\n inst2->SetVersion(L\"7.0.0.0\");\n\n AddInstance(inst2);\n }\n };\n\n virtual void CleanUp() {};\n};\n\nclass AppServerProviderTestPALDependencies : public AppServerProviderPALDependencies\n{\npublic:\n virtual ~AppServerProviderTestPALDependencies() {};\n \n virtual SCXHandle<AppServerEnumeration> CreateEnum()\n {\n return SCXHandle<AppServerEnumeration>(new AppServerTestEnumeration());\n }\n};\n\nclass SCXASProviderTest : public CPPUNIT_NS::TestFixture\n{\n CPPUNIT_TEST_SUITE( SCXASProviderTest );\n\n CPPUNIT_TEST( callDumpStringForCoverage );\n CPPUNIT_TEST( TestDoEnumInstances );\n CPPUNIT_TEST( TestDoGetInstanceGood );\n CPPUNIT_TEST( TestDoGetInstanceNotFound );\n CPPUNIT_TEST( TestEnumerateKeysOnly );\n CPPUNIT_TEST( TestVerifyKeyCompletePartial );\n CPPUNIT_TEST( TestDoInvokeMethodNoAppServer );\n CPPUNIT_TEST( TestDoInvokeMethodMissingArg );\n CPPUNIT_TEST( TestDoInvokeMethodGood );\n\n CPPUNIT_TEST_SUITE_END();\n\nprivate:\n std::vector<std::wstring> m_keyNames;\n\npublic:\n void setUp(void)\n {\n m_keyNames.push_back(L\"Name\");\n\n std::wstring errMsg;\n SCXCore::g_AppServerProvider.UpdateDependencies(SCXCoreLib::SCXHandle<AppServerProviderPALDependencies>(\n new AppServerProviderTestPALDependencies()));\n TestableContext context;\n SetUpAgent<mi::SCX_Application_Server_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context.WasRefuseUnloadCalled() );\n }\n\n void tearDown(void)\n {\n std::wstring errMsg;\n TestableContext context;\n TearDownAgent<mi::SCX_Application_Server_Class_Provider>(context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context.WasRefuseUnloadCalled() );\n }\n\n void callDumpStringForCoverage()\n {\n CPPUNIT_ASSERT(SCXCore::g_AppServerProvider.DumpString().find(L\"ApplicationServerProvider\") != std::wstring::npos);\n }\n\n void TestDoEnumInstances()\n {\n std::wstring errMsg;\n TestableContext context;\n\n StandardTestEnumerateInstances<mi::SCX_Application_Server_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 2u, context.Size());\n ValidateInstance0(context[0], CALL_LOCATION(errMsg));\n ValidateInstance1(context[1], CALL_LOCATION(errMsg));\n }\n\n void ValidateInstance0(const TestableInstance& instance, std::wstring errMsg)\n {\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"/opt/jboss-5.1.0.GA/\",\n instance.GetKey(L\"Name\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 17u, instance.GetNumberOfProperties());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"SCX Application Server\", instance.GetProperty(\n L\"Caption\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Represents a JEE Application Server\", instance.GetProperty(\n L\"Description\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"8280\", instance.GetProperty(\n L\"HttpPort\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"8643\", instance.GetProperty(\n L\"HttpsPort\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"5.1.0.GA\", instance.GetProperty(\n L\"Version\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"5\", instance.GetProperty(\n L\"MajorVersion\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", instance.GetProperty(\n L\"Port\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", instance.GetProperty(\n L\"Protocol\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"/opt/jboss-5.1.0.GA/\", instance.GetProperty(\n L\"DiskPath\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"JBoss\", instance.GetProperty(\n L\"Type\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, instance.GetProperty(\n L\"IsDeepMonitored\", CALL_LOCATION(errMsg)).GetValue_MIBoolean(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, instance.GetProperty(\n L\"IsRunning\", CALL_LOCATION(errMsg)).GetValue_MIBoolean(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", instance.GetProperty(\n L\"Profile\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", instance.GetProperty(\n L\"Cell\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", instance.GetProperty(\n L\"Node\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", instance.GetProperty(\n L\"Server\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n }\n\n void ValidateInstance1(const TestableInstance& instance, std::wstring errMsg)\n {\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"AppSrv01-Node01Cell-Node01-server1\",\n instance.GetKey(L\"Name\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 17u, instance.GetNumberOfProperties());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"SCX Application Server\", instance.GetProperty(\n L\"Caption\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Represents a JEE Application Server\", instance.GetProperty(\n L\"Description\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"9080\", instance.GetProperty(\n L\"HttpPort\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"9443\", instance.GetProperty(\n L\"HttpsPort\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"7.0.0.0\", instance.GetProperty(\n L\"Version\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"7\", instance.GetProperty(\n L\"MajorVersion\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", instance.GetProperty(\n L\"Port\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"\", instance.GetProperty(\n L\"Protocol\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"/opt/websphere/AppServer/profiles/AppSrv01/\", instance.GetProperty(\n L\"DiskPath\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"WebSphere\", instance.GetProperty(\n L\"Type\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, instance.GetProperty(\n L\"IsDeepMonitored\", CALL_LOCATION(errMsg)).GetValue_MIBoolean(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, instance.GetProperty(\n L\"IsRunning\", CALL_LOCATION(errMsg)).GetValue_MIBoolean(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"AppSrv01\", instance.GetProperty(\n L\"Profile\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Node01Cell\", instance.GetProperty(\n L\"Cell\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"Node01\", instance.GetProperty(\n L\"Node\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"server1\", instance.GetProperty(\n L\"Server\", CALL_LOCATION(errMsg)).GetValue_MIString(CALL_LOCATION(errMsg)));\n }\n\n void TestDoGetInstanceGood()\n {\n std::wstring errMsg;\n\n std::vector<std::wstring> keyValues0;\n keyValues0.push_back(L\"/opt/jboss-5.1.0.GA/\");\n TestableContext context0;\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, MI_RESULT_OK, (GetInstance<mi::SCX_Application_Server_Class_Provider,\n mi::SCX_Application_Server_Class>(m_keyNames, keyValues0, context0, CALL_LOCATION(errMsg))));\n ValidateInstance0(context0[0], CALL_LOCATION(errMsg));\n\n std::vector<std::wstring> keyValues1;\n keyValues1.push_back(L\"AppSrv01-Node01Cell-Node01-server1\");\n TestableContext context1;\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, MI_RESULT_OK, (GetInstance<mi::SCX_Application_Server_Class_Provider,\n mi::SCX_Application_Server_Class>(m_keyNames, keyValues1, context1, CALL_LOCATION(errMsg))));\n ValidateInstance1(context1[0], CALL_LOCATION(errMsg));\n }\n\n void TestDoGetInstanceNotFound()\n {\n std::wstring errMsg;\n\n std::vector<std::wstring> keyValues;\n keyValues.push_back(L\"dummy\");\n TestableContext context;\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, MI_RESULT_NOT_FOUND,\n (GetInstance<mi::SCX_Application_Server_Class_Provider,\n mi::SCX_Application_Server_Class>(m_keyNames, keyValues, context, CALL_LOCATION(errMsg))));\n }\n\n void TestEnumerateKeysOnly()\n {\n std::wstring errMsg;\n TestableContext context;\n StandardTestEnumerateKeysOnly<mi::SCX_Application_Server_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 2u, context.Size());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"/opt/jboss-5.1.0.GA/\",\n context[0].GetKey(L\"Name\", CALL_LOCATION(errMsg)));\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, L\"AppSrv01-Node01Cell-Node01-server1\",\n context[1].GetKey(L\"Name\", CALL_LOCATION(errMsg)));\n }\n\n void TestVerifyKeyCompletePartial()\n {\n std::wstring errMsg;\n StandardTestVerifyGetInstanceKeys<mi::SCX_Application_Server_Class_Provider,\n mi::SCX_Application_Server_Class>(m_keyNames, CALL_LOCATION(errMsg));\n }\n\n void InvokeSetDeepMonitoring(mi::SCX_Application_Server_SetDeepMonitoring_Class &param, MI_Result result,\n std::wstring errMsg)\n {\n TestableContext context;\n mi::SCX_Application_Server_Class instanceName;\n mi::Module Module;\n mi::SCX_Application_Server_Class_Provider agent(&Module);\n agent.Invoke_SetDeepMonitoring(context, NULL, instanceName, param);\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, result, context.GetResult());\n // We expect one instance to be returned.\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, 1u, context.Size());\n if (context.GetResult() == MI_RESULT_OK)\n {\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context[0].GetProperty(\"MIReturn\",\n CALL_LOCATION(errMsg)).GetValue_MIBoolean(CALL_LOCATION(errMsg)));\n }\n else\n {\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, false, context[0].GetProperty(\"MIReturn\",\n CALL_LOCATION(errMsg)).GetValue_MIBoolean(CALL_LOCATION(errMsg)));\n }\n }\n\n void TestDoInvokeMethodNoAppServer()\n {\n std::wstring errMsg;\n mi::SCX_Application_Server_SetDeepMonitoring_Class param;\n param.id_value(\"dummy\");\n param.deep_value(true);\n InvokeSetDeepMonitoring(param, MI_RESULT_NOT_FOUND, CALL_LOCATION(errMsg));\n }\n\n void TestDoInvokeMethodMissingArg()\n {\n std::wstring errMsg;\n\n // Test for failure if id argument is missing.\n mi::SCX_Application_Server_SetDeepMonitoring_Class param0;\n param0.deep_value(true);\n InvokeSetDeepMonitoring(param0, MI_RESULT_INVALID_PARAMETER, CALL_LOCATION(errMsg));\n\n // Test for failure if deep argument is missing.\n mi::SCX_Application_Server_SetDeepMonitoring_Class param1;\n param1.id_value(\"/opt/jboss-5.1.0.GA/\");\n InvokeSetDeepMonitoring(param1, MI_RESULT_INVALID_PARAMETER, CALL_LOCATION(errMsg));\n \n }\n\n void TestDoInvokeMethodGood()\n {\n std::wstring errMsg;\n mi::SCX_Application_Server_SetDeepMonitoring_Class param;\n param.id_value(\"/opt/jboss-5.1.0.GA/\");\n param.deep_value(true);\n InvokeSetDeepMonitoring(param, MI_RESULT_OK, CALL_LOCATION(errMsg));\n\n TestableContext context;\n StandardTestEnumerateInstances<mi::SCX_Application_Server_Class_Provider>(\n m_keyNames, context, CALL_LOCATION(errMsg));\n CPPUNIT_ASSERT_MESSAGE(ERROR_MESSAGE, 0 < context.Size());\n CPPUNIT_ASSERT_EQUAL_MESSAGE(ERROR_MESSAGE, true, context[0].GetProperty(\n L\"IsDeepMonitored\", CALL_LOCATION(errMsg)).GetValue_MIBoolean(CALL_LOCATION(errMsg)));\n }\n};\n\nCPPUNIT_TEST_SUITE_REGISTRATION( SCXASProviderTest );\n" } ]
183
Abuelodelanada/hume
https://github.com/Abuelodelanada/hume
0f882e7a83c0b18350f152f35f1f42effce5a2d2
6310a306c5c1363cd6a8ecca1f1cb3b00fc27366
d021e9bf3ac63f640c86b14750d85ac1d7cc12f8
refs/heads/master
2022-06-12T03:29:37.105710
2020-05-07T01:11:47
2020-05-07T01:11:47
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6474359035491943, "alphanum_fraction": 0.6769230961799622, "avg_line_length": 32.91304397583008, "blob_id": "6021b1d7633e228187a8cbed1ce942cea662f46e", "content_id": "fabc45f11dba6e0eca8dcd70dbfa5353cbd88b61", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 780, "license_type": "permissive", "max_line_length": 78, "num_lines": 23, "path": "/humetools.py", "repo_name": "Abuelodelanada/hume", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport sys\nimport argparse\n\n\nclass NotImplementedAction(argparse.Action):\n \"\"\" This class allows to work on getting your Argparse object\n ready even if nothing useful happens when used.\n\n Usage:\n Just set action=NotImplementedAction when calling add_argument, like this:\n\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--missing\",\n help=\"This will do something in the future\",\n action=NotImplementedAction)\n\n GIST URL: https://gist.github.com/buanzo/2a004348340ef79b0139ab38f719cf1e\n \"\"\"\n def __call__(self, parser, namespace, values, option_string=None):\n msg = 'Argument \"{}\" still not implemented.'.format(option_string)\n sys.exit(msg)\n" }, { "alpha_fraction": 0.4769230782985687, "alphanum_fraction": 0.6769230961799622, "avg_line_length": 15.25, "blob_id": "66c182b52c11ea6dbef2fec6ed127641a4f7433c", "content_id": "3e3f295348d1e273248c9e6dd377bca359ebce57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 65, "license_type": "permissive", "max_line_length": 21, "num_lines": 4, "path": "/requirements.txt", "repo_name": "Abuelodelanada/hume", "src_encoding": "UTF-8", "text": "python_pidfile==3.0.0\npsutil==5.7.0\npidfile==0.1.1\npyzmq==19.0.0\n" }, { "alpha_fraction": 0.7560399770736694, "alphanum_fraction": 0.7569482326507568, "avg_line_length": 40.082088470458984, "blob_id": "3d7f8afc9c33bee7475996d93bb9648e7d9822f9", "content_id": "519f95048f2c0d280706579dcc16a5615fe5d13f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 5505, "license_type": "permissive", "max_line_length": 215, "num_lines": 134, "path": "/README.md", "repo_name": "Abuelodelanada/hume", "src_encoding": "UTF-8", "text": "# hume\n\nHume is an agnostic system administration tool/framework. It is in fact a\ncommand line tool to call from your shell scripts to centrally report a\ncertain process/script status, share a piece of data, etc. Read on!\n\nEvery sysadmin is a universe. The same way there are awesome tools for\npentesters such as faraday, which allows each pentester to work using the\ntools he likes, and still be able to structurally share and enhance the data\nthat comes out of them in a central location, hume provides the same for\nsysadmins, devops teams, etc.\n\n# CURRENT STATUS / NEEDS\n\nhume client works and can be used in sysadmin/cron scripts\n\nhumed works in localhost mode only, but master/slave ideas have been\nconsidered (see below) - There is NO QUERY TOOL, but you can get data off\nthe humed.sqlite3 database\n\nWe need a UI/UX designer/developer, maybe a REST API for querytools.\n\n# THIS IS A WORK IN PROGRESS\n\nHume will include a dashboard for queries. If someone writes it. I suck at\nhtml5/js. But the command line tool will allow you to get status on a\nprocess, grouped by hostname. Search by tags, etc.\n\n## What will hume be?\n\nImagine this: You have some cron scripts. They need to run correctly, and you need to know\nif anything happens. You usually check logs via email or some cool\ndashboard. Yeah. But it gets boring, repetitive and you end up not checking\nthe logs. It is a well known sysadmin syndrome.\n\nSo, write those scripts adding hume commands. Something like this:\n```\n#!/bin/bash\n# This script updates wordpress core, plugins and themes\n# on a number of different directories.\nwpcli='/usr/local/bin/wp'\n\n# Maybe hume could read this variables\nHTASK=\"WORDPRESS_UPDATE\"\nHTAGS=\"wordpress,cron,updates\"\n\nhume -c counter-start -t \"$HTASK\" -T \"$HTAGS\" -m \"Starting wordpress update cron process\"\nfor dir in \"/var/www/site1/htdocs\" \"/var/www/site2/htdocs\" \"/var/www/site3/htdocs\"\ndo\n\thume -t \"$HTASK\" -T \"$HTAGS\" -L info -m \"Updating in $dir\"\n cd $dir || hume -t \"$HTASK\" -T \"$HTAGS\" -L error -m \"$dir does not exist\"\n $wpcli core update || hume -t \"$HTASK\" -T \"$HTAGS\" -L error -m \"Core update error in $dir\"\n $wpcli plugin update --all || hume -t \"$HTASK\" -T \"$HTAGS\" -L error -m \"Plugins update error in $dir\"\n $wpcli theme update --all || hume -t \"$HTASK\" -T \"$HTAGS\" -L error -m \"Themes update error in $dir\"\n\thume -t \"$HTASK\" -T \"$HTAGS\" -L info -m \"Update process for $dir finished\"\ndone\nhume -c counter-stop -t \"$HTASK\" -T \"$HTAGS\" -m \"Finished wordpress update cron task\"\n```\n\nThen you could check the status of the latest run of the task:\n\n```\n#!/bin/bash\n# echo check status of wordpress_update task for webserver host\nhumequery -t WORDPRESS_UPDATE --latest --hostname=\"webserver\"\n```\n\nAnd you would get the list of every hume event, plus a summary, including \n\n# Implementation, concepts, ideas\n## Ideas for implementation\n\nhume uses zeromq over loopback to connecto to a hume daemon on the same\nserver. It must reduce its footprint as much as possible, we dont want hume\nto slow down other processes. I am testing zmq-ipc and zmq-tcp, as well as\nPUSH/PULL and REQ/REP scenarios. A systemd unit file is included for the hume\ndaemon (humed). A pid file will be read and checked by the hume client to\nknow beforehand if the hume daemon is working. A watchdog script that\ntriggers a special hume mode should exist to report working status. A lack\nof watchdog-pinging will help the devops team detect the situation quickly.\n\nThe hume daemon will filter/store the hume packets, and send them to the\nmain repository which will be a relational database coupled with redis for\ncurrent-data storage and querying.\n\n## Weird future concepts\n\n* Signed script verification (imagine, the script is created, signed, hume\nchecks the signature and executes/notifies if signature does not verify)\n\n* Of course, authentication and authorization will need to be implemented.\n\n* task templates: imagine this: 'hume template get wordpress_backup': You\nget a wordpress_backup bash script that's only the required hume tasknames,\nrequired informational stages. All comments. You just write the script to\nfollow the devops pattern.\n\n* watchdog command: 'This task needs to run daily' -> cron failed? no hume\ncommand that lets the watchdog now it is effectively running daily.\n\n\nBut first lets make a useful, working prototype.\n\n\n# Components\n\n## hume\n\ncalled from within scripts. writes to a local publish queue. maybe a\nfallback to sqlite that humed can read on startup?\n\n## humed\n\nits the local publish queue. consumes messages, applies\nfiltering/preprocessing, security, etc. Can be set to master or slave mode. \nThis way the hume CLI tool will just push gather some info, then push zmq\nmessages to localhost humed. if localhost humed is a slave, it will have a\nthread to send pending hume messages to the master. query tool should work\nagainst slave or master.\n\n## TO DEFINE: dashboard or fluentd integration\n\nIdea for a dashboard: instead, become a fluentd data source: https://docs.fluentd.org/language-bindings/python\n\n# DEVELOPMENT NOTES\n\n## Define Basic CLI usage\n* register and start process execution\n* add events to process --warn, --info, --error, --debug\n* event flagging for process timeline (instead of starting/stopping the watch, as every event including start/stop of process will include timestamp, we use event flagging to indicate events in the process timeline)\n* stop process / deregister\n\n## Miscelaneous\n* mention export LINENO before calling hume\n" }, { "alpha_fraction": 0.5378327965736389, "alphanum_fraction": 0.543904721736908, "avg_line_length": 28.12925148010254, "blob_id": "2017dbf5252e3fd9033d5d65a94b866a454ef4f5", "content_id": "91d93d1f98e0dd0c610f1609ed642427ff51bebc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4282, "license_type": "permissive", "max_line_length": 76, "num_lines": 147, "path": "/humed.py", "repo_name": "Abuelodelanada/hume", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3\nimport zmq\nimport json\nimport pidfile\nimport sqlite3\nimport datetime\n# import systemd.daemon\nfrom pprint import pprint\n\nDEBUG = True # TODO: set to False :P\n# hume is VERY related to logs\n# better /var/humed/humed.sqlite3 ?\nDBPATH = '/var/log/humed.sqlite3'\nif DEBUG:\n DBPATH = './humed.sqlite3'\n\n\nclass Humed():\n def __init__(self,\n listen_url='tcp://127.0.0.1:198'):\n self.config = {}\n self.config['listen_url'] = listen_url\n if self.prepare_db() is False:\n sys.exit('Humed: Error preparing database')\n\n def prepare_db(self):\n print('Preparing DB')\n try:\n self.conn = sqlite3.connect(DBPATH)\n except Exception as ex:\n print(ex)\n print('Humed: cannot connect to sqlite3 on \"{}\"'.format(DBPATH))\n self.cursor = self.conn.cursor()\n try:\n sql = '''CREATE TABLE IF NOT EXISTS\n transfers (ts timestamp, sent boolean, hume text)'''\n print(sql)\n self.cursor.execute(sql)\n self.conn.commit()\n except Exception as ex:\n print(ex)\n return(False)\n print('DB OK')\n return(True)\n\n def transfer_ok(self, rowid):\n try:\n sql = 'UPDATE transfers SET sent=1 WHERE rowid=?'\n self.cursor.execute(sql, (rowid,))\n self.conn.commit()\n except Exception as ex:\n print(ex)\n return(False)\n return(True)\n\n def add_transfer(self, hume):\n try:\n hume = json.dumps(hume)\n except Exception as ex:\n print('Humed - add_transfer() json dumps exception:')\n print(ex)\n return(None) # FIX: should we exit?\n try:\n now = datetime.datetime.now()\n sql = 'INSERT INTO transfers(ts, sent, hume) VALUES (?,?,?)'\n self.cursor.execute(sql, (now, 0, hume,))\n self.conn.commit()\n except Exception as ex:\n print('Humed: add_transfer() Exception:')\n print(ex)\n return(None)\n return(self.cursor.lastrowid)\n\n def list_transfers(self, pending=False):\n if pending is True:\n sql = 'SELECT rowid,* FROM transfers WHERE sent = 0'\n else:\n sql = 'SELECT rowid,* FROM transfers'\n lista = []\n rows = []\n try:\n self.cursor.execute(sql)\n rows = self.cursor.fetchall()\n except Exception as ex:\n print(ex)\n\n for row in rows:\n lista.append(row)\n return(lista)\n\n def processs_transfers(self):\n # TODO: The master/slave thingy...\n pendientes = self.list_transfers(pending=True)\n pprint(pendientes)\n for item in pendientes:\n # TODO: send to master-hume\n print(item)\n # if sent ok then:\n # self.transfer_ok(archivo=archivo)\n # if error return(False)\n return(True)\n\n def run(self):\n # Humed main loop\n # TODO: 1 - Initiate process-pending-humes-thread\n # 2 - Bind and Initiate loop\n sock = zmq.Context().socket(zmq.PULL)\n sock.bind(self.config['listen_url'])\n # 2a - Await hume message over zmp\n while True:\n hume = {}\n try:\n hume = json.loads(sock.recv())\n except Exception as ex:\n print(ex)\n print('Cannot json-loads the received message. Mmmmm...')\n # 2b - insert it into transfers\n self.add_transfer(hume)\n # pprint(self.list_transfers(pending=True))\n # TODO: 2c - log errors and rowids\n # TODO: deal with exits/breaks\n\n\ndef main():\n print('Starting process')\n try:\n with pidfile.PIDFile():\n print('Process started')\n except pidfile.AlreadyRunningError:\n print('Already running.')\n print('Exiting')\n sys.exit(1)\n\n # Initialize Stuff\n print('initializing hume daemon')\n humed = Humed()\n\n # TODO: Tell systemd we are ready\n # systemd.daemon.notify('READY=1')\n\n print('Ready. serving...')\n humed.run()\n\n\nif __name__ == '__main__':\n # TODO: Add argparse and have master and slave modes\n main()\n" }, { "alpha_fraction": 0.5061601400375366, "alphanum_fraction": 0.5116358399391174, "avg_line_length": 32.58620834350586, "blob_id": "14f1dc41356a82575e8ac93a67332f74e4759500", "content_id": "76ce2201b15963f30ee3468905bba0f44b665754", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5844, "license_type": "permissive", "max_line_length": 78, "num_lines": 174, "path": "/hume.py", "repo_name": "Abuelodelanada/hume", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\nimport os\nimport zmq\nimport sys\nimport stat\nimport psutil\nimport argparse\nimport json\nfrom pprint import pprint\n\nfrom humetools import NotImplementedAction\n\n\nclass Hume():\n def __init__(self, args):\n # self.config = {'url': 'ipc:///tmp/hume.sock'}\n self.config = {'url': 'tcp://127.0.0.1:198'}\n\n # args\n self.args = args\n\n # Prepare object to send\n # Might end up moving some of this stuff around\n # But I like focusing blocks to be developed\n # in such a way that the code can grow organically\n # and be coder-assistive\n self.reqObj = {}\n # To store information related to how hume was executed\n self.reqObj['process'] = {}\n # Hume-specific information\n self.reqObj['hume'] = {}\n self.reqObj['hume']['level'] = args.level\n self.reqObj['hume']['msg'] = args.msg\n self.reqObj['hume']['tags'] = args.tags\n self.reqObj['hume']['task'] = args.task\n\n if self.args.append_pstree:\n self.reqObj['process']['tree'] = self.get_pstree()\n\n ln = self.get_lineno()\n if ln is not None:\n self.reqObj['process']['line_number'] = ln\n del ln\n\n if (len(self.reqObj['process']) == 0):\n del(self.reqObj['process'])\n\n # TODO: process args and add items to reqObj\n pprint(self.args)\n\n #\n pprint(self.reqObj)\n\n print(self.config['url'])\n\n if self.config['url'].startswith('ipc://'):\n if self.test_unix_socket(config['url']):\n print('socket ok')\n else:\n print('socket not writable or other error')\n sys.exit(1)\n\n def test_unix_socket(self, url):\n path = url.replace('ipc://', '')\n if not os.path.exists(path):\n return(False)\n mode = os.stat(path).st_mode\n isSocket = stat.S_ISSOCK(mode)\n if not isSocket:\n return(False)\n if os.access(path, os.W_OK):\n # OK, it's an actual socket we can write to\n return(True)\n return(False)\n\n def send(self, encrypt_to=None):\n # TODO: If we were to encrypt, we would encapsulate\n # self.reqObj to a special structure:\n # {'payload': ENCRYPTED_ASCII_ARMORED_CONTENT,\n # 'encrypted': True}\n # or something like that\n print('connect')\n if encrypt_to is None:\n HUME = self.reqObj\n else:\n HUME = self.encrypt(gpg_encrypt_to)\n # The abstraction level of zeromq does not allow to\n # simply check for correctly sent messages. We should wait for a REPly\n # FIX: see if we can make REP/REQ work as required\n sock = zmq.Context().socket(zmq.PUSH)\n sock.setsockopt(zmq.SNDTIMEO, 5)\n sock.setsockopt(zmq.LINGER, 5)\n try:\n sock.connect(self.config['url'])\n except zmq.ZMQError as exc:\n print(exc)\n sys.exit(2)\n print('send_string')\n try:\n x = sock.send_string(json.dumps(self.reqObj))\n except zmq.ZMQError as exc:\n msg = \"\\033[1;33mEXCEPTION:\\033[0;37m{}\"\n print(msg.format(exc))\n sys.exit(3)\n print(x)\n print('fin')\n return(None)\n\n def get_pstree(self): # FIX: make better version\n ps_tree = []\n h = 0\n me = psutil.Process()\n parent = psutil.Process(me.ppid())\n while parent.ppid() != 0:\n ps_tree.append({'pid': parent.pid,\n 'cmdline': parent.cmdline(),\n 'order': h})\n parent = psutil.Process(parent.ppid())\n h = h+1\n return(ps_tree)\n\n def get_caller(self):\n me = psutil.Process()\n parent = psutil.Process(me.ppid())\n grandparent = psutil.Process(parent.ppid())\n return(grandparent.cmdline())\n\n def get_lineno(self):\n try:\n return(os.environ['LINENO'])\n except Exception:\n # TODO: add stderr warning about no LINENO\n return(None)\n\n\ndef run():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-L\", \"--level\",\n choices=['ok', 'warn', 'error', 'info', 'debug'],\n default=\"info\",\n help=\"Level of update to send, defaults to 'info'\")\n parser.add_argument(\"-c\", \"--cmd\",\n choices=['counter-start',\n 'counter-pause',\n 'counter-stop',\n 'counter-reset'],\n default='',\n required=False,\n help=\"[OPTIONAL] Command to attach to the update.\")\n parser.add_argument(\"-m\", \"--msg\",\n required=True,\n help=\"[REQUIRED] Message to include with this update\")\n parser.add_argument(\"-t\", \"--task\",\n required=False,\n default='',\n help=\"[OPTIONAL] Task name, for example BACKUPTASK.\")\n parser.add_argument('-a', '--append-pstree',\n action='store_true',\n help=\"Append process calling tree\")\n parser.add_argument('-T', '--tags',\n type=lambda arg: arg.split(','),\n help=\"Comma-separated list of tags\")\n parser.add_argument('-e', '--encrypt-to',\n default=None,\n action=NotImplementedAction,\n dest='encrypt_to',\n help=\"[OPTIONAL] Encrypt to this gpg pubkey id\")\n args = parser.parse_args()\n Hume(args).send(encrypt_to=args.encrypt_to)\n\n\nif __name__ == '__main__':\n run()\n sys.exit(0)\n" } ]
5
NuevoIngenioMexicano/DevPlaces
https://github.com/NuevoIngenioMexicano/DevPlaces
642cf8de3c74604ad432216ca2f97ef870d17c9b
e71e14b82995935cd081441be3fbc0e658b849a8
eca6cff250fd108f5dd76358a6ec83fddf131464
refs/heads/master
2020-02-26T16:21:12.375577
2016-07-24T16:57:43
2016-07-24T16:57:43
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7385621070861816, "alphanum_fraction": 0.7565359473228455, "avg_line_length": 26.727272033691406, "blob_id": "af12a77e6f9b4af97f6ad645110decc34df6d8e9", "content_id": "2b1464ba164d014cd99e05d481e452e843aba49f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 612, "license_type": "no_license", "max_line_length": 86, "num_lines": 22, "path": "/myApp/models.py", "repo_name": "NuevoIngenioMexicano/DevPlaces", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\n\nclass Categorias(models.Model):\n\t#Atributos\n\tnombre = models.CharField(max_length=25)\n\tdescripcion = models.CharField(max_length=140)\n\tdef __str__(self):\n\t\treturn self.nombre\n\nclass Publicacion(models.Model):\n\t#Conexiones a otros Modelos\n\tcategoria = models.ForeignKey(Categorias, related_name='categoria_de_la_publicacion')\n\t#Atributos\n\tdescripcion = models.CharField(max_length=400)\n\thora = models.DateField(auto_now_add=True)\n\tlugar = models.CharField(max_length=120)\n\tdef __str__(self):\n\t\treturn self.lugar\n\n\n" }, { "alpha_fraction": 0.6971735954284668, "alphanum_fraction": 0.6971735954284668, "avg_line_length": 28.760000228881836, "blob_id": "1cdb75063f325523ad10fb2b8cedf7ca7b2daae7", "content_id": "c5043b1b39b649cb2e6e906ca41ea044518cab8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "no_license", "max_line_length": 94, "num_lines": 25, "path": "/myApp/forms.py", "repo_name": "NuevoIngenioMexicano/DevPlaces", "src_encoding": "UTF-8", "text": "from __future__ import unicode_literals\n\nfrom django.forms import ModelForm\nfrom . import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django import forms\nfrom .models import Publicacion\n\n\n\nclass Crear(ModelForm):\n\tclass Meta:\n\t\tmodel = models.Publicacion\n\n\t\tfields = ['lugar','descripcion','categoria']\n\t\tlabels = {\n\t\t\t'lugar':_('¿En donde estas?'),\n\t\t\t'descripcion':_('¿Que esta pasando?'),\n\t\t\t'categoria':_('Clasifica tu Evento')\n\t\t}\n\t\twidgets = {\n\t\t\t'lugar': forms.TextInput(attrs={'class':'form-control','placeholder':'Lugar'}),\n\t\t\t'descripcion': forms.TextInput(attrs={'class':'form-control','placeholder':'Descripcion'}),\n\t\t\t'categoria': forms.Select(attrs={'class':'form-control','placeholder':'Categoria'} )\n\t\t}" }, { "alpha_fraction": 0.5487512946128845, "alphanum_fraction": 0.5531987547874451, "avg_line_length": 32.227272033691406, "blob_id": "6209e5b783d8bf59e4ebf6d7bc6f5c478d8588c9", "content_id": "9181df1c36d574348217c47b0d0e0756a2dd998f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2923, "license_type": "no_license", "max_line_length": 119, "num_lines": 88, "path": "/static/js/map.js", "repo_name": "NuevoIngenioMexicano/DevPlaces", "src_encoding": "UTF-8", "text": "function findLocation( selector, getLatitude, getLongitude ) {\n\t\t\t\t\t\t\t\tjQuery(selector).gMap('addMarker', {\n\t\t\t\t\t\t\t\t\tlatitude: getLatitude,\n\t\t\t\t\t\t\t\t\tlongitude: getLongitude,\n\t\t\t\t\t\t\t\t\tcontent: 'You have selected this Location.',\n\t\t\t\t\t\t\t\t\tpopup: true\n\t\t\t\t\t\t\t\t}).gMap('centerAt', {\n\t\t\t\t\t\t\t\t\tlatitude: getLatitude,\n\t\t\t\t\t\t\t\t\tlongitude: getLongitude,\n\t\t\t\t\t\t\t\t\tzoom: 12\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tjQuery('#google-map').gMap({\n\n\t\t\t\t\t\t\t\t address: 'Melbourne, Australia',\n\t\t\t\t\t\t\t\t maptype: 'ROADMAP',\n\t\t\t\t\t\t\t\t zoom: 12,\n\t\t\t\t\t\t\t\t markers: [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\taddress: \"Melbourne, Australia\"\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t ],\n\t\t\t\t\t\t\t\t doubleclickzoom: false,\n\t\t\t\t\t\t\t\t controls: {\n\t\t\t\t\t\t\t\t\t panControl: true,\n\t\t\t\t\t\t\t\t\t zoomControl: true,\n\t\t\t\t\t\t\t\t\t mapTypeControl: true,\n\t\t\t\t\t\t\t\t\t scaleControl: false,\n\t\t\t\t\t\t\t\t\t streetViewControl: false,\n\t\t\t\t\t\t\t\t\t overviewMapControl: false\n\t\t\t\t\t\t\t\t }\n\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tjQuery(window).load( function(){\n\n\t\t\t\t\t\t\t\tvar t = setTimeout( function(){\n\t\t\t\t\t\t\t\t\tif(navigator.geolocation) {\n\t\t\t\t\t\t\t\t\t\tnavigator.geolocation.getCurrentPosition(function(position) {\n\t\t\t\t\t\t\t\t\t\t\tjQuery('#google-map').gMap('addMarker', {\n\t\t\t\t\t\t\t\t\t\t\t\tlatitude: position.coords.latitude,\n\t\t\t\t\t\t\t\t\t\t\t\tlongitude: position.coords.longitude,\n\t\t\t\t\t\t\t\t\t\t\t\tcontent: 'You are here!',\n\t\t\t\t\t\t\t\t\t\t\t\tpopup: true\n\t\t\t\t\t\t\t\t\t\t\t}).gMap('centerAt', {\n\t\t\t\t\t\t\t\t\t\t\t\tlatitude: position.coords.latitude,\n\t\t\t\t\t\t\t\t\t\t\t\tlongitude: position.coords.longitude,\n\t\t\t\t\t\t\t\t\t\t\t\tzoom: 14\n\t\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\t}, function() {\n\t\t\t\t\t\t\t\t\t\t\talert('Couldn\\'t find you :(');\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}, 200 );\n\n\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\tjQuery('#location-submit').click( function(e){\n\n\t\t\t\t\t\t\t\tvar locationFinder = jQuery(this).parent().parent().find('#location-input').val();\n\t\t\t\t\t\t\t\tvar locationFinderIcon = jQuery(this).parent().parent().find('.input-group-addon').find('i');\n\n\t\t\t\t\t\t\t\tjQuery('#location-coordinates').fadeOut();\n\n\t\t\t\t\t\t\t\tif( locationFinder != '' ){\n\t\t\t\t\t\t\t\t\tlocationFinderIcon.removeClass('icon-map-marker').addClass('icon-line-loader icon-spin');\n\n\t\t\t\t\t\t\t\t\tjQuery.ajax({\n\t\t\t\t\t\t\t\t\t\turl: 'http://maps.google.com/maps/api/geocode/json?address=' + encodeURI(locationFinder),\n\t\t\t\t\t\t\t\t\t\t//force to handle it as text\n\t\t\t\t\t\t\t\t\t\tdataType: \"text\",\n\t\t\t\t\t\t\t\t\t\tsuccess: function(data) {\n\t\t\t\t\t\t\t\t\t\t\tvar json = jQuery.parseJSON(data);\n\t\t\t\t\t\t\t\t\t\t\tfindLocation( '#google-map', json.results[0].geometry.location.lat, json.results[0].geometry.location.lng );\n\t\t\t\t\t\t\t\t\t\t\tjQuery('#latitude-text').html('<strong>Latitude:</strong> ' + json.results[0].geometry.location.lat);\n\t\t\t\t\t\t\t\t\t\t\tjQuery('#longitude-text').html('<strong>Longitude:</strong> ' + json.results[0].geometry.location.lng);\n\t\t\t\t\t\t\t\t\t\t\tjQuery('#location-coordinates').fadeIn();\n\t\t\t\t\t\t\t\t\t\t\tlocationFinderIcon.removeClass('icon-line-loader icon-spin').addClass('icon-map-marker');\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\talert('Please enter your Location!');\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\te.preventDefault();\n\n\t\t\t\t\t\t\t});" }, { "alpha_fraction": 0.5607779622077942, "alphanum_fraction": 0.582658052444458, "avg_line_length": 34.25714111328125, "blob_id": "ff303c5758f2e9eded5452aad8e0cb7b34f2fce9", "content_id": "b147b558679d163a2afa63fcd36ff59e420b3712", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1234, "license_type": "no_license", "max_line_length": 161, "num_lines": 35, "path": "/myApp/migrations/0001_initial.py", "repo_name": "NuevoIngenioMexicano/DevPlaces", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.8 on 2016-07-24 12:47\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Categorias',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('nombre', models.CharField(max_length=25)),\n ('descripcion', models.CharField(max_length=140)),\n ],\n ),\n migrations.CreateModel(\n name='Publicacion',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('descripcion', models.CharField(max_length=400)),\n ('hora', models.DateField(auto_now_add=True)),\n ('lugar', models.CharField(max_length=120)),\n ('categoria', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='categoria_de_la_publicacion', to='myApp.Categorias')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.7170731425285339, "alphanum_fraction": 0.7195122241973877, "avg_line_length": 20.605262756347656, "blob_id": "b0b861467f76875f7892563ad965fe69b0c3b668", "content_id": "c9f0567b769469027f7fe8d0778223f96026bb0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 820, "license_type": "no_license", "max_line_length": 52, "num_lines": 38, "path": "/myApp/views.py", "repo_name": "NuevoIngenioMexicano/DevPlaces", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom . import models\nfrom django.views.generic import View\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .forms import Crear\n\n#Create your views here.\n\ndef crear(request):\n\ttemplate_name = 'index2.html'\n\ttodo = models.Publicacion.objects.all()\n\tcontext = {\n\t\t'todo':todo\t\t\t\n\t}\n\treturn render(request, template_name, context)\n\t\n\n@csrf_exempt\ndef ver(request):\n\ttemplate_name = 'crear2.html'\n\tform = Crear()\n\tcontext = {\n\t\t'form':form\n\t}\n\tif request.method == 'POST':\n\t\tform = Crear(request.POST)\n\t\tif form.is_valid:\n\t\t\tform.save()\n\n\treturn render(request, template_name, context)\n\ndef detalle(request, pk):\n\ttemplate_name = 'detalle.html'\n\tdetalle = models.Publicacion.objects.get(pk = pk)\n\tcontext = {\n\t\t'detalle':detalle\n\t}\n\treturn render(request, template_name, context)" } ]
5
Affirm/promise
https://github.com/Affirm/promise
fed90b454238eae8baf0291e9eaf6cb3d438c7d2
b4ec8f19546947b97583d07f460b74e81a9eb671
91d7c2d37e5e1a4d5f89be2a2dd5b843b7a00a26
refs/heads/master
2023-07-06T11:33:20.165892
2016-12-02T04:59:45
2016-12-02T04:59:45
79,600,712
0
2
MIT
2017-01-20T21:33:48
2021-05-05T18:56:57
2017-01-09T09:25:28
Python
[ { "alpha_fraction": 0.3250259459018707, "alphanum_fraction": 0.3385254442691803, "avg_line_length": 49.68421173095703, "blob_id": "b79ea2f92992e0eb3f9901f14a74530429889948", "content_id": "18e2c1a0e693561353f62784d941080a29683fbb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 963, "license_type": "permissive", "max_line_length": 96, "num_lines": 19, "path": "/tests/test_issues.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "# This tests reported issues in the Promise package\nfrom promise import Promise\n\n\ndef test_issue_11():\n # https://github.com/syrusakbary/promise/issues/11\n def test(x): \n def my(resolve, reject): \n if x > 0: \n resolve(x) \n else: \n reject(Exception(x)) \n return Promise(my) \n\n promise_resolved = test(42).then(lambda x: x)\n assert promise_resolved.value == 42\n\n promise_rejected = test(-42).then(lambda x: x, lambda e: str(e))\n assert promise_rejected.value == \"-42\"\n" }, { "alpha_fraction": 0.7758620977401733, "alphanum_fraction": 0.7758620977401733, "avg_line_length": 28, "blob_id": "046a7d6da5ca6f38178281eb70f06654c7c1b8c9", "content_id": "563bfab4c92abc9a7ae38616fcf5832c3bf4cc8f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 58, "license_type": "permissive", "max_line_length": 51, "num_lines": 2, "path": "/.coveragerc", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "[run]\nomit = promise/compat.py,promise/iterate_promise.py\n" }, { "alpha_fraction": 0.6398210525512695, "alphanum_fraction": 0.68232661485672, "avg_line_length": 20.285715103149414, "blob_id": "36a716fe083d985b0bb0340d0e25676566c7c884", "content_id": "45f780ff7d4c18a719f738a2aa3f2dddc58197e7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "permissive", "max_line_length": 68, "num_lines": 21, "path": "/tests/test_complex_threads.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "import time\nimport concurrent.futures\nfrom promise import Promise\nexecutor = concurrent.futures.ThreadPoolExecutor(max_workers=40000);\n\n\ndef combine(r,n):\n return r * n\n\n\ndef promise_factorial(n):\n if n < 2:\n return 1\n time.sleep(.02)\n a = executor.submit(promise_factorial, n - 1)\n return Promise.promisify(a).then(lambda r: combine(r, n))\n\n\ndef test_factorial():\n p = promise_factorial(10)\n assert p.get() == 3628800\n" }, { "alpha_fraction": 0.5905207395553589, "alphanum_fraction": 0.6158826947212219, "avg_line_length": 20.716796875, "blob_id": "5a14a168ea8a8d8a999af7a036778b78cf6f125e", "content_id": "87e192e5eadd9f71755948097130e5e8c4c41871", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11119, "license_type": "permissive", "max_line_length": 124, "num_lines": 512, "path": "/tests/test_extra.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "# This exercises some capabilities above and beyond\n# the Promises/A+ test suite\nimport time\nimport pytest\n\nfrom promise import (\n Promise,\n is_thenable,\n promisify as free_promisify,\n promise_for_dict as free_promise_for_dict,\n)\nfrom concurrent.futures import Future\nfrom threading import Thread\n\nfrom .utils import assert_exception\n\n\nclass DelayedFulfill(Thread):\n def __init__(self, d, p, v):\n self.delay = d\n self.promise = p\n self.value = v\n Thread.__init__(self)\n\n def run(self):\n time.sleep(self.delay)\n self.promise.fulfill(self.value)\n\n\nclass DelayedRejection(Thread):\n def __init__(self, d, p, r):\n self.delay = d\n self.promise = p\n self.reason = r\n Thread.__init__(self)\n\n def run(self):\n time.sleep(self.delay)\n self.promise.reject(self.reason)\n\n\nclass FakeThenPromise():\n def __init__(self, raises=True):\n self.raises = raises\n\n def then(self, s=None, f=None):\n if self.raises:\n raise Exception(\"FakeThenPromise raises in 'then'\")\n\nclass FakeDonePromise():\n def __init__(self, raises=True):\n self.raises = raises\n\n def done(self, s=None, f=None):\n if self.raises:\n raise Exception(\"FakeDonePromise raises in 'done'\")\n\n\ndef df(value, dtime):\n p = Promise()\n t = DelayedFulfill(dtime, p, value)\n t.start()\n\n return p\n\n\ndef dr(reason, dtime):\n p = Promise()\n t = DelayedRejection(dtime, p, reason)\n t.start()\n\n return p\n\n\n# Static methods\ndef test_fulfilled():\n p = Promise.fulfilled(4)\n assert p.is_fulfilled\n assert p.value == 4\n\n\ndef test_rejected():\n p = Promise.rejected(Exception(\"Static rejected\"))\n assert p.is_rejected\n assert_exception(p.reason, Exception, \"Static rejected\")\n\n\n# Fulfill\ndef test_fulfill_self():\n p = Promise()\n with pytest.raises(TypeError) as excinfo:\n p.fulfill(p)\n\n\n# Exceptions\ndef test_exceptions():\n def throws(v):\n assert False\n\n p1 = Promise()\n p1.add_callback(throws)\n p1.fulfill(5)\n\n p2 = Promise()\n p2.add_errback(throws)\n p2.reject(Exception())\n\n with pytest.raises(Exception) as excinfo:\n p2.get()\n\n\ndef test_fake_promise():\n p = Promise()\n p.fulfill(FakeThenPromise())\n assert p.is_rejected\n assert_exception(p.reason, Exception, \"FakeThenPromise raises in 'then'\")\n\n\n# WAIT\ndef test_wait_when():\n p1 = df(5, 0.01)\n assert p1.is_pending\n p1.wait()\n assert p1.is_fulfilled\n\n\ndef test_wait_if():\n p1 = Promise()\n p1.fulfill(5)\n p1.wait()\n assert p1.is_fulfilled\n\n\ndef test_wait_timeout():\n p1 = df(5, 0.1)\n assert p1.is_pending\n p1.wait(timeout=0.05)\n assert p1.is_pending\n p1.wait()\n assert p1.is_fulfilled\n\n\n# GET\ndef test_get_when():\n p1 = df(5, 0.01)\n assert p1.is_pending\n v = p1.get()\n assert p1.is_fulfilled\n assert 5 == v\n\n\ndef test_get_if():\n p1 = Promise()\n p1.fulfill(5)\n v = p1.get()\n assert p1.is_fulfilled\n assert 5 == v\n\n\ndef test_get_timeout():\n p1 = df(5, 0.1)\n assert p1.is_pending\n try:\n v = p1.get(timeout=0.05)\n assert False\n except ValueError:\n pass # We expect this\n assert p1.is_pending\n v = p1.get()\n assert p1.is_fulfilled\n assert 5 == v\n\n\n# Promise.all\ndef test_promise_all_when():\n p1 = Promise()\n p2 = Promise()\n pl = Promise.all([p1, p2])\n assert p1.is_pending\n assert p2.is_pending\n assert pl.is_pending\n p1.fulfill(5)\n assert p1.is_fulfilled\n assert p2.is_pending\n assert pl.is_pending\n p2.fulfill(10)\n assert p1.is_fulfilled\n assert p2.is_fulfilled\n assert pl.is_fulfilled\n assert 5 == p1.value\n assert 10 == p2.value\n assert 5 == pl.value[0]\n assert 10 == pl.value[1]\n\n\ndef test_promise_all_when_mixed_promises():\n p1 = Promise()\n p2 = Promise()\n pl = Promise.all([p1, 32, p2, False, True])\n assert p1.is_pending\n assert p2.is_pending\n assert pl.is_pending\n p1.fulfill(5)\n assert p1.is_fulfilled\n assert p2.is_pending\n assert pl.is_pending\n p2.fulfill(10)\n assert p1.is_fulfilled\n assert p2.is_fulfilled\n assert pl.is_fulfilled\n assert 5 == p1.value\n assert 10 == p2.value\n assert pl.value == [5, 32, 10, False, True]\n\n\ndef test_promise_all_when_if_no_promises():\n pl = Promise.all([10, 32, False, True])\n assert pl.is_fulfilled\n assert pl.value == [10, 32, False, True]\n\n\ndef test_promise_all_if():\n p1 = Promise()\n p2 = Promise()\n pd1 = Promise.all([p1, p2])\n pd2 = Promise.all([p1])\n pd3 = Promise.all([])\n assert p1.is_pending\n assert p2.is_pending\n assert pd1.is_pending\n assert pd2.is_pending\n assert pd3.is_fulfilled\n p1.fulfill(5)\n assert p1.is_fulfilled\n assert p2.is_pending\n assert pd1.is_pending\n assert pd2.is_fulfilled\n p2.fulfill(10)\n assert p1.is_fulfilled\n assert p2.is_fulfilled\n assert pd1.is_fulfilled\n assert pd2.is_fulfilled\n assert 5 == p1.value\n assert 10 == p2.value\n assert 5 == pd1.value[0]\n assert 5 == pd2.value[0]\n assert 10 == pd1.value[1]\n assert [] == pd3.value\n\n\n# promise_for_dict\[email protected](params=[\n Promise.for_dict,\n free_promise_for_dict,\n])\ndef promise_for_dict(request):\n return request.param\n\n\ndef test_dict_promise_when(promise_for_dict):\n p1 = Promise()\n p2 = Promise()\n d = {\"a\": p1, \"b\": p2}\n pd1 = promise_for_dict(d)\n pd2 = promise_for_dict({\"a\": p1})\n pd3 = promise_for_dict({})\n assert p1.is_pending\n assert p2.is_pending\n assert pd1.is_pending\n assert pd2.is_pending\n assert pd3.is_fulfilled\n p1.fulfill(5)\n assert p1.is_fulfilled\n assert p2.is_pending\n assert pd1.is_pending\n assert pd2.is_fulfilled\n p2.fulfill(10)\n assert p1.is_fulfilled\n assert p2.is_fulfilled\n assert pd1.is_fulfilled\n assert pd2.is_fulfilled\n assert 5 == p1.value\n assert 10 == p2.value\n assert 5 == pd1.value[\"a\"]\n assert 5 == pd2.value[\"a\"]\n assert 10 == pd1.value[\"b\"]\n assert {} == pd3.value\n\n\ndef test_dict_promise_if(promise_for_dict):\n p1 = Promise()\n p2 = Promise()\n d = {\"a\": p1, \"b\": p2}\n pd = promise_for_dict(d)\n assert p1.is_pending\n assert p2.is_pending\n assert pd.is_pending\n p1.fulfill(5)\n assert p1.is_fulfilled\n assert p2.is_pending\n assert pd.is_pending\n p2.fulfill(10)\n assert p1.is_fulfilled\n assert p2.is_fulfilled\n assert pd.is_fulfilled\n assert 5 == p1.value\n assert 10 == p2.value\n assert 5 == pd.value[\"a\"]\n assert 10 == pd.value[\"b\"]\n\n\ndef test_done():\n counter = [0]\n\n def inc(_):\n counter[0] += 1\n\n def dec(_):\n counter[0] -= 1\n\n p = Promise()\n p.done(inc, dec)\n p.fulfill(4)\n\n assert counter[0] == 1\n\n p = Promise()\n p.done(inc, dec)\n p.done(inc, dec)\n p.reject(Exception())\n\n assert counter[0] == -1\n\n\ndef test_done_all():\n counter = [0]\n\n def inc(_):\n counter[0] += 1\n\n def dec(_):\n counter[0] -= 1\n\n p = Promise()\n p.done_all()\n p.done_all([(inc, dec)])\n p.done_all([\n (inc, dec),\n (inc, dec),\n {'success': inc, 'failure': dec},\n ])\n p.fulfill(4)\n\n assert counter[0] == 4\n\n p = Promise()\n p.done_all()\n p.done_all([inc])\n p.done_all([(inc, dec)])\n p.done_all([\n (inc, dec),\n {'success': inc, 'failure': dec},\n ])\n p.reject(Exception())\n\n assert counter[0] == 1\n\n\ndef test_then_all():\n p = Promise()\n\n handlers = [\n ((lambda x: x * x), (lambda r: 1)),\n {'success': (lambda x: x + x), 'failure': (lambda r: 2)},\n ]\n\n results = p.then_all() + p.then_all([lambda x: x]) + p.then_all([(lambda x: x * x, lambda r: 1)]) + p.then_all(handlers)\n\n p.fulfill(4)\n\n assert [r.value for r in results] == [4, 16, 16, 8]\n\n p = Promise()\n\n handlers = [\n ((lambda x: x * x), (lambda r: 1)),\n {'success': (lambda x: x + x), 'failure': (lambda r: 2)},\n ]\n\n results = p.then_all() + p.then_all([(lambda x: x * x, lambda r: 1)]) + p.then_all(handlers)\n\n p.reject(Exception())\n\n assert [r.value for r in results] == [1, 1, 2]\n\n\ndef test_do_resolve():\n p1 = Promise(lambda resolve, reject: resolve(0))\n assert p1.is_fulfilled\n assert p1.value == 0\n\n\ndef test_do_resolve_fail_on_call():\n def raises(resolve, reject):\n raise Exception('Fails')\n p1 = Promise(raises)\n assert not p1.is_fulfilled\n assert str(p1.reason) == 'Fails'\n\n\ndef test_catch():\n p1 = Promise(lambda resolve, reject: resolve(0))\n p2 = p1.then(lambda value: 1 / value) \\\n .catch(lambda e: e) \\\n .then(lambda e: type(e))\n assert p2.is_fulfilled\n assert p2.value == ZeroDivisionError\n\n\ndef test_is_thenable_promise():\n promise = Promise()\n assert is_thenable(promise)\n\n\ndef test_is_thenable_then_object():\n promise = FakeThenPromise()\n assert is_thenable(promise)\n\n\ndef test_is_thenable_done_object():\n promise = FakeDonePromise()\n assert is_thenable(promise)\n\n\ndef test_is_thenable_future():\n promise = Future()\n assert is_thenable(promise)\n\n\ndef test_is_thenable_simple_object():\n assert not is_thenable(object())\n\n\[email protected](params=[free_promisify, Promise.promisify])\ndef promisify(request):\n return request.param\n\n\ndef test_promisify_promise(promisify):\n promise = Promise()\n assert promisify(promise) == promise\n\n\ndef test_promisify_then_object(promisify):\n promise = FakeThenPromise(raises=False)\n p = promisify(promise)\n assert isinstance(p, Promise)\n\n\ndef test_promisify_then_object_exception(promisify):\n promise = FakeThenPromise()\n with pytest.raises(Exception) as excinfo:\n promisify(promise)\n assert str(excinfo.value) == \"FakeThenPromise raises in 'then'\"\n\n\ndef test_promisify_done_object(promisify):\n promise = FakeDonePromise(raises=False)\n p = promisify(promise)\n assert isinstance(p, Promise)\n\n\ndef test_promisify_done_object_exception(promisify):\n promise = FakeDonePromise()\n with pytest.raises(Exception) as excinfo:\n promisify(promise)\n assert str(excinfo.value) == \"FakeDonePromise raises in 'done'\"\n\n\ndef test_promisify_future(promisify):\n future = Future()\n promise = promisify(future)\n assert promise.is_pending\n future.set_result(1)\n assert promise.is_fulfilled\n assert promise.value == 1\n\n\ndef test_promisify_future_rejected(promisify):\n future = Future()\n promise = promisify(future)\n assert promise.is_pending\n future.set_exception(Exception('Future rejected'))\n assert promise.is_rejected\n assert_exception(promise.reason, Exception, 'Future rejected')\n\n\ndef test_promisify_object(promisify):\n with pytest.raises(TypeError) as excinfo:\n promisify(object())\n assert str(excinfo.value) == \"Object is not a Promise like object.\"\n\n\ndef test_promisify_promise_subclass():\n class MyPromise(Promise):\n pass\n\n p = Promise()\n p.fulfill(10)\n m_p = MyPromise.promisify(p)\n assert isinstance(m_p, MyPromise)\n assert m_p.get() == p.get()\n" }, { "alpha_fraction": 0.7042253613471985, "alphanum_fraction": 0.7042253613471985, "avg_line_length": 46.33333206176758, "blob_id": "8ba5177a21783c53a8f3f2bc0df37cf05dff5669", "content_id": "ce8cb82ea8b56652431b62b37cd0110d976f191b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "permissive", "max_line_length": 70, "num_lines": 3, "path": "/promise/__init__.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "from .promise import Promise, promise_for_dict, promisify, is_thenable\n\n__all__ = ['Promise', 'promise_for_dict', 'promisify', 'is_thenable']\n" }, { "alpha_fraction": 0.6192893385887146, "alphanum_fraction": 0.6598984599113464, "avg_line_length": 27.14285659790039, "blob_id": "f127f31083d8b65bb8d7fde81cbd2e7ba9083049", "content_id": "2e18e0f80f149006c8154fa9167f92018a2536c4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 197, "license_type": "permissive", "max_line_length": 49, "num_lines": 7, "path": "/tests/conftest.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "import sys\n\ncollect_ignore = []\nif sys.version_info[:2] < (3, 4):\n collect_ignore.append('test_awaitable.py')\nif sys.version_info[:2] < (3, 5):\n collect_ignore.append('test_awaitable_35.py')\n" }, { "alpha_fraction": 0.7865168452262878, "alphanum_fraction": 0.7865168452262878, "avg_line_length": 58.33333206176758, "blob_id": "02875fed6841079aafe91fc500fd583b9d850640", "content_id": "73dd1619c250ecb2b42680afffad6884ae97282f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 178, "license_type": "permissive", "max_line_length": 74, "num_lines": 3, "path": "/tests/utils.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "def assert_exception(exception, expected_exception_cls, expected_message):\n assert isinstance(exception, expected_exception_cls)\n assert str(exception) == expected_message\n" }, { "alpha_fraction": 0.6994219422340393, "alphanum_fraction": 0.7052023410797119, "avg_line_length": 19.969696044921875, "blob_id": "aafa8314b3d6ce5cfca81140547f0612b68b6c2a", "content_id": "7135ac6133c2e3035988d57bdde6e9b9c27a9e8e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 692, "license_type": "permissive", "max_line_length": 51, "num_lines": 33, "path": "/tests/test_awaitable_35.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "import pytest\nimport asyncio\nfrom promise import Promise, promisify, is_thenable\n\n\[email protected]\nasync def test_await():\n assert await Promise.resolve(True)\n\n\[email protected]\nasync def test_promisify_coroutine():\n async def my_coroutine():\n await asyncio.sleep(.01)\n return True\n\n assert await promisify(my_coroutine())\n\n\[email protected]\nasync def test_coroutine_is_thenable():\n async def my_coroutine():\n await asyncio.sleep(.01)\n return True\n\n assert is_thenable(my_coroutine())\n\n\[email protected]\nasync def test_promisify_future():\n future = asyncio.Future()\n future.set_result(True)\n assert await promisify(future)\n" }, { "alpha_fraction": 0.5604693293571472, "alphanum_fraction": 0.5611311793327332, "avg_line_length": 32.17165756225586, "blob_id": "7f464ac451dad6606db934c89e9a0494171a8b64", "content_id": "b2d685bf48c55764526e60fa861b1e1704b86532", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16620, "license_type": "permissive", "max_line_length": 110, "num_lines": 501, "path": "/promise/promise.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "import functools\nfrom threading import Event, RLock\nfrom .compat import Future, iscoroutine, ensure_future, iterate_promise # type: ignore\n\nfrom typing import Callable, Optional, Iterator, Any, Dict, Tuple, Union # flake8: noqa\n\n\nclass CountdownLatch(object):\n __slots__ = ('_lock', 'count')\n\n def __init__(self, count):\n # type: (CountdownLatch, int) -> None\n assert count >= 0, \"count needs to be greater or equals to 0. Got: %s\" % count\n self._lock = RLock()\n self.count = count\n\n def dec(self):\n # type: (CountdownLatch) -> int\n with self._lock:\n assert self.count > 0, \"count needs to be greater or equals to 0. Got: %s\" % self.count\n self.count -= 1\n # Return inside lock to return the correct value,\n # otherwise an other thread could already have\n # decremented again.\n return self.count\n\n\nclass Promise(object):\n \"\"\"\n This is the Promise class that complies\n Promises/A+ specification and test suite:\n http://promises-aplus.github.io/promises-spec/\n \"\"\"\n\n __slots__ = ('state', 'value', 'reason', '_cb_lock', '_callbacks', '_errbacks', '_event', '_future')\n\n # These are the potential states of a promise\n PENDING = -1\n REJECTED = 0\n FULFILLED = 1\n\n def __init__(self, fn=None):\n # type: (Promise, Callable) -> None\n \"\"\"\n Initialize the Promise into a pending state.\n \"\"\"\n self.state = self.PENDING # type: int\n self.value = None # type: Any\n self.reason = None # type: Optional[Exception]\n self._cb_lock = RLock()\n self._callbacks = [] # type: List[Callable]\n self._errbacks = [] # type: List[Callable]\n self._event = Event()\n self._future = None # type: Optional[Future]\n if fn:\n self.do_resolve(fn)\n\n def __iter__(self):\n # type: (Promise) -> Iterator\n return iterate_promise(self)\n\n __await__ = __iter__\n\n @property\n def future(self):\n # type: (Promise) -> Future\n if not self._future:\n self._future = Future()\n self.add_callback(self._future.set_result)\n self.add_errback(self._future.set_exception)\n return self._future\n\n def do_resolve(self, fn):\n try:\n fn(self.fulfill, self.reject)\n except Exception as e:\n self.reject(e)\n\n @classmethod\n def fulfilled(cls, x):\n # type: (Any) -> Promise\n p = cls()\n p.fulfill(x)\n return p\n\n @classmethod\n def rejected(cls, reason):\n # type: (Any) -> Promise\n p = cls()\n p.reject(reason)\n return p\n\n def fulfill(self, x):\n # type: (Promise, Any) -> None\n \"\"\"\n Fulfill the promise with a given value.\n \"\"\"\n\n if self is x:\n raise TypeError(\"Cannot resolve promise with itself.\")\n elif is_thenable(x):\n try:\n self.promisify(x).done(self.fulfill, self.reject)\n except Exception as e:\n self.reject(e)\n else:\n self._fulfill(x)\n\n resolve = fulfilled\n\n def _fulfill(self, value):\n # type: (Promise, Any) -> None\n with self._cb_lock:\n if self.state != self.PENDING:\n return\n\n self.value = value\n self.state = self.FULFILLED\n\n callbacks = self._callbacks\n # We will never call these callbacks again, so allow\n # them to be garbage collected. This is important since\n # they probably include closures which are binding variables\n # that might otherwise be garbage collected.\n #\n # Prevent future appending\n self._callbacks = None\n\n # Notify all waiting\n self._event.set()\n\n for callback in callbacks:\n try:\n callback(value)\n except Exception:\n # Ignore errors in callbacks\n pass\n\n def reject(self, reason):\n # type: (Promise, Exception) -> None\n \"\"\"\n Reject this promise for a given reason.\n \"\"\"\n assert isinstance(reason, Exception), (\"The reject function needs to be called with an Exception. \"\n \"Got %s\" % reason)\n\n with self._cb_lock:\n if self.state != self.PENDING:\n return\n\n self.reason = reason\n self.state = self.REJECTED\n\n errbacks = self._errbacks\n # We will never call these errbacks again, so allow\n # them to be garbage collected. This is important since\n # they probably include closures which are binding variables\n # that might otherwise be garbage collected.\n #\n # Prevent future appending\n self._errbacks = None\n\n # Notify all waiting\n self._event.set()\n\n for errback in errbacks:\n try:\n errback(reason)\n except Exception:\n # Ignore errors in errback\n pass\n\n @property\n def is_pending(self):\n # type: (Promise) -> bool\n \"\"\"Indicate whether the Promise is still pending. Could be wrong the moment the function returns.\"\"\"\n return self.state == self.PENDING\n\n @property\n def is_fulfilled(self):\n # type: (Promise) -> bool\n \"\"\"Indicate whether the Promise has been fulfilled. Could be wrong the moment the function returns.\"\"\"\n return self.state == self.FULFILLED\n\n @property\n def is_rejected(self):\n # type: (Promise) -> bool\n \"\"\"Indicate whether the Promise has been rejected. Could be wrong the moment the function returns.\"\"\"\n return self.state == self.REJECTED\n\n def get(self, timeout=None):\n # type: (Promise, int) -> Any\n \"\"\"Get the value of the promise, waiting if necessary.\"\"\"\n self.wait(timeout)\n\n if self.state == self.PENDING:\n raise ValueError(\"Value not available, promise is still pending\")\n elif self.state == self.FULFILLED:\n return self.value\n raise self.reason\n\n def wait(self, timeout=None):\n # type: (Promise, int) -> None\n \"\"\"\n An implementation of the wait method which doesn't involve\n polling but instead utilizes a \"real\" synchronization\n scheme.\n \"\"\"\n self._event.wait(timeout)\n\n def add_callback(self, f):\n # type: (Promise, Callable) -> None\n \"\"\"\n Add a callback for when this promis is fulfilled. Note that\n if you intend to use the value of the promise somehow in\n the callback, it is more convenient to use the 'then' method.\n \"\"\"\n assert callable(f), \"A function needs to be passed into add_callback. Got: %s\" % f\n\n with self._cb_lock:\n if self.state == self.PENDING:\n self._callbacks.append(f)\n return\n\n # This is a correct performance optimization in case of concurrency.\n # State can never change once it is not PENDING anymore and is thus safe to read\n # without acquiring the lock.\n if self.state == self.FULFILLED:\n f(self.value)\n\n def add_errback(self, f):\n # type: (Promise, Callable) -> None\n \"\"\"\n Add a callback for when this promis is rejected. Note that\n if you intend to use the rejection reason of the promise\n somehow in the callback, it is more convenient to use\n the 'then' method.\n \"\"\"\n assert callable(f), \"A function needs to be passed into add_errback. Got: %s\" % f\n\n with self._cb_lock:\n if self.state == self.PENDING:\n self._errbacks.append(f)\n return\n\n # This is a correct performance optimization in case of concurrency.\n # State can never change once it is not PENDING anymore and is thus safe to read\n # without acquiring the lock.\n if self.state == self.REJECTED:\n f(self.reason)\n\n def catch(self, on_rejection):\n # type: (Promise, Callable) -> Promise\n \"\"\"\n This method returns a Promise and deals with rejected cases only.\n It behaves the same as calling Promise.then(None, on_rejection).\n \"\"\"\n return self.then(None, on_rejection)\n\n def done(self, success=None, failure=None):\n # type: (Promise, Callable, Callable) -> None\n \"\"\"\n This method takes two optional arguments. The first argument\n is used if the \"self promise\" is fulfilled and the other is\n used if the \"self promise\" is rejected. In contrast to then,\n the return value of these callback is ignored and nothing is\n returned.\n \"\"\"\n with self._cb_lock:\n if success is not None:\n self.add_callback(success)\n if failure is not None:\n self.add_errback(failure)\n\n def done_all(self, handlers=None):\n # type: (Promise, List[Callable]) -> List[Promise]\n \"\"\"\n :type handlers: list[(Any) -> object] | list[((Any) -> object, (Any) -> object)]\n \"\"\"\n if not handlers:\n return []\n\n for handler in handlers:\n if isinstance(handler, tuple):\n s, f = handler\n\n self.done(s, f)\n elif isinstance(handler, dict):\n s = handler.get('success')\n f = handler.get('failure')\n\n self.done(s, f)\n else:\n self.done(success=handler)\n\n def then(self, success=None, failure=None):\n # type: (Promise, Callable, Callable) -> Promise\n \"\"\"\n This method takes two optional arguments. The first argument\n is used if the \"self promise\" is fulfilled and the other is\n used if the \"self promise\" is rejected. In either case, this\n method returns another promise that effectively represents\n the result of either the first of the second argument (in the\n case that the \"self promise\" is fulfilled or rejected,\n respectively).\n Each argument can be either:\n * None - Meaning no action is taken\n * A function - which will be called with either the value\n of the \"self promise\" or the reason for rejection of\n the \"self promise\". The function may return:\n * A value - which will be used to fulfill the promise\n returned by this method.\n * A promise - which, when fulfilled or rejected, will\n cascade its value or reason to the promise returned\n by this method.\n * A value - which will be assigned as either the value\n or the reason for the promise returned by this method\n when the \"self promise\" is either fulfilled or rejected,\n respectively.\n :type success: (Any) -> object\n :type failure: (Any) -> object\n :rtype : Promise\n \"\"\"\n ret = self.__class__()\n\n def call_and_fulfill(v):\n \"\"\"\n A callback to be invoked if the \"self promise\"\n is fulfilled.\n \"\"\"\n try:\n if callable(success):\n ret.fulfill(success(v))\n else:\n ret.fulfill(v)\n except Exception as e:\n ret.reject(e)\n\n def call_and_reject(r):\n \"\"\"\n A callback to be invoked if the \"self promise\"\n is rejected.\n \"\"\"\n try:\n if callable(failure):\n ret.fulfill(failure(r))\n else:\n ret.reject(r)\n except Exception as e:\n ret.reject(e)\n\n self.done(call_and_fulfill, call_and_reject)\n\n return ret\n\n def then_all(self, handlers=None):\n # type: (Promise, List[Callable]) -> List[Promise]\n \"\"\"\n Utility function which calls 'then' for each handler provided. Handler can either\n be a function in which case it is used as success handler, or a tuple containing\n the success and the failure handler, where each of them could be None.\n :type handlers: list[(Any) -> object] | list[((Any) -> object, (Any) -> object)]\n :param handlers\n :rtype : list[Promise]\n \"\"\"\n if not handlers:\n return []\n\n promises = [] # type: List[Promise]\n\n for handler in handlers:\n if isinstance(handler, tuple):\n s, f = handler\n\n promises.append(self.then(s, f))\n elif isinstance(handler, dict):\n s = handler.get('success')\n f = handler.get('failure')\n\n promises.append(self.then(s, f))\n else:\n promises.append(self.then(success=handler))\n\n return promises\n\n @classmethod\n def all(cls, values_or_promises):\n # Type: (Iterable[Promise, Any]) -> Promise\n \"\"\"\n A special function that takes a bunch of promises\n and turns them into a promise for a vector of values.\n In other words, this turns an list of promises for values\n into a promise for a list of values.\n \"\"\"\n _len = len(values_or_promises)\n if _len == 0:\n return cls.fulfilled(values_or_promises)\n\n promises = (cls.promisify(v_or_p) if is_thenable(v_or_p) else cls.resolve(v_or_p) for\n v_or_p in values_or_promises) # type: Iterator[Promise]\n\n all_promise = cls() # type: Promise\n counter = CountdownLatch(_len)\n values = [None] * _len # type: List[Any]\n\n def handle_success(original_position, value):\n # type: (int, Any) -> None\n values[original_position] = value\n if counter.dec() == 0:\n all_promise.fulfill(values)\n\n for i, p in enumerate(promises):\n p.done(functools.partial(handle_success, i), all_promise.reject) # type: ignore\n\n return all_promise\n\n @classmethod\n def promisify(cls, obj):\n # type: (Any) -> Promise\n if isinstance(obj, cls):\n return obj\n\n add_done_callback = get_done_callback(obj) # type: Optional[Callable]\n if callable(add_done_callback):\n promise = cls()\n add_done_callback(_process_future_result(promise))\n return promise\n\n done = getattr(obj, \"done\", None) # type: Optional[Callable]\n if callable(done):\n p = cls()\n done(p.fulfill, p.reject)\n return p\n\n then = getattr(obj, \"then\", None) # type: Optional[Callable]\n if callable(then):\n p = cls()\n then(p.fulfill, p.reject)\n return p\n\n if iscoroutine(obj):\n return cls.promisify(ensure_future(obj))\n\n raise TypeError(\"Object is not a Promise like object.\")\n\n @classmethod\n def for_dict(cls, m):\n # type: (Dict[Any, Promise]) -> Promise\n \"\"\"\n A special function that takes a dictionary of promises\n and turns them into a promise for a dictionary of values.\n In other words, this turns an dictionary of promises for values\n into a promise for a dictionary of values.\n \"\"\"\n if not m:\n return cls.fulfilled({})\n\n keys, values = zip(*m.items())\n dict_type = type(m)\n\n def handle_success(resolved_values):\n return dict_type(zip(keys, resolved_values))\n\n return cls.all(values).then(handle_success)\n\n\npromisify = Promise.promisify\npromise_for_dict = Promise.for_dict\n\n\ndef _process_future_result(promise):\n def handle_future_result(future):\n exception = future.exception()\n if exception:\n promise.reject(exception)\n else:\n promise.fulfill(future.result())\n\n return handle_future_result\n\n\ndef is_future(obj):\n # type: (Any) -> bool\n return callable(get_done_callback(obj))\n\n\ndef get_done_callback(obj):\n # type: (Any) -> Callable\n return getattr(obj, \"add_done_callback\", None)\n\n\ndef is_thenable(obj):\n # type: (Any) -> bool\n \"\"\"\n A utility function to determine if the specified\n object is a promise using \"duck typing\".\n \"\"\"\n return isinstance(obj, Promise) or is_future(obj) or (\n hasattr(obj, \"done\") and callable(getattr(obj, \"done\"))) or (\n hasattr(obj, \"then\") and callable(getattr(obj, \"then\"))) or (\n iscoroutine(obj))\n\n" }, { "alpha_fraction": 0.7068063020706177, "alphanum_fraction": 0.7094240784645081, "avg_line_length": 18.100000381469727, "blob_id": "f0cfe1c0fb63c90ad11f3c39d360e22ce6c33c19", "content_id": "0e606a9ecf15a5f4dc85e4f9fa462f23a70328d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 382, "license_type": "permissive", "max_line_length": 43, "num_lines": 20, "path": "/tests/test_awaitable.py", "repo_name": "Affirm/promise", "src_encoding": "UTF-8", "text": "import asyncio\nimport pytest\nimport time\nfrom promise import Promise\n\n\[email protected]\[email protected]\ndef test_await():\n yield from Promise.resolve(True)\n\n\[email protected]\[email protected]\ndef test_await_time():\n def resolve_or_reject(resolve, reject):\n time.sleep(.1)\n resolve(True)\n p = Promise(resolve_or_reject)\n assert p.get() is True\n" } ]
10
Tobias-Braun/cleaner-discord-bot
https://github.com/Tobias-Braun/cleaner-discord-bot
6f2b424c57793329dcb5397f66106ccc1e9ac70a
9821e662db5ba4a8046ff2eab88bce0f10711c9e
43a51d7e6e98aebb6e73ec44295cbc5a2b164651
refs/heads/main
2023-01-07T08:37:31.689071
2020-11-07T12:21:34
2020-11-07T12:21:34
310,837,510
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.667294979095459, "alphanum_fraction": 0.667294979095459, "avg_line_length": 22.577777862548828, "blob_id": "60fc4a798177735c971e3fcec3e2c9ca07ec3863", "content_id": "868c065f5a78aa5fa854fec3af10bd410dcfd56b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1064, "license_type": "no_license", "max_line_length": 61, "num_lines": 45, "path": "/bot.py", "repo_name": "Tobias-Braun/cleaner-discord-bot", "src_encoding": "UTF-8", "text": "import os\nimport discord\nimport asyncio\nimport json\nimport re\nimport os\n\n\nTOKEN = os.environ[\"DISCORD_CLEANER_BOT_TOKEN\"]\n\nclient = discord.Client()\n\nchannels_to_clean = [\"general\", \"lululul😀\"]\nbot_channels_to_clean = [\"bot_usage\"]\n\n\[email protected]\nasync def on_ready():\n print(f'{client.user} has connected to Discord!')\n\n\[email protected]\nasync def on_message(message):\n\n data = {}\n\n with open('config.json') as f:\n data = json.load(f)\n\n cleanToken = data[\"cleanToken\"]\n channels_to_clean = data[\"channelsToClean\"]\n bot_channels_to_clean = data[\"botChannelsToClean\"]\n bot_channel_clean_delay = data[\"botChannelCleaningDelay\"]\n pattern = re.compile(f\"{cleanToken}\")\n print(pattern)\n if pattern.match(message.content):\n channel = message.channel\n print(channel.name)\n if channel.name in channels_to_clean:\n await message.delete()\n if channel.name in bot_channels_to_clean:\n await asyncio.sleep(int(bot_channel_clean_delay))\n await message.delete()\n\nclient.run(TOKEN)\n" }, { "alpha_fraction": 0.657331109046936, "alphanum_fraction": 0.657331109046936, "avg_line_length": 24.20833396911621, "blob_id": "cf021c2f7ee94cc798e14c680e9bb5bee2f2c2dc", "content_id": "20ef7954ed3b6965771cc88c462939c241516a6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 607, "license_type": "no_license", "max_line_length": 66, "num_lines": 24, "path": "/backend.py", "repo_name": "Tobias-Braun/cleaner-discord-bot", "src_encoding": "UTF-8", "text": "from flask import Flask, escape, request, render_template, url_for\nimport json\nimport asyncio\n\napp = Flask(__name__)\nconfig = {}\n\nwith open('config.json') as f:\n config = json.load(f)\n\n\[email protected](\"/\", methods=[\"GET\"])\[email protected]('/dashboard/', methods=[\"GET\"])\ndef render_dashboard():\n return render_template('dashboard.html', config=config)\n\n\[email protected](\"/\", methods=[\"POST\"])\[email protected](\"/dashboard/\", methods=[\"POST\"])\ndef update_config():\n config = request.form\n with open(\"config.json\", \"w\") as f:\n json.dump(config, f)\n return render_template(\"dashboard.html\", config=config)\n\n\n" } ]
2
Fchaubard/resnet
https://github.com/Fchaubard/resnet
0b2db22b69ea7886429365a09578c102384bc784
838799a393005653de8cccb7dd188c019e680410
d703085228e1870965a752d66b747d72953b4b0b
refs/heads/master
2021-01-18T03:07:11.727477
2016-01-22T05:10:59
2016-01-22T05:10:59
50,158,736
1
0
null
2016-01-22T04:59:56
2016-01-18T03:50:53
2016-01-14T14:13:16
null
[ { "alpha_fraction": 0.6910569071769714, "alphanum_fraction": 0.7572590112686157, "avg_line_length": 94.77777862548828, "blob_id": "afc4fdb1cabc26e0b6bf6749140b701ad698ebee", "content_id": "47a31febea8aa05ee2e53464e1080a2c2df09472", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 861, "license_type": "no_license", "max_line_length": 196, "num_lines": 9, "path": "/README.md", "repo_name": "Fchaubard/resnet", "src_encoding": "UTF-8", "text": "# Deep Residual Net\nExample code for [Deep Residual Learning for Image Recognition](http://arxiv.org/abs/1512.03385) \n* Run this script by ```python resnet-small.py``` for 100 epochs get a train accuracy around 89.47% and validation accuracy around 85.95% \n* Then change the learning rate to 0.01, running this training from 100th epoch for 50 iterations, and get a train accuracy around 98.72% and test accuracy around 89.77% \n\n## Differences to the Paper\n* 1*1 convolution operators are used for increasing dimensions.\n* This is a small residual net consists of 52 layers(can change to 20, 32, 44 layers by changing ```n``` in ```ResidualSymbol``` to 3, 5, 7)\n* Using mxnet default data augmentation options include center crop (instead of random crop) and random mirror, no paddings on raw image data and the input image size is 28\\*28(instead of 32\\*32)." }, { "alpha_fraction": 0.5592065453529358, "alphanum_fraction": 0.5932678580284119, "avg_line_length": 45.21296310424805, "blob_id": "038dadecb8cb925f66c8aa48c7fb79413654ed9a", "content_id": "8def76de63eb07a70a34bd620cd54ed07cc2dfaa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4991, "license_type": "no_license", "max_line_length": 210, "num_lines": 108, "path": "/resnet-small.py", "repo_name": "Fchaubard/resnet", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python \n'''\nMSRA Paper: http://arxiv.org/pdf/1512.03385v1.pdf\n'''\n\nimport mxnet as mx\nimport logging\ndef ConvFactory(data, num_filter, kernel, stride=(1, 1), pad=(0, 0), act_type = 'relu',last=False):\n conv = mx.symbol.Convolution(data = data, num_filter = num_filter, kernel = kernel, stride = stride, pad = pad)\n if last:\n return conv\n else:\n bn = mx.symbol.BatchNorm(data=conv)\n act = mx.symbol.Activation(data=bn, act_type=act_type)\n return act\n\ndef ResidualFactory(data, num_filter, diff_dim=False):\n if diff_dim:\n conv1 = ConvFactory( data=data, num_filter=num_filter[0], kernel=(3,3), stride=(2,2), pad=(1,1), last=False)\n conv2 = ConvFactory( data=conv1, num_filter=num_filter[1], kernel=(3,3), stride=(1,1), pad=(1,1), last=True)\n _data = mx.symbol.Convolution(data=data, num_filter=num_filter[1], kernel=(3,3), stride=(2,2), pad=(1,1))\n data = _data+conv2\n bn = mx.symbol.BatchNorm(data=data)\n act = mx.symbol.Activation(data=bn, act_type='relu')\n return act\n else:\n _data=data\n conv1 = ConvFactory(data=data, num_filter=num_filter[0], kernel=(3,3), stride=(1,1), pad=(1,1), last=False)\n conv2 = ConvFactory(data=conv1, num_filter=num_filter[1], kernel=(3,3), stride=(1,1), pad=(1,1), last=True)\n data = _data+conv2\n bn = mx.symbol.BatchNorm(data=data)\n act = mx.symbol.Activation(data=bn, act_type='relu')\n return act\ndef ResidualSymbol(data, n=9):\n \"stage 1\"\n for i in xrange(n):\n data = ResidualFactory(data, (16, 16))\n \"stage 2\"\n for i in xrange(n):\n if i == 0:\n data = ResidualFactory(data, (32, 32), True)\n else:\n data = ResidualFactory(data, (32, 32))\n \"stage 3\"\n for i in xrange(n):\n if i == 0:\n data = ResidualFactory(data, (64, 64), True)\n else:\n data = ResidualFactory(data, (64, 64))\n return data\n\n\ndef get_dataiter(batch_size=128):\n data_shape=(3,28,28)\n train_dataiter = mx.io.ImageRecordIter(\n path_imgrec = \"./data/cifar10/train.rec\",\n mean_img = \"./data/cifar10/mean.bin\",\n rand_crop = True,\n rand_mirror = True,\n shuffle = True,\n data_shape = data_shape,\n batch_size = batch_size,\n preprocess_threads = 2,\n prefetch_buffer = 2,\n )\n test_dataiter = mx.io.ImageRecordIter(\n path_imgrec = \"./data/cifar10/test.rec\",\n mean_img = \"./data/cifar10/mean.bin\",\n rand_crop = False,\n rand_mirror = False,\n data_shape = data_shape,\n batch_size = batch_size,\n preprocess_threads = 2,\n prefetch_buffer = 2,\n )\n return train_dataiter, test_dataiter\n\nif __name__=='__main__':\n logging.basicConfig(level=logging.DEBUG)\n \"before residual net\"\n data = ConvFactory(data=mx.symbol.Variable(name='data'), num_filter=16, kernel=(3,3), stride=(1,1), pad=(1,1))\n \"get residual net\"\n res = ResidualSymbol(data)\n \"global pooling + classify\"\n pool = mx.symbol.Pooling(data=res, kernel=(7,7), pool_type='avg')\n flatten = mx.symbol.Flatten(data=pool, name='flatten')\n \"set num_hidden=1000 when test on ImageNet competition dataset\"\n fc = mx.symbol.FullyConnected(data=flatten, num_hidden=10, name='fc1')\n softmax = mx.symbol.SoftmaxOutput(data=fc, name='softmax')\n\n \"uncomment the following two line to visualize resnet\"\n # g=mx.visualization.plot_network(softmax)\n # g.view()\n batch_size = 128\n train_dataiter, test_dataiter = get_dataiter(batch_size=batch_size)\n finetune=True\n if finetune==False:\n model = mx.model.FeedForward(ctx=mx.gpu(0), symbol=softmax, num_epoch=70, learning_rate=0.1, momentum=0.9, wd=0.0001, \\\n initializer=mx.init.Xavier(rnd_type='gaussian', factor_type=\"in\", magnitude=2),\n # initializer=mx.init.Xavier(),\n # initializer=mx.init.Normal(),\n lr_scheduler=mx.lr_scheduler.FactorScheduler(step =100000000000, factor = 0.95)\n )\n model.fit(X=train_dataiter, eval_data=test_dataiter, batch_end_callback=mx.callback.Speedometer(batch_size),epoch_end_callback=mx.callback.do_checkpoint(\"./models/resnet\"))\n else:\n loaded = mx.model.FeedForward.load('models/resnet', 100)\n continue_model = mx.model.FeedForward(ctx=mx.gpu(0), symbol = loaded.symbol, arg_params = loaded.arg_params, aux_params = loaded.aux_params, num_epoch=10000, learning_rate=0.01, momentum=0.9, wd=0.0001)\n continue_model.fit(X=train_dataiter, eval_data=test_dataiter, batch_end_callback=mx.callback.Speedometer(batch_size),epoch_end_callback=mx.callback.do_checkpoint(\"./models/resnet\"))\n" } ]
2
georgedorn/django-registration
https://github.com/georgedorn/django-registration
d8d3402b39e11664f23a46938fb4d19266ac5a44
18b840aba991a31db210c5c51a8ee0cfd9ee39cf
0652fcf58268c3b23ab9054032de1716377bb699
refs/heads/master
2021-01-16T18:15:05.342380
2013-11-22T05:10:41
2013-11-22T05:10:41
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7734693884849548, "alphanum_fraction": 0.7734693884849548, "avg_line_length": 31.399999618530273, "blob_id": "aa15534ba9f133d0c110b4b15ccb99a8976654ae", "content_id": "ddaa6b0fb4429915fd95bd41855beb4533d34ed2", "detected_licenses": [ "BSD-3-Clause" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "permissive", "max_line_length": 89, "num_lines": 15, "path": "/registration/tests/test_base.py", "repo_name": "georgedorn/django-registration", "src_encoding": "UTF-8", "text": "#find the base.html template that overrides the project one, as urls are also overridden.\n\nimport os, sys\nTESTS_PATH = os.path.dirname(__file__)\nMODULE_PATH = os.path.dirname(TESTS_PATH)\nTEST_TEMPLATE_PATH = os.path.join(MODULE_PATH, 'test_templates')\nTEST_TEMPLATE_DIRS = (TEST_TEMPLATE_PATH,)\n\n\nfrom django.test.utils import override_settings\nfrom django.test import TestCase\n\n@override_settings(TEMPLATE_DIRS=TEST_TEMPLATE_DIRS)\nclass OverriddenTemplatesTestCase(TestCase):\n pass\n " } ]
1
hitswint/TemperatureMonitor
https://github.com/hitswint/TemperatureMonitor
edbdec29bc10d6231738f1abded23e5c16ac45dd
ab6a900e89962e7640aacfe4b45176526e19abf5
b9aa097411b5407ffd225961775f9f8beb1f61f7
refs/heads/master
2021-08-29T21:44:33.168316
2017-12-15T03:49:41
2017-12-15T03:49:41
112,807,046
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.688034176826477, "alphanum_fraction": 0.688034176826477, "avg_line_length": 28.25, "blob_id": "b86acaaf045e60ee34cc5b4362928b5bdeb6c624", "content_id": "c854e741d70b233e3398efc9223137955dc30a0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 55, "num_lines": 8, "path": "/TM/urls.py", "repo_name": "hitswint/TemperatureMonitor", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\nfrom TM.views import index, index_plot\n# from swint.models import Article, Category\n\nurlpatterns = [\n url(r'^$', index, name='index-view'),\n url(r'^plot$', index_plot, name='index-plot-view'),\n]\n" }, { "alpha_fraction": 0.5922330021858215, "alphanum_fraction": 0.5922330021858215, "avg_line_length": 17.727272033691406, "blob_id": "31ea67a71e5275a608ea91fcbb46e907ce1658cc", "content_id": "e3be70924326d536eedd715ea8309f5ad40ab0b6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "no_license", "max_line_length": 70, "num_lines": 22, "path": "/TM/models.py", "repo_name": "hitswint/TemperatureMonitor", "src_encoding": "UTF-8", "text": "from django.db import models\n\n\n# * ArticleSwint\nclass Temperature(models.Model):\n \"\"\"Model for Articles.\"\"\"\n\n time = models.DateTimeField(verbose_name=u\"时间\", auto_now_add=True)\n value = models.TextField(verbose_name=u\"温度\")\n\n class Meta():\n ordering = [\n 'time',\n ]\n\n def __unicode__(self):\n return self.title\n\n __str__ = __unicode__\n\n\n# Create your models here.\n" }, { "alpha_fraction": 0.5871559381484985, "alphanum_fraction": 0.6001079082489014, "avg_line_length": 31.22608757019043, "blob_id": "074c7849f1d14f6d9c8a748f9245c228dae732f7", "content_id": "ef1fcd53e48c11d39d5c5d10496e33ff522e271b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3892, "license_type": "no_license", "max_line_length": 76, "num_lines": 115, "path": "/TM/views.py", "repo_name": "hitswint/TemperatureMonitor", "src_encoding": "UTF-8", "text": "# from django.shortcuts import render\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponse\n# from django.views.generic import ListView\n# from django.conf import settings\nfrom TM.models import Temperature\n# import logging\nfrom django.views.decorators.csrf import csrf_exempt\nimport sqlite3\n# 查看tables:apt安装sqlite3,然后sqlite3 db.sqlite3,输入.tables。\nimport matplotlib.pyplot as plt\n# import os\nimport TM.gl as gl\nfrom channels import Group\n# matplotlib.use('Agg')\n# import matplotlib\n\n# logger = logging.getLogger(__name__)\n\n# Create your views here.\n\n\n@csrf_exempt\ndef index(request):\n if request.method == 'POST':\n add = Temperature(value=request.POST.get(\"temperature_data\", \"\"))\n add.save() # 不save无法保存到数据库\n return HttpResponse(gl.ON_OFF)\n else:\n on_off_value = request.GET.get('on_off_button')\n if on_off_value:\n gl.ON_OFF = int(on_off_value)\n # Channel('websocket.receive').send({'text': str(gl.ON_OFF)})\n Group('default').send({'text': str(gl.ON_OFF)})\n return HttpResponse(gl.ON_OFF)\n # temperature_list = Temperature.objects.all()\n return render_to_response('TM/index.html', {'on_off': gl.ON_OFF})\n\n\ndef index_plot(request):\n # 从sqlite中获取数据。\n conn = sqlite3.connect('db.sqlite3')\n cur = conn.cursor()\n cur.execute(\"SELECT * FROM TM_Temperature\")\n data = cur.fetchall()\n data_0 = [int(row[0]) for row in data][-500:]\n data_2 = [float(row[2]) for row in data][-500:]\n\n plot_file = 'static/TM/plot.png'\n fig1, ax1 = plt.subplots(figsize=(8, 4), dpi=98)\n ax1.set_title(u'房间温度', fontproperties='KaiTi')\n ax1.set_xlabel(u'时间(小时)', fontproperties='KaiTi')\n ax1.set_ylabel(u'温度(\\u2103)', fontproperties='KaiTi')\n plt.ylim(-30, 30)\n ax1.plot(\n data_0,\n data_2, )\n fig1.savefig(plot_file)\n plt.close(fig1)\n\n # temperature_list = Temperature.objects.all()\n return HttpResponse(plot_file)\n\n\n# * Base_Mixin\n# class Base_Mixin(object):\n# \"\"\"Basic mix class.\"\"\"\n\n# def get_context_data(self, *args, **kwargs):\n# context = super(Base_Mixin, self).get_context_data(**kwargs)\n# try:\n# # 网站标题等内容\n# context['website_title'] = settings.WEBSITE_TITLE\n# except Exception:\n# logger.error(u'[BaseMixin]加载基本信息出错')\n# return context\n\n# * Index_View\n# class Index_View(Base_Mixin, ListView):\n# \"\"\"view for index.html\"\"\"\n# model = Temperature\n# # 或者\n# # queryset = Temperature.objects.all()\n# template_name = 'TM/index.html'\n# context_object_name = 'temperature_list'\n\n# # def get(self, request, *args, **kwargs):\n# # article_id = self.kwargs.get('id')\n\n# # # 如果ip不存在就把文章的浏览次数+1。\n# # if ip not in visited_ips:\n# # try:\n# # article = self.queryset.get(id=article_id)\n# # except ArticleSwint.DoesNotExist:\n# # logger.error(u'[ArticleView]访问不存在的文章:[%s]' % article_id)\n# # raise Http404\n# # else:\n# # article.view_times += 1\n# # article.save()\n# # visited_ips.append(ip)\n\n# # # 更新缓存\n# # cache.set(article_id, visited_ips, 15 * 60)\n\n# # return super(Article_View, self).get(request, *args, **kwargs)\n\n# @csrf_exempt\n# def post(self, request, *args, **kwargs):\n# add = Temperature(value=request.POST)\n# add.save() # 不save无法保存到数据库\n# # 或者\n# # Temperature.objects.create(value=request.POST)\n# kwargs['Temp'] = request.POST + 1\n\n# return super(Index_View, self).post(request, *args, **kwargs)\n" }, { "alpha_fraction": 0.4545454680919647, "alphanum_fraction": 0.5454545617103577, "avg_line_length": 10, "blob_id": "36cb06fc81f7530b0407cbaa4d73ed137cfcccc7", "content_id": "b4b9b606f6428795d422046c4826530ead5bc7e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11, "license_type": "no_license", "max_line_length": 10, "num_lines": 1, "path": "/TM/gl.py", "repo_name": "hitswint/TemperatureMonitor", "src_encoding": "UTF-8", "text": "ON_OFF = 0\n" } ]
4
Alesia099/skill4u
https://github.com/Alesia099/skill4u
547d850589c2262c2d1d6d2ec1aba8c56341af70
e90b1cfffe435346b64b074ba8900cdb2e3279b9
ced6b6af7e9c8094110b3a24259a9c6de1ee08f9
refs/heads/master
2020-06-17T21:53:23.678014
2019-07-09T21:22:17
2019-07-09T21:22:17
196,069,223
0
0
null
2019-07-09T19:16:56
2019-07-08T19:59:54
2019-07-08T19:59:52
null
[ { "alpha_fraction": 0.6971317529678345, "alphanum_fraction": 0.7034516334533691, "avg_line_length": 42.787235260009766, "blob_id": "6c4c144e46775d369db1d053d336323d7e95a4c0", "content_id": "cbca8fac3cd8242ad50ff4cc306d737fcbd64742", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2101, "license_type": "no_license", "max_line_length": 115, "num_lines": 47, "path": "/registration/models.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.core.mail import send_mail\nfrom django.contrib.auth.models import PermissionsMixin\nfrom django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager\nfrom django.utils.translation import ugettext_lazy as _\nfrom .validators import validate_birthday, FullNameValidator\nfrom phonenumber_field.modelfields import PhoneNumberField\nfrom .managers import UserManager\n\n\nclass User(AbstractBaseUser, PermissionsMixin):\n full_name_validator = FullNameValidator\n\n email = models.EmailField(_('email'), unique=True)\n full_name = models.CharField(_('full_name'), max_length=100, blank=True)\n #birthday = models.DateField(_(\"birthday\"), validators=[validate_birthday], blank=True)\n region = models.CharField(_(\"region\"), max_length=50)\n city = models.CharField(_(\"city\"), max_length=50)\n phone = PhoneNumberField(_(\"phone\"))\n place_of_study = models.CharField(_(\"place of study\"), max_length=50)\n place_of_work = models.CharField(_(\"place of work\"), max_length=50)\n education = models.CharField(_(\"education\"), max_length=50)\n motivation = models.TextField(blank=True, verbose_name=_(\"about\"))\n is_active = models.BooleanField(default=True, verbose_name=_(\"active\"))\n is_staff = models.BooleanField(default=False, verbose_name=_(\"staff\"))\n is_teacher = models.BooleanField(default=False, verbose_name=_(\"teacher\"))\n date_joined = models.DateTimeField(auto_now_add=True, verbose_name=_(\"date joined\"))\n avatar = models.ImageField(upload_to='avatars/', default='none/blank.jpg', height_field=None, width_field=None)\n\n objects = UserManager()\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = []\n\n class Meta:\n verbose_name = _('user')\n verbose_name_plural = _('users')\n\n def __str__(self):\n return self.full_name\n \n\n def email_user(self, subject, message, from_email=None, **kwargs):\n '''\n Отправляет электронное письмо этому пользователю.\n '''\n send_mail(subject, message, from_email, [self.email], **kwargs)" }, { "alpha_fraction": 0.5666022896766663, "alphanum_fraction": 0.584942102432251, "avg_line_length": 28.600000381469727, "blob_id": "fece7e18dae5d2b5804988787f5adcbda89c1b3e", "content_id": "d31f7b528e4aaf12c6b347bcdec42cad700e0df7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1036, "license_type": "no_license", "max_line_length": 134, "num_lines": 35, "path": "/olympiad/migrations/0002_auto_20190703_2136.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-07-03 21:36\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('olympiad', '0001_initial'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='team',\n old_name='invated',\n new_name='invited',\n ),\n migrations.AlterField(\n model_name='olympiad',\n name='team',\n field=models.ManyToManyField(to='olympiad.Team', verbose_name='team'),\n ),\n migrations.AlterField(\n model_name='task',\n name='creater',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='creater'),\n ),\n migrations.AlterField(\n model_name='team',\n name='capitan',\n field=models.ForeignKey(on_delete='capitan', to=settings.AUTH_USER_MODEL),\n ),\n ]\n" }, { "alpha_fraction": 0.5359525680541992, "alphanum_fraction": 0.5359525680541992, "avg_line_length": 25.47058868408203, "blob_id": "bc386ddd224998f7ae976e72ce4971583d323879", "content_id": "bdfc32358d22c7476b372ffc07a6019050267457", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1349, "license_type": "no_license", "max_line_length": 70, "num_lines": 51, "path": "/registration/trash.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "class UserManager(BaseUserManager):\n use_in_migrations = True\n\n def _create_user(\n self,\n email,\n username,\n full_name,\n birthday,\n region,\n city,\n phone,\n password,\n **extra_fields\n ):\n email = self.normalize_email(email)\n full_name = self.model.normalize_username(full_name)\n extra_fields.setdefault(\"is_staff\", False)\n extra_fields.setdefault(\"is_superuser\", False)\n user = self.model(\n email=email,\n full_name=full_name,\n birthday=birthday,\n region=region,\n city=city,\n phone=phone,\n **extra_fields\n )\n user.set_password(password)\n user.save()\n return user\n\n def create_superuser(\n self,\n email,\n password,\n **extra_fields\n ):\n extra_fields.setdefault(\"is_staff\", True)\n extra_fields.setdefault(\"is_superuser\", True)\n\n if extra_fields.get(\"is_staff\") is not True:\n raise ValueError(\"Superuser must have is_staff=True.\")\n if extra_fields.get(\"is_superuser\") is not True:\n raise ValueError(\"Superuser must have is_superuser=True.\")\n\n return self._create_user(\n email,\n password,\n **extra_fields\n )" }, { "alpha_fraction": 0.5886639952659607, "alphanum_fraction": 0.5979757308959961, "avg_line_length": 47.431373596191406, "blob_id": "431915718bd958e0a0b70ca5f4c5780f53e9b560", "content_id": "baa2f51c8aef13c8cec0cb833f414e6e778a18d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2470, "license_type": "no_license", "max_line_length": 144, "num_lines": 51, "path": "/olympiad/migrations/0001_initial.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-06-29 18:24\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Team',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('max_participations', models.IntegerField(verbose_name='max participations')),\n ('capitan', models.ForeignKey(on_delete='capitam', to=settings.AUTH_USER_MODEL)),\n ('invated', models.ManyToManyField(related_name='invated', to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='Task',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('task', models.TextField()),\n ('input_data', models.CharField(max_length=250, verbose_name='input data')),\n ('answer', models.CharField(max_length=250, verbose_name='answer')),\n ('creater', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='crater')),\n ],\n ),\n migrations.CreateModel(\n name='Olympiad',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=50, verbose_name='')),\n ('duration', models.IntegerField(verbose_name='')),\n ('start_olympiad', models.DateTimeField(verbose_name='date of the start olympiad')),\n ('end_olympiad', models.DateTimeField(verbose_name='date of the end olympiad')),\n ('participation_count', models.IntegerField(verbose_name='participation count')),\n ('max_teams', models.IntegerField(verbose_name='max teams')),\n ('creater', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ('task', models.ManyToManyField(to='olympiad.Task')),\n ('team', models.ManyToManyField(to='olympiad.Team', verbose_name='teams')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.5996480584144592, "alphanum_fraction": 0.6049274206161499, "avg_line_length": 36.56198501586914, "blob_id": "9c3468a5cfb99156da9b4126849ec29d7b995208", "content_id": "8555a33d74f6f5933644be6d6b79ad54e299a013", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4546, "license_type": "no_license", "max_line_length": 137, "num_lines": 121, "path": "/olympiad/views.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import permissions\nfrom rest_framework.authentication import TokenAuthentication\nfrom .serializers import (TaskSerializer, TeamSerializer, OlympiadSerializer)\nfrom .models import (Task, Team, Olympiad)\nfrom registration.models import User\n\n\nclass TaskAPI(APIView):\n \"\"\"Olympiad task\"\"\"\n permission_classes = (permissions.IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n\n def get(self, request):\n task = Task.objects.all()\n serializer = TaskSerializer(task, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n task = request.data.get(\"task\")\n input_data = request.data.get(\"input_data\")\n answer = request.data.get(\"answer\")\n\n if not task or not input_data or not answer:\n return Response({'error': 'Enter all fields.'},\n status=400)\n else:\n Task.objects.create(creater=request.user, task=task, input_data=input_data, answer=answer)\n return Response(status=201)\n\n\nclass TeamAPI(APIView):\n \"\"\"Return teams list\"\"\"\n permission_classes = (permissions.IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n\n def get(self, request):\n team = Team.objects.all()\n serializer = TeamSerializer(team, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n olympiad_id = request.data.get(\"olympiad_id\")\n invited = request.data.get(\"invited\")\n max_participations = request.data.get(\"max_participations\")\n olympiad = Olympiad.objects.get(id=olympiad_id)\n\n if not olympiad_id:\n return Response({'error': 'Olympiad is absent.'},\n status=400)\n else:\n Team.objects.create(capitan=request.user, max_participations=max_participations)\n team = Team.objects.get(capitan=request.user)\n olympiad.team.add(team)\n return Response(status=201)\n \n\nclass InviteToTeam(APIView):\n \"\"\"\"Invite user to Team\"\"\"\n permission_classes = (permissions.IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n\n def get(self, request):\n user = request.user\n team = Team.objects.filter(capitan=user)\n serializer = TeamSerializer(team, many=True)\n return Response(serializer.data)\n\n def post(self, request):\n team_id = request.data.get(\"team_id\")\n invited_id = request.data.get(\"invited_id\")\n \n \n if not team_id or not invited_id:\n return Response({'error': 'Enter all fields.'},\n status=400)\n else:\n team = Team.objects.get(id=team_id)\n user = User.objects.get(id=invited_id)\n \n if not team or not user: \n return Response(status=400)\n else:\n team.invited.add(user)\n return Response(status=201)\n \n\n\nclass OlympiadAPI(APIView):\n \"\"\"Return Olympiad list\"\"\"\n permission_classes = (permissions.IsAuthenticated,)\n authentication_classes = (TokenAuthentication,)\n\n def get(self, request):\n olympiad = Olympiad.objects.all()\n serializer = OlympiadSerializer(olympiad, many=True)\n return Response(serializer.data)\n \n def post(self, request):\n name = request.data.get(\"name\")\n creater = request.user\n duration = request.data.get(\"duration\")\n start_olympiad = request.data.get(\"start_olympiad\")\n end_olympiad = request.data.get(\"end_olympiad\")\n participation_count = request.data.get(\"participation_count\")\n max_teams = request.data.get(\"max_teams\")\n\n if not name or not creater or not duration or not start_olympiad or not end_olympiad or not participation_count or not max_teams:\n return Response({\"error\":\"Enter all fields.\"})\n else:\n Olympiad.objects.create(name=name, \n creater=creater,\n duration=duration, \n start_olympiad=start_olympiad, \n end_olympiad=end_olympiad, \n participation_count=participation_count, \n max_teams=max_teams\n )\n return Response(status=201)\n\n" }, { "alpha_fraction": 0.6794326305389404, "alphanum_fraction": 0.6794326305389404, "avg_line_length": 40.52941131591797, "blob_id": "027989992e7ee37713e6104c6daf277825ddd9e0", "content_id": "5d36db9759fd2aa14c4cb14203b75423b1e24961", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 705, "license_type": "no_license", "max_line_length": 95, "num_lines": 17, "path": "/registration/serializer.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import User\n\nclass UserSerializer(serializers.ModelSerializer):\n password = serializers.CharField(write_only=True, style={'input_type': 'password'})\n password_confirm = serializers.CharField(write_only=True, style={'input_type': 'password'})\n\n class Meta:\n model = User\n fields = ('email', 'full_name', 'password', 'is_teacher', 'password_confirm', 'avatar')\n\n def validate(self, attrs):\n data = super(UserSerializer, self).validate(attrs)\n if data['password'] != data['password_confirm']:\n raise serializers.ValidationError('Password mismatch')\n del data['password_confirm']\n return data" }, { "alpha_fraction": 0.5869688391685486, "alphanum_fraction": 0.5915014147758484, "avg_line_length": 39.1363639831543, "blob_id": "869227a4d996e5e1eb5d9f37512a19978d980ea5", "content_id": "c07ad04e53a6d08b92d5c55a54dd678901a3fe0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1765, "license_type": "no_license", "max_line_length": 90, "num_lines": 44, "path": "/olympiad/models.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom registration.models import User\nfrom django.utils.translation import ugettext_lazy as _\n\n\nclass Task(models.Model):\n \"\"\"\"Olympiad task\"\"\"\n task = models.TextField(blank=False)\n creater = models.ForeignKey(User, verbose_name=_(\"creater\"), on_delete=models.CASCADE)\n input_data = models.CharField(_(\"input data\"), blank=False, max_length=250)\n answer = models.CharField(_(\"answer\"), blank=False, max_length=250)\n\n objects = models.Manager()\n\n\nclass Team(models.Model):\n \"\"\"Teams for Olympiad\"\"\"\n capitan = models.ForeignKey(User, _(\"capitan\"),)\n invited = models.ManyToManyField(User, _(\"invated\"),)\n max_participations = models.IntegerField(_(\"max participations\"), blank=False)\n\n def __str__(self):\n return '%s %s' % (self.capitan, self.invited)\n\n\nclass Olympiad(models.Model):\n name = models.CharField(_(\"\"), max_length=50)\n creater = models.ForeignKey(User, on_delete=models.CASCADE)\n task = models.ManyToManyField(Task)\n duration = models.IntegerField(_(\"\")) # in minutes\n start_olympiad = models.DateTimeField(_(\"date of the start olympiad\"),\n auto_now=False,\n auto_now_add=False\n )\n end_olympiad = models.DateTimeField(_(\"date of the end olympiad\"),\n auto_now=False,\n auto_now_add=False\n )\n participation_count = models.IntegerField(_(\"participation count\"))\n team = models.ManyToManyField(Team, verbose_name=_(\"team\"),)\n max_teams = models.IntegerField(_(\"max teams\"))\n\n def __str__(self):\n return self.name" }, { "alpha_fraction": 0.7582417726516724, "alphanum_fraction": 0.7582417726516724, "avg_line_length": 17.200000762939453, "blob_id": "ae4fac289219413063f0332c2307812e01dc29a8", "content_id": "bab09f7aacf17559eb5f9e5be4a85601da669e1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 91, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/olympiad/apps.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass OlympiadConfig(AppConfig):\n name = 'olympiad'\n" }, { "alpha_fraction": 0.55078125, "alphanum_fraction": 0.7265625, "avg_line_length": 18.69230842590332, "blob_id": "cf325e2199cd7f142aa9103b66667afb641a9c9f", "content_id": "6196856eae149ec92dcd81e9c7444d2407aedcbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 256, "license_type": "no_license", "max_line_length": 31, "num_lines": 13, "path": "/requirements.txt", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "Babel==2.7.0\ndj-database-url==0.5.0\nDjango==2.2.2\ndjango-cors-headers==3.0.2\ndjango-phonenumber-field==2.0.0\ndjangorestframework==3.9.4\ngunicorn==19.9.0\nphonenumberslite==8.10.14\nPillow==6.0.0\npsycopg2==2.8.3\npytz==2019.1\nsqlparse==0.3.0\nwhitenoise==4.1.2\n" }, { "alpha_fraction": 0.6806930899620056, "alphanum_fraction": 0.6896039843559265, "avg_line_length": 33.20338821411133, "blob_id": "c6c163292c9f210d7b6eefdfa0170dfa7da2c545", "content_id": "331de1657bd366cf22b64057ec2a43126755d85f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2020, "license_type": "no_license", "max_line_length": 90, "num_lines": 59, "path": "/registration/views.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "from .models import User\nfrom rest_framework.decorators import api_view, authentication_classes, permission_classes\nfrom rest_framework.response import Response\nfrom rest_framework.authentication import TokenAuthentication\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom registration.serializer import UserSerializer\nfrom django.contrib.auth import authenticate\nfrom django.views.decorators.csrf import csrf_exempt\nfrom rest_framework.authtoken.models import Token\nfrom rest_framework.status import (\n HTTP_400_BAD_REQUEST,\n HTTP_404_NOT_FOUND,\n HTTP_200_OK\n)\n\n@csrf_exempt\n@api_view([\"POST\"])\n@permission_classes((AllowAny,))\ndef login(request):\n email = request.data.get(\"email\")\n password = request.data.get(\"password\")\n if email is None or password is None:\n return Response({'error': 'Please provide both email and password'},\n status=HTTP_400_BAD_REQUEST)\n try:\n user = User.objects.get(email=email, password=password)\n except User.DoesNotExist:\n return Response({'error': 'Invalid Credentials'},\n status=HTTP_404_NOT_FOUND)\n \n token, _ = Token.objects.get_or_create(user=user)\n return Response({'token': token.key},\n status=HTTP_200_OK)\n\n\n@api_view(['GET', 'POST'])\n@permission_classes((AllowAny,))\ndef create(request):\n \"\"\"\n List all code snippets, or create a new snippet.\n \"\"\"\n if request.method == 'GET':\n user = User.objects.all()\n serializer = UserSerializer(user, many=True)\n return Response(serializer.data)\n\n elif request.method == 'POST':\n serializer = UserSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors)\n\n\n@api_view(['GET'])\n@authentication_classes((TokenAuthentication,))\n@permission_classes((IsAuthenticated,))\ndef example_view(request, format=None):\n return Response('Hello')\n\n\n" }, { "alpha_fraction": 0.5452380776405334, "alphanum_fraction": 0.5976190567016602, "avg_line_length": 22.33333396911621, "blob_id": "47608a6c2d1b223d3d025bd9489ccb5b9e0431d1", "content_id": "e8a4539b7f02b712e8e0524ffb74a313aa0da992", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 420, "license_type": "no_license", "max_line_length": 89, "num_lines": 18, "path": "/registration/migrations/0002_auto_20190628_1837.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-06-28 18:37\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('registration', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='full_name',\n field=models.CharField(blank=True, max_length=100, verbose_name='full_name'),\n ),\n ]\n" }, { "alpha_fraction": 0.6883116960525513, "alphanum_fraction": 0.6883116960525513, "avg_line_length": 25.69230842590332, "blob_id": "43e2683826877a10445ce60ea0cbc92b9c25e321", "content_id": "a3b6ec5b7144d2dbde0403f0583447ec227d2e14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 693, "license_type": "no_license", "max_line_length": 67, "num_lines": 26, "path": "/olympiad/serializers.py", "repo_name": "Alesia099/skill4u", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\nfrom .models import Task, Team, Olympiad\nfrom registration.serializer import UserSerializer\n\nclass TaskSerializer(serializers.ModelSerializer):\n \n class Meta:\n model = Task\n fields = ('task', 'input_data')\n\n\nclass TeamSerializer(serializers.ModelSerializer):\n capitan = UserSerializer()\n invited = UserSerializer(many=True)\n\n class Meta:\n model = Team\n fields = ('id', 'capitan', 'invited', 'max_participations')\n\n\nclass OlympiadSerializer(serializers.ModelSerializer):\n team = TeamSerializer(many=True)\n\n class Meta:\n model = Olympiad\n fields = ('id', 'team', 'name', 'participation_count')" } ]
12
kate-ds/Linear_algebra
https://github.com/kate-ds/Linear_algebra
47faee778c1ebb00d9ce08862204fbd35c92fab2
a33539621459242316a33d885662930aa924f28d
9c024f3f107b427c7f10cec322317be9c3fc9735
refs/heads/master
2023-07-01T04:08:01.393380
2021-07-30T08:59:58
2021-07-30T08:59:58
386,343,958
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.39743590354919434, "alphanum_fraction": 0.4615384638309479, "avg_line_length": 32.83333206176758, "blob_id": "c57836949064ceb49e8b0114bda1e45a7f1cda5a", "content_id": "1dc682184909f98a990fc077532c1bcf77a2b552", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1014, "license_type": "no_license", "max_line_length": 85, "num_lines": 30, "path": "/matrix_det.py", "repo_name": "kate-ds/Linear_algebra", "src_encoding": "UTF-8", "text": "def my_det(matrix):\n n = len(matrix)\n assert n == len(matrix[0]), 'Matrix dimention error'\n if n == 1:\n return matrix[0][0]\n elif n == 2:\n return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]\n else:\n det = 0\n for j in range(n):\n minor = [string[:j] + string[j+1:] for string in (matrix[:0]+matrix[1:])]\n det += matrix[0][j]* (-1)**(j)*my_det(minor)\n return det\n\ndef my_det_test():\n a = [[1, -2], [3, 0]]\n b = [[4, -1, 0], [0, 5, 1]]\n c = [[1, 2, 3, 4], [1, 4, 5, 6], [2, 7, 8, 0], [1, 4, 2, 8]]\n d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n e = [[1]]\n print(\"Test1 -\", \"OK\" if my_det(a) == 6 else \"False\")\n print(\"Test2 -\", \"OK\" if my_det(c) == -70 else f\"{print(my_det(c))} - False\")\n print(\"Test3 -\", \"OK\" if my_det(d) == 0 else f\"{print(my_det(d))} - False\")\n try:\n my_det(b)\n except AssertionError:\n print(\"Test4 - OK\")\n print(\"Test5 -\", \"OK\" if my_det(e) == 1 else \"False\")\n\nmy_det_test()" }, { "alpha_fraction": 0.4277286231517792, "alphanum_fraction": 0.49410030245780945, "avg_line_length": 31.285715103149414, "blob_id": "48560ab669f0f3309b95fc9841b56f6cc958cf5b", "content_id": "b712a8ab37f75a7e74ad30e1eb1647e7dc7a5a30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 678, "license_type": "no_license", "max_line_length": 92, "num_lines": 21, "path": "/matrix_multiply.py", "repo_name": "kate-ds/Linear_algebra", "src_encoding": "UTF-8", "text": "def matrix_multiply(matrix1, matrix2):\n n = len(matrix1)\n m = len(matrix2[0])\n mult = [[0 for i in range(n)] for i in range(m)]\n print(mult)\n for i in range(n):\n for j in range(m):\n for k in range(len(matrix2)):\n mult[i][j] += matrix1[i][k] * matrix2[k][j]\n print(mult)\n return mult\n\ndef matrix_multiply_test():\n a = [[1, -2], [3, 0]]\n b = [[4, -1], [0, 5]]\n c = [[1, 2, 3], [4, 5, 6]]\n d = [[1, 2], [3, 4], [5, 6]]\n print(\"Test1 - \", \"OK\" if matrix_multiply(a, b) == [[ 4, -11], [ 12, -3]] else \"False\")\n print(\"Test2 - \", \"OK\" if matrix_multiply(c, d) == [[22, 28], [49, 64]] else \"False\")\n\nmatrix_multiply_test()\n" } ]
2
rcampbell1337/Roman_Numerals
https://github.com/rcampbell1337/Roman_Numerals
5f71c70d04cfdf89f5268c401341a5f97310f540
9e0381844d145351dd30c93b3db27d64c91a758a
550ed954dc1c601798167fa64c9cc5cecc6a46fe
refs/heads/master
2022-05-29T04:27:17.475235
2020-03-08T15:54:37
2020-03-08T15:54:37
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43137967586517334, "alphanum_fraction": 0.4732435345649719, "avg_line_length": 23.183486938476562, "blob_id": "e83d1c8415d527c804a6917369c81cef5f844a3b", "content_id": "890cddd55e549acbdae5291f6f52fa94a895c2bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2747, "license_type": "no_license", "max_line_length": 90, "num_lines": 109, "path": "/roman_Numerals.py", "repo_name": "rcampbell1337/Roman_Numerals", "src_encoding": "UTF-8", "text": "# This is code that i have self written without any tutorial, although i did watch a video\r\n# by Computerphile on this topic about a week ago\r\nimport math\r\n\r\nroman = \"\"\r\n\r\nuser = int(input(\"Please enter a integer value: \"))\r\nstrUser = str(user)\r\nlistnum = [int(i) for i in strUser]\r\nbigguns = listnum[0]\r\n\r\n\r\ndef tens_converter():\r\n global roman\r\n global user\r\n if 5 <= user < 9:\r\n roman = str(roman + \"V\")\r\n while 5 < user < 9:\r\n user = user - 1\r\n roman = str(roman + 'I')\r\n elif user == 4:\r\n roman = str(roman + \"IV\")\r\n elif user < 4:\r\n while user > 0:\r\n user = user - 1\r\n roman = str(roman + 'I')\r\n elif user == 9:\r\n roman = str(roman + \"IX\")\r\n elif 10 < user < 101:\r\n hundreds_converter()\r\n user = listnum[1]\r\n int(user)\r\n tens_converter()\r\n elif 1000 > user > 100:\r\n thousands_converter()\r\n user = int(listnum[1])\r\n user = user * 10\r\n hundreds_converter()\r\n user = listnum[2]\r\n int(user)\r\n tens_converter()\r\n elif user >= 1000:\r\n ten_thousands_converter()\r\n print(user)\r\n user = int(listnum[1])\r\n user = user * 100\r\n print(user)\r\n thousands_converter()\r\n user = int(listnum[2])\r\n user = user * 10\r\n print(user)\r\n hundreds_converter()\r\n print(user)\r\n user = int(listnum[3])\r\n tens_converter()\r\n print(user)\r\n\r\ndef hundreds_converter():\r\n global user\r\n global roman\r\n i = 0\r\n if 10 <= user < 40:\r\n while i < user:\r\n i = i + 10\r\n roman = str(roman + 'X')\r\n elif 40 <= user < 50:\r\n roman = str(roman + \"XL\")\r\n elif 50 <= user < 90:\r\n roman = str(roman + \"L\")\r\n while i < (user - 50):\r\n i = i + 10\r\n roman = str(roman + 'X')\r\n if user == 100:\r\n roman = str(roman + 'C')\r\n elif 90 <= user < 100:\r\n roman = str(roman + \"XC\")\r\n\r\n\r\ndef thousands_converter():\r\n global roman\r\n global user\r\n i = 100\r\n if user == 500:\r\n roman = str(roman + 'D')\r\n elif 500 >= user >= 400:\r\n roman = str(roman + 'CD')\r\n elif 100 < user < 500:\r\n while i < user:\r\n i = i + 100\r\n roman = str(roman + 'C')\r\n elif 500 < user < 900:\r\n roman = str(roman + 'D')\r\n while i <= (user - 500):\r\n i = i + 100\r\n roman = str(roman + 'C')\r\n elif 900 <= user <= 999:\r\n roman = str(roman + 'CM')\r\n\r\n\r\ndef ten_thousands_converter():\r\n global roman\r\n i = 0\r\n while i < (bigguns * 1000):\r\n i = i + 1000\r\n roman = str(roman + 'M')\r\n\r\n\r\ntens_converter()\r\nprint(roman)\r\n\r\n" }, { "alpha_fraction": 0.8059701323509216, "alphanum_fraction": 0.8059701323509216, "avg_line_length": 32.5, "blob_id": "07dc35ffa28b5df3c54a7d08bad0cfb0d0badab3", "content_id": "6a96936eaaeb3053231f1905ff1e78cfcbf50974", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 67, "license_type": "no_license", "max_line_length": 49, "num_lines": 2, "path": "/README.md", "repo_name": "rcampbell1337/Roman_Numerals", "src_encoding": "UTF-8", "text": "# Roman_Numerals\nThis is a roman numeral translator made in python\n" } ]
2
MydonSolutions/SNAPpyPackets
https://github.com/MydonSolutions/SNAPpyPackets
0ea3ce815878d71004468e5a567cbabce0d04e4c
65565ad7edf98371bcfb2b6780a20680afb10347
f2f2383a8a3d827b6aa802e60723d7695d68f270
refs/heads/master
2023-01-19T16:20:54.045550
2020-12-02T16:10:47
2020-12-02T16:10:47
307,637,026
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5960264801979065, "alphanum_fraction": 0.6255267858505249, "avg_line_length": 30.339622497558594, "blob_id": "7dccba1149420fff47843dae93140678d7edc5f5", "content_id": "c57e444d74dcd5301c703e1967c04b67bd878c71", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1661, "license_type": "permissive", "max_line_length": 105, "num_lines": 53, "path": "/send_udp.py", "repo_name": "MydonSolutions/SNAPpyPackets", "src_encoding": "UTF-8", "text": "import socket\nfrom SNAPPacket import SNAPPacket\nimport time\n\nchannels = 256\n\ndef alternate(i, evenVal, oddVal):\n return evenVal if i%2==0 else oddVal\n\ndef int8Comp4(i, realMul, realDiv, realBias, imagMul, imagDiv, imagBias):\n return alternate(i, (int((realMul*i)/realDiv) + realBias)%8, (int((imagMul*i)/imagDiv) + imagBias)%8)\n\n\ndef createPacket(fengId, nchan, schan, real, sampleNumber=0):\n return SNAPPacket(\n 0, #fwVersion\n True, #packetType is voltage\n nchan, #channels\n schan, #channelNum\n fengId, #fEngineId\n sampleNumber, #sampleNumber \n [alternate(i, real, chanI + 8*(chanI%2))#conjugate every second channel\n for chanI in range(nchan) for i in range(16*2*2)]\n )\n\ncachedSampleIs = 1\n\npackets = [createPacket(fengI, channels, channels*strmI, sampleI, sampleI*16) \n for sampleI in range(cachedSampleIs) for strmI in range(1) for fengI in range(1)]\n\nUDP_IP = \"10.11.1.156\"\nUDP_PORT = 4015\nMESSAGE = packets[0].packet()\n\nprint(\"UDP target IP: %s\" % UDP_IP)\nprint(\"UDP target port: %s\" % UDP_PORT)\nprint(len(packets), \"different packets.\")\n\nsock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n\n\nstart = time.time()\n\nwhile('y' in input(\"Send Block? \")):\n for pktI in range(0, 16384):\n for packet in packets:\n sock.sendto(packet.packet(), (UDP_IP, UDP_PORT))\n # sock.sendto(b'hello', (UDP_IP, UDP_PORT))\n packet.update(packetNumber=packet.packetNumber+(16*cachedSampleIs))\n time.sleep(0.00001)\n\nprint(time.time() - start)\n" }, { "alpha_fraction": 0.6103093028068542, "alphanum_fraction": 0.6474226713180542, "avg_line_length": 25.94444465637207, "blob_id": "1e6de7fbc84ce51909f3f7daed9bd02e2b236d86", "content_id": "9448f80b6d3243641b84eadf1957614df0ddb8b5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "permissive", "max_line_length": 67, "num_lines": 18, "path": "/receive_udp.py", "repo_name": "MydonSolutions/SNAPpyPackets", "src_encoding": "UTF-8", "text": "#https://wiki.python.org/moin/UdpCommunication\n\nimport socket\nfrom SNAPPacket import SNAPPacket\n\nUDP_IP = \"0.0.0.0\"\nUDP_PORT = 4015\n\nsock = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\nsock.bind((UDP_IP, UDP_PORT))\n\nwhile True:\n data, addr = sock.recvfrom(8192+16) # buffer size is 8192 bytes\n # print(\"received message: %s\" % data)\n SNAPPacket(packetBytes = data).print(True)\n # if \"n\" in input(\"Continue (Y/n)? \"):\n # break\n" }, { "alpha_fraction": 0.5282996892929077, "alphanum_fraction": 0.5515229105949402, "avg_line_length": 38.12785339355469, "blob_id": "c35a316bc569cab75c651aa94bd781d5cd53ed9a", "content_id": "f71bc4c5740b27cfc91942e00a13eeb0e9219ee7", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8590, "license_type": "permissive", "max_line_length": 119, "num_lines": 219, "path": "/SNAPPacket.py", "repo_name": "MydonSolutions/SNAPpyPackets", "src_encoding": "UTF-8", "text": "mask4bits = ((1 << 4) -1)\nimport numpy as np\n\nmask8bits = ((1 << 8) -1)\nmask16bits = ((1 << 16) -1)\nmask64bits = ((1 << 64) -1)\n\nclass SNAPPacket(object):\n \"\"\"\n ATA SNAP Firmware Manual, Release 2.0.0\n ---------------------------------------\n Section 2.3.2 \"Output Data Formats: Voltage Packets\", pg 5\n https://github.com/realtimeradio/ata_snap/blob/nov-observing/docs/manual.pdf\n\n struct voltage_packet {\n uint8_t version;\n uint8_t type;\n uint16_t n_chans;\n uint16_t chan;\n uint16_t feng_id\n uint64_t timestamp;\n complex4 data[n_chans, 16, 2] // 4-bit real + 4-bit imaginary\n };\n\n • version; Firmware version: Bit [7] is always 1 for Voltage packets. The remaining bits contain a\n compile-time defined firmware version, represented in the form bit[6].bits[5:3].bits[2:0]. This document\n refers to firmware version 2.0.0.\n • type; Packet type: Bit [0] is 1 if the axes of data payload are in order [slowest to fastest] channel x time x\n polarization. This is currently the only supported mode. Bit [1] is 0 if the data payload comprises 4+4 bit\n complex integers. This is currently the only supported mode.\n • n_chans; Number of Channels: Indicates the number of frequency channels present in the payload of\n this data packet.\n • chan; Channel number: The index of the first channel present in this packet. For example, a channel\n number c implies the packet contains channels c to c + n_chans - 1.\n • feng_id; Antenna ID: A runtime configurable ID which uniquely associates a packet with a particular\n SNAP board.\n • timestamp; Sample number: The index of the first time sample present in this packet. For example, a\n sample number 𝑠 implies the packet contains samples 𝑠 to 𝑠 + 15. Sample number can be referred to GPS\n time through knowledge of the system sampling\n \"\"\"\n\n def __init__(self,\n fwVersion: int = None,\n packetType: bool = None,\n channels: int = None,\n channelNum: int = None,\n fEngineId: int = None,\n packetNumber: int = None,\n samples: [int] = None,\n packetBytes: bytearray = None,\n byteorder: str = 'big'\n ):\n self.bytearr = bytearray(8192+16)\n self.payloadbytes = -1\n if packetBytes is not None:\n self.setHeader(\n int.from_bytes(packetBytes[0:1], byteorder=byteorder),\n int.from_bytes(packetBytes[1:2], byteorder=byteorder),\n int.from_bytes(packetBytes[2:4], byteorder=byteorder),\n int.from_bytes(packetBytes[4:6], byteorder=byteorder),\n int.from_bytes(packetBytes[6:8], byteorder=byteorder),\n int.from_bytes(packetBytes[8:16], byteorder=byteorder)\n )\n self.setSampleBytes(packetBytes[16:])\n\n else:\n if not self.setHeader(fwVersion, packetType, channels, channelNum, fEngineId, packetNumber):\n exit()\n if not self.setSamples(samples):\n exit()\n\n def setHeader(self,\n fwVersion: int = None,\n packetType: bool = None,\n channels: int = None,\n channelNum: int = None,\n fEngineId: int = None,\n packetNumber: int = None,\n update: bool = False\n ):\n \n notAllArgs = False\n\n if fwVersion is not None:\n self.fwVersion = fwVersion & mask8bits\n self.bytearr[0] = self.fwVersion\n else:\n notAllArgs = True\n\n if packetType is not None:\n self.packetType = (3 if packetType else 0) & mask8bits\n self.bytearr[1] = self.packetType\n else:\n notAllArgs = True\n\n if channels is not None:\n self.channels = channels & mask16bits\n self.bytearr[2] = (self.channels >> 8) & mask8bits\n self.bytearr[3] = self.channels & mask8bits\n else:\n notAllArgs = True\n\n if channelNum is not None:\n self.channelNum = channelNum & mask16bits\n self.bytearr[4] = (self.channelNum >> 8) & mask8bits\n self.bytearr[5] = self.channelNum & mask8bits\n else:\n notAllArgs = True\n\n if fEngineId is not None:\n self.fEngineId = fEngineId & mask16bits\n self.bytearr[6] = (self.fEngineId >> 8) & mask8bits\n self.bytearr[7] = self.fEngineId & mask8bits\n else:\n notAllArgs = True\n\n if packetNumber is not None:\n self.packetNumber = packetNumber & mask64bits\n self.bytearr[ 8] = (self.packetNumber >> 56) & mask8bits\n self.bytearr[ 9] = (self.packetNumber >> 48) & mask8bits\n self.bytearr[10] = (self.packetNumber >> 40) & mask8bits\n self.bytearr[11] = (self.packetNumber >> 32) & mask8bits\n self.bytearr[12] = (self.packetNumber >> 24) & mask8bits\n self.bytearr[13] = (self.packetNumber >> 16) & mask8bits\n self.bytearr[14] = (self.packetNumber >> 8) & mask8bits\n self.bytearr[15] = self.packetNumber & mask8bits\n else:\n notAllArgs = True\n \n self.payloadbytes = self.channels * 2 * 16\n\n if notAllArgs and not update:\n print(\"Please provide all of the header's arguments.\");\n self.payloadbytes = -1\n return False\n\n return True\n\n def setSamples(self, samples):\n if len(samples)/2 != self.payloadbytes:\n print(\"Header inferred payload byte size {} differs from samples length {}\\n\".format(\n self.payloadbytes, len(samples)/2\n ))\n return False\n for sampleI in range(self.payloadbytes):\n self.bytearr[16+sampleI] = ((samples[2*sampleI] & mask4bits) << 4) + (samples[2*sampleI+1] & mask4bits)\n return True\n\n def setSampleBytes(self, samples):\n if len(samples) != self.payloadbytes:\n print(\"Header inferred payload byte size {} differs from samples length {}\\n\".format(\n self.payloadbytes, len(samples)\n ))\n return False\n self.bytearr[16:self.payloadbytes] = samples\n return True\n\n def packet(self):\n return self.bytearr[:16+self.payloadbytes]\n \n def print(self, headerOnly=False):\n if headerOnly:\n print(self.headerStr())\n else:\n print(self.str())\n\n def twosCompliment(self, value, bits):\n return value if value < (1<<(bits-1)) else (value % (1<<(bits-1))) - (1<<(bits-1))\n\n def str(self):\n return \"\"\"{}\n \\rSamples (0x): {}\"\"\".format(self.headerStr(),\n [complex(self.twosCompliment(i>>4, 4) , self.twosCompliment(i & mask4bits, 4)) \n for i in self.bytearr[16:self.payloadbytes]])\n\n def headerStr(self):\n return \"\"\"Firmware Version: {}\n \\rPacket type: {}\n \\rNumber of Channels: {}\n \\rChannel number: {}\n \\rAntenna ID: {}\n \\rPacket number: {}\n \\rPayload bytes: {}\"\"\".format(self.fwVersion,\n self.packetType,\n self.channels,\n self.channelNum,\n self.fEngineId,\n self.packetNumber,\n self.payloadbytes)\n def update(self,\n fwVersion: int = None,\n packetType: bool = None,\n channels: int = None,\n channelNum: int = None,\n fEngineId: int = None,\n packetNumber: int = None,\n samples: [int] = None\n ):\n self.setHeader(fwVersion, packetType, channels, channelNum, fEngineId, packetNumber, update=True)\n if samples is not None:\n self.setSamples(samples)\n\nif __name__ == '__main__':\n testPacket = SNAPPacket(\n 0,\n True,\n 2,\n 2,\n 0,\n 3735928559,\n [i % 16 for i in range(16*2*2)]\n )\n testPacket.print()\n testPacketBytes = testPacket.packet()\n dupPacket = SNAPPacket(packetBytes=testPacketBytes)\n dupPacket.print()\n dupPacketBytes = dupPacket.packet()\n print(testPacketBytes)\n print(dupPacketBytes)\n" } ]
3
mldbai/test_git_plugin
https://github.com/mldbai/test_git_plugin
788b32f4a1a19eb09f97991c0f61108bc46d8082
5787ed0a4ac8b2b100fbd473b6f03251b929aca5
02d06b86e2337463ae764ced22013448d6d116c1
refs/heads/master
2023-08-31T21:57:52.318129
2016-06-02T14:47:48
2016-06-02T14:47:48
60,270,778
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6341463327407837, "alphanum_fraction": 0.6585366129875183, "avg_line_length": 40, "blob_id": "edc53c9ac0f4b6b70202569632fdb5a9a8ab5921", "content_id": "0c66bbca56aac1868360f68f5def66c6958eacd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 41, "license_type": "no_license", "max_line_length": 40, "num_lines": 1, "path": "/routes.py", "repo_name": "mldbai/test_git_plugin", "src_encoding": "UTF-8", "text": "mldb.plugin.set_return({ \"version\": 2 })\n" } ]
1
juanri0s/python-100-code
https://github.com/juanri0s/python-100-code
8ac9b30aeb647b27ce8cbcc3c37e234cb99d84db
ecdb670587cd1408daeb1e2e7da85055a4f96b64
aebf4b684580e8695954f93a99c2622e1df144f2
refs/heads/master
2021-01-24T11:09:15.632603
2016-10-10T03:13:11
2016-10-10T03:13:11
70,259,406
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6377655863761902, "alphanum_fraction": 0.6489033699035645, "avg_line_length": 35.89610290527344, "blob_id": "5ca4ce69fb56f260795a9b1ce53e7830d8805496", "content_id": "c4fdaf2485ce97a6a328a69750431e75483e3559", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5836, "license_type": "no_license", "max_line_length": 89, "num_lines": 154, "path": "/Trapdoors_And_Catapults_Project.py", "repo_name": "juanri0s/python-100-code", "src_encoding": "UTF-8", "text": "'''\r\nJuan Rios\r\n\r\n\r\n Trapdoors & Catapults is a digital version of Chutes & Ladders.\r\n\r\n RULES:\r\n\r\n PLAYERS. There are two players. Humans are prompted for two names, but\r\n all subsequent action is handled by the program.\r\n\r\n BOARD. The board consists of spaces numbered 0 through 99.\r\n\r\n Ten of the spaces contain a catapult and 10 contain a trapdoor. No space\r\n contains both a catapult and a trapdoor.\r\n\r\n If a player lands on a catapult, the player is flung forward, possibly as\r\n far as but not including the winning space (99).\r\n\r\n If a player lands on a trapdoor, the player is dropped back, possibly as far\r\n as the starting space (0).\r\n\r\n The destination space the player is flung forward to by a catapult or dropped\r\n back to by a trapdoor never contains a catapult or trapdoor. However, any space\r\n may be a destination for multiple trapdoors and/or catapults.\r\n\r\n The spaces that contain trapdoors and catapults and the destination of each\r\n trapdoor and catapult is set at random when the game is set up.\r\n\r\n PLAY. The players begin on space 0. Players move by rolling a die numbered\r\n 1-6. The first to land on space 99 wins.\r\n\r\n The program prints messages telling what happens to each player on each move.\r\n'''\r\n\r\nimport random\r\n\r\ndef getPlayerNames():\r\n print()\r\n player1 = input('Name of first player: ')\r\n player2 = input('Name of second player: ')\r\n\r\n '''Return player1 and player2 '''\r\n return player1, player2\r\n\r\n\r\ndef boardSetup(boardSize, numTrapdoors, numCatapults):\r\n\r\n trapdoors = {} #dictionary 1\r\n catapults = {} #dictionary 2\r\n ''' Select trapdoor-destination pairs at random '''\r\n while len(trapdoors) < numTrapdoors:\r\n trapdoorSpace = random.randint(1, boardSize-2)\r\n if trapdoorSpace in trapdoors:\r\n continue\r\n\r\n ''' Select a destination for this trapdoor. The destination\r\n must be >= 0 and less than the trapdoorSpace and must not be\r\n the location of a trapdoor'''\r\n destination = random.randint(0, trapdoorSpace-1)\r\n while destination in trapdoors:\r\n destination = random.randint(0, trapdoorSpace-1)\r\n\r\n ''' Enter the trapdoorSpace-destination pair into the dictionary '''\r\n trapdoors[trapdoorSpace] = destination\r\n\r\n while len(catapults) < numCatapults:\r\n catapultsSpace = random.randint(1, boardSize-3)\r\n if catapultsSpace in catapults:\r\n continue\r\n destination = random.randint(catapultsSpace + 1, boardSize - 2)\r\n while destination in catapults:\r\n destination = random.randint(catapultsSpace + 1, boardSize - 2)\r\n catapults[catapultsSpace] = destination\r\n\r\n ''' Returns the trapdoors catapults dictionaries '''\r\n return trapdoors, catapults\r\n\r\ndef rollDie():\r\n ''' Roll a six sided die and return the value of the roll '''\r\n return random.randint(1, 6)\r\n\r\ndef switchPlayer(currentPlayer, player1, player2):\r\n if currentPlayer == player1:\r\n return player2\r\n else:\r\n return player1\r\n\r\ndef playGame():\r\n\r\n boardSize = 100\r\n numCatapults = 10\r\n numTrapdoors = 10\r\n\r\n '''' getPlayerNames() to get names for each of the two players '''\r\n player1, player2 = getPlayerNames()\r\n\r\n trapdoors, catapults = boardSetup(boardSize, numTrapdoors, numCatapults)\r\n ''' Initialize the dictionary holding the position of each of the two\r\n players. keys = players. values = position'''\r\n position = {player1:0, player2:0}\r\n\r\n ''' Set the initial player '''\r\n currentPlayer = player1\r\n\r\n ''' Continue play until one player lands on the highest space, and wins '''\r\n while True:\r\n print()\r\n print('Player is', currentPlayer)\r\n print(currentPlayer, 'is on', position[currentPlayer])\r\n move = rollDie()\r\n print(currentPlayer, 'rolls a', move)\r\n\r\n targetPosition = position[currentPlayer] + move\r\n\r\n ''' OVER BOARD SIZE: The roll of the die moves the player beyond\r\n the end of the board. Print error message. '''\r\n if targetPosition > boardSize - 1:\r\n print('Sorry', targetPosition, 'is off the board. No can do,', currentPlayer)\r\n\r\n ''' Switch to the other player '''\r\n currentPlayer = switchPlayer(currentPlayer, player1, player2)\r\n continue\r\n\r\n ''' ON THE BOARD: The target position is on the board, so make the move '''\r\n position[currentPlayer] = targetPosition\r\n print(currentPlayer, 'moves to', position[currentPlayer])\r\n currentPlayer = switchPlayer(currentPlayer, player1, player2)\r\n\r\n\r\n ''' WINNER: If the current player is on the last\r\n space, print a WINS! message and break out of the game loop '''\r\n if position[currentPlayer] == boardSize - 1:\r\n print(currentPlayer , 'you won!')\r\n break\r\n\r\n\r\n ''' TRAPDOOR: The current player has landed on a trapdoor. Move\r\n to the trapdoor destination and print out a message. '''\r\n if position[currentPlayer] in trapdoors:\r\n position[currentPlayer] = trapdoors[position[currentPlayer]]\r\n print('Trapdoor!', currentPlayer, 'falls to', position[currentPlayer])\r\n\r\n currentPlayer = switchPlayer(currentPlayer, player1, player2) #swap\r\n continue\r\n\r\n ''' CATAPULT: If the player has landed on a catapult,\r\n move to the catapult destination and print out a message. '''\r\n if position[currentPlayer] in catapults:\r\n position[currentPlayer] = catapults[position[currentPlayer]]\r\n print('Catapult!', currentPlayer, 'jumps to', position[currentPlayer])\r\n currentPlayer = switchPlayer(currentPlayer, player1, player2) # Swap\r\n continue\r\nplayGame()\r\n" } ]
1
shrenky/PythonPlay
https://github.com/shrenky/PythonPlay
2cdae1b079d1edee9990738a4f72ca9fe9140565
fc2d6a6dd075f7fea2843cf85a9794fe208bfe06
244a9eef40998e63c72283e8ba306f09fc0b4976
refs/heads/master
2016-09-07T03:42:21.212525
2014-07-11T03:43:05
2014-07-11T03:43:05
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5627450942993164, "alphanum_fraction": 0.5764706134796143, "avg_line_length": 35.42856979370117, "blob_id": "f90fd1368cd3514147e91c3b35829e56bca16495", "content_id": "497c1907c7453d66f862be2b75451e13bfaf7da1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 510, "license_type": "no_license", "max_line_length": 67, "num_lines": 14, "path": "/my_wordcounter.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "import string\nfilepath = r'c:\\users\\ysc\\desktop\\sample.txt'\nwith open(filepath, 'r') as f:\n words = {}\n strip = string.whitespace + string.punctuation + string.digits\n print(strip)\n for line in f.readlines():\n for word in line.lower().split():\n word = word.strip(strip)\n if len(word) > 2:\n words[word] = words.get(word, 0) +1\n for word in sorted(words):\n if words[word] > 50:\n print('{0} occurs {1} times'.format(word, words[word]))\n" }, { "alpha_fraction": 0.631147563457489, "alphanum_fraction": 0.631147563457489, "avg_line_length": 16.428571701049805, "blob_id": "abe1d6fad7d6c10d21db10f01e6c6cf344a5e05c", "content_id": "498f7994c2e8fd4182b2aec258803e865989fd4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 122, "license_type": "no_license", "max_line_length": 39, "num_lines": 7, "path": "/using_file.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "poem = '''\\\nPrograimming is fun\nWhen the work is done'''\n\nf = open(r'C:\\users\\ysc\\poem.txt', 'w')\nf.write(poem)\nf.close()\n" }, { "alpha_fraction": 0.557894766330719, "alphanum_fraction": 0.5625730752944946, "avg_line_length": 20.399999618530273, "blob_id": "5ffd88f1cf3d30ff34ebde109dc6b70dff73446f", "content_id": "9ebc0851aef555bc1722068bab715f117710a141", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 855, "license_type": "no_license", "max_line_length": 72, "num_lines": 40, "path": "/classvar.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "class Person:\n '''Represents a persion.'''\n population = 0\n\n def __init__(self, name):\n '''Initializes the person's data'''\n self.name = name\n print('(Initializeing %s)' % self.name)\n\n Person.population += 1\n\n def __del__(self):\n '''I;m dying'''\n print('%s syans bye.' % self.name)\n\n Person.population -= 1\n if Person.population == 0:\n print('Im the last onw')\n else:\n print('There are still %d people left.' % Person.population)\n\n def sayHi(self):\n print('Hi my name is %s' %self.name)\n\n def howMany(self):\n print('We have %d persons here.' % Person.population)\n\nsam = Person('Sam')\nsam.sayHi()\nsam.howMany()\n\ntony = Person('Tony')\ntony.sayHi()\ntony.howMany()\n\nsam.sayHi()\nsam.howMany()\n\nprint(Person.__doc__)\nprint(Person.sayHi.__doc__)" }, { "alpha_fraction": 0.5542168617248535, "alphanum_fraction": 0.5632529854774475, "avg_line_length": 26.70833396911621, "blob_id": "451f7a211de5dbbc57967828fd44403c91439e60", "content_id": "0906e49e04504ae965b8e2045bcb5a31322bf5a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 664, "license_type": "no_license", "max_line_length": 53, "num_lines": 24, "path": "/samtest.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "from html import parser\n\nclass myparser(parser.HTMLParser):\n def __init__(self):\n self.title = ''\n self.titletag = 0\n parser.HTMLParser.__init__(self)\n def handle_starttag(self, tag, attrs):\n if tag == 'title':\n self.titletag = 1\n def handle_endtag(self, tag):\n if tag == 'title':\n self.titletag = 0\n\n def handle_data(self, data):\n if self.titletag == 1:\n self.title += data\n def gettitle(self):\n return self.title\n\nparser = myparser()\nparser.feed('<html><head><title>Test</title></head>'\n '<body><h1>Parse me!</h1></body></html>')\nprint(parser.gettitle())" }, { "alpha_fraction": 0.5083333253860474, "alphanum_fraction": 0.5083333253860474, "avg_line_length": 12.333333015441895, "blob_id": "b586f6d528a6b8629072efeee9724a78b5a76e35", "content_id": "9cccd8be83bb90386abbb6269f32a4dcbbd054ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 240, "license_type": "no_license", "max_line_length": 31, "num_lines": 18, "path": "/function.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "__author__ = 'ysc'\ndef sayHello(s):\n print(s)\n\ndef printMax(a, b):\n if a > b:\n sayHello(\"a is bigger\")\n else:\n sayHello(\"b is bigger\")\n\ndef swap(x, y):\n '''This is\n doc string'''\n pass\n\n\n\nprint(swap.__doc__)\n" }, { "alpha_fraction": 0.6357616186141968, "alphanum_fraction": 0.6556291580200195, "avg_line_length": 21.121952056884766, "blob_id": "e3e20fdf5d92b3afbf6dec97d84e75d75b333117", "content_id": "91f48f9c7a7ca2c6dd80ad2ca750e307cf313702", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 906, "license_type": "no_license", "max_line_length": 48, "num_lines": 41, "path": "/Chess.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "def chess(tr,tc,pr,pc,size):\n\tglobal mark \n\tglobal table\n\tmark+=1\n\tcount=mark\n\tif size==1:\n\t\treturn\n\thalf=size//2\n\tif pr<tr+half and pc<tc+half:\n\t\tchess(tr,tc,pr,pc,half)\n\telse:\n\t\ttable[tr+half-1][tc+half-1]=count\n\t\tchess(tr,tc,tr+half-1,tc+half-1,half)\n\tif pr<tr+half and pc>=tc+half:\n\t\tchess(tr,tc+half,pr,pc,half)\n\telse:\n\t\ttable[tr+half-1][tc+half]=count\n\t\tchess(tr,tc+half,tr+half-1,tc+half,half)\n\tif pr>=tr+half and pc<tc+half:\n\t\tchess(tr+half,tc,pr,pc,half)\n\telse:\n\t\ttable[tr+half][tc+half-1]=count\n\t\tchess(tr+half,tc,tr+half,tc+half-1,half)\n\tif pr>=tr+half and pc>=tc+half:\n\t\tchess(tr+half,tc+half,pr,pc,half)\n\telse:\n\t\ttable[tr+half][tc+half]=count\n\t\tchess(tr+half,tc+half,tr+half,tc+half,half)\n\ndef show(table):\n\tn=len(table)\n\tfor i in range(n):\n\t\tfor j in range(n):\n\t\t\tprint(table[i][j],end='\t')\n\t\tprint('')\n\nmark=0\nn=8\ntable=[[-1 for x in range(n)] for y in range(n)]\nchess(0,0,2,2,n)\nshow(table)" }, { "alpha_fraction": 0.65625, "alphanum_fraction": 0.671875, "avg_line_length": 18.615385055541992, "blob_id": "843ae6925749fecc0c3abb5112a61a0a3364e13e", "content_id": "985be1d01dee11cc61f0c3a7070f9696850f9066", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 44, "num_lines": 13, "path": "/pickling.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "import pickle as p\n\nshoplistfile = 'shoplist.data'\n\nshoplist = ['apple', 'mango', 'carrot']\n\nf = open(r'C:\\users\\ysc\\soplistfile', 'wb')\np.dump(shoplist, f)\nf.close()\n\nf1 = open(r'C:\\users\\ysc\\soplistfile', 'rb')\nstorelist1 = p.load(f1)\nprint(storelist1)\n\n" }, { "alpha_fraction": 0.5614035129547119, "alphanum_fraction": 0.5964912176132202, "avg_line_length": 9.454545021057129, "blob_id": "f9e16bae4bfeddaf22d2d3934c8078eda9a64a82", "content_id": "664b67fb5cebb5deefdeac690f127332c477fcf0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "no_license", "max_line_length": 21, "num_lines": 11, "path": "/pagetest.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "s = [1, True,'d']\nresult = all(s)\nprint(result)\n\ni = 12\nprint(bin(3))\n\ndef test():\n pass\n\nprint(callable(test))" }, { "alpha_fraction": 0.5726495981216431, "alphanum_fraction": 0.6025640964508057, "avg_line_length": 18.58333396911621, "blob_id": "80bb25d2213e3eae1d4b1f8fb90aeeb35c94c9dc", "content_id": "5bd08280b36bf2fd4814da0019bc80eb15b24bb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 234, "license_type": "no_license", "max_line_length": 30, "num_lines": 12, "path": "/my_bank.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "class Bank():\n crisis = False\n def create_atm(self):\n while not self.crisis:\n yield '$100'\n\nhsbc = Bank()\natm1 = hsbc.create_atm()\nprint(next(atm1))\nprint(next(atm1))\nhsbc.crisis = False\nprint(atm1.__next__())" }, { "alpha_fraction": 0.5875216722488403, "alphanum_fraction": 0.6100519895553589, "avg_line_length": 16.515151977539062, "blob_id": "5babd8ce4fef681b8761b065de28edadcb1b8ae9", "content_id": "1c21eb84e83dcd39f65fb4a8097292ab45e083bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 577, "license_type": "no_license", "max_line_length": 37, "num_lines": 33, "path": "/my_generator.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "def quarters(next_quarter=0.0):\n while True:\n yield next_quarter\n next_quarter += 0.25\n\nresult = []\nfor x in quarters():\n result.append(x)\n if x >= 1.0:\n break\n else:\n print(x)\n\nmyliterator = [x*x for x in range(3)]\nfor i in myliterator:\n print(i)\n\nfor i in myliterator:\n print(i)\n\nmygenerator = (x*x for x in range(3))\nfor i in mygenerator:\n print(i)\n\ndef create_generator():\n mylist = range(3)\n for i in mylist:\n yield i*i\n\nmygenerator1 = create_generator()\nprint(mygenerator1)\nfor i in mygenerator1:\n print(i)" }, { "alpha_fraction": 0.6144578456878662, "alphanum_fraction": 0.6325300931930542, "avg_line_length": 14.090909004211426, "blob_id": "c467009e0be5bad12779d81de2afeb7cfb360c30", "content_id": "89f259a4a84c8ecef08251d83866401bed944d0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 166, "license_type": "no_license", "max_line_length": 27, "num_lines": 11, "path": "/list.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "__author__ = 'ysc'\nlist = []\nlist.append(\"item1\")\nlist.append(\"item2\")\nprint(list)\nfor item in list:\n print(item)\n\nprint(list.pop(0))\n\nprint(\"length:\", len(list))\n" }, { "alpha_fraction": 0.6136986017227173, "alphanum_fraction": 0.619178056716919, "avg_line_length": 19.05555534362793, "blob_id": "9309fb477419c56e088c61e0d324ece089ca1599", "content_id": "311f29d2b99540c056a5a924783336b9df0e3349", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 365, "license_type": "no_license", "max_line_length": 62, "num_lines": 18, "path": "/backup_ver1.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "__author__ = 'ysc'\nimport os\nimport time\n\nsource = [r'C:\\Users\\ysc\\Source']\n\ntarget_dir = r'C:\\Users\\ysc\\Backup'\n\ntarget = target_dir + time.strftime(('%Y%m%d%H%M%S')) + '.zip'\n\nzip_command = 'Rar a %s *.* %s' % (target, source[0])\n\nprint(zip_command)\n\nif os.system(zip_command) == 0:\n print('Successfule backup to', target)\nelse:\n print('backup failed')\n\n\n\n\n" }, { "alpha_fraction": 0.607299268245697, "alphanum_fraction": 0.6583941578865051, "avg_line_length": 47.64285659790039, "blob_id": "86edd7cf2fb30146869c73a0c1199a5001537255", "content_id": "afe20d40bac83516022e7963da1337ba1a23986d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 685, "license_type": "no_license", "max_line_length": 114, "num_lines": 14, "path": "/my_taobao.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "from requests import session\n\nloginurl = r'https://login.taobao.com/member/login.jhtml'\nshuurl = r'http://shu.taobao.com/trendindex?query=%E4%B8%96%E7%95%8C%E6%9D%AF'\npayload = {'tz_offset': '480', 'username': 'xxx', 'password': 'xxx', 'realm': 'user-realms'}\nwith session() as c:\n result = c.post(loginurl, data=payload, verify=False)\n request = c.get(shuurl)\n #print(request.url)\n result2 = c.post(request.url, data=payload, verify=False)\n h = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',\n 'Referer': 'https://login.taobao.com'}\n request2 = c.get(shuurl, headers=h)\n print(request2.text)\n\n\n\n\n" }, { "alpha_fraction": 0.37980085611343384, "alphanum_fraction": 0.3826458156108856, "avg_line_length": 32.28571319580078, "blob_id": "6b66dfebd38647fc0be159b29b7f9a62aa1f2ff4", "content_id": "b6a5605c306d18fa42a0c6ff918b0771ca6eeb67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 703, "license_type": "no_license", "max_line_length": 66, "num_lines": 21, "path": "/my_externalsites.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "filepath = r'c:\\users\\ysc\\desktop\\html.txt'\nwith open(filepath, 'r') as f:\n sites = []\n for line in f.readlines():\n i = 0\n while True:\n site = None\n i = line.find('https://', i)\n if i > -1:\n i += len('https://')\n for j in range(i, len(line)):\n if not (line[j].isalnum() or line[j] in \".-\"):\n site = line[i:j].lower()\n sites.append(site)\n break\n #if site and '.' in site:\n # sites.setdefault(site, set()).add(f.name)\n i = j\n else:\n break\n print(sites)\n\n\n\n\n" }, { "alpha_fraction": 0.517241358757019, "alphanum_fraction": 0.532567024230957, "avg_line_length": 20.75, "blob_id": "01c1e97b24e94e9a31aadab0558881a38c28295b", "content_id": "c9ebd5a625e0599547f212a67d72f11f9ea9ef60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "no_license", "max_line_length": 47, "num_lines": 12, "path": "/personclass.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "__author__ = 'ysc'\nclass Person:\n def __init__(self, *args):\n self.name = args[0]\n self.age = args[1]\n def sayHi(self):\n print('Hello, how are you?', self.name)\n print('aget',self.age)\n\np = Person('Sam', 18)\nprint(p)\np.sayHi()\n" }, { "alpha_fraction": 0.5570200681686401, "alphanum_fraction": 0.5575931072235107, "avg_line_length": 27.62295150756836, "blob_id": "355cff48f975d271e4cc0b090dc811827dd3b3c4", "content_id": "1d62134d2456f8bc3dd0fecb3d9aceabca295c24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1745, "license_type": "no_license", "max_line_length": 147, "num_lines": 61, "path": "/htmltest.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "from html import parser\nimport sys, re\n\nclass TitleParser(parser.HTMLParser):\n def __init__(self):\n self.title = None\n self.taglevels = []\n self.handledtags = ['title', 'ul', 'li']\n self.processing = None\n parser.HTMLParser.__init__(self)\n\n def handle_starttag(self, tag, attrs):\n if len(self.taglevels) and self.taglevels[-1] == tag:\n self.handle_endtag(tag)\n\n self.taglevels.append(tag)\n\n if tag in self.handledtags:\n self.data = ''\n self.processing = tag\n if tag == 'ul':\n print('List statted')\n\n def handle_data(self, data):\n if self.processing:\n self.data += data\n\n def handle_endtag(self, tag):\n if not tag in self.taglevels:\n return\n\n while len(self.taglevels):\n starttag = self.taglevels.pop()\n\n if starttag in self.handledtags:\n self.finishprocessing(starttag)\n\n if starttag == tag:\n break\n\n def cleanse(self):\n self.data = re.sub('\\s+', ' ', self.data)\n\n def finishprocessing(self, tag):\n self.cleanse()\n if tag == 'title' and tag == self.processing:\n print('Document title: ' + self.data)\n self.title = self.data\n elif tag == 'ul':\n print('List ended')\n elif tag == 'li' and tag == self.processing:\n print('list item: ' + self.data)\n\n self.processing = None\n\n def gettitle(self):\n return self.title\n\nmyparser = TitleParser()\nmyparser.feed('<HTML><HEAD><TITLE>Doc Title</TITLE></HEAD><BODY>This is my body<UL><LI>first item<LI>second item</LI><LI>thirs item</BODY></HTML>')\nprint(myparser.gettitle())" }, { "alpha_fraction": 0.6111111044883728, "alphanum_fraction": 0.6180555820465088, "avg_line_length": 17, "blob_id": "4f9cd0eae3f26f8c1dfbc3a2e65284e634ca7dee", "content_id": "37439932ce99056a530c1874cafbc70565bc75f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "no_license", "max_line_length": 49, "num_lines": 16, "path": "/object.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "__author__ = 'ysc'\nshoplist = [\"apple\", \"Mango\", \"Carrot\", \"Banana\"]\nmylist = shoplist\n\ndel shoplist[0]\n\nprint(\"Shop list is\", shoplist)\nprint(\"My list is\", mylist)\n\nprint(\"===============\")\n\nmylist = shoplist[:]\ndel mylist[0]\n\nprint(\"Shop list is\", shoplist)\nprint(\"My list is\", mylist)\n" }, { "alpha_fraction": 0.5942623019218445, "alphanum_fraction": 0.6024590134620667, "avg_line_length": 19.25, "blob_id": "8df7327d988c43419f54432cb033cc9acc050325", "content_id": "583a0421527daa5d387500b15cde167dcc4785a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 45, "num_lines": 12, "path": "/condition.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "__author__ = 'ysc'\nnumber= 23\nguess = int(input('Enter an integer:'))\nif guess == number:\n print('Congratulations, you guessed it.')\n print('(but y;;;;;;')\nelif guess < number:\n print(\"lower\")\nelse:\n print(\"higher\")\n\nprint(\"Done\")\n\n" }, { "alpha_fraction": 0.6639999747276306, "alphanum_fraction": 0.6639999747276306, "avg_line_length": 14.625, "blob_id": "8ecf737e549b5da402ac0412c12d67e73c157993", "content_id": "d8f467a5efe6fb91afd2e22c6bb2ed559423a986", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 125, "license_type": "no_license", "max_line_length": 40, "num_lines": 8, "path": "/baidutest.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "import requests\nimport io\n\nr = requests.get('http://www.baidu.com')\nf = r.read()\n\nfor line in f.readlines():\n print(line)\n" }, { "alpha_fraction": 0.5337423086166382, "alphanum_fraction": 0.546012282371521, "avg_line_length": 13.727272987365723, "blob_id": "9c74d866582c95790db736ea6e62442f3c5aec3a", "content_id": "df4d67da7b6bb3c396e8c1338c2e317e01923cca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 163, "license_type": "no_license", "max_line_length": 37, "num_lines": 11, "path": "/mod1.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "__author__ = 'ysc'\nif __name__ == \"__main__\":\n print(\"Run myself\")\nelse:\n print(\"Import by another module\")\n\n\ndef say():\n print(\"Saying\")\n\nVersion = 1.0\n\n" }, { "alpha_fraction": 0.6343283653259277, "alphanum_fraction": 0.6940298676490784, "avg_line_length": 12.5, "blob_id": "7cfaeef1918b877630c83ee15015efeb7bb3a8e7", "content_id": "23e5a415a672e187466b14ab5ecdb697d7820bf5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 138, "license_type": "no_license", "max_line_length": 31, "num_lines": 10, "path": "/testsys.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "import sys\nprint(sys.getdefaultencoding())\ns = \"你好\"\nprint(len(s))\ns1 = str(s)\nprint(s1)\nprint(type(s))\nprint(type(s1))\n\nprint(0x493e0)" }, { "alpha_fraction": 0.60550457239151, "alphanum_fraction": 0.642201840877533, "avg_line_length": 10, "blob_id": "1bac28811d2b7966ed8cbc8dec396fe28307fae8", "content_id": "c3890fcee3200d1d2c1a62ee3da27123ff95d47c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "no_license", "max_line_length": 31, "num_lines": 10, "path": "/temp1.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "__author__ = 'ysc'\nimport mod1\nimport sys\nmod1.say()\nprint(\"Version:\", mod1.Version)\n\na = 5\ndir()\ndel a\ndir()" }, { "alpha_fraction": 0.5649999976158142, "alphanum_fraction": 0.5649999976158142, "avg_line_length": 17.272727966308594, "blob_id": "4b64165e41a08a9dd09decb1c8f4948d2d6b677c", "content_id": "7e544f3d17d043624ad765ea52d68fd9f6f77056", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 39, "num_lines": 11, "path": "/my_dictactions.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "def add_dvd():\n print('add ')\n\ndef edit_dvd():\n print('edit ')\n\nfunctions = dict(a=add_dvd, e=edit_dvd)\naction = input('pls input command:'\n '(A)dd (E)dit \\n')\n\nfunctions[action]()" }, { "alpha_fraction": 0.48148149251937866, "alphanum_fraction": 0.7453703880310059, "avg_line_length": 70.66666412353516, "blob_id": "81d9538fdc8fe01f98377ae5064207d1cc9c59d5", "content_id": "4c3e669f838fcd3ea4a5e0e89fa9f3e15a02974f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 220, "license_type": "no_license", "max_line_length": 106, "num_lines": 3, "path": "/logintest.py", "repo_name": "shrenky/PythonPlay", "src_encoding": "UTF-8", "text": "import re\nurl = \"item[1]=new title_array('6月17日','http://web.btv.com.cn/CN02/special/C10113/20140618/100736.shtml')\"\nurl1 = 'https://27.112.85.200/CN02/special/C10113/20140618/,DanaInfo=.awfdCfy1GkxwKo0+100736.shtml'\n\n" } ]
24
louiserfallon/NetworkXOperations
https://github.com/louiserfallon/NetworkXOperations
c1f37d29c01a6d9269524b35902844abc8dd8c6a
1fb929d2d7e0d5cc630d488c6aa15e8269a831ee
2a695c80307b8b3669b058120a16e8f7aad617ca
refs/heads/master
2020-07-04T18:58:40.281454
2016-12-22T01:11:57
2016-12-22T01:11:57
74,147,094
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5997515320777893, "alphanum_fraction": 0.6315528154373169, "avg_line_length": 40.06122589111328, "blob_id": "eb0401ac5e60a18aaae9363c4c407391aa1655da", "content_id": "675e0b728fe0b361bfd0916f0e5180eb6376ed80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4025, "license_type": "no_license", "max_line_length": 163, "num_lines": 98, "path": "/HW3/3a_code_for_attributes.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 17 15:32:52 2016\n\n@author: George Pastakas \n\"\"\"\n\nimport os\nimport pandas as pd\nimport networkx as nx\nfrom collections import OrderedDict\nimport json\n\n# Change directory to your local directory to run code - Run code at the parent directory of 'Data_Group_HW' folder\n#os.chdir('C:/Users/user/Dropbox (Personal)/Imperial College Business School/MSc Business Analytics/Autumn Term/Network Analytics/Git_Repo/NetworkXOperations/HW3')\n\n# Create an empty list for the villages characteristics\ncsd = []\n\n# Load the info for the households of all villages\nhh_data = pd.read_stata('Data_Group_HW/household_characteristics.dta')\n\n# The villages we need\nv_id = [1, 2, 3, 4, 6, 9, 12, 15, 19, 20, 21, 23, 24, 25, 29, 31, 32, 33, 36, \\\n 39, 42, 43, 45, 46, 47, 48, 50, 51, 52, 55, 57, 59, 60, 62, 64 ,65, \\\n 67, 68, 70,71, 72, 73, 75]\n\nfor i in v_id:\n vil_dict = OrderedDict()\n\n # MF dummy variables of village i\n mf = pd.read_csv('Data_Group_HW/MF dummy/MF' + str(i) + '.csv', names = ['MF'])\n \n # Take the household data for village i\n v_data = hh_data[hh_data['village'] == i]\n v_data = v_data.reset_index()\n \n # Merge the two dataframes based on HH ids\n v_data = pd.concat([mf, v_data], axis = 1)\n \n # Read adjacency matrix for village i HH\n adj = pd.read_csv('Data_Group_HW/Adjacency Matrices/adj_allVillageRelationships_HH_vilno_' \\\n + str(i) + '.csv', header = None)\n\n # Create undirected graph based on adjacency matrix\n G = nx.from_numpy_matrix(adj.as_matrix())\n\n ### 1/ Number of village\n vil_dict['village'] = i\n\n ### 2/ MF take up rate\n vil_dict['mf'] = v_data[v_data['leader'] == 0]['MF'].mean()\n \n ### 3/ Average degree centrality of leaders\n v_data['degree'] = list(nx.degree(G).values())\n \n vil_dict['degree_leader'] = v_data[v_data['leader'] == 1][v_data['hhSurveyed'] == 1]['degree'].mean()\n\n ### 4/ Average eigenvector centrality of leaders\n v_data['eigenvector'] = list(nx.eigenvector_centrality(G, tol = 5e-06).values())\n \n vil_dict['eigenvector_centrality_leader'] = v_data[v_data['leader'] == 1]['eigenvector'].mean()\n \n ### 5/ Average betweenness centrality of leaders\n v_data['betweenness'] = list(nx.betweenness_centrality(G).values())\n \n vil_dict['betweenness_centrality_leader'] = v_data[v_data['leader'] == 1][v_data['hhSurveyed'] == 1]['betweenness'].mean()\n\n ### 9/ Average closeness centrality of leaders\n v_data['closeness'] = list(nx.closeness_centrality(G).values())\n \n vil_dict['closeness_centrality_leader'] = v_data[v_data['leader'] == 1][v_data['hhSurveyed'] == 1]['closeness'].mean()\n \n ### 11/ Number of households\n vil_dict['numHH'] = v_data.shape[0]\n\n ### 12/ Fraction of leaders\n vil_dict['fractionLeaders'] = v_data[v_data['leader'] == 1].shape[0]/v_data.shape[0]\n\n ### extra/ Fraction of taking leaders (divided by the total number of leaders)\n vil_dict['fractionTakingLeaders_leaders'] = v_data[v_data['leader'] == 1][v_data['MF'] == 1].shape[0]/ \\\n v_data[v_data['leader'] == 1].shape[0]\n\n ### extra/ Average eigenvector centrality of taking leaders\n vil_dict['eigenvector_centrality_taking_leader'] = v_data[v_data['leader'] == 1][v_data['MF'] == 1]['eigenvector'].mean()\n \n # Append dictionary with village i characteristics to the list\n csd.append(vil_dict)\n \n# Convert list of dictionaries to json file and then to pandas\nfinal_df = pd.read_json(json.dumps(csd, indent = 2))\nfinal_df = final_df[['village', 'mf', 'degree_leader', 'eigenvector_centrality_leader', \\\n 'betweenness_centrality_leader', 'closeness_centrality_leader', \\\n 'numHH', 'fractionLeaders', \\\n 'fractionTakingLeaders_leaders', 'eigenvector_centrality_taking_leader']]\n\n# Export dataframe to .csv file\nfinal_df.to_csv('Data_Group_HW/our_cross_sectional.csv', sep = ',', index = False) \n" }, { "alpha_fraction": 0.7886699438095093, "alphanum_fraction": 0.7943349480628967, "avg_line_length": 83.58333587646484, "blob_id": "2bf62e0e53ad404b70840f4357fa5e9dc3f8558d", "content_id": "5bdde22d283d091f1f0a73a29f989666614db08c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 4076, "license_type": "no_license", "max_line_length": 461, "num_lines": 48, "path": "/HW3/Group1_HW3_Q3b - LF.Rmd", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "---\ntitle: \"Group_1_HW3_Q3b_LF\"\nauthor: \"Louise Fallon\"\ndate: \"18 December 2016\"\noutput: pdf_document\n---\n```{r echo=FALSE, eval=FALSE}\n##not to be included, but typos that need to be fixed in the report:\n## paraemters > parameters at the start\n## rolloing-horizon, twice in question 2\n```\n\n## Model\n\nThe data was collected through a questionnaire that focused on village, household and individual characteristics, including network data. This was supported by and matched with regular administrative data on who joined the program.\nThe discrete time models that were estimated had the following structure:\n\n1. The set of initial leaders (exogenously chosen) were informed and chose whether or not to participate.\n2. In each time period, households passed information on with a certain probability that varied according to\nwhether the household had chosen to participate ($q^P$) or not ($q^N$).\n3. In each time period, the previously informed households decide whether to participate or not.\nIn the baseline “information” model, the probability that an individual takes up microfinance, given that they are informed, $p_i(\\alpha,\\beta)$ is given by:\n$$p_i = P (participation|X_i) = \\Delta(\\alpha + X_i\\beta)$$\nWhere X contains attributes of the individual and its neighbours (but does not include \"endorsement\": whether the neighbours have taken up or not).\n\n###Estimation Procedure\nThe final model was fit using a Method of Simulated Moments approach. The dynamic simulation was run 75 times for each possible combination of parameters, $\\theta$ = ($q^N, q^P, p_i(\\alpha,\\beta)$), the moments were averaged across those simulations, and then the set of parameters that minimised the square of the average difference between the simulated moments and the empirically collected moments is identified as the set of estimates for those parameters.\n\nThe moments used to estimate the model include\n\n* One non-network moment: the share of leaders who take up microfinance\n* Three proportion-based network moments: The share of households who take up microfinance with none of their neighbours having taken up, The share of households that take up microfinance - and are in the neighbourhood of a leader that takes up microfinance, and the share of \n* Two covariance-based network moments: The covariance of the proportion of households taking up compared to the share of their neighbours who take up microfinance, and the covariance of the proportion of households taking up compared to the proportion of second-degree neighbours that take up\n\nTo estimate the standard errors for the parameter estimates, a grid-based Bayesian bootstrap algorithm is used, using 1000 samples (resampling with replacement), finding the optimal parameters for each sample (weighted due to the random sampling method), and using this to estimate the sample distribution.\n\n###Robustness Checks\nThe following were undertaken to check and justify the use of the “information model”:\n\n* A model including endorsement effects was also run, and those effects not found to be significant.\n* The model was estimated with a different set of moments, and found that the parameters were comparable, and still significantly different.\n* Microfinance participation was replaced with a “placebo” outcome, “type of roof”, which gave very high parameters, which was expected for cases where information transmission is not highly relevant.\n* The model was compared to a model only using distance to the leaders.\n\n###Conclusions Drawn\nWith the chosen model (without endorsement), the paper estimates $q^N = 0.1$ and $q^P = 0.5$, both being individually statistically significant, and significantly different from each other. This implies that the probability of a neighbour taking up microfinance from someone who is informed is higher if that person has also taken up microfinance.\n\nThe robustness assessment implies the adoption of microfinance depends on more than just the closeness to the leaders, although there is an identified limitation that the dynamic model is more accurate for later time periods.\n" }, { "alpha_fraction": 0.6608876585960388, "alphanum_fraction": 0.6849283576011658, "avg_line_length": 35.25862121582031, "blob_id": "f9cadf5f794682ac0994fbda79455885b24fbc44", "content_id": "09d4320f65463339407463354a57ccd605c97bcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4326, "license_type": "no_license", "max_line_length": 112, "num_lines": 116, "path": "/Group1_HW1.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Nov 21 19:52:42 2016\r\n\r\n@author: Group 1\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport networkx as nx\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom collections import Counter\r\n\r\n# Function to read in two adjacency matrices in Q2\r\n# If the 0-1 adjacency matrix contains more edges than the weighted adjacency matrix, \r\n# Add the 0-weight edges to the final graph\r\ndef graphAdjMatrix(nonweightedAdjMat, weightedAdjMat):\r\n \r\n G1 = nx.Graph(nonweightedAdjMat)\r\n G2 = nx.Graph(weightedAdjMat)\r\n \r\n G1_edge = G1.edges()\r\n G2_edge = G2.edges()\r\n \r\n if len(G1_edge) > len(G2_edge):\r\n for (src, dest) in G1_edge:\r\n if (src, dest) not in G2_edge:\r\n G2.add_edge(src, dest, weight = 0)\r\n \r\n return G2\r\n\r\nDGraph = nx.read_weighted_edgelist(\"HW1_problem1.txt\",create_using=nx.DiGraph())\r\n\r\n# Figure Size\r\nplt.figure(figsize = (4, 3))\r\n\r\n# Graph Drawing for Qn 1\r\npos = nx.circular_layout(DGraph)\r\nedge_labels = dict([((u,v), d['weight']) for u,v,d in DGraph.edges(data=True)])\r\nnx.draw_networkx_edge_labels(DGraph, pos, edge_labels = edge_labels)\r\nnx.draw_networkx_labels(DGraph, pos)\r\nnx.draw(DGraph, pos, node_size = 500, node_color = 'lightblue')\r\n\r\n# Qn 1a: Print Incidence Matrix\r\nincidence_matrix = nx.incidence_matrix(DGraph, nodelist = sorted(DGraph.nodes()), oriented=True, weight = None)\r\nprint(pd.DataFrame(incidence_matrix.todense(), index = sorted(DGraph.nodes())))\r\n\r\n# Qn 1b: Shortest Paths Matrix\r\nshortestpaths = nx.floyd_warshall_numpy(DGraph, nodelist = sorted(DGraph.nodes()), weight = 'weight')\r\nprint(pd.DataFrame(shortestpaths, columns = sorted(DGraph.nodes()), index = sorted(DGraph.nodes())))\r\n\r\n# Qn 1c: Diameter of the graph\r\nshortestpaths[np.isfinite(shortestpaths)].max()\r\n\r\n# Qn 1d: Degree Distribution\r\n## Degree Distribution Table\r\ndegreeTable = pd.DataFrame.from_dict(nx.degree(DGraph), 'index').sort_index()\r\ndegreeTable.columns = ['degree']\r\nprint(degreeTable)\r\n\r\n## Degree Distrubtion Plot\r\nin_degrees = DGraph.in_degree()\r\nin_values = sorted(set(in_degrees.values()))\r\nin_degree_values = list(in_degrees.values())\r\n\r\nout_degrees = DGraph.out_degree()\r\nout_values = sorted(set(out_degrees.values()))\r\nout_degree_values = list(out_degrees.values())\r\n\r\nin_hist = [x + y for x, y in zip(in_degree_values, out_degree_values)]\r\n\r\nplt.figure(figsize = (4, 3))\r\n\r\nplt.hist(in_hist, width = 0.60, bins = np.arange(max(in_hist)+2)-0.3, color = 'lightblue')\r\nplt.title('Degree distribution of the graph')\r\nplt.xlabel('Degree')\r\nplt.ylabel('Number of nodes')\r\nplt.xticks(range(max(in_hist)+1))\r\nplt.yticks(range(Counter(in_hist).most_common(1)[0][1]+2))\r\nplt.show()\r\n\r\n# Qn 1e: Weakly Connected Graph\r\nnx.is_weakly_connected(DGraph) # Weakly connected graph test\r\nnx.is_strongly_connected(DGraph) # Strongly connected graph test\r\n\r\n# Qn 2: Visualization Graph\r\nadjMatrix = np.loadtxt(\"HW2_problem2.txt\", dtype=int)\r\n\r\n# Use graphAdjMatrix() function to read in both 0-1 and weighted adjacency matrices\r\n# Ensure that no 0-weighted edges are missed out\r\nadjShape = np.shape(adjMatrix)\r\ngraph = graphAdjMatrix(adjMatrix[0 : adjShape[1], ], adjMatrix[adjShape[1] : adjShape[0], ])\r\n\r\n# Graph without weights\r\nplt.figure(figsize = (12, 10))\r\n\r\npos = nx.spring_layout(graph, k=0.25, iterations=100)\r\nnx.draw(graph, pos, node_color = 'blue', width = 3.0)\r\nnx.draw_networkx_labels(graph, pos, font_color = \"white\", font_size=10)\r\n\r\n# Graph with weights denoted by darkness of edges, weight is also labelled\r\nplt.figure(figsize = (12, 10))\r\n\r\npos = nx.spring_layout(graph,k=0.25,iterations=100)\r\nnx.draw(graph, pos, node_color = 'black', edge_color = [d['weight'] for (u, v, d) in graph.edges(data = True)], \r\n width = 5.0, edge_cmap=plt.cm.Blues)\r\nnx.draw_networkx_labels(graph, pos, font_color = \"white\", font_size=10)\r\nnx.draw_networkx_edge_labels(graph, pos, edge_labels = nx.get_edge_attributes(graph, 'weight'), font_size = 8)\r\n\r\n# Circular Layout, weights denoted by darkness of edges\r\nplt.figure(figsize = (12, 10))\r\n\r\npos = nx.circular_layout(graph)\r\nnx.draw(graph, pos, node_color = 'black', edge_color = [d['weight'] for (u, v, d) in graph.edges(data = True)], \r\n width=2.5, edge_cmap=plt.cm.Blues)\r\nnx.draw_networkx_labels(graph, pos, font_color=\"white\", font_size=10)\r\n\r\n\r\n" }, { "alpha_fraction": 0.8513513803482056, "alphanum_fraction": 0.8513513803482056, "avg_line_length": 36, "blob_id": "f393cce34ebf630bdc89b44858e9327bda4d4f02", "content_id": "41feca97a58c12e96394b00e175074cffb525fb5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 74, "license_type": "no_license", "max_line_length": 52, "num_lines": 2, "path": "/README.md", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# NetworkXOperations\nGroup Repo for Network X basic operations assignment\n" }, { "alpha_fraction": 0.6219627857208252, "alphanum_fraction": 0.6400911211967468, "avg_line_length": 35.3206901550293, "blob_id": "acae1c077b45a582f56cd6373f5706252502ee80", "content_id": "554884b011c723cce65a1600a2b1b1fc9e6ec5db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10536, "license_type": "no_license", "max_line_length": 152, "num_lines": 290, "path": "/HW2/Group2_HW2_GP.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 23 14:56:48 2016\n\nAuthor: George Pastakas\nTitle: Homework 2\nSubtitle: Group Part\n\"\"\"\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nimport matplotlib.pyplot as plt\nfrom matplotlib import pyplot\nfrom haversine import haversine\nfrom mpl_toolkits.basemap import Basemap\nfrom gurobipy import *\nfrom ortools.constraint_solver import pywrapcp\nfrom ortools.constraint_solver import routing_enums_pb2\n\n# Change working directory\nos.chdir('C:/Users/user/Dropbox (Personal)/Imperial College Business School/MSc Business Analytics/Autumn Term/Network Analytics/Homework 2/Group Part')\n\n##############\n### PART 2 ###\n##############\n\n# Load HW1_problem21.txt file\ndf = pd.read_csv('HW2_problem2.txt', sep = ' ', header = None).drop(0, 1)\n\n# Create numpy matrices\nn = df.shape[1]\nadjMatrix = np.matrix(df.iloc[:n, :])\nweights = np.matrix(df.iloc[n:, :], dtype = [('weight', float)])\n\n# Create graphs\nGw = nx.from_numpy_matrix(weights)\n\n# Calculate 4 centrality measures\n# 1. Shortest-path betweenness centrality for nodes\nbw = nx.betweenness_centrality(Gw, normalized = True, weight = 'weight')\n# 2. Current-flow closeness centrality for nodes\ncfc = nx.current_flow_closeness_centrality(Gw, weight = 'weight', solver = 'full')\n# 3. Eigenvector centrality for the graph G\nev = nx.eigenvector_centrality(Gw, max_iter = 100, tol = 1e-06, weight = 'weight')\n# 4. Current-flow betweenness centrality for nodes\ncfbw = nx.current_flow_betweenness_centrality(Gw, normalized = True, weight = 'weight', solver='full')\n\n# Set the 4 centrality measures as node attributes\nnx.set_node_attributes(Gw, 'betweenness', bw)\nnx.set_node_attributes(Gw, 'current_flow_closeness', cfc)\nnx.set_node_attributes(Gw, 'eigenvector', ev)\nnx.set_node_attributes(Gw, 'current_flow_betweenness', cfbw)\ncentrality_measures = ['betweenness', 'current_flow_closeness', \\\n 'eigenvector', 'current_flow_betweenness']\n \nfor cm in centrality_measures:\n # Visualise the graph\n plt.figure(figsize = (10, 10))\n plt.title(cm + ' centrality measure')\n pos = nx.spring_layout(Gw, k = .25, iterations = 2000)\n labs = nx.get_node_attributes(Gw, cm)\n for key, value in labs.items(): \n labs[key] = round(value, 3)\n nx.draw(Gw, pos, node_color = 'lightblue', edge_color = [d['weight'] for (u, v, d) in Gw.edges(data = True)], \n width = 3, edge_cmap=plt.cm.Blues, alpha = .4, \n node_size = np.add(np.multiply(list(nx.get_node_attributes(Gw, cm).values()), 10000), 200))\n nx.draw_networkx_labels(Gw, pos, labels =labs, font_color = 'black', font_size = 8)\n #nx.draw_networkx_edge_labels(Gw, pos, edge_labels = nx.get_edge_attributes(Gw, 'weight'), font_size = 8)\n\n##############\n### PART 3 ###\n##############\n\n### Q. a ###\n\n# Read file\nf = open('HW2_tsp.txt', 'r')\n\n# Create a dataframe with the required data\nrows = f.read().split('\\n')[10: -1]\nnodes = []\nfor i in range(len(rows)):\n nodes.append(rows[i].split(' ')) \nnodes_df = pd.DataFrame(nodes, columns=['id', 'latitude', 'longitude'])\nnodes_df = nodes_df.set_index(nodes_df['id'].values)\nnodes_df = nodes_df.drop('id', 1)\nnodes_df['latitude'] = pd.to_numeric(nodes_df['latitude']) / 1000\nnodes_df['longitude'] = pd.to_numeric(nodes_df['longitude']) / 1000\n\n# Draw scatterplot\nplt.figure(figsize = (6, 6))\nplt.scatter(nodes_df['longitude'], nodes_df['latitude'], alpha = .5, color = 'b')\nplt.title('Djibouti cities')\nplt.xlabel('Longitude')\nplt.ylabel('Latitude')\nplt.show()\n\n# Draw map\nplt.figure(figsize = (6, 6))\nmap = Basemap(width = 500000, height = 500000, projection = 'lcc', \\\n resolution = 'l', lat_0 = 12, lon_0 = 43)\nmap.drawcoastlines()\n#map.drawcounties()\nxn, yn = map(nodes_df['longitude'].values, nodes_df['latitude'].values)\nmap.scatter(xn, yn, marker = 'o', alpha = .5, color = 'b')\nmap.bluemarble()\nplt.title('Djibouti cities')\nplt.show()\n\n# Create a dataframe with the distances\ndistances = pd.DataFrame([[0] * nodes_df.shape[0]] * nodes_df.shape[0], index = nodes_df.index.values, columns = nodes_df.index.values)\nfor i in range(len(rows)):\n for j in range(len(rows)):\n distances.iloc[i, j] = haversine((nodes_df['latitude'][i], nodes_df['longitude'][i]), (nodes_df['latitude'][j], nodes_df['longitude'][j]))\n\n### Q. b ###\n\n# Distance callback\nclass CreateDistanceCallback(object):\n \"\"\"Create callback to calculate distances between points.\"\"\"\n def __init__(self):\n \"\"\"Array of distances between points.\"\"\"\n self.matrix = (np.array(distances).tolist())\n\n def Distance(self, from_node, to_node):\n return self.matrix[from_node][to_node]\n\ndef main():\n # Cities\n city_names = distances.index.tolist()\n tsp_size = len(city_names)\n\n # Create routing model\n if tsp_size > 0:\n # TSP of size tsp_size\n # Second argument = 1 to build a single tour (it's a TSP).\n # Nodes are indexed from 0 to tsp_size - 1. By default the start of\n # the route is node 0.\n routing = pywrapcp.RoutingModel(tsp_size, 1, 1)\n search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()\n\n # Setting first solution heuristic: the\n # method for finding a first solution to the problem.\n search_parameters.first_solution_strategy = (routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n\n # Create the distance callback, which takes two arguments (the from and to node indices)\n # and returns the distance between these nodes.\n \n dist_between_nodes = CreateDistanceCallback()\n dist_callback = dist_between_nodes.Distance\n routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)\n # Solve, returns a solution if any.\n assignment = routing.SolveWithParameters(search_parameters)\n if assignment:\n # Solution cost.\n print('Total distance: ' + str(assignment.ObjectiveValue()) + ' miles\\n')\n # Inspect solution.\n # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1\n route_number = 0\n index = routing.Start(route_number) # Index of the variable for the starting node.\n route = ''\n while not routing.IsEnd(index):\n # Convert variable indices to node indices in the displayed route.\n route += str(city_names[routing.IndexToNode(index)]) + ' -> '\n index = assignment.Value(routing.NextVar(index))\n route += str(city_names[routing.IndexToNode(index)])\n print('Route:\\n\\n' + route)\n else:\n print('No solution found.')\n else:\n print('Specify an instance greater than 0.')\n return(route)\n \noptimal_route = main().split(' -> ')\noptimal_route = [int(x) for x in optimal_route]\n\n# Draw scatterplot with optimal trip\nplt.figure(figsize = (10, 10))\nplt.scatter(nodes_df['longitude'], nodes_df['latitude'], alpha = .5, color = 'b')\nplt.title('Djibouti cities')\nplt.xlabel('Longitude')\nfor i in range(len(optimal_route[:-1])):\n x = [nodes_df.iloc[optimal_route[i]-1, 1], nodes_df.iloc[optimal_route[i+1]-1, 1]]\n y = [nodes_df.iloc[optimal_route[i]-1, 0], nodes_df.iloc[optimal_route[i+1]-1, 0]]\n plt.plot(x, y, color = 'b', alpha = .5)\npyplot.show()\n \n### Q. c ###\n\n# Traveling salesman problem using GUROBI\nn = distances.shape[0]\n\n# Callback - use lazy constraints to eliminate sub-tours\ndef subtourelim(model, where):\n if where == GRB.callback.MIPSOL:\n selected = []\n # make a list of edges selected in the solution\n for i in range(n):\n sol = model.cbGetSolution([model._vars[i,j] for j in range(n)])\n selected += [(i,j) for j in range(n) if sol[j] > 0.5]\n # find the shortest cycle in the selected edge list\n tour = subtour(selected)\n if len(tour) < n:\n # add a subtour elimination constraint\n expr = 0\n for i in range(len(tour)):\n for j in range(i+1, len(tour)):\n expr += model._vars[tour[i], tour[j]]\n model.cbLazy(expr <= len(tour)-1)\n\n# Given a list of edges, finds the shortest subtour\ndef subtour(edges):\n visited = [False]*n\n cycles = []\n lengths = []\n selected = [[] for i in range(n)]\n for x,y in edges:\n selected[x].append(y)\n while True:\n current = visited.index(False)\n thiscycle = [current]\n while True:\n visited[current] = True\n neighbors = [x for x in selected[current] if not visited[x]]\n if len(neighbors) == 0:\n break\n current = neighbors[0]\n thiscycle.append(current)\n cycles.append(thiscycle)\n lengths.append(len(thiscycle))\n if sum(lengths) == n:\n break\n return cycles[lengths.index(min(lengths))]\n\n# Create model and variables\nm = Model()\nvars = {}\nfor i in range(n):\n for j in range(i + 1):\n vars[i, j] = m.addVar(obj = distances.iloc[i, j], vtype = GRB.BINARY,\n name = 'e' + str(i) + '_' + str(j))\n vars[j, i] = vars[i, j]\n m.update()\n\n# Add degree-2 constraint, and forbid loops\nfor i in range(n):\n m.addConstr(quicksum(vars[i, j] for j in range(n)) == 2)\n vars[i, i].ub = 0\nm.update()\n\n# Optimize model\nm._vars = vars\nm.params.LazyConstraints = 1\nm.optimize(subtourelim)\n\nsolution = m.getAttr('x', vars)\nselected = [(i,j) for i in range(n) for j in range(n) if solution[i,j] > 0.5]\nassert len(subtour(selected)) == n\n\n# Draw scatterplot with optimal trip\nplt.figure(figsize = (10, 10))\nplt.scatter(nodes_df['longitude'], nodes_df['latitude'], alpha = .5, color = 'b')\nplt.title('Djibouti cities')\nplt.xlabel('Longitude')\nplt.ylabel('Latitude')\nfor i in range(len(selected)):\n x = [nodes_df.iloc[selected[i][0], 1], nodes_df.iloc[selected[i][1], 1]]\n y = [nodes_df.iloc[selected[i][0], 0], nodes_df.iloc[selected[i][1], 0]]\n plt.plot(x, y, color = 'b', alpha = .5)\n \npyplot.show()\n\n# Draw map with optimal trip\nplt.figure(figsize = (10, 10))\nmap = Basemap(width = 500000, height = 500000, projection = 'lcc', \\\n resolution = 'l', lat_0 = 12, lon_0 = 43)\nmap.drawcoastlines()\n#map.drawcounties()\nxn, yn = map(nodes_df['longitude'].values, nodes_df['latitude'].values)\nmap.scatter(xn, yn, marker = 'o', alpha = .5, color = 'b')\nfor i in range(len(selected)):\n x = [nodes_df.iloc[selected[i][0], 1], nodes_df.iloc[selected[i][1], 1]]\n y = [nodes_df.iloc[selected[i][0], 0], nodes_df.iloc[selected[i][1], 0]]\n x, y = map(x, y)\n map.plot(x, y, color = 'b', alpha = .5) \nmap.bluemarble()\nplt.title('Djibouti cities')\nplt.show()\n\n\n\n" }, { "alpha_fraction": 0.6293558478355408, "alphanum_fraction": 0.6422386765480042, "avg_line_length": 42.01818084716797, "blob_id": "987f87df8dacecc19a02184ee1d102ce13bcd62f", "content_id": "c3ead1b12aa8396eb6c5a2585a5fc86450123417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 4735, "license_type": "no_license", "max_line_length": 287, "num_lines": 110, "path": "/HW3/Group1_HW3_Q2 - SM.Rmd", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "---\ntitle: \"Group 1 HW 3 - Q2\"\nauthor: \"Siow Meng Low\"\ndate: \"17 December 2016\"\noutput: pdf_document\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = TRUE)\n```\n\n## Forecasting Model \n\nIn the _Bass Model_ article, the forecasting model is given as below:\n\n\\begin{center}\n$$F_t = (p + q[C_{t-1} / m])(m - C_{t-1})$$\n$$F_t = pm + (q - p) C_{t-1} - \\frac{q}{m} C_{t-1}^2$$\n\\end{center}\n\nThe paraemters used in the above equation is described below: \n\n* $F_t$: Forecasted number of new adopters during time period $t$, denoted as $N(t)$ in the class lecture notes\n* $C_{t-1}$: Cumulative number of people who have adopted the product up to time $t - 1$\n* $p$: Coefficient of innovation (a.k.a. Rate of spontatneous adoption in the class lecture notes)\n* $q$: Coefficient of imitation (a.k.a. Rate of imitation in the class lecture notes)\n* $m$: Market size, the number of people estimated to eventually adopt the new product\n\nFrom the above equation, we can see that $F_t$ is a function of $C_{t-1}$ and $C_{t-1}^2$. In the article, the authors proposed to minimise the sum of squared forecast errors $\\sum_{t=1}^{N} E_t^2$ where: \n\n* $S_t$: the actual number of new adopters in period $t$, denoted as $S(t)$ in the class lecture notes\n* $E_t = F_t - S_t$, $E_t$ is the forecast error for period $t$ \n\nThis is the same technique used in the Ordinary Least Square Estimation of Linear Regression, where we take $F_t$ (the forecasted number of new adopters in period _t_) to be $\\hat{S_t}$ (the estimated number of adopters in period t). The equation for linear regression can be written as:\n\n\\begin{center}\n$$F_t = \\hat{p}\\hat{m} + (\\hat{q} - \\hat{p}) C_{t-1} - \\frac{\\hat{q}}{\\hat{m}} C_{t-1}^2$$\n$$\\hat{S_t} = \\hat{a} + \\hat{b} C_{t-1} + \\hat{c} C_{t-1}^2$$\n\\end{center}\n\nwhere:\n\n\\begin{center}\n$$\\hat{S_t} = F_t$$\n$$\\hat{a} = \\hat{p}\\hat{m}$$\n$$\\hat{b} = \\hat{q} - \\hat{p}$$\n$$\\hat{c} = - \\frac{\\hat{q}}{\\hat{m}}$$\n\\end{center}\n\nThe system of equations involving $\\hat{p}$, $\\hat{q}$, and $\\hat{m}$ can be rewritten as follows:\n\n\\begin{center}\n$$\\hat{m} = \\frac{-\\hat{b} \\pm \\sqrt{\\hat{b}^2 - 4\\hat{a}\\hat{c}}}{2\\hat{c}}$$\n$$\\hat{p} = \\frac{\\hat{a}}{\\hat{m}}$$\n$$\\hat{q} = - \\hat{c}\\hat{m}$$\n\\end{center}\n\nNote that for $\\hat{m}$, we are only interested in its non-negative real root, since the market size should always be greater than or equal to zero. \n\nIn the following section, we shall perform least square regression (dependent variable is $S_t$ and independent variables are $C_{t-1}$ and $C_{t-1}^2$) using R, in order to obtain the rolling horizon estimates of $p$, $q$, $m$, and $F_t$. \n\n## Rolling Horizon Estimate using Ordinary Least Square Regression \n\n```{r Libraries, echo = FALSE}\nlibrary(pander)\n```\n\nThe table that contains the box office revenue data of \"The Doctor\" is included in the CSV file, _TheDoctorData.csv_. First, we shall read the revenue data from the CSV and calculate $C_{t-1}$ for each period. \n\n```{r ReadData, results = \"asis\"}\nsetwd(\"C:/Users/admin/Desktop/Imperial MSc/Network Analytics/Assignment 3\")\n\ndoctorData <- read.csv(\"TheDoctorData.csv\")\ndoctorData$\"Ctlag\" <- c(0, doctorData$Ct[1:(nrow(doctorData) - 1)])\n\npander(doctorData, \n caption = \"Revenues and Cumulative Revenues in $ Millions for THE DOCTOR\")\n\n```\n\nNext, starting at week 5 ($t = 5$), we shall use the observed cumulative revenues, $C_{t-1}$ to obtain the rolloing-horizon estimates of the parameters. \n\nIn the following section, OLS regressions are performed (for $t = 5, 6, ..., 12$) and the eight sets of estimated parameters are tabulated below: \n\n```{r Regression, results = \"asis\"}\nfinalTable = data.frame()\n\n# Start forecasting at t = 5\ntValues <- doctorData$Week[5 : nrow(doctorData)]\nfor (tValue in tValues) {\n modelDoctor <- lm(St ~ I(Ctlag) + I(Ctlag^2), data = doctorData[1 : (tValue - 1), ])\n a <- modelDoctor$coefficients[1]\n b <- modelDoctor$coefficients[2]\n c <- modelDoctor$coefficients[3]\n m <- c((-b + sqrt(b^2 - 4 * a * c)) / (2 * c), (-b - sqrt(b^2 - 4 * a * c)) / (2 * c))\n m <- m[!is.nan(m) & m >= 0] # Only get the positive root\n p <- a / m\n q <- -c * m\n Ft <- predict(modelDoctor, newdata = data.frame(Ctlag = doctorData$Ctlag[tValue]))\n finalTable <- rbind(finalTable, data.frame(week = tValue, p = p, q = q, m = m, \n Ft = Ft, St = doctorData$St[tValue], \n row.names = NULL))\n}\n\npanderOptions('round', 3)\npander(finalTable, caption = \"Rolling Horizon Estimates of p, q, m, and Ft\")\n\n```\n\nFrom the above estimates, we can see that the estimated $F_t$ is quite different from the actual $S_t$. The rolloing-horizon approach may not be suitable in this case. \n\n" }, { "alpha_fraction": 0.6687741279602051, "alphanum_fraction": 0.6870390176773071, "avg_line_length": 36.959999084472656, "blob_id": "79b39ab1066605b9e25b12cc2e45aa3649de60d9", "content_id": "aa0091770adadc36a0afa073945f7f97a57776b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5694, "license_type": "no_license", "max_line_length": 168, "num_lines": 150, "path": "/Group1_HW1_LSM.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 17 23:50:27 2016\n\n@author: siowmeng\n\"\"\"\n\nimport pandas as pd\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\"\"\"\nFunction to draw the weighted directed graph\nInput: a DiGraph object containing all the nodes, edges and edge weights\nOutput: None Returned (the graph will be printed)\n\"\"\"\n\n# Read the edgelist from file directly and load into networkx graph\nDG = nx.read_weighted_edgelist('HW1_problem1.txt', create_using = nx.DiGraph())\n\n# Qn 1a: Print Incidence Matrix (weight value is printed)\nincDF = pd.DataFrame(nx.incidence_matrix(DG, nodelist = sorted(DG.nodes()), \n oriented = True, weight = 'weight').todense(), \n index = sorted(DG.nodes()))\nprint(incDF)\n\n# Qn 1b: Shortest Paths Matrix\n#paths = nx.johnson(DG, weight='weight') # Returns a dict of dict containing the shortest paths between all source-destination pairs\npaths = nx.floyd_warshall_numpy(DG, nodelist = sorted(DG.nodes()), weight = 'weight') # Returns a matrix with shortest-path lengths between all source-destination pairs\nprint(paths)\n\n# Qn 1c: Diameter of the graph\npaths[np.isfinite(paths)].max()\n#paths.max()\n#nx.diameter(DG)\n\n# Qn 1d: Degree Distribution\ndegreeTable = pd.DataFrame.from_dict(nx.degree(DG), 'index').sort_index()\ndegreeTable.columns = ['degree']\nprint(degreeTable)\n\n# Distribution plot\nplt.figure()\nplt.plot(range(len(nx.degree_histogram(DG))), nx.degree_histogram(DG), 'bv-')\nplt.xlabel('Degree')\nplt.xticks(range(len(nx.degree_histogram(DG))))\nplt.yticks(range(max(nx.degree_histogram(DG)) + 1))\nplt.ylabel('Number of nodes')\nplt.title('Degree Distribution of HW1 Problem 1')\nplt.savefig('Problem1_DegreeDistribution.pdf')\nplt.close()\n\n# Distribution plot (separate for in-degree and out-degree)\nplt.figure()\ninDegree = DG.in_degree().values()\nmaxInDegree = max(DG.in_degree().values())\ninDegreeCount = [list(inDegree).count(x) for x in (range(maxInDegree + 1))]\nplt.plot(range(maxInDegree + 1), inDegreeCount, 'bv-')\noutDegree = DG.out_degree().values()\nmaxOutDegree = max(DG.out_degree().values())\noutDegreeCount = [list(outDegree).count(x) for x in (range(maxOutDegree + 1))]\nplt.plot(range(maxOutDegree + 1), outDegreeCount, 'ro-')\nplt.legend(['In-degree','Out-degree'])\nplt.xlabel('Degree')\nplt.xticks(range(max(maxInDegree, maxOutDegree) + 1))\nplt.yticks(range(max(sorted(inDegreeCount, reverse = True)[0], \n sorted(outDegreeCount, reverse = True)[0]) + 1))\nplt.ylabel('Number of nodes')\nplt.title('Degree Distribution of HW1 Problem 1')\nplt.savefig('Problem1_DegreeDistribution2.pdf')\nplt.close()\n\n# Histogram plot\nplt.figure()\nplt.bar(range(len(nx.degree_histogram(DG))), nx.degree_histogram(DG), width = 0.5, color='b')\nplt.title(\"Degree Histogram of HW1 Problem 1\")\nplt.xlabel(\"Degree\")\nplt.ylabel(\"Number of nodes\")\nplt.xticks(np.arange(0.25, len(nx.degree_histogram(DG)) + 0.25), range(len(nx.degree_histogram(DG))))\nplt.yticks(range(max(nx.degree_histogram(DG)) + 2))\nplt.savefig('Problem1_DegreeHistogram.pdf')\nplt.close()\n\n# Histogram plot (separate for in-degree and out-degree)\nplt.figure()\nplt.bar(range(maxInDegree + 1), inDegreeCount, width = 0.5, color='b')\nplt.bar(range(maxOutDegree + 1), outDegreeCount, width = 0.5, color='r', bottom = inDegreeCount)\nplt.legend(['In-degree','Out-degree'])\nplt.title(\"Degree Histogram of HW1 Problem 1\")\nplt.xlabel(\"Degree\")\nplt.ylabel(\"Number of nodes\")\nplt.xticks(np.arange(0.25, max(maxInDegree, maxOutDegree) + 1.25), range(max(maxInDegree, maxOutDegree) + 1))\nplt.yticks(range(max(np.add(inDegreeCount, outDegreeCount)) + 2))\nplt.savefig('Problem1_DegreeHistogram2.pdf')\nplt.close()\n \n# Qn 1e: Weakly Connected Graph\nnx.is_weakly_connected(DG) # Weakly connected graph test\nnx.is_strongly_connected(DG) # Strongly connected graph test\n\n# Function to draw the graph\ndef drawWeightedGraph(weightedGraph, filename, figSize):\n \n plt.figure(figsize = figSize)\n \n pos = nx.spring_layout(weightedGraph)\n nx.draw_networkx_nodes(weightedGraph, pos = pos, node_size = 200, alpha = 0.8)\n nx.draw_networkx_labels(weightedGraph, pos = pos, font_size = 8) \n\n nx.draw_networkx_edges(weightedGraph, pos = pos,\n edge_color = [d['weight'] for (u, v, d) in weightedGraph.edges(data = True)])\n nx.draw_networkx_edge_labels(weightedGraph, pos = pos, \n edge_labels = nx.get_edge_attributes(weightedGraph, 'weight'),\n font_size = 6, font_color = 'k')\n \n# nx.draw_networkx(weightedGraph, pos = pos) \n \n plt.legend()\n plt.axis('off')\n plt.savefig(filename)\n\n# Invoke the custom function to draw the directed graph (with weights)\ndrawWeightedGraph(DG, 'Problem1_DirectedGraph.pdf', (5, 5))\n\n# Function to read in two adjacency matrices\n# If the 0-1 adjacency matrix contains more edges than the weighted adjacency matrix, \n# Add the 0-weight edges to the final graph\ndef graphAdjMatrix(nonweightedAdjMat, weightedAdjMat):\n \n G1 = nx.Graph(nonweightedAdjMat)\n G2 = nx.Graph(weightedAdjMat)\n \n G1_edge = G1.edges()\n G2_edge = G2.edges()\n \n if len(G1_edge) > len(G2_edge):\n for (src, dest) in G1_edge:\n if (src, dest) not in G2_edge:\n G2.add_edge(src, dest, weight = 0)\n \n return G2\n\n# Qn 2\nadjDF = pd.read_table('HW2_problem2.txt', sep = ' ', header = None, skipinitialspace = True)\n\nUG = graphAdjMatrix(adjDF.iloc[0 : adjDF.shape[1], ].as_matrix(), \n adjDF.iloc[adjDF.shape[1] : adjDF.shape[0], ].as_matrix())\n\ndrawWeightedGraph(UG, 'Problem2_UndirectedGraph.pdf', (15, 12))\n" }, { "alpha_fraction": 0.6938095092773438, "alphanum_fraction": 0.7161904573440552, "avg_line_length": 23.600000381469727, "blob_id": "8258bc1480b02f7cb068301ebc9464c840316a8f", "content_id": "245882a0b334cb82e734d99a476ea0d93b8d31ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2100, "license_type": "no_license", "max_line_length": 118, "num_lines": 85, "path": "/Group_work1.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 17 14:46:30 2016\n\n@author: cheungcecilia\n\"\"\"\n\nimport networkx as nx\nimport pandas as pd\nimport numpy as np\n\n# read text file\ndata = pd.read_csv('/Users/cheungcecilia/Desktop/Network Analytics/Homework/HW1_problem1.txt', sep=\" \", header = None)\n\n# create empty directed graph\nDG = nx.DiGraph()\n\n# read dataframe into graph\nfor i in range(0, len(data.index)): \n DG.add_edge(data.iloc[i,0], data.iloc[i,1], weight = data.iloc[i,2])\n \n\n# turn directed graph into incidence matrix\nA = nx.incidence_matrix(DG, nodelist = sorted(DG.nodes()))\nprint(A.toarray())\n\n#shortest path matrix\nF = nx.floyd_warshall_numpy(DG, nodelist = sorted(DG.nodes()))\nprint(F)\n\n#diameter of the graph\nfrom numpy import inf\nF[F == inf] = 0\nnp.matrix.max(F)\n\n#plot degree distribution in graph\nimport pylab as plt\nin_degrees = DG.in_degree() # dictionary node:degree\nin_values = sorted(set(in_degrees.values()))\nin_degree_values = list(in_degrees.values())\n\nout_degrees = DG.out_degree()\nout_values = sorted(set(out_degrees.values()))\nout_degree_values = list(out_degrees.values())\n\nin_hist = [x + y for x, y in zip(in_degree_values, out_degree_values)]\n\nplt.hist(in_hist, bins = np.arange(6)-0.5)\nplt.xlabel('Degree')\nplt.ylabel('Number of nodes')\n\n#check connected graph\nnx.is_strongly_connected(DG)\n\n\n#part 2\n\n#load adjacency matrix\na = np.loadtxt('/Users/cheungcecilia/Desktop/Network Analytics/Homework/HW2_problem2.txt')\n\ngraph = nx.from_numpy_matrix(a[34:68,0:34])\npos=nx.get_node_attributes(graph,'pos')\n\n#circular looking graph\n\nedges,weights = zip(*nx.get_edge_attributes(graph,'weight').items())\n\npos=nx.spring_layout(graph,k=0.6,iterations=100)\nnx.draw_networkx(graph,pos, edge_color=weights, width=1.5, edge_cmap=plt.cm.Blues)\n\n#shows that 32, 33, 0 and 2 have the most connections, intensities of lines represent the weight\n\n\n\n\n\n\n#extra stuff\n\n#weight labels\nlabels = nx.get_edge_attributes(graph,'weight')\nnx.draw_networkx_edge_labels(graph, pos, edge_labels=labels)\n\n#node labels\nnx.draw_networkx_labels(graph, pos, font_size = 8, font_color = 'r')\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6687082648277283, "alphanum_fraction": 0.6815145015716553, "avg_line_length": 26.507936477661133, "blob_id": "ec2eea52c20e2bdbbf7117ec191cd6ca85ed2c27", "content_id": "a992e1734d0828a0cb3efbaecd909e8b9353c324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1796, "license_type": "no_license", "max_line_length": 101, "num_lines": 63, "path": "/Group1_HW1_NV.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nSpyder Editor\r\n\r\nThis is a temporary script file.\r\n\"\"\"\r\n\r\nimport networkx as nx\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport collections\r\nfrom itertools import chain\r\n\r\n## Individual Work\r\nA = nx.read_weighted_edgelist(\"HW1_problem1.txt\", delimiter = ' ', create_using = nx.DiGraph())\r\n\r\nB = nx.adjacency_matrix(A, nodelist = ['a','b','c','d','e'])\r\n\r\nB.todense()\r\n\r\n## Group Work - part one\r\n# Print out the node-arc incidence matrix\r\nC = nx.incidence_matrix(A, nodelist=['a','b','c','d','e'], edgelist=None, oriented=True, weight=None)\r\nC.todense()\r\n\r\n# Print the shortest-path matrix\r\nD = nx.floyd_warshall_numpy(A, nodelist=['a','b','c','d','e'], weight='weight')\r\nprint(D)\r\n\r\n# Calculate the diameter of the graph\r\ndistances = nx.all_pairs_dijkstra_path_length(A)\r\nalldistancevalues = chain(*(row.values() for row in distances.values()))\r\nmax(d for d in alldistancevalues if d != \"inf\")\r\n \r\n# Plot the degree distrubition of a graph\r\ndegreeSeq = A.degree()\r\ndegreecount=collections.Counter(dict.values(degreeSeq))\r\ndeg, cnt = zip(*degreeCount.items())\r\n\r\nplt.bar(deg, cnt, width=0.20, color='g')\r\nplt.title(\"Degree Histogram\")\r\nplt.ylabel(\"Count\")\r\nplt.xlabel(\"Degree\")\r\nplt.show()\r\n\r\n# Check that it is a connected graph\r\nnx.is_strongly_connected(A)\r\nnx.is_weakly_connected(A)\r\n\r\n## Group Work - part two\r\na = np.loadtxt(\"HW2_problem2.txt\", dtype=int)\r\n\r\nb = nx.from_numpy_matrix(a[:34,:34], parallel_edges=False, create_using=None)\r\n\r\n# Visualization Graph\r\nc = nx.from_numpy_matrix(a[34:68,], parallel_edges=False, create_using=None)\r\nplt.figure(num=None, figsize=(10, 10), dpi=80)\r\nplt.axis('off')\r\nfig = plt.figure(1)\r\npos = nx.spring_layout(c)\r\nnx.draw_networkx_nodes(c,pos)\r\nnx.draw_networkx_edges(c,pos)\r\nnx.draw_networkx_labels(c,pos)\r\n" }, { "alpha_fraction": 0.6898651719093323, "alphanum_fraction": 0.7172684073448181, "avg_line_length": 29.25, "blob_id": "9d3fea98187e9ed42d5ee825c11ce1b2c9441ce7", "content_id": "c5872c4b06179e67df6fe187a452de2d7e83dc1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2299, "license_type": "no_license", "max_line_length": 143, "num_lines": 76, "path": "/Group1_HW1_LF.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 17 13:47:19 2016\n\n@author: louisefallon\n\"\"\"\n\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ngraph = nx.read_weighted_edgelist(\"HW1_problem1.txt\",create_using=nx.DiGraph())\n\nincidence = nx.incidence_matrix(graph,\n nodelist=['a','b','c','d','e'],\n oriented=True)\n\nprint(incidence.todense())\n\n## Edges go from -1 to 1. (e.g. the first column is telling us there is an\n## edge from A to D)\n\n\nshortestpath = nx.floyd_warshall_numpy(graph, nodelist=['a','b','c','d','e']) \nprint(shortestpath)\n##works for neg values.\n##https://networkx.github.io/documentation/networkx-1.10/reference/generated/networkx.algorithms.shortest_paths.dense.floyd_warshall_numpy.html\n##https://networkx.github.io/documentation/networkx-1.10/reference/algorithms.shortest_paths.html\n\n\ndiameter = np.amax(shortestpath[shortestpath < np.Inf])\nprint(diameter)\n\n#%%\n\nimport collections\ndegrees = graph.degree() # dictionary node:degree\ndegreeCount=collections.Counter(dict.values(degrees))\ndeg, cnt = zip(*degreeCount.items())\n\nplt.bar(deg, cnt, width=0.1, color='b')\nplt.title(\"Degree Histogram\")\nplt.ylabel(\"Count\")\nplt.xlabel(\"Degree\")\nplt.show()\n\n#%%\n\nnx.is_weakly_connected(graph)\n##The graph is weakly connected (you can get from\n## any node to any other, ignoring direction)\nnx.is_strongly_connected(graph)\n##The graph is weakly connected (you can get from\n## any node to any other, including direction)\n\n#%%\ngraphmatrix = np.loadtxt(\"HW2_problem2.txt\")\n#%%\ngraph3 = nx.from_numpy_matrix(graphmatrix[34:68,0:34])\npos=nx.circular_layout(graph3)\nnx.draw_networkx(graph3,pos)\nlabels = nx.get_edge_attributes(graph3,'weight')\nnx.draw_networkx_edge_labels(graph3, pos,edge_labels=labels)\n#%%\npos=nx.circular_layout(graph3)\nnx.draw_networkx(graph3,pos)\n#%%\npos=nx.spring_layout(graph3,k=0.25,iterations=100)\nnx.draw_networkx(graph3,pos)\n#%%\npos=nx.spring_layout(graph3,k=0.25,iterations=100)\nedges,weights = zip(*nx.get_edge_attributes(graph3,'weight').items())\nnx.draw(graph3, pos, node_color='b', edge_color=weights, width=5.0, edge_cmap=plt.cm.Blues)\nnx.draw_networkx_labels(graph3, pos,font_color=\"c\", font_size=10)\n##Weights shown by colour as there are too many lines for numbered weights\n" }, { "alpha_fraction": 0.6457175016403198, "alphanum_fraction": 0.6595864295959473, "avg_line_length": 41.914207458496094, "blob_id": "4f013138d32e084899fceb0640e51360a3c92f33", "content_id": "eb8c0cd5aefde824b51ae1f8621bb31cb69035f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16007, "license_type": "no_license", "max_line_length": 140, "num_lines": 373, "path": "/HW2/Group1_HW2 - Draft.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 24 16:56:32 2016\n\n@author: siowmeng\n\"\"\"\n\nimport math\nimport pandas as pd\nimport networkx as nx\nimport numpy as np\nimport operator\nfrom haversine import haversine\n\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\n\nfrom ortools.constraint_solver import pywrapcp\nfrom ortools.constraint_solver import routing_enums_pb2\n\nimport gurobipy\n\n# Function to read in two adjacency matrices in Q2\n# If the 0-1 adjacency matrix contains more edges than the weighted adjacency matrix, \n# Add the 0-weight edges to the final graph\ndef graphAdjMatrix(nonweightedAdjMat, weightedAdjMat): \n G1 = nx.Graph(nonweightedAdjMat)\n G2 = nx.Graph(weightedAdjMat)\n \n G1_edge = G1.edges()\n G2_edge = G2.edges()\n \n if len(G1_edge) > len(G2_edge):\n for (src, dest) in G1_edge:\n if (src, dest) not in G2_edge:\n G2.add_edge(src, dest, weight = 0)\n \n return G2\n\n# Calculate Euclidean and Haversine distance given the coordinates matrices\ndef calcDistance(coordMat, coordMat_latlong): \n # Initialize the Euclidean Distance Matrix\n distMat = np.zeros((coordMat.shape[0], coordMat.shape[0]))\n # Initialize the Haversine Distance Matrix\n havDistMat = np.zeros((coordMat.shape[0], coordMat.shape[0]))\n \n for i in range(coordMat.shape[0]):\n for j in range(i + 1, coordMat.shape[0]):\n # Update Euclidean distance between city i & j\n distMat[i][j] = math.sqrt((coordMat[j][0] - coordMat[i][0])**2 + (coordMat[j][1] - coordMat[i][1])**2)\n distMat[j][i] = distMat[i][j]\n # Update Haversine distance between city i & j\n havDistMat[i][j] = haversine((coordMat_latlong[i][0], coordMat_latlong[i][1]), (coordMat_latlong[j][0], coordMat_latlong[j][1]))\n havDistMat[j][i] = havDistMat[i][j]\n \n distDF = pd.DataFrame(distMat, index = coordDF.index, columns = coordDF.index)\n havDistDF = pd.DataFrame(havDistMat, index = coordDF.index, columns = coordDF.index)\n return distDF, havDistDF\n\n# Plot path\ndef plotPath(worldCoordinates, tour, filename):\n # Plot the World map around Djibouti\n mapDjibouti = Basemap(projection = 'mill', \n llcrnrlat = worldCoordinates.min(axis = 0)[0] - 0.3, \n llcrnrlon = worldCoordinates.min(axis = 0)[1] - 0.3, \n urcrnrlat = worldCoordinates.max(axis = 0)[0] + 0.3, \n urcrnrlon = worldCoordinates.max(axis = 0)[1] + 0.3, \n resolution = 'i')\n # Draw coastline, country borders, and background image\n mapDjibouti.drawcoastlines(linewidth = 1.0)\n mapDjibouti.drawcountries(linewidth = 2.0, color = 'red')\n mapDjibouti.bluemarble()\n \n # Plot all the cities in Djibouti\n xPlot, yPlot = mapDjibouti(worldCoordinates[ : , 1], worldCoordinates[ : , 0]) # x is longitude, y is latitude\n mapDjibouti.plot(xPlot, yPlot, 'co', markersize = 5)\n \n k = 1\n for (lat, long) in worldCoordinates:\n xlabel, ylabel = mapDjibouti(long, lat)\n plt.text(xlabel, ylabel, k, fontsize = 5)\n k += 1 \n \n xs = []\n ys = []\n \n # Plot the optimal tour\n for i in tour: \n x, y = mapDjibouti(worldCoordinates[i - 1, 1], worldCoordinates[i - 1, 0])\n xs.append(x)\n ys.append(y)\n \n print('Route in', filename, ':', tour)\n mapDjibouti.plot(xs, ys, color = 'blue', linewidth = 1, label = 'Tour')\n \n # Set the title and save to PDF\n plt.title('Djibouti TSP')\n plt.savefig(filename)\n plt.show()\n plt.close()\n\n''' Qn 2 '''\nadjMatrix = np.loadtxt(\"HW2_problem 2.txt\", dtype=int)\n\n# Use graphAdjMatrix() function to read in both 0-1 and weighted adjacency matrices\n# Ensure that no 0-weighted edges are missed out\nadjShape = np.shape(adjMatrix)\ngraph = graphAdjMatrix(adjMatrix[0 : adjShape[1], ], adjMatrix[adjShape[1] : adjShape[0], ])\n\n#%%\n#Top 2 nodes by betweenness centrality measure\nbetweenness = nx.betweenness_centrality(graph)\nsorted(betweenness, key=betweenness.get, reverse=True)[:2]\n# sorted(nx.betweenness_centrality(graph).items(), reverse = True, key = operator.itemgetter(1))\n\n## These two nodes are the two for which the highest sum of\n## fractions of shortest paths for all pairs run through these\n## nodes. Implying that they are \"between\" the most pairs, and\n## so have a high importance within the network.\n\n## The reason we use (weight = None) in the function and calculate \n## the betweenness centrality for an \"unweighted graph\" is that\n## the edge weights represent the friendship strength between two nodes.\n## The shortest path in this case will be defined as the \"least friendly path\"\n## between two nodes. Hence we calculate the betweenness\n## centrality based on unweighted graph. In this case, the shortest path will be\n## the \"shortest route\" to reach a person via friends (regardless of the friendship \n## strength)\n\n#%%\nflowcloseness = nx.current_flow_closeness_centrality(graph, weight = 'weight')\nsorted(flowcloseness, key=flowcloseness.get, reverse=True)[:2]\n# sorted(nx.current_flow_closeness_centrality(graph, weight = 'weight').items(), reverse = True, key = operator.itemgetter(1))\n\n## Flow closeness centrality (similar to Information Centrality)\n## takes into account not just the shortest paths but all possible\n## paths, and identifies the nodes through which the highest amount\n## of information (or current for electrical networks) is passed.\n## In this case we get the two nodes 0 and 33, with the highest\n## information flow centrality. This is similar to betweenness\n## but node 0 has higher centrality when you only take into account\n## shortest paths, and node 33 has higher centrality when you take\n## into account all paths (which may be more robust).\n\n#%%\neigenvector = nx.eigenvector_centrality(graph, weight = 'weight')\nsorted(eigenvector, key=eigenvector.get, reverse=True)[:2]\n# sorted(nx.eigenvector_centrality(graph, weight = 'weight').items(), reverse = True, key = operator.itemgetter(1))\n\n## Eigenvector centrality takes into account the fact that the\n## importance of a node's neighbours is an input into the importance\n## of that node. We can see here that node 2 has a high eigenvector\n## centrality because it has important neighbours (e.g. node 0, and 32)\n## whereas node 0 has lower importance, most likely because it has\n## lots of neighbours of lower importance.\n\n#%% \ncloseness = nx.closeness_centrality(graph)\nsorted(closeness, key=closeness.get, reverse=True)[:2]\n# sorted(nx.closeness_centrality(graph).items(), reverse = True, key = operator.itemgetter(1))\n\n## These two nodes are the two that have the\n## lowest sum distance to all other nodes. Implying that\n## they are the \"closest\" to the most other nodes.\n## The 0 node is included here, but the 33rd node is 3rd,\n## implying that node 2 is \"closer\" to the rest of the \n## network as a whole than node 33.\n\n## The reason we use (distance = None) in the function and calculate \n## the closeness centrality for an \"unweighted graph\" is that\n## the edge weights represent the friendship strength between two nodes.\n## The shortest path in this case will be defined as the \"least friendly path\"\n## between two nodes. Hence we calculate the betweenness\n## centrality based on unweighted graph. In this case, the shortest path will be\n## the \"shortest route\" to reach a person via friends (regardless of the friendship \n## strength)\n\n#%% (or degree)\ndegree = nx.degree_centrality(graph)\nsorted(degree, key=degree.get, reverse=True)[:2]\n# sorted(nx.degree_centrality(graph).items(), reverse = True, key = operator.itemgetter(1))\n\n## These two nodes are the two that have the highest\n## number of neighbours. This simple metric for centrality\n## identifies nodes 33 and 0 as the highest \"importance\"\n## for this network.\n\n# Set the 4 centrality measures as node attributes\nnx.set_node_attributes(graph, 'betweenness', betweenness)\nnx.set_node_attributes(graph, 'current_flow_closeness', flowcloseness)\nnx.set_node_attributes(graph, 'eigenvector', eigenvector)\nnx.set_node_attributes(graph, 'closeness', closeness)\nnx.set_node_attributes(graph, 'degree', degree)\ncentrality_measures = ['betweenness', 'current_flow_closeness', \\\n 'eigenvector', 'closeness', 'degree']\n \npos = nx.spring_layout(graph, k = .25, iterations = 2000)\nfor cm in centrality_measures:\n # Visualise the graph\n plt.figure(figsize = (10, 10))\n plt.title(cm + ' centrality measure')\n labs = nx.get_node_attributes(graph, cm)\n for key, value in labs.items(): \n labs[key] = round(value, 3)\n nx.draw(graph, pos, node_color = 'lightblue', edge_color = [d['weight'] for (u, v, d) in graph.edges(data = True)], \n width = 3, edge_cmap=plt.cm.Blues, alpha = .4, \n node_size = np.add(np.multiply(list(nx.get_node_attributes(graph, cm).values()), 10000), 200))\n nx.draw_networkx_labels(graph, pos, labels =labs, font_color = 'black', font_size = 8)\n #nx.draw_networkx_edge_labels(Gw, pos, edge_labels = nx.get_edge_attributes(Gw, 'weight'), font_size = 8)\n plt.show()\n plt.close()\n\n\n''' Qn 3a: Plot coordinates '''\n# Read the coordinates from file\ncoordDF = pd.read_table('HW2_tsp.txt', sep = ' ', header = None, skiprows = 10, \n index_col = 0, names = [\"x\", \"y\"])\n\n# Matrix containing (x, y) as Cartesian coordinates pair\ncoordMat = coordDF.as_matrix()\n# Matrix containing (lat, long) as Latitude & Longitude pair\ncoordMat_latlong = coordMat / 1000\n\n# Get Euclidean Distance and Haversine Distance\neucDistDF, havDistDF = calcDistance(coordMat, coordMat_latlong)\nhavDistMat = havDistDF.as_matrix()\n\n''' Qn 3b: Google OR Tools '''\n# Distance callback\nclass CreateDistanceCallback(object):\n \"\"\"Create callback to calculate distances between points.\"\"\"\n def __init__(self, distMat):\n \"\"\"Array of distances between points.\"\"\"\n self.matrix = distMat\n\n def Distance(self, from_node, to_node):\n return self.matrix[from_node][to_node]\n\ndef ortools(distMat):\n \n tsp_size = distMat.shape[0]\n selected = []\n bestRoute = ''\n \n # Create routing model\n if tsp_size > 0: \n \n bestObj = np.Inf\n \n search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters() \n # Setting first solution heuristic: the\n # method for finding a first solution to the problem.\n search_parameters.first_solution_strategy = (\n routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n \n # Create the distance callback, which takes two arguments (the from and to node indices)\n # and returns the distance between these nodes. \n dist_between_nodes = CreateDistanceCallback(distMat)\n dist_callback = dist_between_nodes.Distance \n \n for i in range(tsp_size):\n # TSP of size tsp_size\n # Second argument = 1 to build a single tour (it's a TSP).\n # Nodes are indexed from 0 to tsp_size - 1. By default the start of\n # the route is node 0.\n routing = pywrapcp.RoutingModel(tsp_size, 1, i)\n \n routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)\n # Solve, returns a solution if any.\n assignment = routing.SolveWithParameters(search_parameters)\n if assignment:\n if assignment.ObjectiveValue() < bestObj:\n bestObj = assignment.ObjectiveValue()\n route_number = 0\n index = routing.Start(route_number) # Index of the variable for the starting node.\n bestRoute = ''\n selected = []\n while not routing.IsEnd(index):\n # Convert variable indices to node indices in the displayed route.\n bestRoute += str(routing.IndexToNode(index) + 1) + ' -> '\n selected.append(routing.IndexToNode(index) + 1)\n index = assignment.Value(routing.NextVar(index))\n \n bestRoute += str(routing.IndexToNode(index) + 1)\n selected.append(routing.IndexToNode(index) + 1)\n \n else:\n print('No solution found for starting node:', i)\n \n print(\"Total distance:\", str(bestObj), \" km\\n\")\n print(\"ORTools Route:\\n\\n\", bestRoute) \n \n else:\n print('Specify an instance greater than 0.')\n \n return selected\n\nortoolsTour = ortools(havDistMat)\n\nplotPath(coordMat_latlong, ortoolsTour, 'Djibouti-ortools.pdf')\n \n''' Qn 3c: Gurobi Solver '''\n# Given the selected path, find the subtour (for Qn 3c: Gurobi)\ndef findSubTour(selectedPairs):\n notVisited = np.unique(selectedPairs).tolist()\n neighbours = [notVisited[0]]\n visited = []\n\n while (len(neighbours) > 0):\n currCity = neighbours.pop()\n neighbours1 = [j for i, j in selectedPairs.select(currCity, '*') if j in notVisited and j not in neighbours]\n neighbours2 = [i for i, j in selectedPairs.select('*', currCity) if i in notVisited and i not in neighbours]\n notVisited.remove(currCity)\n visited.append(currCity)\n while len(neighbours1) > 0:\n neighbours.append(neighbours1.pop())\n while len(neighbours2) > 0:\n neighbours.append(neighbours2.pop())\n\n return visited, notVisited \n\n# Add lazy constraints to eliminate subtours (for Qn 3c: Gurobi)\ndef elimSubTour(model, where):\n if where == gurobipy.GRB.Callback.MIPSOL:\n vals = model.cbGetSolution(model._xVar)\n selectedPairs = gurobipy.tuplelist((i, j) for i, j in vals.keys() if vals[i, j] > 0.5)\n visited, notVisited = findSubTour(selectedPairs)\n # If there is subtour, add constraint: the cut should have at least 2 edges\n if len(notVisited) > 0:\n model.cbLazy(gurobipy.quicksum(model._xVar[i, j] for j in notVisited for i in visited if i < j) + \n gurobipy.quicksum(model._xVar[j, i] for j in notVisited for i in visited if i > j) \n >= 2)\n\n# Initialize Gurobi Model\ntspModel = gurobipy.Model('DjiboutiTSP')\n# All distinct city pairs\ntuplelist = [(x,y) for x in range(1, coordMat.shape[0] + 1) for y in range(1, coordMat.shape[0] + 1) if x < y]\n# Distance between city pairs\ndistlist = [havDistMat[x - 1, y - 1] for x in range(1, coordMat.shape[0] + 1) for y in range(x + 1, coordMat.shape[0] + 1)]\n# Declare Decision Variables (with Objective Coefficients)\nxVar = tspModel.addVars(tuplelist, obj = distlist, vtype = gurobipy.GRB.BINARY, name = 'x')\n\n# Constraints: Degree = 2\ntspModel.addConstrs((sum(xVar.select(i, '*')) + sum(xVar.select('*', i))) == 2 for i in range(1, coordMat.shape[0] + 1))\n\n# Enable Lazy Constraints\ntspModel.setParam(\"LazyConstraints\", 1)\n# Store the decision variables as private variable (for access later)\ntspModel._xVar = xVar\n# Solve the TSP using elimSubTour as a sub-routine\ntspModel.optimize(elimSubTour)\n\n# Get the selected path\nvals = tspModel.getAttr('x', xVar)\ngurobiSelected = gurobipy.tuplelist((i, j) for i, j in vals.keys() if vals[i,j] > 0.5)\n\ngurobiTour = findSubTour(gurobiSelected)[0]\ngurobiTour.append(gurobiTour[0]) # Return to the first city for complete tour\n\n''' Qn 3d: Plot the Tour '''\nplotPath(coordMat_latlong, gurobiTour, 'Djibouti-gurobi.pdf')\n\n''' Print the total distance for ortools tour '''\nsumDist = 0\nfor i in range(len(ortoolsTour) - 1):\n sumDist += havDistMat[ortoolsTour[i] - 1, ortoolsTour[i + 1] - 1]\nprint('ortools distance:', sumDist)\n\n''' Print the total distance for gurobi tour '''\nsumDist = 0\nfor i in range(len(gurobiTour) - 1):\n sumDist += havDistMat[gurobiTour[i] - 1, gurobiTour[i + 1] - 1]\nprint('gurobi distance:', sumDist)\n" }, { "alpha_fraction": 0.6767112612724304, "alphanum_fraction": 0.7018558979034424, "avg_line_length": 49.11000061035156, "blob_id": "0c2fbd1cb12bc1623471476627139243f2c64a00", "content_id": "e40ac323da530e24488f455f45e17f342f945aa0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "RMarkdown", "length_bytes": 5011, "license_type": "no_license", "max_line_length": 596, "num_lines": 100, "path": "/Group1_HW1.Rmd", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "---\ntitle: \"Network Analytics\"\nsubtitle: \"Homework 1 - Group Part\"\nauthor: \"Group 1\"\ndate: \"November 22, 2016\"\noutput: pdf_document\ngeometry: margin=0.5in\n---\n\n```{r setup, include=FALSE}\nknitr::opts_chunk$set(echo = FALSE)\n\n#install.packages(c(\"png\", \"grid\"))\nlibrary(png)\nlibrary(grid)\n```\n\n## Exercise 1\n\nIn this exercise we will use the directed graph specified in the `HW1_problem1.txt` file. The directed graph is shown in the following figure.\n\n```{r fig.width=2, fig.height=2, fig.align='center'}\nimg1 <- readPNG(\"graph1.png\")\ngrid.raster(img1)\n```\n\n\n**(a)** First print the node-arc incidence matrix, where each row represents a node and each column represents an edge. If an edge goes from node $i$ to node $j$ then $\\alpha_{ik} = -1$ and $\\alpha_{jk} = 1$. The rest of the elements are equal to zero. The resulting matrix is as follows:\n\nTable: Adjacency matrix of directed graph\n\n| |\\ 0 | \\ 1 | \\ 2 | \\ 3 |\\ 4 | \\ 5 | \\ 6 |\n|---|---|---|---|---|---|---|---| \n| a |\\ 0|\\ 0 |-1| -1| \\ 0| \\ 0| \\ 0|\n| b | -1|-1 |\\ 1|\\ 0|\\ 1| \\ 0| \\ 0 |\n| c |\\ 0 |\\ 1 |\\ 0|\\ 0|\\ 0| \\ 0| -1 |\n| d |\\ 0 |\\ 0 |\\ 0|\\ 1| -1| -1| \\ 1 |\n| e |\\ 1 |\\ 0 |\\ 0|\\ 0| \\ 0| \\ 1| \\ 0 |\n\n**(b)** Next, we will calculate and print the shortest-path matrix which presents the lengths of the shortest paths between all the nodes. Since this graph includes negative weight, we use Floyd-Warshall algorithm to compute all-pairs shortest path lengths. Note that in case there is no possible path from node $i$ to node $j$, then the shortest path length, $\\alpha_{ij} = \\infty$. The shortest-path matrix is the following:\n\nTable: Shortest paths matrix of directed graph\n\n| | a | b | c | d | e |\n|---|---|---|---|---|---|\n| a | \\ 0 | \\ 5 | 15| \\ 3 | 6 |\n| b |$\\infty$| \\ 0 | 10| \\ 8 | 7 |\n| c |$\\infty$| \\ 6 | \\ 0|-2 | 1 |\n| d |$\\infty$| \\ 8 | 18| \\ 0 | 3 |\n| e |$\\infty$|$\\infty$|$\\infty$|$\\infty$| 0 |\n\n**(c)** The diameter $d$ of the graph, which is the longest shortest path amongst all the paths, is the maximum finite element in the second table, and is in this case 18.\n\n**(d)** The total degree distribution of the graph represents the total number of edges (including both incoming and outgoing edges) each node is connected to and is shown in the following bar chart.\n\n```{r fig.width=2.5, fig.height=2.5, fig.align='center'}\nimg2 <- readPNG(\"bar1.png\")\ngrid.raster(img2)\n```\n\n**(e)** Finally, we will check whether the graph is connected. As it is a directed graph it can be either *strongly connected*, which is the case when there is a path from each node to every other node in the graph, or *weakly connected*, which is the case when the equivalent undirected graph is connected. Our graph is weakly connected but not strongly connected.\n\n---\n\n## Exercise 2\n\nIn this exercise we will use the undirected graph specified in the `HW2_problem2.txt` file.\n\nThe file containts information about an undirected graph of 34 nodes and is consisted of a matrix of 68 rows and 34 columns. The first 34 rows represent the adjacency matrix of the undirected graph and the rest of the rows contain the weights associated with each edge.\n\nBefore drawing the graph, we create and apply the function `graphAdjMatrix()` to the two matrices that represent the adjacency matrix and the corresponding weights to check if the adjacency matrix contains more edges than the weighted adjacency matrix (i.e. edges with 0 weight). In case it does, the function adds 0-weight edges to the final graph for the edges that are actually represented in the adjacency matrix but cannot be recognised in the weight-related matrix due to the value of their weight which is equal to zero. In this particular graph though, we do not have such 0-weight edges.\n\nWe first draw the undirected network without the weights. The resulting graph is as follows:\n\n```{r fig.width=5, fig.height=4, fig.align='center'}\nimg3 <- readPNG(\"graph2_1.png\")\ngrid.raster(img3)\n```\n\nThen we represent the weights of the edges using both labels (number shown on each edge) and colours (darker colour indicates heavier weight) of the edges. We present the graph in two different layouts (spring layout and circular layout).\n\n```{r fig.width=5, fig.height=5, fig.align='center'}\nimg4 <- readPNG(\"graph2_2.png\")\ngrid.raster(img4)\n```\n\nThe above two graphs were plotted using spring layout. This layout attempts to minimise the number of crossing edges and allow us to insepct the structure of the graph.\n\n```{r fig.width=5, fig.height=5, fig.align='center'}\nimg5 <- readPNG(\"graph2_3.png\")\ngrid.raster(img5)\n```\n\nThe last circular format (shown above) of the graph, which represents edge-weights using colour (with darker colour indicating heavier weight), gives a clearer image of the structure of the graph, as we can easily see which nodes are the ones with more edges and which ones are not. At the same time, we can easily compare the weights of different edges that belong to the same nodes.\n\n---\n\n## Notes\n\nThe code used in the assignment is included in the `Group1_HW1.py` file.\n" }, { "alpha_fraction": 0.669570803642273, "alphanum_fraction": 0.6860277652740479, "avg_line_length": 34.21590805053711, "blob_id": "13987545809e6e5cfc0229e99ed703f4622a2075", "content_id": "49ddaae416b6bac38830619e020d05b624b582aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6198, "license_type": "no_license", "max_line_length": 92, "num_lines": 176, "path": "/HW2/Group1_HW2_LF.py", "repo_name": "louiserfallon/NetworkXOperations", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\n\n@author: louisefallon\n\"\"\"\n\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n#%% load hw2 data\ngraphmatrix = np.loadtxt(\"HW2_problem 2.txt\")\n#%% draw graph\ngraph = nx.from_numpy_matrix(graphmatrix[34:68,0:34])\npos=nx.circular_layout(graph)\nnx.draw_networkx(graph,pos)\nlabels = nx.get_edge_attributes(graph,'weight')\nnx.draw_networkx_edge_labels(graph, pos,edge_labels=labels)\n\n#%%\n#Top 2 nodes by betweenness centrality measure\nbetweenness = nx.betweenness_centrality(graph)\nsorted(betweenness, key=betweenness.get, reverse=True)[:2]\n\n## These two nodes are the two for which the highest sum of\n## fractions of shortest paths for all pairs run through these\n## nodes. Implying that they are \"between\" the most pairs, and\n## so have a high importance within the network.\n\n#%%\nflowcloseness = nx.current_flow_closeness_centrality(graph)\nsorted(flowcloseness, key=flowcloseness.get, reverse=True)[:2]\n\n## Flow closeness centrality (similar to Information Centrality)\n## takes into account not just the shortest paths but all possible\n## paths, and identifies the nodes through which the highest amount\n## of information (or current for electrical networks) is passed.\n## In this case we get the two nodes 0 and 33, with the highest\n## information flow centrality. This is similar to betweenness\n## but node 0 has higher centrality when you only take into account\n## shortest paths, and node 33 has higher centrality when you take\n## into account all paths (which may be more robust).\n\n#%%\neigenvector = nx.eigenvector_centrality(graph)\nsorted(eigenvector, key=eigenvector.get, reverse=True)[:2]\n\n## Eigenvector centrality takes into account the fact that the\n## importance of a node's neighbours is an input into the importance\n## of that node. We can see here that node 2 has a high eigenvector\n## centrality because it has important neighbours (e.g. node 0, and 32)\n## whereas node 0 has lower importance, most likely because it has\n## lots of neighbours of lower importance.\n\n#%% \ncloseness = nx.closeness_centrality(graph)\nsorted(closeness, key=closeness.get, reverse=True)[:2]\n\n## These two nodes are the two that have the\n## lowest sum distance to all other nodes. Implying that\n## they are the \"closest\" to the most other nodes.\n## The 0 node is included here, but the 33rd node is 3rd,\n## implying that node 2 is \"closer\" to the rest of the \n## network as a whole than node 33.\n\n#%% (or degree)\ndegree = nx.degree_centrality(graph)\nsorted(degree, key=degree.get, reverse=True)[:2]\n\n## These two nodes are the two that have the highest\n## number of neighbours. This simple metric for centrality\n## identifies nodes 33 and 0 as the highest \"importance\"\n## for this network.\n\n#%%\n\ndat = pd.read_csv(\"HW2_tsp.txt\", sep=\" \", header=None, skiprows=10,\n names=[\"idx\",\"lat\",\"long\"],index_col=0)\n\ndat['lat'] = dat['lat']/1000\ndat['long'] = dat['long']/1000\n\n#%%\nfrom mpl_toolkits.basemap import Basemap\n \n#%%\nthemap = Basemap(projection='gall',\n llcrnrlon = 41.5, # lower-left corner longitude\n llcrnrlat = 10.8, # lower-left corner latitude\n urcrnrlon = 43.5, # upper-right corner longitude\n urcrnrlat = 12.9, # upper-right corner latitude\n resolution = 'l',\n area_thresh = 100000.0,\n )\n \nthemap.drawcoastlines()\nthemap.drawcountries()\nthemap.fillcontinents(color = '#A1D490')\nthemap.drawmapboundary(fill_color='lightblue')\nx,y = themap(list(dat['long']), list(dat['lat']))\nthemap.plot(x, y, \n '^', # marker shape\n color='darkblue', # marker colour\n markersize=10 # marker size\n )\n\nplt.show()\n \n#%%\nfrom ortools.constraint_solver import pywrapcp\nfrom ortools.constraint_solver import routing_enums_pb2\nfrom geopy.distance import vincenty\n\n#%%\ndistancematrix = pd.DataFrame(np.zeros((38, 38)))\n\n##populate the data frame with the distances between each pair\nfor i in list(range(0,38)):\n for k in list(range(0,38)):\n distancematrix.iloc[i][k] = (vincenty((dat.iloc[k][0],dat.iloc[k][1]),\n (dat.iloc[i][0],dat.iloc[i][1])).kilometers)\n\n#%%\n\nclass CreateDistanceCallback(object):\n \"\"\"Create callback to calculate distances between points.\"\"\"\n def __init__(self):\n \"\"\"Array of distances between points.\"\"\"\n\n self.matrix = distancematrix.as_matrix()\n \n def Distance(self, from_node, to_node):\n return self.matrix[from_node][to_node]\n\n#%%\n\n##code from Google's OR toolsdocumentation\ntsp_size=38 \nif tsp_size > 0:\n \n routing = pywrapcp.RoutingModel(tsp_size, 1,1)\n search_parameters = pywrapcp.RoutingModel.DefaultSearchParameters()\n\n # Setting first solution heuristic: the\n # method for finding a first solution to the problem.\n search_parameters.first_solution_strategy = (\n routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n\n # Create the distance callback, which takes two arguments (the from and to node indices)\n # and returns the distance between these nodes.\n\n dist_between_nodes = CreateDistanceCallback()\n dist_callback = dist_between_nodes.Distance\n routing.SetArcCostEvaluatorOfAllVehicles(dist_callback)\n#%%\ncity_names = range(0, 38)\n \n# Solve, returns a solution if any.\nassignment = routing.SolveWithParameters(search_parameters)\nif assignment:\n # Solution cost.\n print (\"Total distance: \" + str(assignment.ObjectiveValue()) + \" km\\n\")\n # Inspect solution.\n # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1\n route_number = 0\n index = routing.Start(route_number) # Index of the variable for the starting node.\n route = ''\n while not routing.IsEnd(index):\n # Convert variable indices to node indices in the displayed route.\n route += str(city_names[routing.IndexToNode(index)]) + ' -> '\n index = assignment.Value(routing.NextVar(index))\n route += str(city_names[routing.IndexToNode(index)])\n print (\"Route:\\n\\n\" + route)\nelse:\n print ('No solution found.')\n" } ]
13
vhugoxx/gaming
https://github.com/vhugoxx/gaming
d90eafcec94b48397c0105ff7fe6ded1bed02ebf
b0453ae3daeb767d3af39524ff92b7dead68cbd0
aa8ee2534c2edeb2692840955061ef2d4f4f88cf
refs/heads/dev
2023-01-21T12:04:56.874193
2020-12-06T22:38:02
2020-12-06T22:38:02
319,146,642
0
0
null
2020-12-06T22:39:56
2020-12-01T15:41:16
2020-12-01T15:41:14
null
[ { "alpha_fraction": 0.6949806809425354, "alphanum_fraction": 0.7516087293624878, "avg_line_length": 32.739131927490234, "blob_id": "fa16738d72faec31126d77e9151a3cbecae889f3", "content_id": "4c3e0b7c9afea66c42cd9a20312adf0cbce4ae80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 777, "license_type": "no_license", "max_line_length": 67, "num_lines": 23, "path": "/emp3.py", "repo_name": "vhugoxx/gaming", "src_encoding": "UTF-8", "text": "from telethon import TelegramClient, events, sync\nfrom telethon.tl.functions.messages import GetHistoryRequest\n\n# These example values won't work. You must get your own api_id and\n# api_hash from https://my.telegram.org, under API Development.\napi_id = 2996268\napi_hash = 'af5c9894512ba0234919e240764b13bd'\nphone_number = '00351939426865'\n\nclient = TelegramClient('APISession_CFG_TT', api_id, api_hash)\nclient.start()\n\nif not client.is_user_authorized():\n client.send_code_request(phone_number)\n me = client.sign_in(phone_number, input('Enter code: '))\n\nmy_private_channel_id = None\nmy_private_channel = None\n\nfor dialog in client.iter_dialogs():\n my_private_channel = dialog\n my_private_channel_id = dialog.id\n print(my_private_channel, my_private_channel_id)\n\n" }, { "alpha_fraction": 0.6724599003791809, "alphanum_fraction": 0.7459893226623535, "avg_line_length": 28.959999084472656, "blob_id": "b82d82711fcaf3bd1b63de926565bfb8b70f7b68", "content_id": "95ad2efbec5e69d8e1654a96d095ca20f14ac72b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 748, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/empates.py", "repo_name": "vhugoxx/gaming", "src_encoding": "UTF-8", "text": "from telethon import TelegramClient, events, sync\n\n# These example values won't work. You must get your own api_id and\n# api_hash from https://my.telegram.org, under API Development.\napi_id = 2996268\napi_hash = 'af5c9894512ba0234919e240764b13bd'\n\nclient = TelegramClient('APISession', api_id, api_hash)\nclient.start()\n\nprint(client.get_me().stringify())\n\nclient.send_message('+351939426865', 'Hello! Talking to you from Telethon')\n# client.send_file('username', '/home/myself/Pictures/holidays.jpg')\n\n# client.download_profile_photo('me')\n\nmessages = client.get_messages('+351910825970')\nprint(messages)\n# message\ns[0].download_media()\n\[email protected](events.NewMessage(pattern='(?i)hi|hello'))\nasync def handler(event):\n await event.respond('Hey!')" }, { "alpha_fraction": 0.7749999761581421, "alphanum_fraction": 0.7749999761581421, "avg_line_length": 40, "blob_id": "db5343680c1d39a944cf58ba0f519834a05d4f8d", "content_id": "c4fa83d9b0ef20d38d19017f68341bb230a0ddbe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 40, "license_type": "no_license", "max_line_length": 40, "num_lines": 1, "path": "/README.md", "repo_name": "vhugoxx/gaming", "src_encoding": "UTF-8", "text": "## This is where will make serious money" }, { "alpha_fraction": 0.6807909607887268, "alphanum_fraction": 0.7382297515869141, "avg_line_length": 29.371429443359375, "blob_id": "f1d03db8663ae7863a590332014eaf479d318f9c", "content_id": "5ca6436aa74fbfbec2d463213705f99d46b9492a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 78, "num_lines": 35, "path": "/green.py", "repo_name": "vhugoxx/gaming", "src_encoding": "UTF-8", "text": "from telethon import TelegramClient, events, sync\nfrom telethon.tl.functions.messages import GetHistoryRequest\n\n# These example values won't work. You must get your own api_id and\n# api_hash from https://my.telegram.org, under API Development.\napi_id = 2241619\napi_hash = '71718cf1b0182ccd6bbca48e418c8343'\nphone_number = '00351939426865'\n\nclient = TelegramClient('APISession_hugo', api_id, api_hash)\nclient.start()\n\nprint(client.get_me().stringify())\n\nclient.send_message('+351939426865', 'teste de python')\n\nif not client.is_user_authorized():\n client.send_code_request(phone_number)\n me = client.sign_in(phone_number, input('Enter code: '))\n\nchannel_username='https://t.me/joinchat/AAAAAFFVzbofUqSnF98mFQ' # your channel\nchannel_entity=client.get_entity(channel_username)\nposts = client(GetHistoryRequest(\n peer=channel_entity,\n limit=2,\n offset_date=None,\n offset_id=0,\n max_id=0,\n min_id=0,\n add_offset=0,\n hash=0))\n# messages stored in `posts.messages`\n\nprint('Channel Entity:', channel_entity)\nprint('Posts received:', posts)" } ]
4
Mariya74/PY13_Less2.1
https://github.com/Mariya74/PY13_Less2.1
8a8fad2a8bb0415a6c54310a721d78c1b355e78d
3b457d629c42b3a0459dbe233120b32ba2a0606a
c44c88462617c3e665f82812e0214a653d79338a
refs/heads/master
2021-04-27T10:00:50.565909
2018-02-22T19:45:00
2018-02-22T19:45:00
122,385,430
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5668126940727234, "alphanum_fraction": 0.5690032839775085, "avg_line_length": 38.57777786254883, "blob_id": "6a5977a02d16ed62cd5c1ec797a3013bfeded11a", "content_id": "4c83733c9801d55b9ab6489266a92ee8dbd3e85d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1905, "license_type": "no_license", "max_line_length": 139, "num_lines": 45, "path": "/cooke.py", "repo_name": "Mariya74/PY13_Less2.1", "src_encoding": "UTF-8", "text": "\r\ndef read_cook_book():\r\n recipts = {}\r\n file = open(\"рецепты.txt\", encoding=\"UTF8\")\r\n for line in file:\r\n name = line.strip().lower()\r\n if name != \"\":\r\n count = int(file.readline().strip())\r\n ingridients = []\r\n for i in range(count):\r\n ingridients_list = file.readline().strip().split(' | ')\r\n ingridient = {'ingridient_name': ingridients_list[0], 'quantity': int(ingridients_list[1]), 'measure': ingridients_list[2]}\r\n ingridients.append(ingridient)\r\n recipts[name] = ingridients\r\n return recipts\r\n\r\n\r\ndef get_shop_list_by_dishes(cook_book, dishes, person_count):\r\n shop_list = {}\r\n for dish in dishes:\r\n for ingridient in cook_book[dish]:\r\n new_shop_list_item = dict(ingridient)\r\n new_shop_list_item['quantity'] *= person_count\r\n if new_shop_list_item['ingridient_name'] not in shop_list:\r\n shop_list[new_shop_list_item['ingridient_name']] = new_shop_list_item\r\n else:\r\n shop_list[new_shop_list_item['ingridient_name']]['quantity'] += new_shop_list_item['quantity']\r\n return shop_list\r\n\r\n\r\ndef print_shop_list(shop_list):\r\n for shop_list_item in shop_list.values():\r\n print('{} {} {}'.format(shop_list_item['ingridient_name'],\r\n shop_list_item['quantity'],\r\n shop_list_item['measure']))\r\n\r\n\r\ndef create_shop_list():\r\n cook_book = read_cook_book()\r\n person_count = int(input('Введите количество человек: '))\r\n dishes = input('Введите блюда в расчете на одного человека (через запятую): ').lower().split(', ')\r\n shop_list = get_shop_list_by_dishes(cook_book, dishes, person_count)\r\n print_shop_list(shop_list)\r\n\r\n\r\ncreate_shop_list()" } ]
1
AndrewLvov/Strings
https://github.com/AndrewLvov/Strings
9ab2deceaf8c95dcc15295ed246728aac5d3132a
34f4f502ca4bbb452eeb48b455b50aaf2288db4b
84a39145d84bfba6e049006d8b35cf2644795601
refs/heads/master
2015-07-25T07:41:11.997916
2014-10-04T09:59:38
2014-10-04T09:59:38
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5891719460487366, "alphanum_fraction": 0.6369426846504211, "avg_line_length": 28.4375, "blob_id": "f60ff17763777dee01b76b10c3f72f7567f6529b", "content_id": "f023c98507dba4da37261dd4e403b13682a881fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1086, "license_type": "no_license", "max_line_length": 68, "num_lines": 32, "path": "/main.py", "repo_name": "AndrewLvov/Strings", "src_encoding": "UTF-8", "text": "def slices(container):\n # третий элемент (индексация начинается с нуля)\n print(\"Third element: {}\".format(container[2]))\n # -2 означает предпоследний, -1 - соотв. последний\n print(\"Last two: {}\".format(container[-2:]))\n # container[2] - 1 элемент, container[2:] - от третьего до конца\n print(\"Reversed: {}\".format(container[5:1:-1]))\n # через 1\n print(\"Skipping 1 each time: {}\".format(container[::2]))\n\narr = [1, 2, 't', [1, 1, 1], \"string here\", 44.0]\ns1 = \"Hello, my dear friend!\"\n# slices(arr)\n# slices(s1)\n# print(arr)\n# print(s1)\n\n# копия всего массива!!\narr2 = arr[:]\narr2[0] = 'abracadabra'\nprint(\"Arr after arr2 change: {}\".format(arr))\nprint(\"Arr2 after arr2 change: {}\".format(arr2))\n\nprint()\narr3 = arr\narr3[4] = 'Hello from arr3'\nprint(\"Arr after arr2 change: {}\".format(arr))\nprint(\"Arr3 after arr2 change: {}\".format(arr3))\n# arr3 теперь ссылается на то же, что и arr\n\nprint(s1 * 3)\nprint(arr[0:2] * 3)\n" } ]
1
landon-campbell/dictionary
https://github.com/landon-campbell/dictionary
ca499ce74fa526e237b0b4236c283ee82b052ae5
a57176c4479a3b04c4ae4b3d432bfd29930039da
724c84e101b6369973559db385a8c8fc17395e49
refs/heads/main
2023-06-09T18:03:18.420903
2021-06-29T21:10:31
2021-06-29T21:10:31
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4618973433971405, "alphanum_fraction": 0.47382062673568726, "avg_line_length": 31.258621215820312, "blob_id": "bd853139c52bb991beebf72b5ed9b684bbae6f71", "content_id": "cf60ca8571f64c21d2251c2c96dabacde90a01c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1929, "license_type": "no_license", "max_line_length": 117, "num_lines": 58, "path": "/dictionary/app.py", "repo_name": "landon-campbell/dictionary", "src_encoding": "UTF-8", "text": "from flask import Flask\r\nfrom flask.templating import render_template\r\napp = Flask(__name__)\r\n\r\n\r\n\r\[email protected]('/')\r\ndef hello_world():\r\n return \"hello world - go to <a href='/dictionary'>dictionary</a>\"\r\n\r\n\r\[email protected]('/dictionary')\r\ndef dictionaryhome():\r\n alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\r\n return render_template('dictionaryhome1.html', alpha=alpha)\r\n\r\[email protected]('/dictionary/<string:given_word>')\r\ndef dictionary(given_word):\r\n alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\r\n f = open('words.txt')\r\n word_list = f.read().splitlines()\r\n count = 0\r\n for word in word_list:\r\n match = 0\r\n for i in range(0, len(given_word)):\r\n if len(given_word) <= len(word):\r\n if given_word[i].upper() == word[i]:\r\n match += 1 \r\n if match == (len(given_word)):\r\n count += 1\r\n\r\n for letter in alpha:\r\n new_word = given_word + letter\r\n count2 = 0\r\n for word in word_list:\r\n match2 = 0\r\n for i in range(0, len(new_word)):\r\n if len(new_word) <= len(word):\r\n if new_word[i].upper() == word[i]:\r\n match2 += 1 \r\n if match2 == (len(new_word)):\r\n count2 += 1\r\n if count2 == 0:\r\n alpha.remove(letter)\r\n\r\n\r\n\r\n # for letter in alpha:\r\n # for word in word_list:\r\n # new_word = given_word + letter\r\n # if len(new_word) <= len(word):\r\n # if new_word[-1].upper() == word[len(new_word)-1]:\r\n # second_count += 1\r\n # if second_count == 0:\r\n # alpha.remove(letter)\r\n \r\n\r\n return render_template('dictionarylist1.html', given_word=given_word, count=count, alpha=alpha)\r\n" } ]
1
fstanis/Newsumm
https://github.com/fstanis/Newsumm
cabcc43db43e46460be5c4a3c8208c4a067d93c8
1e1725bedbb0728b13c21d6ce833f158662980a8
6ebda80de615e4bb444e3239c6e31f7832c8aa00
refs/heads/main
2023-04-19T04:46:37.722449
2021-03-24T20:58:01
2021-03-25T12:51:09
365,047,247
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6574281454086304, "alphanum_fraction": 0.6648304462432861, "avg_line_length": 38.78767013549805, "blob_id": "2f03c347ccd90102fa679e0114f2bf2d72a508a5", "content_id": "6922ff6394c979fe4921ac7ff386089d22a52c85", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 5809, "license_type": "permissive", "max_line_length": 151, "num_lines": 146, "path": "/mobile/src/main/java/me/stanis/newsumm/util/audio/AudioEncoder.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.util.audio\n\nimport android.media.MediaCodec\nimport android.media.MediaCodecInfo\nimport android.media.MediaExtractor\nimport android.media.MediaFormat\nimport android.media.MediaMuxer\nimport kotlinx.coroutines.CoroutineScope\nimport kotlinx.coroutines.Deferred\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.async\nimport kotlinx.coroutines.withContext\nimport java.io.FileDescriptor\n\nclass AudioEncoder(\n fdOut: FileDescriptor,\n private val bitrate: Int = DEFAULT_BITRATE\n) {\n suspend fun addInput(fd: FileDescriptor) = withContext(Dispatchers.IO) {\n processInputFile(fd)\n }\n\n suspend fun finish() = withContext(Dispatchers.IO) {\n check(::encoder.isInitialized) { \"finish() called before any inputs were added\" }\n endInput()\n outputTask.await()\n muxer.stop()\n muxer.release()\n }\n\n private val muxer = MediaMuxer(fdOut, OUTPUT_FORMAT)\n private lateinit var encoder: MediaCodec\n private lateinit var outputTask: Deferred<Unit>\n private var offsetTime = 0L\n private var muxerTrack = -1\n\n private fun initEncoder(inputFormat: MediaFormat) {\n val sampleRate = inputFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE)\n val channelCount = inputFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT)\n if (::encoder.isInitialized) {\n check(encoder.inputFormat.getInteger(MediaFormat.KEY_SAMPLE_RATE) == sampleRate) { \"all inputs must have the same sample rate\" }\n check(encoder.inputFormat.getInteger(MediaFormat.KEY_CHANNEL_COUNT) == channelCount) { \"all inputs must have the same number of channels\" }\n return\n }\n encoder = MediaCodec.createEncoderByType(OUTPUT_AUDIO_FORMAT)\n encoder.configure(MediaFormat().apply {\n setString(MediaFormat.KEY_MIME, OUTPUT_AUDIO_FORMAT)\n setInteger(MediaFormat.KEY_BIT_RATE, bitrate)\n setInteger(MediaFormat.KEY_AAC_PROFILE, AAC_PROFILE)\n setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, MAX_INPUT_SIZE)\n setInteger(MediaFormat.KEY_SAMPLE_RATE, sampleRate)\n setInteger(MediaFormat.KEY_CHANNEL_COUNT, channelCount)\n }, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)\n encoder.start()\n outputTask = CoroutineScope(Dispatchers.IO).async { processOutput() }\n }\n\n private fun processInputFile(fd: FileDescriptor) {\n val extractor = MediaExtractor()\n extractor.setDataSource(fd)\n require(extractor.trackCount == 1) { \"more than one track found in input file\" }\n extractor.selectTrack(0)\n val trackFormat = extractor.getTrackFormat(0)\n require(isWavFormat(trackFormat)) { \"input file is not in WAVE format\" }\n initEncoder(trackFormat)\n while (true) {\n val inputBufferId = encoder.dequeueInputBuffer(-1)\n check(inputBufferId > -1)\n val read = extractor.readSampleData(encoder.getInputBuffer(inputBufferId)!!, 0)\n if (read < 0) {\n encoder.queueInputBuffer(inputBufferId, 0, 0, 0, 0)\n break\n }\n val sampleTimeUs = extractor.sampleTime + offsetTime\n encoder.queueInputBuffer(inputBufferId, 0, read, sampleTimeUs, 0)\n extractor.advance()\n }\n offsetTime += trackFormat.getLong(MediaFormat.KEY_DURATION)\n extractor.release()\n }\n\n private fun endInput() {\n encoder.queueInputBuffer(\n encoder.dequeueInputBuffer(-1),\n 0,\n 0,\n offsetTime,\n MediaCodec.BUFFER_FLAG_END_OF_STREAM\n )\n }\n\n private fun processOutput() {\n val bufferInfo = MediaCodec.BufferInfo()\n while (!isEndOfStream(bufferInfo)) {\n val outputBufferId = encoder.dequeueOutputBuffer(bufferInfo, -1)\n if (outputBufferId == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {\n check(muxerTrack == -1)\n muxerTrack = muxer.addTrack(encoder.outputFormat)\n muxer.start()\n continue\n }\n check(outputBufferId > -1)\n if (!isCodecConfig(bufferInfo)) {\n muxer.writeSampleData(\n muxerTrack,\n encoder.getOutputBuffer(outputBufferId)!!,\n bufferInfo\n )\n }\n encoder.releaseOutputBuffer(outputBufferId, false)\n }\n }\n\n private fun isWavFormat(trackFormat: MediaFormat) =\n trackFormat.getString(MediaFormat.KEY_MIME) == MediaFormat.MIMETYPE_AUDIO_RAW\n\n private fun isEndOfStream(bufferInfo: MediaCodec.BufferInfo) =\n bufferInfo.flags and MediaCodec.BUFFER_FLAG_END_OF_STREAM != 0\n\n private fun isCodecConfig(bufferInfo: MediaCodec.BufferInfo) =\n bufferInfo.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG != 0\n\n companion object {\n const val OUTPUT_FORMAT = MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4\n const val OUTPUT_AUDIO_FORMAT = MediaFormat.MIMETYPE_AUDIO_AAC\n const val AAC_PROFILE = MediaCodecInfo.CodecProfileLevel.AACObjectLC\n const val MAX_INPUT_SIZE = 64 * 1024\n const val DEFAULT_BITRATE = 64000\n }\n}\n" }, { "alpha_fraction": 0.6798473000526428, "alphanum_fraction": 0.6820288896560669, "avg_line_length": 33.92380905151367, "blob_id": "7860ba1a1bd88acb6b6e27d661338a68dd5b2f48", "content_id": "f1a44bbedf5661dae672f806ed726d714b7dcb83", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 3667, "license_type": "permissive", "max_line_length": 97, "num_lines": 105, "path": "/mobile/src/main/java/me/stanis/newsumm/util/audio/TTSEngine.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.util.audio\n\nimport android.content.Context\nimport android.speech.tts.TextToSpeech\nimport android.speech.tts.UtteranceProgressListener\nimport kotlinx.coroutines.CompletableDeferred\nimport kotlinx.coroutines.CoroutineStart\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.GlobalScope\nimport kotlinx.coroutines.async\nimport kotlinx.coroutines.withContext\nimport java.io.File\nimport java.util.*\n\nclass TTSEngine(context: Context) {\n private val tts = GlobalScope.async(start = CoroutineStart.LAZY) {\n createTextToSpeech(context).also {\n it.setOnUtteranceProgressListener(progressListener)\n }\n }\n private val utterances = mutableMapOf<String, CompletableDeferred<Unit>>()\n\n private val progressListener = object : UtteranceProgressListener() {\n override fun onStart(utteranceId: String?) {}\n\n override fun onDone(utteranceId: String?) {\n utteranceId ?: return\n utterances[utteranceId]?.complete(Unit)\n utterances.remove(utteranceId)\n }\n\n override fun onError(utteranceId: String?) {\n utteranceId ?: return\n utterances[utteranceId]?.completeExceptionally(Exception(\"error creating utterance\"))\n utterances.remove(utteranceId)\n }\n }\n\n val maxSpeechInputLength get() = TextToSpeech.getMaxSpeechInputLength()\n\n suspend fun waitForLoad() {\n tts.await()\n }\n\n suspend fun isLanguageAvailable(language: String) =\n tts.await().isLanguageAvailable(Locale(language)) == TextToSpeech.LANG_AVAILABLE\n\n suspend fun synthesizeToFile(charSequence: CharSequence, language: String, file: File) =\n withContext(Dispatchers.IO) {\n setLanguage(language)\n val id = createUtterance()\n tts.await().synthesizeToFile(charSequence, null, file, id)\n utterances[id]!!.await()\n }\n\n suspend fun speak(charSequence: CharSequence, language: String) {\n setLanguage(language)\n val id = createUtterance()\n tts.await().speak(charSequence, TextToSpeech.QUEUE_ADD, null, id)\n utterances[id]!!.await()\n }\n\n suspend fun synthesizeToTempFile(charSequence: CharSequence, language: String): File =\n withContext(Dispatchers.IO) {\n val file = File.createTempFile(\"tts\", \".wav\")\n synthesizeToFile(charSequence, language, file)\n file\n }\n\n private fun createUtterance(): String {\n val id = UUID.randomUUID().toString()\n val deferred = CompletableDeferred<Unit>()\n utterances[id] = deferred\n return id\n }\n\n private suspend fun setLanguage(language: String) {\n tts.await().language = Locale(language)\n }\n\n companion object {\n private suspend fun createTextToSpeech(context: Context): TextToSpeech {\n val status = CompletableDeferred<Int>()\n val tts = TextToSpeech(context) { status.complete(it) }\n check(status.await() == TextToSpeech.SUCCESS)\n return tts\n }\n }\n}\n" }, { "alpha_fraction": 0.6993415951728821, "alphanum_fraction": 0.7051938772201538, "avg_line_length": 30.79069709777832, "blob_id": "f91537debc9e0dd5162cf17ba63f64a54aed30ba", "content_id": "28f1e368ed42beca316ad0cef51a3eeab0cfbd00", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1367, "license_type": "permissive", "max_line_length": 86, "num_lines": 43, "path": "/mobile/src/main/java/me/stanis/newsumm/util/audio/AudioPlayer.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.util.audio\n\nimport android.content.Context\nimport android.media.AudioAttributes\nimport android.media.MediaPlayer\nimport android.net.Uri\nimport dagger.hilt.android.qualifiers.ActivityContext\nimport javax.inject.Inject\n\nclass AudioPlayer @Inject constructor(@ActivityContext private val context: Context) {\n private val player = MediaPlayer().apply {\n setAudioAttributes(\n AudioAttributes.Builder()\n .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)\n .setUsage(AudioAttributes.USAGE_ASSISTANT)\n .build()\n )\n }\n\n fun start(uri: Uri) {\n player.setDataSource(context, uri)\n player.prepare()\n player.start()\n }\n\n fun stop() = player.stop()\n}\n" }, { "alpha_fraction": 0.6097525358200073, "alphanum_fraction": 0.6115097403526306, "avg_line_length": 34.20103073120117, "blob_id": "3d69a90d6f73e221d2b5fe7453aa55c29355cf9a", "content_id": "4a36589f15e289a3bb8e46040605d5e41da8ae26", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 6829, "license_type": "permissive", "max_line_length": 99, "num_lines": 194, "path": "/mobile/src/main/java/me/stanis/newsumm/ui/MainActivity.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.ui\n\nimport android.content.Intent\nimport android.os.Bundle\nimport android.view.Menu\nimport android.view.MenuItem\nimport android.view.View\nimport android.webkit.URLUtil\nimport androidx.activity.viewModels\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.core.content.ContextCompat\nimport androidx.core.net.toUri\nimport androidx.fragment.app.DialogFragment\nimport androidx.fragment.app.Fragment\nimport androidx.lifecycle.lifecycleScope\nimport dagger.hilt.android.AndroidEntryPoint\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.withTimeoutOrNull\nimport me.stanis.newsumm.R\nimport me.stanis.newsumm.data.Article\nimport me.stanis.newsumm.databinding.ActivityMainBinding\nimport me.stanis.newsumm.util.audio.ArticleTTS\nimport me.stanis.newsumm.util.audio.AudioPlayer\nimport me.stanis.newsumm.util.network.NetworkChecker\nimport me.stanis.newsumm.util.webcontent.WebContentLoader\nimport java.io.IOException\nimport javax.inject.Inject\n\n@AndroidEntryPoint\nclass MainActivity : AppCompatActivity() {\n private lateinit var binding: ActivityMainBinding\n private var menu: Menu? = null\n\n private val viewModel: MainViewModel by viewModels()\n private val ttsMenuItem get() = menu?.findItem(R.id.action_tts)\n private val alertPrompt by lazy { UrlAlertPrompt(this) }\n private val iconSpeech by lazy { ContextCompat.getDrawable(this, R.drawable.ic_speech) }\n private val iconSpeechUnavailable by lazy {\n ContextCompat.getDrawable(this, R.drawable.ic_speech_unavailable)\n }\n\n @Inject\n lateinit var webContentLoader: WebContentLoader\n\n @Inject\n lateinit var articleTTS: ArticleTTS\n\n @Inject\n lateinit var audioPlayer: AudioPlayer\n\n @Inject\n lateinit var networkChecker: NetworkChecker\n\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n binding = ActivityMainBinding.inflate(layoutInflater)\n setContentView(binding.root)\n if (savedInstanceState == null) processIntent(intent)\n viewModel.state.observe(this) {\n binding.progressBar.visibility = if (it.isLoading) View.VISIBLE else View.GONE\n when (it.articleStatus) {\n is ArticleStatus.Ready -> {\n binding.errorStatus.visibility = View.GONE\n binding.articleTitle.text = it.articleStatus.article.title\n binding.articleContent.text =\n it.articleStatus.article.sentences.joinToString(\"\\n\\n\")\n }\n is ArticleStatus.None -> {\n binding.errorStatus.visibility = View.GONE\n binding.articleTitle.text = \"\"\n binding.articleContent.text = getString(R.string.no_article_loaded)\n }\n is ArticleStatus.Error -> {\n binding.errorStatus.visibility = View.VISIBLE\n binding.errorStatus.text = it.articleStatus.error\n }\n }\n when (it.speechStatus) {\n is SpeechStatus.Ready ->\n ttsMenuItem?.apply {\n isEnabled = true\n icon = iconSpeech\n }\n is SpeechStatus.None ->\n ttsMenuItem?.apply {\n isEnabled = false\n icon = iconSpeech\n }\n is SpeechStatus.Unavailable ->\n ttsMenuItem?.apply {\n isEnabled = false\n icon = iconSpeechUnavailable\n }\n }\n val a = DialogFragment()\n a.show(supportFragmentManager, \"test\")\n }\n alertPrompt.setCallback {\n load(it)\n }\n }\n\n override fun onOptionsItemSelected(item: MenuItem) =\n when (item.itemId) {\n R.id.action_load -> {\n openUrlPrompt()\n true\n }\n R.id.action_tts -> {\n viewModel.state.value?.speechStatus?.let {\n if (it is SpeechStatus.Ready) {\n audioPlayer.play(it.uri)\n }\n }\n true\n }\n R.id.action_send -> TODO()\n else -> super.onOptionsItemSelected(item)\n }\n\n private fun load(url: String) = lifecycleScope.launch(Dispatchers.Default) {\n viewModel.setArticleLoading()\n viewModel.setSpeechLoading()\n try {\n val content = webContentLoader.parseURL(url)\n viewModel.setArticle(content)\n runTTS(content)\n } catch (e: IOException) {\n viewModel.setArticleError(\"Error loading article\")\n }\n }\n\n private suspend fun runTTS(article: Article) {\n val langAvailable =\n withTimeoutOrNull(1000L) { articleTTS.isEligible(article) } ?: false\n if (!langAvailable) {\n viewModel.setSpeechUnavailable()\n return\n }\n viewModel.setSpeechUri(articleTTS.run(article).toUri())\n }\n\n private fun openUrlPrompt(text: String = \"\") {\n if (text.isNotEmpty()) {\n alertPrompt.text = text\n }\n alertPrompt.setIsOnline(networkChecker.isOnline())\n alertPrompt.show()\n }\n\n override fun onCreateOptionsMenu(menu: Menu): Boolean {\n super.onCreateOptionsMenu(menu)\n this.menu = menu\n menuInflater.inflate(R.menu.menu, menu)\n return true\n }\n\n override fun onNewIntent(intent: Intent?) {\n super.onNewIntent(intent)\n processIntent(intent)\n }\n\n private fun processIntent(intent: Intent?) {\n intent\n ?.takeIf { it.action == Intent.ACTION_SEND }\n ?.getStringExtra(Intent.EXTRA_TEXT)\n ?.also {\n if (URLUtil.isNetworkUrl(it)) {\n openUrlPrompt(it)\n } else if (!URLUtil.isValidUrl(it)) {\n viewModel.setArticle(\n Article(title = getString(R.string.pasted_article), sentences = listOf(it))\n )\n }\n }\n }\n}\n" }, { "alpha_fraction": 0.6654240489006042, "alphanum_fraction": 0.6691519021987915, "avg_line_length": 29.225351333618164, "blob_id": "48bad2c7d8f9bfdffff7e6eda82919edc3353e8c", "content_id": "a11972a572f5696508c649c38388d8bb9eb22895", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2146, "license_type": "permissive", "max_line_length": 84, "num_lines": 71, "path": "/mobile/src/main/java/me/stanis/newsumm/ui/UrlAlertPrompt.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.ui\n\nimport android.content.Context\nimport android.content.DialogInterface\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.webkit.URLUtil\nimport androidx.appcompat.app.AlertDialog\nimport me.stanis.newsumm.R\nimport me.stanis.newsumm.databinding.DialogUrlBinding\n\nclass UrlAlertPrompt(context: Context) {\n private var callback: ((String) -> Unit)? = null\n private val binding = DialogUrlBinding.inflate(LayoutInflater.from(context))\n private val dialog = AlertDialog.Builder(context)\n .setView(binding.root)\n .setMessage(R.string.article_url)\n .setPositiveButton(R.string.load) { _: DialogInterface, _: Int -> onLoad() }\n .create()\n\n private val errorDialog = AlertDialog.Builder(context)\n .setOnDismissListener { show() }\n .setMessage(R.string.invalid_url)\n .create()\n\n fun show(): Unit = dialog.show()\n\n var text: CharSequence\n get() = binding.url.text\n set(value) {\n binding.url.setText(value)\n }\n\n fun setIsOnline(isOnline: Boolean) {\n binding.appearOffline.visibility = if (isOnline) View.GONE else View.VISIBLE\n }\n\n fun setCallback(cb: (String) -> Unit) {\n callback = cb\n }\n\n fun clearCallback() {\n callback = null\n }\n\n private fun onLoad() {\n val url = text.toString()\n if (!URLUtil.isNetworkUrl(url)) {\n errorDialog.show()\n } else {\n callback?.invoke(text.toString())\n text = \"\"\n }\n }\n}\n" }, { "alpha_fraction": 0.6739025712013245, "alphanum_fraction": 0.6782441139221191, "avg_line_length": 31.40625, "blob_id": "c2eea0e977e9b6e53ee2ccf292c78c599ed21e21", "content_id": "53b7add229f1e4236de5cbc8547f236e4d8662f2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2073, "license_type": "permissive", "max_line_length": 91, "num_lines": 64, "path": "/mobile/src/main/java/me/stanis/newsumm/util/audio/ArticleTTS.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.util.audio\n\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.flow.Flow\nimport kotlinx.coroutines.flow.asFlow\nimport kotlinx.coroutines.flow.collect\nimport kotlinx.coroutines.flow.map\nimport kotlinx.coroutines.withContext\nimport me.stanis.newsumm.data.Article\nimport java.io.File\nimport java.io.FileInputStream\nimport java.io.FileOutputStream\nimport javax.inject.Inject\n\nclass ArticleTTS @Inject constructor() {\n @Inject\n lateinit var ttsEngine: TTSEngine\n\n suspend fun isEligible(article: Article) =\n ttsEngine.isLanguageAvailable(article.language)\n && article.sentences.all { it.length <= ttsEngine.maxSpeechInputLength }\n\n suspend fun run(article: Article): File {\n val lines = article.sentences\n .map { it.trim() }\n .filter { it.isNotEmpty() }\n .asFlow()\n return mergeAudioFiles(lines.map {\n ttsEngine.synthesizeToTempFile(it, article.language)\n })\n }\n\n private suspend fun mergeAudioFiles(inputs: Flow<File>) = withContext(Dispatchers.IO) {\n val outfile = File.createTempFile(\"tts\", \".mp4\")\n val fos = FileOutputStream(outfile)\n val encoder = AudioEncoder(fos.fd)\n inputs.collect {\n with(FileInputStream(it)) {\n encoder.addInput(fd)\n close()\n }\n it.delete()\n }\n encoder.finish()\n fos.close()\n outfile\n }\n}" }, { "alpha_fraction": 0.773097813129425, "alphanum_fraction": 0.7785326242446899, "avg_line_length": 31.711111068725586, "blob_id": "129a175bce3370fa5d737a075c58ab1206a92eed", "content_id": "318bceb23ce90c6dd15cfe41ce9051253291777b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1472, "license_type": "permissive", "max_line_length": 77, "num_lines": 45, "path": "/mobile/src/main/java/me/stanis/newsumm/HiltModules.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm\n\nimport android.content.Context\nimport android.net.ConnectivityManager\nimport com.google.mlkit.nl.languageid.LanguageIdentification\nimport dagger.Module\nimport dagger.Provides\nimport dagger.hilt.InstallIn\nimport dagger.hilt.android.components.ApplicationComponent\nimport dagger.hilt.android.qualifiers.ApplicationContext\nimport me.stanis.newsumm.util.audio.TTSEngine\nimport javax.inject.Singleton\n\n@Module\n@InstallIn(ApplicationComponent::class)\nobject AppModule {\n @Provides\n @Singleton\n fun provideConnectivityManager(@ApplicationContext context: Context) =\n context.getSystemService(ConnectivityManager::class.java)!!\n\n @Provides\n @Singleton\n fun provideTTS(@ApplicationContext context: Context) = TTSEngine(context)\n\n @Provides\n @Singleton\n fun provideLanguageIdentifier() = LanguageIdentification.getClient()\n}\n" }, { "alpha_fraction": 0.6709331274032593, "alphanum_fraction": 0.6742361783981323, "avg_line_length": 35.69696807861328, "blob_id": "703c4fc9b8e84fe7a0f581fbade8f23fdb806fa1", "content_id": "c5a097abfeb9bf8cc719c59a421130b9a1f0f5af", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2422, "license_type": "permissive", "max_line_length": 96, "num_lines": 66, "path": "/mobile/src/main/java/me/stanis/newsumm/util/webcontent/Sumy.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.util.webcontent\n\nimport android.content.Context\nimport android.util.Log\nimport com.chaquo.python.PyException\nimport com.chaquo.python.Python\nimport com.chaquo.python.android.AndroidPlatform\nimport dagger.hilt.android.qualifiers.ApplicationContext\nimport kotlinx.coroutines.*\nimport javax.inject.Inject\nimport javax.inject.Singleton\n\n@Singleton\nclass Sumy @Inject constructor(@ApplicationContext context: Context) {\n private val module = GlobalScope.async(start = CoroutineStart.LAZY) {\n Python.start(AndroidPlatform(context))\n Python.getInstance().getModule(\"sumy_wrapper\")\n }\n\n // TODO: This can fail and needs a way to retry\n private var punktStatus = GlobalScope.async(start = CoroutineStart.LAZY) { downloadPunkt() }\n\n private suspend fun downloadPunkt() = withContext(Dispatchers.IO) {\n try {\n module.await().callAttr(\"download_punkt\").toBoolean()\n } catch (e: PyException) {\n val error = e.message?.removePrefix(\"ValueError: \") ?: \"\"\n Log.e(\"Download error\", error)\n false\n }\n }\n\n suspend fun summarizeHTML(html: String, language: String, sentencesCount: Int) =\n withContext(Dispatchers.Default) {\n check(punktStatus.await())\n module.await()\n .callAttr(\"summarize_html\", html, language, sentencesCount)\n .toJava(Array<String>::class.java)\n .toList()\n }\n\n suspend fun summarizeText(text: String, language: String, sentencesCount: Int) =\n withContext(Dispatchers.Default) {\n check(punktStatus.await())\n module.await()\n .callAttr(\"summarize_text\", text, language, sentencesCount)\n .toJava(Array<String>::class.java)\n .toList()\n }\n}\n" }, { "alpha_fraction": 0.739811897277832, "alphanum_fraction": 0.7448275685310364, "avg_line_length": 34.44444274902344, "blob_id": "556e807ca643b39bad36f835cb7e5b561c692b0a", "content_id": "d99e0edae818a7186f14257c38b53276991b3583", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1595, "license_type": "permissive", "max_line_length": 74, "num_lines": 45, "path": "/mobile/src/main/python/sumy_wrapper.py", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom sumy.parsers.html import HtmlParser\nfrom sumy.parsers.plaintext import PlaintextParser\nfrom sumy.nlp.tokenizers import Tokenizer\nfrom sumy.summarizers.lsa import LsaSummarizer\nfrom sumy.nlp.stemmers import Stemmer\nfrom sumy.utils import get_stop_words\nimport nltk\n\ndef _summarize(parser, language, sentences_count):\n stemmer = Stemmer(language)\n summarizer = LsaSummarizer(stemmer)\n summarizer.stop_words = get_stop_words(language)\n sentences = summarizer(parser.document, sentences_count)\n return [str(s) for s in sentences]\n\ndef summarize_html(input, language, sentences_count):\n return _summarize(\n HtmlParser.from_string(input, None, Tokenizer(language)),\n language,\n sentences_count\n )\n\ndef summarize_text(input, language, sentences_count):\n return _summarize(\n PlaintextParser.from_string(input, Tokenizer(language)),\n language,\n sentences_count\n )\n\ndef download_punkt():\n return nltk.download('punkt', quiet=True, raise_on_error=True)\n" }, { "alpha_fraction": 0.6337028741836548, "alphanum_fraction": 0.6376940011978149, "avg_line_length": 32.161766052246094, "blob_id": "5de21e749e09f9da686d26d0891aa96436800d65", "content_id": "7ddce27fef4f2d195a6f753c27c5c251ecd6623d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2255, "license_type": "permissive", "max_line_length": 75, "num_lines": 68, "path": "/shared/src/main/java/me/stanis/newsumm/data/Article.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.data\n\nimport android.os.Parcel\nimport android.os.Parcelable\nimport com.google.android.gms.wearable.DataMap\nimport java.util.*\nimport kotlin.collections.ArrayList\n\ndata class Article(\n val url: String = UUID.randomUUID().toString(),\n val title: String = \"\",\n val sentences: List<String> = listOf(),\n val language: String = \"\"\n) : Parcelable {\n fun writeToDataMap(dataMap: DataMap) = with(dataMap) {\n putString(\"url\", url)\n putString(\"title\", title)\n putStringArrayList(\"sentences\", ArrayList(sentences))\n putString(\"language\", language)\n }\n\n override fun writeToParcel(parcel: Parcel, flags: Int) = with(parcel) {\n writeString(url)\n writeString(title)\n writeStringList(sentences)\n writeString(language)\n }\n\n companion object CREATOR : Parcelable.Creator<Article> {\n override fun createFromParcel(parcel: Parcel) =\n Article(\n url = parcel.readString() ?: \"\",\n title = parcel.readString() ?: \"\",\n sentences = parcel.createStringArrayList() ?: listOf(),\n language = parcel.readString() ?: \"\"\n )\n\n fun createFromDataMap(dataMap: DataMap) =\n Article(\n url = dataMap.getString(\"url\"),\n title = dataMap.getString(\"title\"),\n sentences = dataMap.getStringArrayList(\"sentences\"),\n language = dataMap.getString(\"language\")\n )\n\n override fun newArray(size: Int): Array<Article?> {\n return arrayOfNulls(size)\n }\n }\n\n override fun describeContents() = 0\n}\n" }, { "alpha_fraction": 0.7555555701255798, "alphanum_fraction": 0.7632850408554077, "avg_line_length": 35.96428680419922, "blob_id": "79355f7e40598252eef3f60dba764aa36d40c1b6", "content_id": "5c9c173e6bcd4bc047e37a1de2761be3c2fb70cd", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 1035, "license_type": "permissive", "max_line_length": 96, "num_lines": 28, "path": "/mobile/src/main/java/me/stanis/newsumm/util/network/NetworkChecker.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.util.network\n\nimport android.net.ConnectivityManager\nimport android.net.NetworkCapabilities\nimport javax.inject.Inject\n\nclass NetworkChecker @Inject constructor(private val connectivityManager: ConnectivityManager) {\n fun isOnline() = connectivityManager\n .getNetworkCapabilities(connectivityManager.activeNetwork)\n ?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)\n ?: false\n}\n" }, { "alpha_fraction": 0.7384615540504456, "alphanum_fraction": 0.7384615540504456, "avg_line_length": 20.66666603088379, "blob_id": "eaa5050938fffd6cfd1493a1276bc2ba8cc477c7", "content_id": "70658e875f7dbdfb4ba506225a49fdaf88539759", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 65, "license_type": "permissive", "max_line_length": 28, "num_lines": 3, "path": "/settings.gradle", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "rootProject.name = \"Newsumm\"\ninclude ':mobile'\ninclude ':shared'\n" }, { "alpha_fraction": 0.7986111044883728, "alphanum_fraction": 0.7986111044883728, "avg_line_length": 35, "blob_id": "20e7f66f9df4ec48a89205859e39cd6308a4b836", "content_id": "1c7bf6e6c492cff594a5958f8d18efbd3acf6e29", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 144, "license_type": "permissive", "max_line_length": 73, "num_lines": 4, "path": "/README.md", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "# Newsumm\n\nNewsumm is a simple app that summarizes news articles and turns them into\nmini-podcasts using your device's built-in text-to-speech.\n" }, { "alpha_fraction": 0.6584707498550415, "alphanum_fraction": 0.6611694097518921, "avg_line_length": 36.47190856933594, "blob_id": "87e124650eaf931e8a316bd04153fcdbdb7c7277", "content_id": "8b1ac9560dbce19cce266f601449899770e74a14", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 3335, "license_type": "permissive", "max_line_length": 95, "num_lines": 89, "path": "/mobile/src/main/java/me/stanis/newsumm/util/webcontent/WebContentLoader.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.util.webcontent\n\nimport android.content.Context\nimport android.webkit.WebSettings\nimport com.google.mlkit.nl.languageid.LanguageIdentifier\nimport dagger.hilt.android.qualifiers.ActivityContext\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.tasks.await\nimport kotlinx.coroutines.withContext\nimport me.stanis.newsumm.data.Article\nimport org.jsoup.Jsoup\nimport org.jsoup.nodes.Document\nimport java.util.*\nimport javax.inject.Inject\n\nclass WebContentLoader @Inject constructor(\n @ActivityContext context: Context,\n private val sumy: Sumy,\n private val languageIdentifier: LanguageIdentifier\n) {\n companion object {\n private const val SENTENCE_COUNT = 7\n\n private val bannedTags = listOf(\"img\", \"picture\", \"figure\", \"script\", \"style\")\n private val validLanguages = setOf(\"cs\", \"de\", \"en\", \"es\", \"fr\", \"it\", \"pt\")\n }\n\n private val userAgent = WebSettings.getDefaultUserAgent(context)\n\n suspend fun parseURL(url: String, tryAMP: Boolean = true): Article {\n val doc = withContext(Dispatchers.IO) { Jsoup.connect(url).userAgent(userAgent).get() }\n if (tryAMP) {\n val ampURL = getAmpUrl(doc)\n if (ampURL.isNotEmpty()) {\n return parseURL(ampURL, false)\n }\n }\n val title = doc.title()\n val language = detectLanguage(doc)\n doc.select(bannedTags.joinToString(\",\")).remove()\n val sentences = sumy.summarizeHTML(\n doc.html(),\n language.takeIf { validLanguages.contains(it) } ?: \"en\",\n SENTENCE_COUNT)\n return Article(\n url = url,\n title = title,\n language = language,\n sentences = sentences\n )\n }\n\n private suspend fun detectLanguage(doc: Document): String {\n val htmlLang = doc.selectFirst(\"html[lang]\")?.attr(\"lang\")\n if (!htmlLang.isNullOrEmpty()) {\n return htmlLang.replace(Regex(\"-.*\"), \"\").toLowerCase(Locale.ROOT)\n }\n val description = doc.selectFirst(\"meta[name=description]\")?.attr(\"content\")\n ?: return LanguageIdentifier.UNDETERMINED_LANGUAGE_TAG\n return languageIdentifier.identifyLanguage(description).await()\n }\n\n private fun getArticleImage(doc: Document): String {\n val fbImage = doc.selectFirst(\"meta[property=\\\"og:image\\\"]\")?.attr(\"content\")\n ?.takeIf { it.isNotEmpty() }\n val twitterImage = doc.selectFirst(\"meta[property=\\\"twitter:image\\\"]\")?.attr(\"content\")\n ?.takeIf { it.isNotEmpty() }\n return fbImage ?: twitterImage ?: \"\"\n }\n\n private fun getAmpUrl(doc: Document) =\n doc.selectFirst(\"link[rel=amphtml][href]\")?.attr(\"href\") ?: \"\"\n}\n" }, { "alpha_fraction": 0.5633231997489929, "alphanum_fraction": 0.5896656513214111, "avg_line_length": 24.973684310913086, "blob_id": "9d6f55ce6817b4609f020cd93b53407d4ff93127", "content_id": "ad85abd317b62463493ca9eb0126b1e1bc424603", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 987, "license_type": "permissive", "max_line_length": 99, "num_lines": 38, "path": "/build.gradle", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\nbuildscript {\n ext {\n hilt_version = '2.28-alpha'\n kotlin_version = '1.4.31'\n ktlint_version = '0.39.0'\n\n app_id = 'me.stanis.newsumm'\n min_sdk_mobile = 26\n min_sdk_wear = 26\n target_sdk = 30\n version_code = 1\n version_name = '1.0'\n }\n repositories {\n google()\n jcenter()\n maven { url \"https://chaquo.com/maven\" }\n }\n dependencies {\n classpath 'com.android.tools.build:gradle:4.1.3'\n classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n classpath \"com.google.dagger:hilt-android-gradle-plugin:$hilt_version\"\n classpath \"com.chaquo.python:gradle:9.1.0\"\n }\n}\n\nallprojects {\n repositories {\n google()\n jcenter()\n maven { url 'https://jitpack.io' }\n }\n}\n\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}\n" }, { "alpha_fraction": 0.7253825068473816, "alphanum_fraction": 0.7285209894180298, "avg_line_length": 31.679487228393555, "blob_id": "f8ceeaf103d6b1c087eb89d73a705d7dbfd11a6e", "content_id": "4742b05f49034390e9e0d871cb9f8fbce1d465fa", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Kotlin", "length_bytes": 2549, "license_type": "permissive", "max_line_length": 98, "num_lines": 78, "path": "/mobile/src/main/java/me/stanis/newsumm/ui/MainViewModel.kt", "repo_name": "fstanis/Newsumm", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\npackage me.stanis.newsumm.ui\n\nimport android.net.Uri\nimport androidx.hilt.lifecycle.ViewModelInject\nimport androidx.lifecycle.LiveData\nimport androidx.lifecycle.MutableLiveData\nimport androidx.lifecycle.ViewModel\nimport me.stanis.newsumm.data.Article\n\nclass MainViewModel @ViewModelInject constructor() : ViewModel() {\n private val mutableState = MutableLiveData(State())\n val state: LiveData<State> get() = mutableState\n\n fun setArticle(article: Article) {\n mutableState.postValue(state.value!!.copy(articleStatus = ArticleStatus.Ready(article)))\n }\n\n fun clearArticle() {\n mutableState.postValue(State())\n }\n\n fun setArticleLoading() {\n mutableState.postValue(state.value!!.copy(articleStatus = ArticleStatus.Loading))\n }\n\n fun setArticleError(error: String) {\n mutableState.postValue(state.value!!.copy(articleStatus = ArticleStatus.Error(error)))\n }\n\n fun setSpeechLoading() {\n mutableState.postValue(state.value!!.copy(speechStatus = SpeechStatus.Loading))\n }\n\n fun setSpeechUri(uri: Uri) {\n mutableState.postValue(state.value!!.copy(speechStatus = SpeechStatus.Ready(uri)))\n }\n\n fun setSpeechUnavailable() {\n mutableState.postValue(state.value!!.copy(speechStatus = SpeechStatus.Unavailable))\n }\n}\n\ndata class State(\n val speechStatus: SpeechStatus = SpeechStatus.None,\n val articleStatus: ArticleStatus = ArticleStatus.None\n) {\n val isLoading = speechStatus is SpeechStatus.Loading || articleStatus is ArticleStatus.Loading\n}\n\nsealed class SpeechStatus {\n data class Ready(val uri: Uri) : SpeechStatus()\n object Loading : SpeechStatus()\n object None : SpeechStatus()\n object Unavailable : SpeechStatus()\n}\n\nsealed class ArticleStatus {\n data class Ready(val article: Article) : ArticleStatus()\n object Loading : ArticleStatus()\n object None : ArticleStatus()\n data class Error(val error: String) : ArticleStatus()\n}\n" } ]
16
mac1331/TFG
https://github.com/mac1331/TFG
d58b64dbb635fa44412d733eb6236bf788d4354f
7f69e466a8f2fa4c33236fbdfafd08433aec77b1
fcb3965c88e1c64eff9501867684875309ad9e64
refs/heads/master
2022-08-14T07:33:54.009448
2020-05-19T19:51:28
2020-05-19T19:51:28
256,809,305
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.510869562625885, "alphanum_fraction": 0.5579710006713867, "avg_line_length": 26.600000381469727, "blob_id": "857ea49da6cc7be65eff818758686aa4a2ebe933", "content_id": "9822664e72b6a799ef7fb39c49593b91bd248ef1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 276, "license_type": "no_license", "max_line_length": 57, "num_lines": 10, "path": "/Python_codes/serial_test.py", "repo_name": "mac1331/TFG", "src_encoding": "UTF-8", "text": "import serial\nimport time\nif __name__ == '__main__':\n ser = serial.Serial('/dev/ttyACM1', 57600, timeout=1)\n ser.flush()\n while True:\n ser.write(b\"vec,-0,0\\n\")\n line = ser.readline().decode('utf-8').rstrip()\n print(line)\n time.sleep(0.01)\n" }, { "alpha_fraction": 0.7799999713897705, "alphanum_fraction": 0.7799999713897705, "avg_line_length": 24, "blob_id": "aa06dfdfa19d3102e8e673bf8e3ca4df4251e7cb", "content_id": "39e442bfa8cd1ab51e484a51d55e97c30d22ecd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 50, "license_type": "no_license", "max_line_length": 43, "num_lines": 2, "path": "/README.md", "repo_name": "mac1331/TFG", "src_encoding": "UTF-8", "text": "# TFG\nThe code repository of my bachellor thesis.\n" }, { "alpha_fraction": 0.47138965129852295, "alphanum_fraction": 0.48365122079849243, "avg_line_length": 25.214284896850586, "blob_id": "1af5e5b9448b9ab8ca0e9bc20d36d93d29ad47ba", "content_id": "77567e24f64ea79006f682cfb4b908ff2ed87fd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 734, "license_type": "no_license", "max_line_length": 60, "num_lines": 28, "path": "/Arduino/serial-Ard-RPI_test/serial-Ard-RPI_test.ino", "repo_name": "mac1331/TFG", "src_encoding": "UTF-8", "text": "void setup() {\n Serial.begin(9600);\n}\nvoid loop() {\n if (Serial.available() > 0) {\n String inSer = Serial.readStringUntil('\\n');\n if (inSer.startsWith(\"vec,\")) {\n String input = inSer;\n inSer = \"\";\n int auxX, auxY, auxi, firstVal, secondVal;\n bool nf = false;\n for (int i = 0; i < input.length(); i++) {\n if (input.substring(i, i + 1) == \",\") {\n if (nf == true) {\n firstVal = input.substring(auxi + 1, i).toInt();\n secondVal = input.substring(i + 1).toInt();\n break;\n }\n auxi = i;\n nf = true;\n }\n }\n Serial.print(firstVal+secondVal);\n Serial.print(\" \");\n Serial.println(secondVal);\n }\n }\n}\n" }, { "alpha_fraction": 0.5408039093017578, "alphanum_fraction": 0.5931790471076965, "avg_line_length": 18.547618865966797, "blob_id": "f93f0761b9135e950206f4e36a7d3ac84fedc9b7", "content_id": "8eb62a743a8f1fcc2be738f768f3c06efd01f261", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3284, "license_type": "no_license", "max_line_length": 75, "num_lines": 168, "path": "/Arduino/Robot3r_V2/Robot3r_V2.ino", "repo_name": "mac1331/TFG", "src_encoding": "UTF-8", "text": "//RPI first test conection test\n\n\n//Motors conections declaration\nint motor1A = 4; //speed\nint motor1B = 22; //dir\nint motor1C = 24;\nint motor1I = 2; //encoder input\nvolatile int motor1Count = 0;\nvolatile int dir1 = 0;\nint flag1 = 0;\n\nint motor2A = 5; //speed\nint motor2B = 26; //dir\nint motor2C = 28;\nint motor2I = 3; //encoder input\nvolatile int motor2Count = 0;\nvolatile int dir2 = 0;\nint flag2 = 0;\n\nint motor3A = 6; //speed\nint motor3B = 30; //dir\nint motor3C = 32;\nint motor3I = 18; //encoder input\nvolatile int motor3Count = 0;\nvolatile int dir3 = 0;\nint flag3 = 0;\n\n\nint currentPwm1;\nint currentPwm2;\nint currentPwm3;\n\n\n\nint val = 0;\nint finishedX = 1;\nint finishedY = 1;\nint vectorX = 1;\nint vectorY = 1;\nint negX = 0;\nint negY = 0;\nfloat rad120 = 2 * 3.1415 / 3;\n\n\nvoid setup() {\n Serial.begin(57600); // Start serial communication at 9600 bps\n // Serial.setTimeout(20);\n pinMode(motor1I, INPUT);\n pinMode(motor2I, INPUT);\n pinMode(motor3I, INPUT);\n\n pinMode(motor1A, OUTPUT);\n pinMode(motor1B, OUTPUT);\n pinMode(motor1C, OUTPUT);\n pinMode(motor2A, OUTPUT);\n pinMode(motor2B, OUTPUT);\n pinMode(motor2C, OUTPUT);\n pinMode(motor3A, OUTPUT);\n pinMode(motor3B, OUTPUT);\n pinMode(motor3C, OUTPUT);\n\n cw1();\n cw2();\n cw3();\n}\n\nvoid loop() {\n if (Serial.available() > 0) {\n String inSer = Serial.readStringUntil('\\n');\n if (inSer.startsWith(\"vec,\")) {\n String input = inSer;\n inSer = \"\";\n int auxX, auxY, auxi, firstVal, secondVal;\n bool nf = false;\n for (int i = 0; i < input.length(); i++) {\n if (input.substring(i, i + 1) == \",\") {\n if (nf == true) {\n firstVal = input.substring(auxi + 1, i).toInt();\n secondVal = input.substring(i + 1).toInt();\n break;\n }\n auxi = i;\n nf = true;\n }\n }\n Serial.print(firstVal);\n Serial.print(\" \");\n Serial.println(secondVal);\n vectorX = firstVal;\n vectorY = secondVal;\n }\n\n }\n //val = 100;\n\n currentPwm1 = vectorX;\n currentPwm2 = vectorX * cos(rad120) - vectorY * sin(rad120);\n currentPwm3 = vectorX * cos(-rad120) - vectorY * sin(-rad120);\n //Serial.println(val);\n if (currentPwm1 < 0) {\n ccw1();\n analogWrite(motor1A, -currentPwm1 );\n }\n else {\n cw1();\n analogWrite(motor1A, currentPwm1 );\n }\n if (currentPwm2 < 0) {\n ccw2();\n analogWrite(motor2A, -currentPwm2 );\n }\n else {\n cw2();\n analogWrite(motor2A, currentPwm2 );\n }\n if (currentPwm3 < 0) {\n ccw3();\n analogWrite(motor3A, -currentPwm3 );\n }\n else {\n cw3();\n analogWrite(motor3A, currentPwm3 );\n }\n\n}\n\n\n\n\n\n\n\n\n\n//direction controller function\nvoid ccw1() {\n digitalWrite(motor1B, LOW);\n digitalWrite(motor1C, HIGH);\n dir1 = 0;\n}\nvoid cw1() {\n digitalWrite(motor1B, HIGH);\n digitalWrite(motor1C, LOW);\n dir1 = 1;\n}\n\nvoid ccw2() {\n digitalWrite(motor2B, LOW);\n digitalWrite(motor2C, HIGH);\n dir2 = 0;\n}\nvoid cw2() {\n digitalWrite(motor2B, HIGH);\n digitalWrite(motor2C, LOW);\n dir2 = 1;\n}\n\nvoid ccw3() {\n digitalWrite(motor3B, LOW);\n digitalWrite(motor3C, HIGH);\n dir3 = 0;\n}\nvoid cw3() {\n digitalWrite(motor3B, HIGH);\n digitalWrite(motor3C, LOW);\n dir3 = 1;\n}\n" } ]
4
EmanuelAlogna/IAML-Ass03
https://github.com/EmanuelAlogna/IAML-Ass03
c64703e5adb0af7f617072b3611380eb49e2e726
2a310254e0fe16a72fcde8a6384d69990876aaca
05635d2b257afe73c9e4c146087af0b164007c61
refs/heads/master
2022-12-26T06:14:42.021603
2018-09-12T18:36:07
2018-09-12T18:36:07
303,229,931
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5311399102210999, "alphanum_fraction": 0.5521133542060852, "avg_line_length": 31.957782745361328, "blob_id": "c9a2db751147deca144a7b9a3b3df372e6a74793", "content_id": "d3707992912a4c1a95e45e5741b7d71c0fde6aef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12492, "license_type": "no_license", "max_line_length": 108, "num_lines": 379, "path": "/As301_cnn.py", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "#<!--------------------------------------------------------------------------->\n#<!-- ITU - IT University of Copenhage -->\n#<!-- Computer Science Department -->\n#<!-- Eye Information Research Group -->\n#<!-- Introduction to Image Analysis and Machine Learning Course -->\n#<!-- File : As301_classifier.py -->\n#<!-- Description: Script to train a car detector based on binary classifier-->\n#<!-- Author : Fabricio Batista Narcizo -->\n#<!-- : Rued Langgaards Vej 7 - 4D25 - DK-2300 - Kobenhavn S. -->\n#<!-- : narcizo[at]itu[dot]dk -->\n#<!-- Responsable: Dan Witzner Hansen (witzner[at]itu[dot]dk) -->\n#<!-- Fabricio Batista Narcizo (fabn[at]itu[dot]dk) -->\n#<!-- Information: No additional information -->\n#<!-- Date : 24/04/2018 -->\n#<!-- Change : 24/04/2018 - Creation of this script -->\n#<!-- Review : 24/04/2018 - Finalized -->\n#<!--------------------------------------------------------------------------->\n\n__version__ = \"$Revision: 2018042401 $\"\n\n########################################################################\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport random\nimport sklearn\nfrom sklearn import svm\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport sys\n\nimport imutils\nimport matplotlib.pyplot as plt\n\nfrom glob import glob\nfrom random import shuffle\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.layers import Convolution2D, MaxPooling2D\nfrom keras.utils import np_utils\nfrom keras.datasets import mnist\nfrom keras.models import load_model\n\nfrom skimage import transform as tf\nfrom keras.utils import plot_model\n\n########################################################################\n\ndef loadDataset(dataset):\n \"\"\"\n This function load all images from a dataset and return a list of Numpy images.\n \"\"\"\n # List of images.\n images = []\n\n\n\n # Read all filenames from the dataset.\n for filename in dataset:\n # Read the input image.\n image = cv2.imread(filename)\n\n # Add the current image on the list.\n if image is not None: \n images.append(image)\n else:\n print(\"Could not read file: {}\".format(filename))\n sys.exit()\n\n # Return the images list.\n return images\n\ndef sampleNegativeImages(images, negativeSample, size=(64, 64), N=200):\n \"\"\"\n The dataset has several images of high resolution without cars,\n i.e. called here as negative images. This function select \"N\" 64x64 negative\n sub-images randomly from each original negative image.\n \"\"\"\n # Initialize internal state of the random number generator.\n random.seed(1)\n\n # Final image resolution.\n w, h = size[0], size[1]\n\n resizedImages = []\n \n for image in images:\n res = cv2.resize(image, dsize=(1728, 1152), interpolation=cv2.INTER_CUBIC)\n resizedImages.append(res)\n\n for image in resizedImages:\n images.append(image)\n\n # Read all images from the negative list.\n\n i=0\n for image in images:\n\n if i > 4:\n N = 100\n for j in range(N):\n # random.random produced random number in [0,1) range\n y = int(random.random() * (len(image) - h))\n x = int(random.random() * (len(image[0]) - w))\n sample = image[y:y + h, x:x + w].copy()\n negativeSample.append(sample)\n\n # Create Afine transform\n afine_tf = tf.AffineTransform(shear = random.uniform(-0.2,0.2))\n # Apply transform to image data\n shearedImage = tf.warp(sample, inverse_map=afine_tf)\n negativeSample.append(shearedImage)\n i = i + 1\n\n print(\"Non-car dataset:\")\n print(len(negativeSample))\n \n return\n\n\ndef samplePositiveImages(images, positiveSample, size=(64, 64), N=200):\n \"\"\"\n The dataset has not enough positive images, so we'll increase it by generating new positive\n images by, first, using linear transormation (rotation and reflection) on the\n available positive subset\n \"\"\"\n\n for image in images:\n \n rotated = imutils.rotate_bound(image, random.randint(-15,15))\n \n h, w, channels = rotated.shape\n cropped_img = rotated[w//2 - 64//2:w//2 + 64//2, h//2 - 64//2:h//2 + 64//2]\n\n positiveSample.append(image);\n positiveSample.append(cropped_img)\n positiveSample.append(np.fliplr(image))\n positiveSample.append(np.fliplr(cropped_img))\n \n supportList = []\n for img in positiveSample:\n supportList.append(img)\n\n for img in supportList:\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #convert it to hsv\n hsv = hsv + 10\n img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n positiveSample.append(img)\n \n hsv = hsv - 20\n img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n positiveSample.append(img)\n\n print(\"Car dataset:\")\n print(len(positiveSample))\n\n return\n\ndef getY(positiveImages, negativeImages):\n \n sizePositive = len(positiveImages)\n sizeNegative = len(negativeImages)\n\n labels = []\n \n for x in range (0, sizePositive):\n labels.append(1)\n\n for x in range (0, sizeNegative):\n labels.append(-1)\n\n return labels;\n\n#<!--------------------------------------------------------------------------->\n#<!--------------------------------------------------------------------------->\n#<!--------------------------------------------------------------------------->\n#<!--------------------------------------------------------------------------->\n\n\n\ndef main():\n\n # Folder where the dataset images are saved.\n folder = \"./inputs\"\n\n # Dataset filenames.\n positiveFile = glob(\"%s/cars/*.png\" % folder)\n negativeFile = glob(\"%s/non-cars/*.png\" % folder)\n\n # Vectors used to train the dataset.\n positiveList = []\n negativeList = []\n negativeSample = []\n positiveSample = []\n labels = []\n X = []\n\n # As 3.02. (a) : Load our car images dataset.\n positiveList = loadDataset(positiveFile)\n negativeList = loadDataset(negativeFile)\n\n\n # As 3.02. (b) : Get a sample of negative images. (returns list in negativeSample)\n sampleNegativeImages(negativeList, negativeSample, size=(64,64), N=200)\n \n samplePositiveImages(positiveList, positiveSample, size=(64,64), N=200)\n\n\n #-----------------------------------------------------------#\n # #\n # Classification Model using Convolutionary neural network #\n # #\n #-----------------------------------------------------------#\n \n y = getY(positiveSample, negativeSample)\n\n for image in positiveSample:\n X.append(image)\n\n for image in negativeSample:\n X.append(image)\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.85, random_state=1, shuffle=True)\n\n X_train = np.array(X_train)\n y_train = np.array(y_train)\n X_test = np.array(X_test)\n y_test = np.array(y_test)\n\n print (X_train.shape)\n\n print(\"Count of non-car/car in training data\")\n print(y_train.shape[0])\n print(\"Count of non-car/car in test data\")\n print(y_test.shape[0])\n\n # the final preprocessing step for the input data is to convert our data\n # type to float 32 and normalize our data values to the range[0, 1]\n X_train = X_train.astype('float32')\n X_test = X_test.astype('float32')\n X_train /= 255\n X_test /= 255\n\n\n y_trainBeforeProcessing = y_train\n y_testBeforeProcessing = y_test\n\n print(\"Before Categorization\")\n print(y_train[np.where(y_train == -1.0)].shape)\n print(y_train[np.where(y_train == 1.0)].shape)\n \n print(y_train[:5])\n # preprocessing class labels for Keras\n y_train_1hot = []\n for y in y_train:\n if y == -1:\n y_train_1hot.append([1,0])\n elif y == 1:\n y_train_1hot.append([0,1])\n\n y_test_1hot = []\n for y in y_test:\n if y == -1:\n y_test_1hot.append([1,0])\n elif y == 1:\n y_test_1hot.append([0,1])\n\n y_train = np.array(y_train_1hot)\n y_test = np.array(y_test_1hot)\n\n #print(\"After Categorization\")\n #print(sum([row[0] for row in y_train]))\n #print(sum([row[1] for row in y_train]))\n # sys.exit()\n \"\"\"\n model = Sequential()\n\n # 32 corresponds to the number of convolution filters to use\n # 3 corresponds to the numbers of rows in each convolution kernel\n # 3 corresponds to the number of columns in each convolution kernel\n model.add(Convolution2D(32, (3, 3), activation='relu', input_shape=(64,64,3)))\n\n model.add(Convolution2D(32, (3, 3), activation='relu'))\n model.add(Dropout(0.25)) # this layer is important because it prevents overfitting\n model.add(MaxPooling2D(pool_size=(2,2)))\n model.add(Dropout(0.25)) # this layer is important because it prevents overfitting\n model.add(Flatten())\n model.add(Dense(128, activation='relu'))\n model.add(Dropout(0.5))\n model.add(Dense(2, activation='sigmoid')) #output layer with size of 2 (2 classes)\n\n # compile model\n model.compile(loss='binary_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n # fit model on training data\n history = model.fit(X_train, y_train, validation_split=0.1765,\n batch_size=32, nb_epoch=5, verbose=1)\n\n # evaluate model on the train data\n print(\"Train Model Eval: {}\".format(model.evaluate(X_train, y_train, verbose=1)))\n\n # evaluate model on test data\n print(\"Test Model Eval: {}\".format(model.evaluate(X_test, y_test, verbose=1)))\n \n model.save('./outputs/datamodel5epochsNewDataset.h5')\n \"\"\"\n model = load_model('./outputs/datamodel5epochsNewDataset.h5')\n\n print(model.summary())\n \n y_test_pred = model.predict(X_test)\n\n y_test_pred_format = []\n for row in y_test_pred:\n if row[0] > row[1]:\n y_test_pred_format.append(-1)\n else:\n y_test_pred_format.append(1)\n \n y_train_pred = model.predict(X_train)\n\n y_train_pred_format = []\n for row in y_train_pred:\n if row[0] > row[1]:\n y_train_pred_format.append(-1)\n else:\n y_train_pred_format.append(1)\n\n print(\"Confusion on the test set.\")\n print(\"1st Col/Row: Non-Cars | 2nd Col/Row: Cars\")\n cm_test = confusion_matrix(y_testBeforeProcessing, y_test_pred_format)\n print(cm_test)\n\n print(\"Confusion on the training set.\")\n print(\"1st Col/Row: Non-Cars | 2nd Col/Row: Cars\")\n cm_train = confusion_matrix(y_trainBeforeProcessing, y_train_pred_format)\n print(cm_train)\n\n accuracyTest = sklearn.metrics.accuracy_score(y_testBeforeProcessing, y_test_pred_format)\n print(\"Accuracy on the test set: {}\".format(accuracyTest))\n\n accuracyTrain = sklearn.metrics.accuracy_score(y_trainBeforeProcessing, y_train_pred_format)\n print(\"Accuracy on the training set: {}\".format(accuracyTrain))\n\n\n \"\"\"\n # list all data in history\n print(history.history.keys())\n # summarize history for accuracy\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('Model accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.ylim((0,1))\n plt.show()\n # summarize history for loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('Model loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train', 'Test'], loc='upper left')\n plt.show()\n \"\"\"\n\n#<!--------------------------------------------------------------------------->\n#<!-- -->\n#<!--------------------------------------------------------------------------->\n\n# put executing code in main, so that the defined functions\n# can be imported in a separate script without executing\n# the code\nif __name__ == \"__main__\":\n main()\n\n" }, { "alpha_fraction": 0.5434389114379883, "alphanum_fraction": 0.5886877775192261, "avg_line_length": 33.77952575683594, "blob_id": "60edf28e5624d38cfabffa34f0b1c37d809fcf72", "content_id": "c474e26be4e93b2a9cac7036b64465ff95d24ee2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4420, "license_type": "no_license", "max_line_length": 113, "num_lines": 127, "path": "/As301_pca_visualization.py", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "#<!--------------------------------------------------------------------------->\n#<!-- File : As301_pca_visualization -->\n#<!--------------------------------------------------------------------------->\n\n__version__ = \"$Revision: 2018042401 $\"\n\n########################################################################\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom sklearn.decomposition import PCA\nimport sys\n\nimport As301_classifier\n\n########################################################################\n\ndataset = np.load(\"./outputs/dataset.npy\")\ndf = pd.read_csv(\"./outputs/hog_dataset.csv\", index_col=0)\nindices = df.index.values\nfeatures = dataset[:,:-1]\nlabels = dataset[:,-1]\n\n########################################################################\n\n# We are going to apply PCA to reduce the dimensions of our HOG feature\n# to see if there is a obvious separation between the two classes \n# car and non-car\n\n########################################################################\npca = PCA(n_components=2)\n\nfig_imgs = plt.figure(\"PCA Analysis\", figsize=(12,4))\n\ncolors = ['navy', 'darkorange']\nlw = 2\n\npositive_set = np.array([row for row in dataset if (row[-1] == 1 )])\npos_size = positive_set.shape[0]\nnegative_set = np.array([row for row in dataset if (row[-1] == -1) ])\nneg_size = negative_set.shape[0]\n\nfeatures_pca = pca.fit(np.vstack((positive_set,negative_set))).transform(np.vstack((positive_set,negative_set))) \nprint(features_pca.shape)\nprint(labels.shape)\ndata_pca = np.vstack((features_pca.T, indices, labels)).T\nprint(data_pca[:5])\n\n# Percentage of variance explained for each components\nprint('explained variance ratio (first two components): {0}'\n .format(str(pca.explained_variance_ratio_)))\nvar_expl_1st, var_expl_2nd = pca.explained_variance_ratio_\n\nsub = fig_imgs.add_subplot(1,3,1)\n\nplt.scatter(features_pca[:pos_size,0], features_pca[:pos_size,1], \n color=colors[0], alpha=.8, lw=lw, label='car')\nplt.scatter(features_pca[pos_size:,0], features_pca[pos_size:,1], \n color=colors[1], alpha=.8, lw=lw, label='non-car')\nplt.legend(loc='best', shadow=False, scatterpoints=1)\nplt.title('PCA of Car/Non-Car dataset')\n\n# 1st principal component explains 26% of the total variance\nplt.xlabel('1st principal component')\nplt.xlim((-4,4))\n\n# 2nd principal component explains 8% of the total variance\nplt.ylabel('2nd principal component')\nplt.ylim((-4,4))\n\nplt.plot()\n\n\n# Analyze the corner cases ('non-car' label but value of 1st component less than 0.5)\nspecial_cases = np.array([row for row in data_pca if (row[-1] == -1 and row[0] < 0.5)])\nimg2_neg_set = np.array([row for row in data_pca if (row[-1] == -1 and row[0] >= 0.5)])\nimg2_pos_set = np.array([row for row in data_pca if (row[-1] == 1)])\n\nsub = fig_imgs.add_subplot(1,3,2)\n\nplt.scatter(img2_pos_set[:,0], img2_pos_set[:,1], \n color=colors[0], alpha=.8, lw=lw, label='car')\nplt.scatter(img2_neg_set[:,0], img2_neg_set[:,1], \n color=colors[1], alpha=.8, lw=lw, label='non-car')\nplt.scatter(special_cases[:,0], special_cases[:,1], \n color=\"red\", alpha=.8, lw=lw, label='special cases of non-car')\nplt.legend(loc='best', shadow=False, scatterpoints=1)\nplt.title('Highlighting instances of Non-Cars\\nthat are very similar to Cars', fontsize=8)\nplt.xlabel(r\"$1^{st}$ principal component\")\nplt.xlim((-4,4))\nplt.ylabel(r\"$2^{nd}$ principal component\")\nplt.ylim((-4,4))\n\nplt.plot()\n\n# analyze the special non-car indices \nspecial_indices = special_cases[:,-2].astype(np.int)\nspecial_filenames = df.iloc[list(special_indices)][\"files\"].values\n\nres = cv2.imread(special_filenames[0])\n\nfor fname in list(special_filenames)[1:]:\n img = cv2.imread(fname)\n res = np.hstack((res,img))\n\n# create a 5x5 collage\ncollage = np.zeros((5*64,5*64,3), dtype=int)\ncollage[0:64,0:5*64,:] = res[:,0:5*64,:].copy()\ncollage[64:128,0:5*64,:] = res[:,5*64:10*64,:].copy()\ncollage[128:192,0:5*64,:] = res[:,10*64:15*64,:].copy()\ncollage[192:256,0:5*64,:] = res[:,15*64:20*64,:].copy()\ncollage[256:320,0:5*64,:] = res[:,20*64:25*64,:].copy()\ncollage = collage.astype(np.uint8)\n\nsub = fig_imgs.add_subplot(1,3,3)\nsub.set_title(\"Special Case Images\")\nsub.imshow(collage)\nsub.axis(\"off\")\n\nplt.plot()\n\n\nplt.show()\n\n########################################################################\n\n\n\n" }, { "alpha_fraction": 0.5599443912506104, "alphanum_fraction": 0.5858136415481567, "avg_line_length": 31.360361099243164, "blob_id": "1ab4c62aa420ba7ce00a2619b1336d0f3009667b", "content_id": "bed32f218fbdabc716ae5c58b13f602f3c3edcdb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3595, "license_type": "no_license", "max_line_length": 79, "num_lines": 111, "path": "/As301_pca_viz_compare.py", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "#<!--------------------------------------------------------------------------->\n#<!-- File : As301_pca_viz_compare -->\n#<!--------------------------------------------------------------------------->\n\n__version__ = \"$Revision: 2018042401 $\"\n\n########################################################################\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\nimport sys\n\nimport As301_classifier\n\n########################################################################\n\ndataset = np.load(\"./outputs/dataset.npy\")\ndf = pd.read_csv(\"./outputs/hog_dataset.csv\", index_col=0)\nindices = df.index.values\nfeatures = dataset[:,:-1]\nlabels = dataset[:,-1]\n\npositive_set = np.array([row for row in dataset if (row[-1] == 1 )])\npos_size = positive_set.shape[0]\nnegative_set = np.array([row for row in dataset if (row[-1] == -1) ])\nneg_size = negative_set.shape[0]\n\n########################################################################\n\n# Compare 2D PCA of the HOG features and the PCA applied on the \n# raw image data (grayscale).\n\n########################################################################\npca = PCA(n_components=2)\n\nfig_imgs = plt.figure(\"PCA HOG Comparison\", figsize=(12,4))\n\ncolors = ['navy', 'darkorange']\nlw = 2\n\nsub = fig_imgs.add_subplot(1,2,1)\n\nimg_data = []\n\nfor fpath in list(df[\"files\"]):\n img = cv2.imread(fpath)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img_data.append(gray.flatten())\n\nimg_data = np.array(img_data)\n\n\nscaler = StandardScaler()\nimg_data = scaler.fit_transform(img_data)\n\nimg_pca = pca.fit(img_data).transform(img_data)\nprint('explained variance ratio (first two components): {0}'\n .format(str(pca.explained_variance_ratio_)))\n\nplt.scatter(img_pca[:pos_size,0], img_pca[:pos_size,1], \n color=colors[0], alpha=.8, lw=lw, label='car')\nplt.scatter(img_pca[pos_size:,0], img_pca[pos_size:,1], \n color=colors[1], alpha=.8, lw=lw, label='non-car')\nplt.legend(loc='best', shadow=False, scatterpoints=1)\nplt.title('PCA of Car/Non-Car dataset (raw image data)')\n\n# 1st principal component explains 40% of the total variance\nplt.xlabel('1st principal component')\nplt.xlim((-140,170))\n\n# 2nd principal component explains 10% of the total variance\nplt.ylabel('2nd principal component')\nplt.ylim((-65,65))\n\nplt.plot()\n\nfull_set = np.vstack((positive_set,negative_set))\nfeatures_pca = pca.fit(full_set).transform(full_set) \ndata_pca = np.vstack((features_pca.T, indices, labels)).T\n\n# Percentage of variance explained for each components\nprint('explained variance ratio (first two components): {0}'\n .format(str(pca.explained_variance_ratio_)))\nvar_expl_1st, var_expl_2nd = pca.explained_variance_ratio_\n\nsub = fig_imgs.add_subplot(1,2,2)\n\nplt.scatter(features_pca[:pos_size,0], features_pca[:pos_size,1], \n color=colors[0], alpha=.8, lw=lw, label='car')\nplt.scatter(features_pca[pos_size:,0], features_pca[pos_size:,1], \n color=colors[1], alpha=.8, lw=lw, label='non-car')\nplt.legend(loc='best', shadow=False, scatterpoints=1)\nplt.title('PCA of Car/Non-Car dataset (HOG)')\n\n# 1st principal component explains 26% of the total variance\nplt.xlabel('1st principal component')\nplt.xlim((-4,4))\n\n# 2nd principal component explains 8% of the total variance\nplt.ylabel('2nd principal component')\nplt.ylim((-4,4))\n\nplt.plot()\n\nplt.show()\n\n########################################################################\n\n\n\n" }, { "alpha_fraction": 0.5296592116355896, "alphanum_fraction": 0.5522928237915039, "avg_line_length": 35.56615447998047, "blob_id": "7d39a94729b51642be901ce741a7cb28dff80101", "content_id": "fc45f305deccfe22719f92a2ff5c3280fd38eda2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11885, "license_type": "no_license", "max_line_length": 157, "num_lines": 325, "path": "/As301_classifier.py", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "#<!--------------------------------------------------------------------------->\n#<!-- ITU - IT University of Copenhage -->\n#<!-- Computer Science Department -->\n#<!-- Eye Information Research Group -->\n#<!-- Introduction to Image Analysis and Machine Learning Course -->\n#<!-- File : As301_classifier.py -->\n#<!-- Description: Script to train a car detector based on binary classifier-->\n#<!-- Author : Fabricio Batista Narcizo -->\n#<!-- : Rued Langgaards Vej 7 - 4D25 - DK-2300 - Kobenhavn S. -->\n#<!-- : narcizo[at]itu[dot]dk -->\n#<!-- Responsable: Dan Witzner Hansen (witzner[at]itu[dot]dk) -->\n#<!-- Fabricio Batista Narcizo (fabn[at]itu[dot]dk) -->\n#<!-- Information: No additional information -->\n#<!-- Date : 24/04/2018 -->\n#<!-- Change : 24/04/2018 - Creation of this script -->\n#<!-- Review : 24/04/2018 - Finalized -->\n#<!--------------------------------------------------------------------------->\n\n__version__ = \"$Revision: 2018042401 $\"\n\n########################################################################\nimport cv2\nimport numpy as np\nimport os\nimport pandas as pd\nimport random\nimport sklearn\nfrom sklearn import svm\nfrom sklearn.externals import joblib\nfrom sklearn.model_selection import train_test_split\nimport sys\n\nimport imutils\n\nfrom glob import glob\n\n########################################################################\n\ndef loadDataset(dataset):\n \"\"\"\n This function load all images from a dataset and return a list of Numpy images.\n \"\"\"\n # List of images.\n images = []\n\n\n\n # Read all filenames from the dataset.\n for filename in dataset:\n # Read the input image.\n image = cv2.imread(filename)\n\n # Add the current image on the list.\n if image is not None: \n images.append(image)\n else:\n print(\"Could not read file: {}\".format(filename))\n sys.exit()\n\n # Return the images list.\n return images\n\ndef sampleNegativeImages(images, negativeSample, size=(64, 64), N=200):\n \"\"\"\n The dataset has several images of high resolution without cars,\n i.e. called here as negative images. This function select \"N\" 64x64 negative\n sub-images randomly from each original negative image.\n \"\"\"\n # Initialize internal state of the random number generator.\n random.seed(1)\n\n # Final image resolution.\n w, h = size[0], size[1]\n\n resizedImages = []\n \n for image in images:\n res = cv2.resize(image, dsize=(1728, 1152), interpolation=cv2.INTER_CUBIC)\n resizedImages.append(res)\n\n for image in resizedImages:\n images.append(image)\n\n # Read all images from the negative list.\n\n i = 0\n for image in images:\n\n if i > 4:\n N = 100\n for j in range(N):\n # random.random produced random number in [0,1) range\n y = int(random.random() * (len(image) - h))\n x = int(random.random() * (len(image[0]) - w))\n sample = image[y:y + h, x:x + w].copy()\n negativeSample.append(sample)\n\n # Create Afine transform\n afine_tf = tf.AffineTransform(shear = random.uniform(-0.2,0.2))\n # Apply transform to image data\n shearedImage = tf.warp(sample, inverse_map=afine_tf)\n negativeSample.append(shearedImage)\n i = i + 1\n\n return\n\n\ndef samplePositiveImages(images, positiveSample, size=(64, 64), N=200):\n \"\"\"\n The dataset has not enough positive images, so we'll increase it by generating new positive\n images by, first, using linear transormation (rotation and reflection) on the\n available positive subset\n \"\"\"\n\n for image in images:\n \n rotated = imutils.rotate_bound(image, random.randint(-15,15))\n \n h, w, channels = rotated.shape\n cropped_img = rotated[w//2 - 64//2:w//2 + 64//2, h//2 - 64//2:h//2 + 64//2]\n\n positiveSample.append(image);\n positiveSample.append(cropped_img)\n positiveSample.append(np.fliplr(image))\n positiveSample.append(np.fliplr(cropped_img))\n \n supportList = []\n for img in positiveSample:\n supportList.append(img)\n\n for img in supportList:\n hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #convert it to hsv\n hsv = hsv + 10\n img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n positiveSample.append(img)\n \n hsv = hsv - 20\n img = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)\n positiveSample.append(img)\n\n return\n\n\ndef showImages(images):\n \"\"\"\n Helper function to view images generated in the script without having to store\n them on the disk. Use 'a' and 'd' key to go to the next image.\n \"\"\"\n idx = 0\n\n while True:\n\n cv2.imshow(\"Image\", images[idx])\n\n if cv2.waitKey(15) & 0xFF == ord(\"d\"):\n if idx+1 >= len(images):\n print(\"This is the last image in the set.\")\n else:\n idx += 1\n print(\"Viewing image no. {0} / {1}\".format(idx+1, len(images)))\n\n if cv2.waitKey(15) & 0xFF == ord(\"a\"):\n if idx-1 < 0:\n print(\"This is the first image in the set.\")\n else:\n idx -= 1\n print(\"Viewing image no. {0} / {1}\".format(idx+1, len(images)))\n\n if cv2.waitKey(15) & 0xFF == ord(\"q\"):\n break\n\ndef computeHOG(images, hogList, size=(64, 64)):\n \"\"\"\n This function computes the Histogram of Oriented Gradients (HOG) of each\n image from the dataset.\n [Code from Exercise 10 solution. Could be used for a SVM with HOG Features]\n \"\"\"\n # Creates a HOG descriptor with custom parameters\n # (only changed the window size from the default settings to function\n # correctly for our 64x64 input images)\n # see (https://stackoverflow.com/questions/28390614/opencv-hogdescripter-python?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa)\n hog = cv2.HOGDescriptor(\"./inputs/hog.xml\")\n \n # Read all images from the image list.\n for image in images:\n \n # Image resolution\n h, w = image.shape[:2]\n\n # Calculate HOG\n if w >= size[0] and h >= size[1]:\n\n # Region of Interest\n y = (h - size[1]) // 2\n x = (w - size[0]) // 2\n roi = image[y:y + size[1], x:x + size[0]].copy()\n\n # Compute HOG\n grayscale = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)\n hogList.append(hog.compute(grayscale))\n\n return \n\ndef main():\n\n # Folder where the dataset images are saved.\n folder = \"./inputs\"\n\n # Dataset filenames.\n positiveFile = glob(\"%s/cars/*.png\" % folder)\n negativeFile = glob(\"%s/non-cars/*.png\" % folder)\n\n # Vectors used to train the dataset.\n positiveList = []\n negativeList = []\n negativeSample = []\n positiveSample = []\n labels = []\n\n # As 3.02. (a) : Load our car images dataset.\n positiveList = loadDataset(positiveFile)\n negativeList = loadDataset(negativeFile)\n\n\n print(\"Initial size of car set: {0} \\t\\t (dim: {1})\".format(len(positiveList), positiveList[0].shape))\n print(\"Initial size of non-car set: {0} \\t\\t (dim: {1})\".format(len(negativeList), negativeList[0].shape))\n\n\n # As 3.02. (b) : Get a sample of negative images. (returns list in negativeSample)\n sampleNegativeImages(negativeList, negativeSample, size=(64,64), N=200)\n \n # As 3.02. (c) : [EXTRA] increase the car dataset by generating new positive images\n samplePositiveImages(positiveList, positiveSample, size=(64,64), N=200)\n \n\n print(\"Size of non-car sample set: {0} \\t (dim: {1})\".format(len(negativeSample), negativeSample[0].shape))\n print(\"Size of car sample set: {0} \\t\\t (dim: {1})\".format(len(positiveSample), positiveSample[0].shape))\n\n #--------------------------------------------------#\n # #\n # Classification Model using SVM with HOG Features #\n # #\n #--------------------------------------------------#\n\n # Computing the HOG features for each image\n hogList = []\n computeHOG(positiveSample, hogList, size=(64,64))\n computeHOG(negativeSample, hogList, size=(64,64))\n hogList = [vec.flatten() for vec in hogList]\n\n print(\"Vector Length of one HOG: {}\".format(len(hogList[0])))\n\n # create the labels (1: car, -1: non-car)\n [labels.append(+1) for _ in range(len(positiveSample))]\n [labels.append(-1) for _ in range(len(negativeSample))]\n\n # Split into a train/test/validation set (70/15/15)\n np_labels = np.array(labels).reshape(len(labels),1)\n np_hogs = np.array(hogList)\n dataset = np.hstack((np_hogs,np_labels))\n \n np.save('./outputs/dataset.npy', dataset)\n\n # store the 2500 images in a separate output folder\n if not os.path.isdir(\"./outputs/extra_images/\"):\n os.makedirs(\"./outputs/extra_images/\")\n\n file_names = []\n idx = 0\n for image in (positiveSample + negativeSample):\n fname = \"./outputs/extra_images/Cars_\" + str(idx) + \"_Extra.png\"\n cv2.imwrite(fname, image)\n file_names.append(fname) \n idx += 1\n print(\"Done storing the \" + str(len(positiveSample+negativeSample)) + \" images.\")\n\n # also store as CSV \n df = pd.DataFrame(data={\n 'files' : file_names,\n 'HOG' : [row for row in dataset[:,:-1]], \n 'label' : dataset[:,-1]})\n df.to_csv(\"./outputs/hog_dataset.csv\")\n\n X_train, X_test, y_train, y_test = train_test_split(dataset[:,:-1], dataset[:,-1], test_size=0.15, random_state=1)\n X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.1765, random_state=1)\n\n print(\"sizes of train/validation/test sets: {0}/{1}/{2}\".format(X_train.shape[0],X_val.shape[0],X_test.shape[0]))\n\n kernel = \"rbf\" # \"linear\"\n\n svc = svm.SVC(kernel=kernel, probability=True, class_weight='balanced')\n svc.fit(X_train,y_train)\n \n # store prediction results on the validation set\n train_pred = svc.predict(X_train)\n val_pred = svc.predict(X_val)\n test_pred = svc.predict(X_test)\n\n train_acc = sklearn.metrics.accuracy_score(y_train,train_pred)\n val_acc = sklearn.metrics.accuracy_score(y_val, val_pred)\n test_acc = sklearn.metrics.accuracy_score(y_test, test_pred)\n print(\"Accuracy on the training set: \\t\\t {number:.{digit}f}\".format(number=train_acc, digit=3))\n print(\"Accuracy on the validation set: \\t {number:.{digit}f}\".format(number=val_acc, digit=3))\n\n # confusion matrix on the validation set\n print(\"Confusion on the validation set.\")\n print(\"1st Col/Row: Non-Cars | 2nd Col/Row: Cars\")\n print(sklearn.metrics.confusion_matrix(y_val, val_pred))\n\n print(\"\\n\\nAccuracy on the test set: \\t {number:.{digit}f}\".format(number=test_acc, digit=3))\n print(\"Confusion on the test set.\")\n print(\"1st Col/Row: Non-Cars | 2nd Col/Row: Cars\")\n print(sklearn.metrics.confusion_matrix(y_test, test_pred))\n\n joblib.dump(svc, './inputs/svm_model_weights_' + kernel + '.pkl') \n\n#<!--------------------------------------------------------------------------->\n#<!-- -->\n#<!--------------------------------------------------------------------------->\n\n# put executing code in main, so that the defined functions\n# can be imported in a separate script without executing\n# the code\nif __name__ == \"__main__\":\n main()\n\n" }, { "alpha_fraction": 0.5179404616355896, "alphanum_fraction": 0.5483895540237427, "avg_line_length": 34.04557800292969, "blob_id": "dc001fd9f8bc5f9a19ab92cc989ab40b870b1510", "content_id": "a33726627fd64a42508555363d7d73e4366e8657", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13071, "license_type": "no_license", "max_line_length": 109, "num_lines": 373, "path": "/As301_detector.py", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "#<!--------------------------------------------------------------------------->\n#<!-- ITU - IT University of Copenhage -->\n#<!-- Computer Science Department -->\n#<!-- Eye Information Research Group -->\n#<!-- Introduction to Image Analysis and Machine Learning Course -->\n#<!-- File : As301_detector.py.py -->\n#<!-- Description: Script to detect cars using a binary classifier -->\n#<!-- Author : Fabricio Batista Narcizo -->\n#<!-- : Rued Langgaards Vej 7 - 4D25 - DK-2300 - Kobenhavn S. -->\n#<!-- : narcizo[at]itu[dot]dk -->\n#<!-- Responsable: Dan Witzner Hansen (witzner[at]itu[dot]dk) -->\n#<!-- Fabricio Batista Narcizo (fabn[at]itu[dot]dk) -->\n#<!-- Information: No additional information -->\n#<!-- Date : 24/04/2018 -->\n#<!-- Change : 24/04/2018 - Creation of this script -->\n#<!-- Review : 24/04/2018 - Finalized -->\n#<!--------------------------------------------------------------------------->\n\n__version__ = \"$Revision: 2018042401 $\"\n\n########################################################################\nimport cv2\nfrom enum import Enum\nimport keras\nfrom keras.models import load_model\nimport numpy as np\nfrom pathlib import Path\nfrom skimage.transform import pyramid_gaussian\nfrom sklearn.externals import joblib\nimport sys\nimport time\n\nimport As301_classifier\n\n########################################################################\n\nINPUT_FILEPATH = Path(\"./inputs/videos/Cars_05.mov\")\nFILENAME = INPUT_FILEPATH.stem\n\n# Setup Video\n\nRECORD_VIDEO = True\n\nif RECORD_VIDEO:\n print(\"Recording a video of \" + FILENAME + \".mov\")\n\ncapture = cv2.VideoCapture(str(INPUT_FILEPATH))\n\n# Get the video frame rate.\nfps = int(round(capture.get(cv2.CAP_PROP_FPS)))\nw = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH) * 0.5)\nh = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT) * 0.5)\n\n# Check if the fps variable has a correct value.\nfps = fps if fps > 0 else 30\n\nframe_count = 0\nisColor = True\nfourcc = cv2.VideoWriter_fourcc(*\"mp4v\")\nif RECORD_VIDEO:\n record = cv2.VideoWriter(\"outputs/\" + FILENAME + \"_record.mov\",\n fourcc, fps, (w, h), isColor)\n\n# Setup Classifiers\n\nclass Classifier(Enum):\n SVM = 0\n CNN = 1 \n\n# pre-load all models\nCLF_SVM = joblib.load(\"./inputs/svm_model_weights_rbf.pkl\")\nCLF_CNN = load_model(\"./outputs/datamodel30epochs.h5\")\n\n\n########################################################################\n\n# We are going to apply both Image Pyramids and Sliding Windows \n# for our car detector and then use our classification model on the\n# image patches\n\n########################################################################\n\n# script for sliding window from \"Sliding Windows for Object Detection with Python and OpenCV\"\n# (see https://www.pyimagesearch.com/2015/03/23/sliding-windows-for-object-detection-with-python-and-opencv/)\ndef sliding_window(image, stepSize=(8,8), windowSize=(64,64)):\n # slide a window across the image\n for y in range(0, image.shape[0], stepSize[0]):\n for x in range(0, image.shape[1], stepSize[1]):\n # yield the current window\n yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])\n\n# function returns a list of rectangles that were detected as cars\ndef detectCars(frame, model = Classifier.SVM):\n\n org_height, org_width = frame.shape[:2] \n\n # store the frame in different dimensions \n # and begin with the lowest resolution\n scaled_frames = list(pyramid_gaussian(frame, downscale=1.5, max_layer=2))\n scaled_frames = list(reversed(scaled_frames))\n\n detected_cars = []\n rectangles = []\n\n # loop over every image scale\n for image_scaled in scaled_frames:\n\n # loop over window in the image\n scaled_height, scaled_width = image_scaled.shape[:2]\n SCALING_FACTOR = (org_height / scaled_height + org_width / scaled_width) / 2.0\n \n if scaled_height < 64 or scaled_width < 64:\n continue\n\n windows = list(sliding_window(image_scaled))\n\n windows = [w for w in windows if (w[0] <= scaled_width - 64 and w[1] <= scaled_height - 64)]\n\n x = [w[0] for w in windows]\n y = [w[1] for w in windows]\n image_window = np.array([w[2] for w in windows])\n\n # convert from float [0,1] range to integer [0,255] range\n image_window = image_window * 255\n image_window = image_window.astype(np.uint8)\n\n predictions = []\n\n if model == Classifier.SVM:\n\n hogList = []\n\n # Compute the HOG\n As301_classifier.computeHOG(image_window,hogList, size=(64,64))\n\n try:\n hog_features = np.array(hogList)\n num_patches, num_hog_features = hog_features.shape[:2]\n hog_features = hog_features.reshape((num_patches,num_hog_features))\n predictions = CLF_SVM.predict(hog_features)\n except IndexError:\n print(\"Caught an IndexError\")\n print((x,y))\n print(hogList)\n sys.exit()\n\n elif model == Classifier.CNN:\n\n # TODO: don't forget to scale the input into [0,1] range from [0,255]\n\n predictions = CLF_CNN.predict_classes(np.array(image_window))\n\n else:\n raise Exception(\"Did not specify a valid model.\")\n\n # create a list of detected cars in the image\n\n for idx, pred in enumerate(predictions):\n if pred == 1:\n detected_cars.append((x[idx],y[idx],SCALING_FACTOR)) \n\n res_image = frame.copy()\n for (x,y,scale) in detected_cars:\n rectangles.append((\n int(x * scale),\n int(y * scale),\n int(64 * scale),\n int(64 * scale)\n ))\n\n return rectangles\n\n# uses background substraction to find ROIs for our classifier\ndef backgroundDetection(frame):\n rectangles = []\n processed = fgbg.apply(frame)\n _, contours, hierarchy = cv2.findContours(processed, cv2.RETR_LIST,\n cv2.CHAIN_APPROX_SIMPLE)\n\n for cnt in contours:\n area = cv2.contourArea(cnt)\n if (area < 500):\n continue\n x,y,w,h = cv2.boundingRect(cnt)\n rectangles.append((x,y,w,h))\n\n return rectangles\n\n# returns True if (x1,y1,a1,b1) encloses (x2,y2,a2,b2) with a certain \n# (x,y) = coords of the top left corner point\n# (a,b) = coords of the bottom right corner point\n# margin of pixel allowance\ndef rectangleOverlap(rect1 = (0,0,0,0), rect2 = (0,0,0,0), margin=0):\n x1, y1, a1, b1 = rect1\n x2, y2, a2, b2 = rect2\n\n overlapCheck = (\n x2 > x1 - margin and\n a2 < a1 + margin and\n y2 > y1 - margin and\n b2 < b1 + margin\n )\n\n return overlapCheck \n\n# https://www.pyimagesearch.com/2014/11/17/non-maximum-suppression-object-detection-python/\n# (code from https://stackoverflow.com/questions/37847923/combine-overlapping-rectangles-python)\ndef non_max_suppression_fast(boxes, overlapThresh):\n # if there are no boxes, return an empty list\n if len(boxes) == 0:\n return []\n\n # if the bounding boxes integers, convert them to floats --\n # this is important since we'll be doing a bunch of divisions\n if boxes.dtype.kind == \"i\":\n boxes = boxes.astype(\"float\") \n # initialize the list of picked indexes \n pick = []\n\n # grab the coordinates of the bounding boxes\n x1 = boxes[:,0]\n y1 = boxes[:,1]\n x2 = boxes[:,2]\n y2 = boxes[:,3]\n\n # compute the area of the bounding boxes and sort the bounding\n # boxes by the bottom-right y-coordinate of the bounding box\n area = (x2 - x1 + 1) * (y2 - y1 + 1)\n idxs = np.argsort(y2)\n\n # keep looping while some indexes still remain in the indexes\n # list\n while len(idxs) > 0:\n # grab the last index in the indexes list and add the\n # index value to the list of picked indexes\n last = len(idxs) - 1\n i = idxs[last]\n pick.append(i)\n\n # find the largest (x, y) coordinates for the start of\n # the bounding box and the smallest (x, y) coordinates\n # for the end of the bounding box\n xx1 = np.maximum(x1[i], x1[idxs[:last]])\n yy1 = np.maximum(y1[i], y1[idxs[:last]])\n xx2 = np.minimum(x2[i], x2[idxs[:last]])\n yy2 = np.minimum(y2[i], y2[idxs[:last]])\n\n # compute the width and height of the bounding box\n w = np.maximum(0, xx2 - xx1 + 1)\n h = np.maximum(0, yy2 - yy1 + 1)\n\n # compute the ratio of overlap\n overlap = (w * h) / area[idxs[:last]]\n\n # delete all indexes from the index list that have\n idxs = np.delete(idxs, np.concatenate(([last], np.where(overlap > overlapThresh)[0])))\n\n # return only the bounding boxes that were picked using the\n # integer data type\n return boxes[pick].astype(\"int\")\n\n\n# Create an OpenCV window.\nif not RECORD_VIDEO:\n cv2.namedWindow(\"Video\", cv2.WINDOW_AUTOSIZE)\n\nfgbg = cv2.createBackgroundSubtractorMOG2()\n\n# measure the frame by frame calculation performance\nframe_times = []\n \nwhile True:\n # Capture frame-by-frame.\n retval, frame = capture.read()\n time_diff = time.time()\n\n # Check if there is a valid frame.\n if not retval:\n break\n\n # Resize the frame.\n scaleX, scaleY = (0.5,0.5)\n frame = cv2.resize(frame, (0, 0), fx=scaleX, fy=scaleY)\n\n bgRectangles = backgroundDetection(frame)\n\n # remove too small rectangles\n bgRectangles = [(x,y,w,h) for (x,y,w,h) in bgRectangles if (w*h > 700 and w*h < 65000)]\n # remove rectangles that aren't square\n bgRectangles = [(x,y,w,h) for (x,y,w,h) in bgRectangles if ((w/h > 0.2) if h > w else (h/w > 0.2))]\n\n bg_rect_overlap_free = []\n\n # remove overlapping rectangles\n for (x1,y1,w1,h1) in bgRectangles:\n isOverlapping = False\n for (x2,y2,w2,h2) in bgRectangles:\n if (\n (x1,y1,w1,h1) != (x2,y2,w2,h2) and \n rectangleOverlap((x2,y2,x2+w2,y2+h2), (x1,y1,x1+w1,y1+h1), margin=20)\n ):\n isOverlapping = True\n break\n if not isOverlapping:\n bg_rect_overlap_free.append((x1,y1,w1,h1))\n\n detectedRect = []\n\n # (x,y,w,h)\n for (x,y,w,h) in bg_rect_overlap_free:\n PIXEL_BOUND = 20\n bound_x = PIXEL_BOUND if x >= PIXEL_BOUND else x\n bound_y = PIXEL_BOUND if y >= PIXEL_BOUND else y\n # cv2.rectangle(frame, (x-bound_x, y-bound_y), (x+w+bound_x, y+h+bound_y), (0,0,255), 2 )\n detections = detectCars(frame[y-bound_y:y+h+bound_y,x-bound_x:x+w+bound_x,:], model=Classifier.SVM)\n detections = [(x1+(x-bound_x),y1+(y-bound_y),w1,h1) for (x1,y1,w1,h1) in detections]\n detectedRect += detections\n\n # print(\"Detections before overlap {0}\".format(len(detectedRect)))\n\n # convert from (x,y,w,h) to (x1,y1,x2,y2) for non-maximum suppression\n detectedRect = np.array([(x,y,x+w,y+h) for (x,y,w,h) in detectedRect])\n\n detectedRect = non_max_suppression_fast(detectedRect, 0.1)\n\n # print(\"Detections after overlap {0}\".format(len(detectedRect)))\n\n for (x1,y1,x2,y2) in detectedRect:\n cv2.rectangle(frame,(x1,y1),(x2,y2), (0,255,0), 2)\n\n # detect_count = 0\n # for (x1,y1,w1,h1) in detectedRect:\n # isOverlapping = False\n # for (x2,y2,w2,h2) in detectedRect:\n # if (\n # (x1,y1,w1,h1) != (x2,y2,w2,h2) and \n # rectangleOverlap((x2,y2,x2+w2,y2+h2), (x1,y1,x1+w1,y1+h1), margin=10)\n # ):\n # isOverlapping = True\n # break\n\n # if not isOverlapping:\n # detect_count += 1\n # cv2.rectangle(frame,(x1,y1),(x1+w1,y1+h1),(0,255,0),2)\n\n # print(\"Detections after overlap {0}\".format(detect_count))\n\n time_diff = time.time() - time_diff\n\n frame_times.append(time_diff)\n\n # Display the resulting frame.\n if RECORD_VIDEO == True:\n record.write(frame)\n if frame_count % 30 == 0:\n print(\"Processed {0} frames \\t({1} seconds of video)\".format(frame_count, frame_count//30))\n print(\"Average processing time for one frame {0}\".format(str(np.mean(np.array(frame_times)))))\n else:\n cv2.imshow(\"Video\", frame)\n if cv2.waitKey(fps) & 0xFF == ord(\"q\"):\n break \n\n frame_count += 1\n\n\n#<!--------------------------------------------------------------------------->\n#<!-- -->\n#<!--------------------------------------------------------------------------->\nif RECORD_VIDEO:\n record.release()\n\ncapture.release()\ncv2.destroyAllWindows()" }, { "alpha_fraction": 0.5605912804603577, "alphanum_fraction": 0.579974889755249, "avg_line_length": 32.35348892211914, "blob_id": "9f71a99585aa929e410b8816caf2f04d4a21b152", "content_id": "1beb4a5eda8e3d7559e74a0bb1ae4b80b8940bc5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7171, "license_type": "no_license", "max_line_length": 91, "num_lines": 215, "path": "/Ex10TemplateCode/Ex1001_svm_training.py", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "#<!--------------------------------------------------------------------------->\n#<!-- ITU - IT University of Copenhage -->\n#<!-- Computer Science Department -->\n#<!-- Eye Information Research Group -->\n#<!-- Introduction to Image Analysis and Machine Learning Course -->\n#<!-- File : Ex1001_svm_training.py -->\n#<!-- Description: Script to train a pedestrian detector based on SVM -->\n#<!-- Author : Fabricio Batista Narcizo -->\n#<!-- : Rued Langgaards Vej 7 - 4D25 - DK-2300 - Kobenhavn S. -->\n#<!-- : narcizo[at]itu[dot]dk -->\n#<!-- Responsable: Dan Witzner Hansen (witzner[at]itu[dot]dk) -->\n#<!-- Fabricio Batista Narcizo (fabn[at]itu[dot]dk) -->\n#<!-- Information: No additional information -->\n#<!-- Date : 29/03/2018 -->\n#<!-- Change : 29/03/2018 - Creation of this script -->\n#<!-- Review : 29/03/2018 - Finalized -->\n#<!--------------------------------------------------------------------------->\n\n__version__ = \"$Revision: 2018032901 $\"\n\n########################################################################\nimport cv2\nimport numpy as np\nimport random\nimport sys\nimport os\ncwd = os.getcwd() + \"\\\\\"\n\n########################################################################\n\ndef loadDataset(dataset):\n \"\"\"\n This function load all images from a dataset and return a list of Numpy images.\n \"\"\"\n # List of images.\n images = []\n\n # Read the dataset file.\n file = open(dataset)\n filename = file.readline()\n\n # Read all filenames from the dataset.\n while (filename != \"\"):\n # Get the current filename.\n\n filename = (dataset.rsplit(\"/\", 1)[0] + \"/\" +\n filename.split(\"/\", 1)[1].strip(\"\\n\"))\n\n # Read the input image.\n # ERROR: My image files in the dataset seem to be corrupted\n # Will add the code to the Ass3 Repo as template for our\n # car detector. There the images do not seem to be corrupted.\n image = cv2.imread(full_path)\n # C:\\Users\\Peter Mortimer\\Desktop\\IAML\\Week10\\Exercises_10_material\\inputs\\Train\\pos\n\n if image is None:\n print(\"Could not read the file: {}\".format(full_path))\n \n # Read the next image filename.\n filename = file.readline()\n \n # Add the current image on the list.\n if image is not None: \n images.append(image)\n\n # Return the images list.\n return images\n\ndef getSVMDetector(svm):\n \"\"\"\n This function calculates and returns the feature descriptor.\n \"\"\"\n # Retrieves all the support vectors.\n sv = svm.getSupportVectors()\n\n # Retrieves the decision function.\n rho, _, _ = svm.getDecisionFunction(0)\n\n # Transpose the support vectors matrix.\n sv = np.transpose(sv)\n\n # Returns the feature descriptor.\n return np.append(sv, [[-rho]], 0)\n\ndef sampleNegativeImages(images, negativeSample, size=(64, 128), N=10):\n \"\"\"\n INRIA Dataset has several images of different resolution without pedestrians,\n i.e. called here as negative images. This function select \"N\" 64x128 negative\n sub-images randomly from each original negative image.\n \"\"\"\n # Initialize internal state of the random number generator.\n random.seed(1)\n\n # Final image resolution.\n w, h = size[0], size[1]\n\n # Read all images from the negative list.\n for image in images:\n\n for j in range(N):\n # random.random produced random number in [0,1) range\n y = int(random.random() * (len(image) - h))\n x = int(random.random() * (len(image[0]) - w))\n sample = image[y:y + h, x:x + w].copy()\n negativeSample.append(sample)\n\n return negativeSample\n\ndef computeHOG(images, hogList, size=(64, 128)):\n \"\"\"\n This function computes the Histogram of Oriented Gradients (HOG) of each\n image from the dataset.\n \"\"\"\n # Creates the HOG descriptor and detector with default parameters.\n hog = cv2.HOGDescriptor()\n\n # Read all images from the image list.\n for image in images:\n \n # Image resolution\n h, w = image.shape[:2]\n\n # Calculate HOG\n if w >= size[0] and h >= size[1]:\n\n # Region of Interest\n y = (h - size[1]) // 2\n x = (w - size[0]) // 2\n roi = image[y:y + size[1], x:x + size[0]].copy()\n\n # Compute HOG\n grayscale = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)\n hogList.append(hog.compute(grayscale))\n\n return hogList\n\n\n# Dataset filenames.\npositiveFile = \"./inputs/train/pos.lst\"\nnegativeFile = \"./inputs/train/neg.lst\"\n\n# Vectors used to train the dataset.\nhogList = []\npositiveList = []\nnegativeList = []\nnegativeSample = []\nhardNegativeList = []\nlabels = []\n\n# Load the INRIA dataset.\npositiveList = loadDataset(positiveFile)\nnegativeList = loadDataset(negativeFile)\n\nprint(str(len(positiveList)))\nprint(str(len(negativeList)))\n\n# Get a sample of negative images.\nsampleNegativeImages(negativeList, negativeSample)\n\n# Compute the Histogram of Oriented Gradients (HOG).\ncomputeHOG(positiveList, hogList)\ncomputeHOG(negativeSample, hogList)\nif len(hogList) == 0:\n exit(0)\n\n# Create the class labels, i.e. (+1) positive and (-1) negative.\n[labels.append(+1) for _ in range(len(positiveList))]\n[labels.append(-1) for _ in range(len(negativeSample))]\n\n# Create an empty SVM model.\nsvm = cv2.ml.SVM_create()\n\n# Define the SVM parameters.\n# By default, Dalal and Triggs (2005) use a soft (C=0.01) linear SVM trained with SVMLight.\nsvm.setDegree(3)\ncriteria = (cv2.TERM_CRITERIA_MAX_ITER + cv2.TERM_CRITERIA_EPS, 1000, 1e-3)\nsvm.setTermCriteria(criteria)\nsvm.setGamma(0)\nsvm.setKernel(cv2.ml.SVM_LINEAR)\nsvm.setNu(0.5)\nsvm.setP(0.1)\nsvm.setC(0.01)\nsvm.setType(cv2.ml.SVM_EPS_SVR)\n\nsvm.train(np.array(hogList), cv2.ml.ROW_SAMPLE, np.array(labels))\n\n# Create the HOG descriptor and detector with default params.\nhog = cv2.HOGDescriptor()\nhog.setSVMDetector(getSVMDetector(svm))\n\n# Add the wrong identification sample for the second round of training\n# (hard examples)\nfor image in negativeList:\n # Detects objects od different sizes in the input image\n rectangles, _ = hog.detectMultiScale(image)\n\n # Get the ROI in the false positive pedestrian\n for (x, y, w, h) in rectangles:\n roi = image[y:y + h, x:x + w]\n hardNegativeList.append(cv2.resize(roi, (64,128)))\n\n# Compute the Histogram of Oriented Gradients (HOG)\ncomputeHog(hardNegativeList, hogList)\n\n# Update the class labels, i.e. (-1) hard negative.\n# (these are added to the list with pos. and neg. images)\n[labels.append(-1) for _ in range(len(hardNegativeList))]\n\n# Train the SVM based on HOG Features\nsvm.train(np.array(hogList), cv2.ml.ROW_SAMPLE, np.array(labels))\n\n# Save the HOG feature.\nfeature = getSVMDetector(svm)\nnp.save(\"./outputs/feature.npy\", feature)\nprint(\"stored SVM weights\")\n" }, { "alpha_fraction": 0.4359150230884552, "alphanum_fraction": 0.4561343491077423, "avg_line_length": 36.90909194946289, "blob_id": "f1093a10cc0b31b3775e0793bdf6d534a893da65", "content_id": "61d51f300c6ea51481eb7f1cd453981c0e1c7a99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2918, "license_type": "no_license", "max_line_length": 83, "num_lines": 77, "path": "/Ex10TemplateCode/Ex1002_pedestrian_detector.py", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "#<!--------------------------------------------------------------------------->\n#<!-- ITU - IT University of Copenhage -->\n#<!-- Computer Science Department -->\n#<!-- Eye Information Research Group -->\n#<!-- Introduction to Image Analysis and Machine Learning Course -->\n#<!-- File : Ex1002_pedestrian_detector.py -->\n#<!-- Description: Script to detect pedestrians using HOG and SVM -->\n#<!-- Author : Fabricio Batista Narcizo -->\n#<!-- : Rued Langgaards Vej 7 - 4D25 - DK-2300 - Kobenhavn S. -->\n#<!-- : narcizo[at]itu[dot]dk -->\n#<!-- Responsable: Dan Witzner Hansen (witzner[at]itu[dot]dk) -->\n#<!-- Fabricio Batista Narcizo (fabn[at]itu[dot]dk) -->\n#<!-- Information: No additional information -->\n#<!-- Date : 29/03/2018 -->\n#<!-- Change : 29/03/2018 - Creation of this script -->\n#<!-- Review : 29/03/2018 - Finalized -->\n#<!--------------------------------------------------------------------------->\n\n__version__ = \"$Revision: 2018032901 $\"\n\n########################################################################\nimport cv2\nimport numpy as np\n\n########################################################################\n\ndef loadDataset(dataset):\n \"\"\"\n This function load all images from a dataset and return a list of Numpy images.\n \"\"\"\n # List of images.\n images = []\n\n # Read the dataset file.\n file = open(dataset)\n filename = file.readline()\n\n # Read all filenames from the dataset.\n while (filename != \"\"):\n # Get the current filename.\n filename = (dataset.rsplit(\"/\", 1)[0] + \"/\" +\n filename.split(\"/\", 1)[1].strip(\"\\n\"))\n \n # Read the input image.\n image = cv2.imread(filename)\n \n # Read the next image filename.\n filename = file.readline()\n \n # Add the current image on the list.\n if image is not None: \n images.append(image)\n\n # Return the images list.\n return images\n\n# Create the HOG descriptor and import the HOG feature.\nfeature = np.load(\"./outputs/feature.npy\")\nhog = cv2.HOGDescriptor()\nhog.setSVMDetector(feature)\n\n# Dataset filename.\npositiveFile = \"./inputs/Test/pos.lst\"\n\n# Load the INRIA dataset.\npositiveList = loadDataset(positiveFile)\n\n# --- ADD CODE HERE TO READ A VIDEO INTO IMAGES ---\n\n# Detects objects of different sizes in the input image\nrectangles, _ = hog.detectMultiScale(image)\n\n# Draw the detetcted pedestrians\nfor (x, y, w, h) in rectangles:\n cv2.rectangle(image, (x,y), (x + w, y + h), (0,0,255))\n\n# --- ADD CODE TO DISPLAY THE RESULT IMAGE ---" }, { "alpha_fraction": 0.7790697813034058, "alphanum_fraction": 0.7994186282157898, "avg_line_length": 85, "blob_id": "0b2f4bd5cfa66bcbab61aafee5f30fdb2810c2d5", "content_id": "0137951d0adf18148f54e4eb22acd86e01f29843", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 344, "license_type": "no_license", "max_line_length": 187, "num_lines": 4, "path": "/README.md", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "# IAML-Ass03\nThis is the repository for Assignment #3 of Introduction to Image Analysis and Machine Learning (IAML) at ITU Copenhagen (Spring 2018). This repository will also include the final report.\n\nI did not upload the image and video files used in the assignment. These you should download and copy into the directory of your git project.\n" }, { "alpha_fraction": 0.48463156819343567, "alphanum_fraction": 0.5056841969490051, "avg_line_length": 33.17266082763672, "blob_id": "83c797639c51112df9bb3810fef4fe2431e002b2", "content_id": "716ac13bae9cc88c77ea4ccfc9a5d677967f1246", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4750, "license_type": "no_license", "max_line_length": 79, "num_lines": 139, "path": "/warmUpAnnotations.py", "repo_name": "EmanuelAlogna/IAML-Ass03", "src_encoding": "UTF-8", "text": "#<!--------------------------------------------------------------------------->\n#<!-- ITU - IT University of Copenhage -->\n#<!-- Computer Science Department -->\n#<!-- Eye Information Research Group -->\n#<!-- Introduction to Image Analysis and Machine Learning Course -->\n#<!-- File : warmUpAnnotations.py -->\n#<!-- Description: Example of code for select regions of interest in images -->\n#<!-- Author : Fabricio Batista Narcizo -->\n#<!-- : Rued Langgaards Vej 7 - 4D25 - DK-2300 - Kobenhavn S. -->\n#<!-- : narcizo[at]itu[dot]dk -->\n#<!-- Responsable: Dan Witzner Hansen (witzner[at]itu[dot]dk) -->\n#<!-- Fabricio Batista Narcizo (fabn[at]itu[dot]dk) -->\n#<!-- Information: You DO NOT need to change this file -->\n#<!-- Date : 24/04/2018 -->\n#<!-- Change : 24/04/2018 - Creation of this script -->\n#<!-- Review : 24/04/2018 - Finalized -->\n#<!--------------------------------------------------------------------------->\n\n__version__ = \"$Revision: 2018042401 $\"\n\n###############################################################################\nimport cv2\nimport time\nimport os\n\n###############################################################################\n# Global variables.\npoints = []\ncropping = False\n\ndef saveImage(image):\n \"\"\"Save a new positive image in the dataset.\"\"\"\n # Folder where the image will be saved.\n folder = \"./inputs/cars/\"\n\n # Current image ID.\n index = 0\n while True:\n # Create the image filename.\n filename = \"%sCars_%03d.png\" % (folder, index + 1)\n\n # Check if it is available in the folder and avoid to overwrite it.\n if not os.path.isfile(filename):\n\n # Save the image as grayscale.\n cv2.imwrite(filename, image)\n print(\"Saved: %s\" % filename) \n break\n\n # Try to use a new image ID.\n index += 1\n\ndef selectROI(event, x, y, flags, param):\n \"\"\"Select a region of interest using the mouse.\"\"\"\n # Global variables.\n global points, cropping\n\n # Event for the left mouse button click.\n if event == cv2.EVENT_LBUTTONDOWN:\n points = [(x, y)]\n cropping = True\n\n # Event for the left mouse button release.\n elif event == cv2.EVENT_LBUTTONUP:\n # Check the upper left corner.\n if len (points) == 0:\n return\n\n # Calculate the width and height of bouding box.\n width = int(x) - points[0][0]\n height = int(y) - points[0][1]\n\n # Aspect ratio.\n if width < height:\n width = int(height)\n else:\n height = int(width)\n\n # Record the ending (x, y) coordinates and indicate that\n # the cropping operation is finished.\n points.append((points[0][0] + width, points[0][1] + height))\n cropping = False\n\n # Draw a rectangle around the region of interest.\n image = frame.copy()\n cv2.rectangle(image, points[0], points[1], (0, 255, 0), 2)\n cv2.imshow(\"Video\", image)\n\n # Press the key \"S\" on your keyboard to save the selected ROI.\n key = cv2.waitKey(0)\n if key == ord(\"s\"):\n roi = frame[points[0][1]:points[1][1], points[0][0]:points[1][0]]\n roi = cv2.resize(roi, (64, 64)) \n saveImage(roi)\n\n\n# Defines the filepath.\nfilepath = \"./inputs/videos/Cars_05.mov\"\n\n# Create a capture video object.\ncapture = cv2.VideoCapture(filepath)\n\n# Get the video frame rate.\nfps = int(round(capture.get(cv2.CAP_PROP_FPS)))\n\n# Check if the fps variable has a correct value.\nfps = fps if fps > 0 else 30\n\n# Create an OpenCV window.\ncv2.namedWindow(\"Video\", cv2.WINDOW_AUTOSIZE)\ncv2.setMouseCallback(\"Video\", selectROI)\n\n# Press the key \"P\" on your keyboard to pause the video.\nisPaused = False\n\n# This repetion will run while there is a new frame in the video file or\n# while the user do not press the \"q\" (quit) keyboard button.\nwhile True:\n # Capture frame-by-frame.\n if not isPaused:\n retval, frame = capture.read()\n\n # Check if there is a valid frame.\n if not retval:\n break\n\n # Display the resulting frame.\n cv2.imshow(\"Video\", frame)\n\n # Check the keyboard events.\n key = cv2.waitKey(fps)\n if key == ord(\"q\"):\n break\n elif key == 32:\n isPaused = not isPaused \n\n# When everything done, release the capture and record objects.\ncapture.release()\ncv2.destroyAllWindows()\n" } ]
9
red23495/random_util
https://github.com/red23495/random_util
91a679c7476d92cea01a6292df50492d4e2bdac6
23836045afc4ec3e2c48a903bd02b5f2a70cea5a
24d0326a2ee9c61da4d3b996881ead895b8611c4
refs/heads/master
2022-04-24T21:39:35.635248
2020-04-28T20:40:23
2020-04-28T20:40:23
258,608,344
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8181818127632141, "alphanum_fraction": 0.8181818127632141, "avg_line_length": 26.5, "blob_id": "2f70551473b730a5a4ba515d7ad3480e53b08382", "content_id": "06854dd76ab040d214034a9ccc0f2eee3d75d2bf", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 55, "license_type": "permissive", "max_line_length": 40, "num_lines": 2, "path": "/README.md", "repo_name": "red23495/random_util", "src_encoding": "UTF-8", "text": "# random_util\nA collection of random utility functions\n" }, { "alpha_fraction": 0.5782918334007263, "alphanum_fraction": 0.6494662165641785, "avg_line_length": 35.290321350097656, "blob_id": "f2253b4846f8f7ff7ce3abe13e6ebd3d337991d4", "content_id": "39321474f7d0a67e45a8543cd02a62fa9c749ca9", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1124, "license_type": "permissive", "max_line_length": 71, "num_lines": 31, "path": "/Python/Algebra/test/test_binary_exponentiation.py", "repo_name": "red23495/random_util", "src_encoding": "UTF-8", "text": "import unittest\nfrom ..binary_exponentiation import mod_pow\n\n\nclass BinaryExponentiationTest(unittest.TestCase):\n\n def test_calculates_power_properly(self):\n self.assertEqual(mod_pow(2, 2), 4)\n self.assertEqual(mod_pow(1, 10), 1)\n self.assertEqual(mod_pow(10, 5), 100000)\n \n def test_calculates_properly_for_big_result(self):\n self.assertEqual(mod_pow(10, 100000), 10**100000)\n \n def test_calculates_zero_when_base_is_zero(self):\n self.assertEqual(mod_pow(0, 10), 0)\n \n def test_calculates_one_when_power_is_zero(self):\n self.assertEqual(mod_pow(200, 0), 1)\n \n def test_calculates_positive_when_base_negative_and_pow_even(self):\n self.assertEqual(mod_pow(-2, 4), 16)\n \n def test_calculates_negative_when_base_negative_and_pow_odd(self):\n self.assertEqual(mod_pow(-2, 3), -8)\n \n def test_mods_result_properly_when_mod_given(self):\n self.assertEqual(mod_pow(2, 2, 1), 0)\n self.assertEqual(mod_pow(1, 10, 17), 1)\n self.assertEqual(mod_pow(10, 5, 15), 10)\n self.assertEqual(mod_pow(10, 5, 100001), 100000)" }, { "alpha_fraction": 0.561847984790802, "alphanum_fraction": 0.5678092241287231, "avg_line_length": 27, "blob_id": "9eba57c0586d9a6e8fe03db61e977ec3c60cbd9c", "content_id": "88b1348d6545ee213b897fb7b8a78131e338984e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 671, "license_type": "permissive", "max_line_length": 65, "num_lines": 24, "path": "/Python/Algebra/binary_exponentiation.py", "repo_name": "red23495/random_util", "src_encoding": "UTF-8", "text": "def mod_pow(base, power, mod=None):\n \"\"\"\n Implements divide and conquere binary exponetiation algorithm\n Complexity: O(log power) \n source: https://cp-algorithms.com/algebra/binary-exp.html\n Params:\n @base: base number which needs to be multiplied\n @power: power to which base should be raised\n @mod: modulas with which number should be mod'ed\n returns: (base^power)%mod\n \"\"\"\n if mod:\n base %= mod\n result = 1\n while power > 0:\n if power & 1:\n result *= base\n if mod:\n result %= mod\n base *= base\n if mod:\n base %= mod\n power //= 2\n return result" } ]
3
Skymirrh/qBittorrent-rutracker-plugin
https://github.com/Skymirrh/qBittorrent-rutracker-plugin
dcd003423cbfc08d92110cad7a4c7a4eea88689d
8711bfc13405c6cf1b849acb4098b3dc7b5e9c18
d583d64a6eeae346a24c3fe13358bedee6cc82e8
refs/heads/master
2021-01-17T14:29:48.846085
2021-01-04T12:08:48
2021-01-04T12:08:48
14,812,546
20
14
null
null
null
null
null
[ { "alpha_fraction": 0.7602179646492004, "alphanum_fraction": 0.7629427909851074, "avg_line_length": 27.230770111083984, "blob_id": "6d4794fccb9c7cfe6a6484d2bcc9733824a5bbe6", "content_id": "9f0a4263e0cf76a7802fdb038e76a9b2a5c68444", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 367, "license_type": "permissive", "max_line_length": 78, "num_lines": 13, "path": "/ISSUE_TEMPLATE.md", "repo_name": "Skymirrh/qBittorrent-rutracker-plugin", "src_encoding": "UTF-8", "text": "Hello! Before reporting a bug, please review the Troubleshooting instructions:\n\nhttps://github.com/Skymirrh/qBittorrent-RuTracker-plugin#troubleshooting\n\nThen, fill out of the following form:\n\n* Operating System: {type here}\n* qBittorrent version: {type here}\n* Python version: {type here}\n* Output of `python nova2.py rutracker all archlinux`:\n```\n{output here}\n```\n" }, { "alpha_fraction": 0.5579254031181335, "alphanum_fraction": 0.5619202256202698, "avg_line_length": 44.303680419921875, "blob_id": "615647d765dbe9c72979f9c14aaae87bfec0268b", "content_id": "3b42f228262a88af4fe541747bd40e90c782b99d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14773, "license_type": "permissive", "max_line_length": 193, "num_lines": 326, "path": "/rutracker.py", "repo_name": "Skymirrh/qBittorrent-rutracker-plugin", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"RuTracker search engine plugin for qBittorrent.\"\"\"\n#VERSION: 1.16\n#AUTHORS: Skymirrh ([email protected])\n\n# Replace YOUR_USERNAME_HERE and YOUR_PASSWORD_HERE with your RuTracker username and password\ncredentials = {\n 'login_username': u'YOUR_USERNAME_HERE',\n 'login_password': u'YOUR_PASSWORD_HERE',\n}\n\n# List of RuTracker mirrors\nmirrors = [\n 'https://rutracker.org',\n 'https://rutracker.net',\n 'https://rutracker.nl',\n]\n\n# Logging\nimport logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.WARNING)\n\n# Try blocks are used to circumvent Python2/3 modules discrepancies and use a single script for both versions.\ntry:\n import cookielib\nexcept ImportError:\n import http.cookiejar as cookielib\n \ntry: \n from urllib import urlencode, quote, unquote\n from urllib2 import build_opener, HTTPCookieProcessor, URLError, HTTPError\nexcept ImportError:\n from urllib.parse import urlencode, quote, unquote\n from urllib.request import build_opener, HTTPCookieProcessor\n from urllib.error import URLError, HTTPError\n\ntry:\n from HTMLParser import HTMLParser\nexcept ImportError:\n from html.parser import HTMLParser\n \nimport tempfile\nimport os\nimport re\n\nfrom novaprinter import prettyPrinter\n\ndef dict_encode(dict, encoding='cp1251'):\n \"\"\"Encode dict values to encoding (default: cp1251).\"\"\"\n encoded_dict = {}\n for key in dict:\n encoded_dict[key] = dict[key].encode(encoding)\n return encoded_dict\n\nclass rutracker(object):\n \"\"\"RuTracker search engine plugin for qBittorrent.\"\"\"\n name = 'RuTracker'\n url = 'https://rutracker.org' # We MUST produce an URL attribute at instantiation time, otherwise qBittorrent will fail to register the engine, see #15\n \n @property\n def forum_url(self):\n return self.url + '/forum'\n \n @property\n def login_url(self):\n return self.forum_url + '/login.php'\n \n @property\n def download_url(self):\n return self.forum_url + '/dl.php'\n \n @property\n def search_url(self):\n return self.forum_url + '/tracker.php'\n\n def __init__(self):\n \"\"\"Initialize RuTracker search engine, signing in using given credentials.\"\"\"\n # Initialize various objects.\n self.cj = cookielib.CookieJar()\n self.opener = build_opener(HTTPCookieProcessor(self.cj))\n self.url = self.initialize_url() # Override url with the actual URL to be used (in case official URL isn't accessible)\n self.credentials = credentials\n # Add submit button additional POST param.\n self.credentials['login'] = u'Вход'\n # Send POST information and sign in.\n try:\n logging.info(\"Trying to connect using given credentials.\")\n response = self.opener.open(self.login_url, urlencode(dict_encode(self.credentials)).encode())\n # Check if response status is OK.\n if response.getcode() != 200:\n raise HTTPError(response.geturl(), response.getcode(), \"HTTP request to {} failed with status: {}\".format(self.login_url, response.getcode()), response.info(), None)\n # Check if login was successful using cookies.\n if not 'bb_session' in [cookie.name for cookie in self.cj]:\n logging.debug(self.cj)\n raise ValueError(\"Unable to connect using given credentials.\")\n else:\n logging.info(\"Login successful.\")\n except (URLError, HTTPError, ValueError) as e:\n logging.error(e)\n\n def initialize_url(self):\n \"\"\"Try to find a reachable RuTracker mirror.\"\"\"\n errors = []\n for mirror in mirrors:\n try:\n self.opener.open(mirror)\n logging.info(\"Found reachable mirror: {}\".format(mirror))\n return mirror\n except URLError as e:\n logging.warning(\"Could not resolve mirror: {}\".format(mirror))\n errors.append(e)\n logging.error(\"Unable to resolve any RuTracker mirror -- exiting plugin search\")\n raise RuntimeError(\"\\n{}\".format(\"\\n\".join([str(error) for error in errors])))\n \n def download_torrent(self, url):\n \"\"\"Download file at url and write it to a file, print the path to the file and the url.\"\"\"\n # Make temp file.\n file, path = tempfile.mkstemp('.torrent')\n file = os.fdopen(file, \"wb\")\n # Set up fake POST params, needed to trick the server into sending the file.\n id = re.search(r'dl\\.php\\?t=(\\d+)', url).group(1)\n post_params = {'t': id,}\n # Download torrent file at url.\n try:\n response = self.opener.open(url, urlencode(dict_encode(post_params)).encode())\n # Only continue if response status is OK.\n if response.getcode() != 200:\n raise HTTPError(response.geturl(), response.getcode(), \"HTTP request to {} failed with status: {}\".format(url, response.getcode()), response.info(), None)\n except (URLError, HTTPError) as e:\n logging.error(e)\n raise e\n # Write it to a file.\n data = response.read()\n file.write(data)\n file.close()\n # Print file path and url.\n print(path+\" \"+url)\n\n class Parser(HTMLParser):\n \"\"\"Implement a simple HTML parser to parse results pages.\"\"\"\n \n def __init__(self, engine):\n \"\"\"Initialize the parser with url and tell him if he's on the first page of results or not.\"\"\"\n # In Python 3 convert_charrefs is set to True by default: handle_data() receives HTML entities as regular data, handle_entityref() does nothing.\n # In Python 2 there is no convert_charrefs: HTML entities are always processed by handle_entityref().\n # Thus, we make Python 3 work like Python 2 in order to standardize HTML entities handling.\n try:\n HTMLParser.__init__(self, convert_charrefs=False)\n except:\n HTMLParser.__init__(self)\n self.engine = engine\n self.results = []\n self.other_pages = []\n self.tr_counter = 0\n self.cat_re = re.compile(r'tracker\\.php\\?f=\\d+')\n self.name_re = re.compile(r'viewtopic\\.php\\?t=\\d+')\n self.pages_re = re.compile(r'tracker\\.php\\?.*?start=(\\d+)')\n self.size_re = re.compile(r'[^.0-9a-zA-Z]+')\n self.reset_current()\n\n def reset_current(self):\n \"\"\"Reset current_item (i.e. torrent) to default values.\"\"\"\n self.current_item = {'cat': None,\n 'name': None,\n 'link': None,\n 'size': None,\n 'size_extension': None,\n 'seeds': None,\n 'leech': None,\n 'desc_link': None,}\n\n def handle_data(self, data):\n \"\"\"Retrieve inner text information based on rules defined in do_tag().\"\"\"\n for key in self.current_item:\n if self.current_item[key] == True:\n if key == 'size':\n try:\n value = float(data)\n self.current_item['size'] = self.size_re.sub(r'', data)\n self.current_item['size_extension'] = 'waitForEntityRef' # Flag size_extension as parsable in subsequents entityref checks\n except ValueError:\n pass # Ignore float parsing errors -- this just means we'll get the data later from <a> tag\n elif key == 'size_extension':\n self.current_item['size'] += data.strip()\n self.current_item['size_extension'] = 'parsed'\n else:\n self.current_item[key] = data\n logging.debug('handle_data: ' + str((self.tr_counter, key, data, self.current_item[key])))\n if 'size_extension' in self.current_item and self.current_item['size_extension'] == 'parsed':\n del self.current_item['size_extension']\n logging.debug('handle_data: ' + str((self.tr_counter, self.current_item['size'])))\n\n def handle_entityref(self, entity):\n \"\"\"When encountering a &nbsp; right after setting size, next handle_data() will receive size extension (e.g. 'MB', 'GB')\"\"\"\n if entity == \"nbsp\" and 'size_extension' in self.current_item and self.current_item['size_extension'] == 'waitForEntityRef':\n self.current_item['size_extension'] = True\n\n def handle_starttag(self, tag, attrs):\n \"\"\"Pass along tag and attributes to dedicated handlers. Discard any tag without handler.\"\"\"\n try:\n getattr(self, 'do_{}'.format(tag))(attrs)\n except:\n pass\n \n def handle_endtag(self, tag):\n \"\"\"Add last item manually on html end tag.\"\"\"\n # We add last item found manually because items are added on new\n # <tr class=\"tCenter\"> and not on </tr> (can't do it without the attribute).\n if tag == 'html' and self.current_item['seeds'] != None:\n self.results.append(self.current_item)\n\n def do_tr(self, attr):\n \"\"\"<tr class=\"tCenter\"> is the big container for one torrent, so we store current_item and reset it.\"\"\"\n params = dict(attr)\n try:\n if 'tCenter' in params['class']:\n # Of course we won't store current_item on first <tr class=\"tCenter\"> seen, since there's no data yet\n if self.tr_counter != 0:\n # We only store current_item if torrent is still alive.\n if self.current_item['seeds'] != None:\n self.results.append(self.current_item)\n else:\n self.tr_counter -= 1 # We decrement by one to keep a good value.\n logging.debug('do_tr: ' + str(self.current_item))\n self.reset_current()\n self.tr_counter += 1\n except KeyError:\n pass\n\n def do_a(self, attr):\n \"\"\"<a> tags can specify torrent link in \"href\" or category or name. Also used to retrieve further results pages.\"\"\"\n params = dict(attr)\n try:\n if self.cat_re.search(params['href']):\n self.current_item['cat'] = True\n elif 'data-topic_id' in params and self.name_re.search(params['href']): # data-topic_id is needed to avoid conflicts.\n self.current_item['desc_link'] = self.engine.forum_url + '/' + params['href']\n self.current_item['link'] = self.engine.download_url + '?t=' + params['data-topic_id']\n self.current_item['name'] = True\n # If we're on the first page of results, we search for other pages.\n elif self.first_page:\n pages = self.pages_re.search(params['href'])\n if pages:\n if pages.group(1) not in self.other_pages:\n self.other_pages.append(pages.group(1))\n except KeyError:\n pass\n\n def do_td(self, attr):\n \"\"\"<td> tags give us number of leechers in inner text and can signal torrent size in child <a> tag OR directly in inner text.\"\"\"\n params = dict(attr)\n try:\n if 'tor-size' in params['class']:\n self.current_item['size'] = True\n elif 'leechmed' in params['class']:\n self.current_item['leech'] = True\n except KeyError:\n pass\n\n def do_b(self, attr):\n \"\"\"<b class=\"seedmed\"> give us number of seeders in inner text.\"\"\"\n params = dict(attr)\n try:\n if 'seedmed' in params['class']:\n self.current_item['seeds'] = True\n except KeyError:\n pass\n\n def search(self, what, start=0):\n \"\"\"Search for what starting on specified page. Defaults to first page of results.\"\"\"\n logging.debug(\"parse_search({}, {})\".format(what, start))\n \n # If we're on first page of results, we'll try to find other pages\n if start == 0:\n self.first_page = True\n else:\n self.first_page = False\n \n try:\n response = self.engine.opener.open('{}?nm={}&start={}'.format(self.engine.search_url, quote(what), start))\n # Only continue if response status is OK.\n if response.getcode() != 200:\n raise HTTPError(response.geturl(), response.getcode(), \"HTTP request to {} failed with status: {}\".format(self.engine.search_url, response.getcode()), response.info(), None)\n except (URLError, HTTPError) as e:\n logging.error(e)\n raise e\n \n # Decode data and feed it to parser\n data = response.read().decode('cp1251')\n self.feed(data)\n\n def search(self, what, cat='all'):\n \"\"\"Search for what on the search engine.\"\"\"\n # Instantiate parser\n self.parser = self.Parser(self)\n \n # Decode search string\n what = unquote(what)\n logging.info(\"Searching for {}...\".format(what))\n \n # Search on first page.\n logging.info(\"Parsing page 1.\")\n self.parser.search(what)\n \n # If multiple pages of results have been found, repeat search for each page.\n logging.info(\"{} pages of results found.\".format(len(self.parser.other_pages)+1))\n for start in self.parser.other_pages:\n logging.info(\"Parsing page {}.\".format(int(start)//50+1))\n self.parser.search(what, start)\n \n # PrettyPrint each torrent found, ordered by most seeds\n self.parser.results.sort(key=lambda torrent:torrent['seeds'], reverse=True)\n for torrent in self.parser.results:\n torrent['engine_url'] = 'https://rutracker.org' # Kludge, see #15\n if __name__ != \"__main__\": # This is just to avoid printing when I debug.\n prettyPrinter(torrent)\n \n self.parser.close()\n logging.info(\"{} torrents found.\".format(len(self.parser.results)))\n\n# For testing purposes.\nif __name__ == \"__main__\":\n engine = rutracker()\n engine.search('lazerhawk')\n engine.download_torrent('https://rutracker.org/forum/dl.php?t=4578927')\n" }, { "alpha_fraction": 0.6742067337036133, "alphanum_fraction": 0.7298146486282349, "avg_line_length": 80.64102935791016, "blob_id": "39797963f7a43e71d74402b45bfbd90a109170e8", "content_id": "ee2d563587eb3d845218aaa11800b9fc70165824", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3183, "license_type": "permissive", "max_line_length": 495, "num_lines": 39, "path": "/README.md", "repo_name": "Skymirrh/qBittorrent-rutracker-plugin", "src_encoding": "UTF-8", "text": "qBittorrent RuTracker plugin\n===============================\n\nqBittorrent search engine plugin for RuTracker. In case [rutracker.org](https://rutracker.org) is DNS blocked, the plugin will try to reach [official RuTracker mirrors](http://rutracker.wiki/%D0%A7%D1%82%D0%BE_%D0%B4%D0%B5%D0%BB%D0%B0%D1%82%D1%8C,_%D0%B5%D1%81%D0%BB%D0%B8_%D0%B2%D0%B0%D0%BC_%D0%B7%D0%B0%D0%B1%D0%BB%D0%BE%D0%BA%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD_%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF_%D0%BD%D0%B0_rutracker.org#.D0.97.D0.B5.D1.80.D0.BA.D0.B0.D0.BB.D0.B0_rutracker.org) instead.\n\nNothing fancy, it follows the [writing plugin guide recommandations](https://github.com/qbittorrent/search-plugins/wiki/How-to-write-a-search-plugin).\n\nInstallation\n------------\n* [Download the latest release.](https://github.com/Skymirrh/qBittorrent-RuTracker-plugin/releases/latest)\n* Edit `rutracker.py` by replacing `YOUR_USERNAME_HERE` and `YOUR_PASSWORD_HERE` with your RuTracker username and password.\n* Move `rutracker.py` and `rutracker.png` to qBittorrent search engines directory:\n * Windows: `%localappdata%\\qBittorrent\\nova3\\engines\\`\n * Linux: `~/.local/share/data/qBittorrent/nova3/engines/`\n * OS X: `~/Library/Application Support/qBittorrent/nova3/engines/`\n * *Note: If you use Python 2 instead of Python 3, replace `nova3` with `nova`.*\n* RuTracker search engine should now be available in qBittorrent.\n\nTroubleshooting\n---------------\nIf you get no results from RuTracker when you search something, please:\n * Check that at least one mirror from the list of [official RuTracker mirrors](http://rutracker.wiki/%D0%A7%D1%82%D0%BE_%D0%B4%D0%B5%D0%BB%D0%B0%D1%82%D1%8C,_%D0%B5%D1%81%D0%BB%D0%B8_%D0%B2%D0%B0%D0%BC_%D0%B7%D0%B0%D0%B1%D0%BB%D0%BE%D0%BA%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD_%D0%B4%D0%BE%D1%81%D1%82%D1%83%D0%BF_%D0%BD%D0%B0_rutracker.org#.D0.97.D0.B5.D1.80.D0.BA.D0.B0.D0.BB.D0.B0_rutracker.org) is working.\n * Check that you are not captcha-blocked (try to manually connect to the website: after logging in once, the captcha will disappear and the script will work).\n * Check that the script credentials are correct (try to manually connect to the website by copy/pasting username and password from `rutracker.py`).\n * If it still does not work, follow the steps for reporting a bug below.\n\nBug reporting\n-------------\n* Find your qBittorrent version (see qBittorrent title bar).\n* Find your Python version (run `python --version` from command prompt).\n* Navigate to qBittorrent search engines directory:\n * Windows: `%localappdata%\\qBittorrent\\nova3\\engines\\`\n * Linux: `~/.local/share/data/qBittorrent/nova3/engines/`\n * OS X: `~/Library/Application Support/qBittorrent/nova3/engines/`\n * *Note: If you use Python 2 instead of Python 3, replace `nova3` with `nova`.*\n* Edit `rutracker.py` and replace `logger.setLevel(logging.WARNING)` with `logger.setLevel(logging.INFO)`.\n* Move to parent directory (`cd ..` or manual browsing to `nova3`).\n* From the `nova3` directory, run `python nova2.py rutracker all archlinux` in a command prompt.\n* [Create a new issue](https://github.com/Skymirrh/qBittorrent-RuTracker-plugin/issues/new) and fill out the form with the information above." } ]
3
gagands/RecommendationSystem
https://github.com/gagands/RecommendationSystem
18ff952b9d8679d169f83187317e96430b39b3de
6a1b4c475db91ee9b8129fe05fe18876dcfc2b75
7e8c3c64b4aad68b3c3eb7139cb66b80826bcf92
refs/heads/master
2020-07-27T13:19:43.582572
2019-12-17T16:50:04
2019-12-17T16:50:04
209,103,539
2
0
null
2019-09-17T16:27:13
2019-11-05T03:12:13
2019-11-05T03:15:01
Python
[ { "alpha_fraction": 0.6256809234619141, "alphanum_fraction": 0.6295719742774963, "avg_line_length": 27.577777862548828, "blob_id": "f9ddf62233de3c1dc640d68b64ca8fa6b40b139f", "content_id": "962d7f2ccfd8ba200d53de910c49050a82c81b4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1285, "license_type": "no_license", "max_line_length": 77, "num_lines": 45, "path": "/import_all_data_to_csv.py", "repo_name": "gagands/RecommendationSystem", "src_encoding": "UTF-8", "text": "# # This file will import all data from firebase and convert to different csv\n# #\n#\n#\n# from google.cloud import firestore\n# from langdetect import detect\n# from langdetect import DetectorFactory\n# from langdetect.lang_detect_exception import LangDetectException\n#\n# DetectorFactory.seed = 0\n#\n# db = firestore.Client(\"poetry-dev\")\n# items_ref = db.collection(u'items')\n# items = items_ref.get()\n#\n# result_csv_file = open(\"detected_languages.csv\", \"w\")\n# error_csv_file = open(\"errors.csv\", \"w\")\n# result_csv_file.write(\"\")\n#\n# for item in items:\n# poem_body = item.get(\"body\")\n# body = poem_body\n# # print(item.get('body'))\n# # print(body[0:100])\n#\n# try:\n# detected_lang = detect(body)\n# result_csv_file.write(item.get(\"itemId\"))\n# result_csv_file.write(', ')\n# result_csv_file.write(detected_lang)\n# result_csv_file.write(', ')\n# result_csv_file.write(item.get(\"language\"))\n# # result_csv_file.write(item.get('body'))\n# result_csv_file.write(\"\\n \")\n#\n#\n# except LangDetectException as e:\n#\n# error_csv_file.write(body)\n# error_csv_file.write(\", \")\n# # error_csv_file.write(\"LangDetectException\" + e.message)\n# error_csv_file.write(\"\\n\")\n#\n# except Exception as e:\n# print(e)" }, { "alpha_fraction": 0.6771300435066223, "alphanum_fraction": 0.6771300435066223, "avg_line_length": 34.26315689086914, "blob_id": "f0acc0c1d3b069cafa2bb25cad6e87b5381fcec9", "content_id": "d963700457e32368aea23db7c458a8ee1d4ae3bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 669, "license_type": "no_license", "max_line_length": 115, "num_lines": 19, "path": "/detecting_unique_languages.py", "repo_name": "gagands/RecommendationSystem", "src_encoding": "UTF-8", "text": "# detects no. of poems of user's choice from detected_languages.csv\n# add _CountryCode in the end of language\n#\n\nimport pandas as pd\n\ncol_names = ['poemId', 'detected_lang', 'user_lang']\ndf = pd.read_csv(\"detected_languages.csv\", sep=', ', header=None, names=col_names)\n\n# df = df.groupby('detected_lang').nunique()\n# print (df)\n\n\nen_only = df[df.detected_lang == 'hi'] # enter language to be detected in ''\nen_only['detected_lang'] = en_only['detected_lang'].astype(str) + '_IN' # for adding _CountryCode with 'language'\n\nen_only.to_csv(r'hindi_poems.csv') # create the csv named 'language'_poems.csv\nprint (df['detected_lang'].unique())\nprint (en_only)" }, { "alpha_fraction": 0.6814159154891968, "alphanum_fraction": 0.682300865650177, "avg_line_length": 26.560976028442383, "blob_id": "6cbb14badea21ee03449167b4cedec361fb5afb4", "content_id": "2658c4d15f8a152a6ad90dde2f9aa7e3f06eac25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1130, "license_type": "no_license", "max_line_length": 82, "num_lines": 41, "path": "/detect_all_lang.py", "repo_name": "gagands/RecommendationSystem", "src_encoding": "UTF-8", "text": "# runs on the fire-store database and fetches languages of all poems to a csv file\n\nfrom google.cloud import firestore\nfrom langdetect import detect\nfrom langdetect import DetectorFactory\nfrom langdetect.lang_detect_exception import LangDetectException\n\nDetectorFactory.seed = 0\n\ndb = firestore.Client(\"poetry-dev\")\nitems_ref = db.collection(u'items')\nitems = items_ref.get()\n\nresult_csv_file = open(\"detected_languages.csv\", \"w\")\nerror_csv_file = open(\"errors.csv\", \"w\")\nresult_csv_file.write(\"\")\n\nfor item in items:\n poem_body = item.get(\"body\")\n body = poem_body\n # print(item.get('body'))\n\n try:\n detected_lang = detect(body)\n result_csv_file.write(item.get(\"itemId\"))\n result_csv_file.write(', ')\n result_csv_file.write(detected_lang)\n result_csv_file.write(', ')\n result_csv_file.write(item.get(\"language\"))\n result_csv_file.write(\"\\n \")\n\n\n except LangDetectException as e:\n\n error_csv_file.write(body)\n error_csv_file.write(\", \")\n error_csv_file.write(\"LangDetectException\" + e.message)\n error_csv_file.write(\"\\n\")\n\n except Exception as e:\n print(e)\n" }, { "alpha_fraction": 0.646616518497467, "alphanum_fraction": 0.6574770212173462, "avg_line_length": 29.69230842590332, "blob_id": "bf59d095dba758a29c673e12d96b1a1bfe5c19fd", "content_id": "3d9f390f492e54c95ed0fa28581c101bf148eca1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1197, "license_type": "no_license", "max_line_length": 121, "num_lines": 39, "path": "/update_poem_language.py", "repo_name": "gagands/RecommendationSystem", "src_encoding": "UTF-8", "text": "# This file is for testing code before implementing on large scale\nfrom google.cloud import firestore\nimport pandas as pd\n\ndb = firestore.Client(\"poetry-dev\")\nitems_ref = db.collection(u'items')\nitems = items_ref.get()\n\n\n# for testing by updating single poems\ndef batch_update_single_poem():\n batch = db.batch()\n poem_id = '-KSiT_YxIuwCU7bE4ZQN'\n candidate_poem_ref = items_ref.document(poem_id)\n lang = unicode('en_US')\n batch.update(candidate_poem_ref, {u\"language\": lang})\n batch.commit()\n\n\n# for updating the whole lot\n\n# df = pd.read_csv('hindi_poems.csv') # change the file to language you want to update\n# sliced_df = df.loc[6500:6999] # only 500 commits in one go\n# print (sliced_df)\n\n# def batch_update_en_US():\n# batch = db.batch()\n# for i in sliced_df.index:\n# poem_id = sliced_df['poemId'][i]\n# candidate_poem = items_ref.document(poem_id)\n# lang = unicode(sliced_df['detected_lang'][i]) #unicode prevents 'lang_country' from turning to blog object\n# print (poem_id, lang)\n# batch.update(candidate_poem, {u\"language\": lang})\n#\n# batch.commit()\n\n\n# batch_update_en_US()\nbatch_update_single_poem()\n" } ]
4
RaphiJS6-13/JS-and-Ruby-projects
https://github.com/RaphiJS6-13/JS-and-Ruby-projects
c676b21991740dfcf7639cbc1bb781c564960452
df93935d3aa0ca48ff3c9a483d575403b967c9cb
305bd06f92b8c185ae2ececfa8d376a242eaa19f
refs/heads/master
2020-07-02T09:50:36.342636
2020-05-22T18:54:11
2020-05-22T18:54:11
201,492,529
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3761163651943207, "alphanum_fraction": 0.376881867647171, "avg_line_length": 29.13846206665039, "blob_id": "65093e68463dc4d25d0c5caa6f5fa025b81e69c2", "content_id": "7c364182893499465f6e8715ad993e8ed91f5aa6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 3919, "license_type": "no_license", "max_line_length": 114, "num_lines": 130, "path": "/ES6class.js", "repo_name": "RaphiJS6-13/JS-and-Ruby-projects", "src_encoding": "UTF-8", "text": "\nfunction Class(struct) {\n this.vars = {};\n this.getters = [];\n this.setters = [];\n struct.forEach(function(item){\n if (\"init\" in item)\n {\n if (Object.keys(item).length > 1) {\n delete item.init;\n throw new SyntaxError('Unexpected excess key-value pair(s) \"' + String(Object.keys(item)) + '\".');\n }\n this.base = item.init;\n }\n else if (\"extends\" in item)\n {\n this.extend = item.extends;\n }\n else if (\"get\" in item) {\n this.getters.push(item);\n }\n else if (\"set\" in item) {\n this.setters.push(item);\n }\n else if (\"private\" in item)\n {\n if (\"equals\" in item) {\n this.vars[item.private] = {private: item.equals};\n }\n else {\n this.vars[item.private] = {private: undefined};\n }\n }\n else if (\"public\" in item)\n {\n if (\"equals\" in item) {\n this.vars[item.public] = {public: item.equals};\n }\n else {\n this.vars[item.public] = {public: undefined};\n }\n }\n });\n \n var base;\n if (this.base) {\n base = this.base;\n }\n else\n base = function() {};\n var extend = this.extend;\n var vars = this.vars;\n var setters = this.setters;\n var getters = this.getters;\n function klass() {\n var self = vars;\n function setter(key) {\n return function(item) {\n self[key] = item;\n };\n }\n function getter(key) {\n return function() {\n return self[key];\n };\n }\n for(var key in self) {\n if (\"public\" in self[key] ) {\n self[key] = self[key].public;\n Object.defineProperty(this, key, {\n get: getter(key),\n set: setter(key)\n });\n this[key] = self[key];\n }\n else {\n self[key] = self[key].private;\n if (typeof self[key] === \"function\") {\n (function(){\n var x = {};\n Object.defineProperty(x, key, {\n value: self[key]\n });\n \n })();\n }\n }\n }\n var bigger = getters.length > setters.length ? getters.length : setters.length;\n for(var i = 0; i < bigger; i++) {\n var g_now = getters[i];\n var s_now = setters[i];\n if (s_now && g_now && g_now.get === s_now.set){\n Object.defineProperty(this, g_now.get, {\n get: function() {\n return g_now.do(self);\n },\n set: function(item) {\n return s_now.do(self, item);\n }\n });\n }\n else {\n if (g_now) {\n Object.defineProperty(this, g_now.get, {\n get: function() {\n return g_now.do(self);\n }\n });\n }\n if (s_now) {\n Object.defineProperty(this, s_now.set, {\n set: function(item) {\n s_now.do(self, item);\n }\n });\n }\n }\n }\n if (extend) {\n base.prototype = extend.prototype;\n console.log(Object.keys(new base()));\n }\n var arr = [self];\n for(var k = 0; arguments[k] != undefined; k++) {\n arr.push(arguments[k]);\n }\n base.apply(this, arr);\n }\n return klass;\n}\n" }, { "alpha_fraction": 0.6631243228912354, "alphanum_fraction": 0.678002119064331, "avg_line_length": 21.404762268066406, "blob_id": "af241623339d997489639fd484dd4def4a459828", "content_id": "194ec2874a2e6e01bdfdb1dfabd16b43d3354c90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Ruby", "length_bytes": 941, "license_type": "no_license", "max_line_length": 70, "num_lines": 42, "path": "/RubyFileVirus.rb", "repo_name": "RaphiJS6-13/JS-and-Ruby-projects", "src_encoding": "UTF-8", "text": "class Virus\n\tdef initialize\n\t\t@num = 1\n\tend\n\tprivate\n\t#Generate file names\n\tdef gen i\n\t\tstr = []\n\t\tchars = \"abcdefghijklmnopqrstuvwxyz0123456789_\"\n\t\twhile i > 0\n\t\t\tstr << char[i % char.length].chr\n\t\t\ti /= chars.length\n\t\tend\n\t\treturn str.reverse\n\tend\n\t#Change the file names\n\tdef genFileNames\n\t\t@x = self.gen(@num).join()\n\t\t@num += 1\n\t\treturn @x\n\tend\n\tpublic\n\t#Exhaust the memory by creating tons of files that execute themselves\n\tdef spread!\n\t#Get file Name: see line #7\n\t\tname = self.genFileNames\n\t\t#Create a file with e generated name\n\t\tstart = File.new(\"#{name}.txt\", \"w+\")\n\t\t#Set the file content to an assignment to do the whole thing again\n\t\tstart.puts(\"x = Virus.new\")\n\t\tstart.puts(\"x.spread!\")\n\t\t#Read the file\n\t\trecur = File.read(\"#{name}.txt\")\n\t\t# - Execute it\n\t\t# - Doesn't close the files,\n\t\t#\tfor the enhancement of the de-enhancement of the computer's memory\n\t\teval recur\n\tend\nend\n#AND START IT UP!\nrun = Virus.new\nrun.spread!\n" }, { "alpha_fraction": 0.5416316390037537, "alphanum_fraction": 0.5525651574134827, "avg_line_length": 28.177913665771484, "blob_id": "d603d007576e7314e642eaf7330bfc05eb4cf58d", "content_id": "4d98a4d523ca6a68a15d39fb396a6e6ced7edf7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4756, "license_type": "no_license", "max_line_length": 96, "num_lines": 163, "path": "/calc.py", "repo_name": "RaphiJS6-13/JS-and-Ruby-projects", "src_encoding": "UTF-8", "text": "from re import search as re_test\nfrom re import match, sub\nfrom decimal import Decimal\n\nclass ParseError(SyntaxError):\n pass\n\ndef tokenize(code: str):\n code = code + \" \"\n output: [{str: str}] = []\n token: {str: str} = {}\n nested: int = 0\n column: int = 1\n for i in range(0, len(code)):\n c = code[i]\n if c == '(':\n if token != {}:\n output.append(token)\n nested += 1\n output.append({'column': column, 'type': 'group', 'value': '('})\n token = {}\n elif c == ')':\n if token != {}:\n output.append(token)\n if nested == 0:\n raise ParseError(f\"column {column}: unexpected token ')'\")\n output.append({'column': column, 'type': 'group', 'value': ')'})\n nested -= 1\n token = {}\n elif re_test(r'[\\d\\.]', c) or (c in '+-' and re_test(r'\\d', code[i+1])):\n if token != {}:\n token['value'] += c\n else:\n token = {'column': column, 'type': 'num', 'value': c}\n elif re_test(r'\\s', c):\n if token != {}:\n output.append(token)\n token = {}\n elif c in '+-*/':\n if token != {}:\n output.append(token)\n output.append({'column': column, 'type': 'op', 'value': c})\n token = {}\n else:\n raise ParseError(f\"column {column}: unexpected token '{c}'\")\n column += 1\n\n if nested != 0:\n raise ParseError(f\"column {len(code)}: unmatched '('\")\n return output\n\nclass Op:\n def __init__(self, kind: str, column: int):\n self.__kind = kind\n self.__col = column\n self.right = None\n self.left = None\n @property\n def kind(self) -> str:\n return self.__kind\n @property\n def column(self) -> int:\n return self.__col\n def __str__(self):\n l = self.left\n r = self.right\n if isinstance(l, dict):\n l = l['value']\n if isinstance(r, dict):\n r = r['value']\n return f\"({self.__kind} {l} {r})\"\n \ndef AST(tokens) -> list:\n while True:\n end_paren: int = None\n for i in range(0, len(tokens)):\n if isinstance(tokens[i],dict) and tokens[i]['value'] == ')':\n end_paren = i\n break\n if end_paren == None:\n break\n start_paren = end_paren\n while True:\n now = tokens[start_paren]\n if (not isinstance(now, Op))\\\n and now['value'] == '(':\n break\n start_paren -= 1\n prologue = tokens[0:start_paren]\n epilogue = tokens[end_paren+1:]\n section = tokens[start_paren+1: end_paren]\n if len(section) != 1:\n section = AST(section)\n \n tokens = prologue + section + epilogue\n\n if len(tokens) == 1:\n return tokens\n elif len(tokens) == 2:\n if isinstance(tokens[0], dict) and tokens[0]['type'] == 'op':\n raise ParseError(f\"column {tokens[0]['column']}: unexpected token '{tokens[0]['value']}'\")\n else:\n raise ParseError(f\"column {tokens[1]['column']}: unexpected token '{tokens[1]['value']}'\")\n elif len(tokens) == 3:\n ret = Op(tokens[1]['value'],\\\n tokens[1]['column'])\n if not isinstance(tokens[0], Op):\n tokens[0]['value'] = \\\n Decimal(tokens[0]['value'])\n if not isinstance(tokens[2], Op):\n tokens[2]['value'] =\\\n Decimal(tokens[2]['value'])\n ret.left = tokens[0]\n ret.right = tokens[2]\n return [ret]\n else:\n for x in (tokens[0], tokens[2]):\n if not (isinstance(x, Op) or x['type'] == 'num'):\n raise ParseError(f\"column {x.column}: unexpected token '{x.value}'\")\n for x in (tokens[1], tokens[3]):\n if isinstance(x, Op) or x['type'] == 'num':\n raise ParseError(f\"column {x.column}: unexpected token '{x.value}'\")\n \n if '*/+-'.index(tokens[1]['value']) < '*/+-'.index(tokens[3]['value']):\n first = AST(tokens[0:3])\n return AST(first + tokens[3:])\n else:\n middle = AST(tokens[2:5])\n return AST(tokens[0:2] + middle + tokens[5:])\ndef evaluate(code):\n if isinstance(code, dict):\n return code['value']\n if isinstance(code.left, Op):\n code.left = evaluate(code.left)\n if isinstance(code.right, Op):\n code.right = evaluate(code.right)\n if isinstance(code.left, dict):\n code.left = code.left['value']\n if isinstance(code.right, dict):\n code.right = code.right['value']\n if code.kind == '+':\n return code.left + code.right\n elif code.kind == '-':\n return code.left - code.right\n elif code.kind == '*':\n return code.left * code.right\n else:\n return code.left / code.right\n\nwhile True:\n try:\n text = input()\n if text.strip() == '':\n continue\n print(evaluate(AST(tokenize(text))[0]))\n except EOFError: pass\n except ParseError as e:\n msg = sub(r\"column \\d+: \", \"\", str(e))\n print(f\"error: {msg}\")\n col = int(match(r'column (\\d+)', str(e)).group(1))\n part = (len(str(e)) - 2) - str(e).index(\"'\")\n print(text)\n print((\" \" * (col-1)) + ('~' * part))\n" } ]
3
redwingsdan/python-tests
https://github.com/redwingsdan/python-tests
e405dfcc8b0e63536938b5d97ed95ae006dd9753
5c2313fff5ef94b5c179fe22e3c4dba0185b986d
813d52150d9875eb988f747db317b51232f68020
refs/heads/master
2022-11-28T20:18:44.747831
2020-08-04T04:39:40
2020-08-04T04:39:40
284,878,652
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.554347813129425, "alphanum_fraction": 0.5652173757553101, "avg_line_length": 29.75, "blob_id": "013484635dc05ebfac74753b52112bfee314d4d0", "content_id": "9126b990b33a3c686ccf55e9cef54cdcfbef7411", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 368, "license_type": "no_license", "max_line_length": 59, "num_lines": 12, "path": "/diceroll.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "import random\n\ndef start_dice_roll():\n min = 1\n max = 6\n roll_again = 'yes'\n while roll_again == 'y' or roll_again == 'yes':\n diceroll = random.randint(min, max)\n print('Roll 1: ' + str(diceroll))\n diceroll = random.randint(min, max)\n print('Roll 2: ' + str(diceroll))\n roll_again = input('Roll the dice again? ').lower()" }, { "alpha_fraction": 0.7651991844177246, "alphanum_fraction": 0.7735849022865295, "avg_line_length": 42.45454406738281, "blob_id": "9ac9060294a6f5db01a9ae92b3cfd46a1bea1b04", "content_id": "a94cad7e440a8df2fa3e2e6852bddbee78aa1caa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 477, "license_type": "no_license", "max_line_length": 105, "num_lines": 11, "path": "/filemanipulation.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "import os\nimport shutil\n#w = write permissions (create if not exists)\n#r = read permissions\n#a = append to end of file\nmyFile = open('filemanipulationtest.txt', 'w+')\nmyFile.write('This is a test string')\nmyFile.close()\nos.rename('D:/Python/filemanipulationtest.txt', 'D:/Python/filedir1/filemanipulationtest.txt')\nshutil.move('D:/Python/filedir1/filemanipulationtest.txt', 'D:/Python/filedir2/filemanipulationtest.txt')\nos.remove('D:/Python/filedir2/filemanipulationtest.txt')" }, { "alpha_fraction": 0.616797924041748, "alphanum_fraction": 0.6469816565513611, "avg_line_length": 28.346153259277344, "blob_id": "24b1dd3001573805d699d48f2487179db6389b78", "content_id": "e92e78aafd35071095a16e0aefab4f48ecd81953", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 762, "license_type": "no_license", "max_line_length": 54, "num_lines": 26, "path": "/passwordgenerator.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "import random\n\ndef shuffle(string):\n tempPass = list(string)\n random.shuffle(tempPass)\n return ''.join(tempPass)\n \ndef generate_char():\n number = random.randint(0,3)\n if number == 0:\n return chr(random.randint(65,90)) #uppercase\n elif number == 1:\n return chr(random.randint(97,122)) #lowercase\n elif number == 2:\n return chr(random.randint(48,57)) #digit\n else:\n return chr(random.randint(33,64)) #punctuation\n\ndef start_password_generation(total_characters):\n password = ''\n if not total_characters.isdigit():\n total_characters = 8\n for num in range(int(total_characters)):\n password += generate_char()\n password = shuffle(password)\n print('Generated password is: ' + password)" }, { "alpha_fraction": 0.64897221326828, "alphanum_fraction": 0.6634289622306824, "avg_line_length": 44.64948272705078, "blob_id": "bb88c0758062c206859406a9fc27e78c1bffd2b6", "content_id": "cbd23f5a0ba2aea7f4e1268677f2c35f42b2c896", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4427, "license_type": "no_license", "max_line_length": 212, "num_lines": 97, "path": "/cryptochallenge.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "import codecs\nfrom binascii import hexlify, unhexlify\n\nclass InvalidMessageException(Exception):\n pass\n\n#read in a file name and return the contents as a string\ndef read_file_data(file_name):\n file = open(file_name, 'r')\n return file.read()\n#decode the hex string data into bytes (equivalent to unhexlify)\ndef convert_hex_str_to_bytes(hex_str):\n return codecs.decode(hex_str, 'hex')\n#decode the hex data, then encode it into the base64 format, and then decode into a string\ndef hex_to_base_64(hex_data):\n return codecs.encode(convert_hex_str_to_bytes(hex_data), 'base64').decode()\n#iterate through each character in the 2 byte arrays and xor them with each other\ndef xor_bytes(input_bytes1, input_bytes2):\n return bytes([byte1 ^ byte2 for (byte1, byte2) in zip(input_bytes1, input_bytes2)])\n#return the matched xor data for a given encrypted hex value\ndef find_best_xor_match(data_hex):\n best_match = None\n ascii_text_chars = list(range(97, 122)) + [32] #determine a list of ascii characters to match\n #iterate through all 255 ascii characters for the encrpytion\n for i in range(1,255):\n xor_key = bytes([i]) #create a key from the character\n xor_key_str = xor_key * len(data_hex) #match the key length with the hex text\n xor_byte_data = xor_bytes(data_hex, xor_key_str) #xor the key with the hex text\n number_letters = sum([x in ascii_text_chars for x in xor_byte_data]) #score the resulting data by totaling the matching ascii characters (more ascii characters means likely a more readable string of text)\n #Use the best scored data for the guess\n if best_match == None or number_letters > best_match['number_letters']:\n best_match = {'message': xor_byte_data, 'number_letters': number_letters, 'key': xor_key}\n #Ensure the best answer is at least 70% readable, otherwise throw an exception\n if best_match['number_letters'] > 0.7*len(data_hex):\n return best_match\n else:\n raise InvalidMessageException('Best candidate message is: %s' % best_match['message'])\n \ndef challenge_1():\n file_data = read_file_data('hextext.txt')\n base_64_data = hex_to_base_64(file_data)\n print(base_64_data)\n \ndef challenge_2():\n file_data_1 = read_file_data('hextext2a.txt')\n file_data_2 = read_file_data('hextext2b.txt')\n data_1_hex = convert_hex_str_to_bytes(file_data_1)\n data_2_hex = convert_hex_str_to_bytes(file_data_2)\n xor_byte_data = xor_bytes(data_1_hex, data_2_hex)\n print(xor_byte_data.hex())\n \ndef challenge_3():\n file_data = read_file_data('hextext3.txt')\n data_hex = convert_hex_str_to_bytes(file_data)\n best_match = find_best_xor_match(data_hex)\n print('message: ' + str(best_match['message']))\n print('letters: ' + str(best_match['number_letters']))\n print('key: ' + str(best_match['key']))\n \ndef challenge_4():\n data_list = []\n #Iterate through each line of a file and convert the values from hex and add them to the list\n with open('hextext4.txt') as file_content:\n for line in file_content:\n data_list.append(convert_hex_str_to_bytes(line.strip()))\n possible_matches = list()\n #Iterate through each data line and try to find a valid xor match\n #Non-valid matches will throw an exception (since they weren't encrypted)\n for (line_number, text) in enumerate(data_list):\n try:\n best_match_message = find_best_xor_match(text)['message']\n except InvalidMessageException:\n pass\n else:\n possible_matches.append({\n 'line_number': line_number,\n 'original_text': text,\n 'message': best_match_message\n })\n if len(possible_matches) > 1:\n print(\"Error: more than one match\")\n else:\n #Print the object formatted as key: value\n for (key, value) in possible_matches[0].items():\n print(f'{key}: {value}')\n\ndef challenge_5():\n file_data = read_file_data('hextext5.txt')\n #Convert file data and key to bytes\n byte_data = bytes(file_data, 'utf8')\n xor_key = bytes('ICE', 'utf8')\n #get the xor to match at least the length of the message\n xor_key_str = xor_key*(len(byte_data)//len(xor_key) + 1) #message length / key length without remainder + 1 \n xor_byte_data = xor_bytes(byte_data, xor_key_str) #xor the key with the hex text\n print(xor_byte_data.hex())\n \nchallenge_5()" }, { "alpha_fraction": 0.48051947355270386, "alphanum_fraction": 0.5532467365264893, "avg_line_length": 19.3157901763916, "blob_id": "f3e543768a820586992b822412a74718f4e8c4a7", "content_id": "f64af8750aa5f887fd565534108edfd42e90e727", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/fixedvsfloatingdecimals.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "def rec(y, z):\n return 108 - ((815-1500/z)/y)\n \ndef floatpt(N):\n x = [4, 4.25]\n for i in range(2, N+1):\n x.append(rec(x[i-1], x[i-2]))\n return x\n \ndef fixedpt(N):\n x = [Decimal(4), Decimal(17)/Decimal(4)]\n for i in range(2, N+1):\n x.append(rec(x[i-1], x[i-2]))\n return x\nN = 20 \nflt = floatpt(N)\nfxd = fixedpt(N)\nfor i in range(N):\n print str(i) + ' | '+str(flt[i])+' | '+str(fxd[i])" }, { "alpha_fraction": 0.6925418376922607, "alphanum_fraction": 0.7077625393867493, "avg_line_length": 25.31999969482422, "blob_id": "40263204c79d8e79ab1f0c484d10fe986b2d637c", "content_id": "d7897e197dd1a8951257e9f84469c47df7dcf3c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 657, "license_type": "no_license", "max_line_length": 75, "num_lines": 25, "path": "/menu.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "import numbergame\nimport rockpaperscissors\nimport passwordgenerator\nimport diceroll\nimport ciphers\n\nselection = input(\"Select Program:\\n\" +\n\"1. Number Guessing\\n\" +\n\"2. Rock, Paper, Scissors\\n\" + \n\"3. Password Generator\\n\" + \n\"4. Dice Rolling\\n\" + \n\"5. Ciphers\\n\" + \n\"\")\nif selection == str(1):\n numbergame.start_number_game()\nelif selection == str(2):\n rockpaperscissors.start_rock_paper_scissors_game()\nelif selection == str(3):\n passwordgenerator.start_password_generation(input('Password Length: '))\nelif selection == str(4):\n diceroll.start_dice_roll()\nelif selection == str(5):\n ciphers.convert_cipher()\nelse:\n print('Invalid input')" }, { "alpha_fraction": 0.5267422795295715, "alphanum_fraction": 0.5364667773246765, "avg_line_length": 23.719999313354492, "blob_id": "6443a7929bb329aa71ec19c94dee5265b875ecf0", "content_id": "521c20e74d104c68dd16f83806e1b0fc26dec50d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 67, "num_lines": 25, "path": "/numbergame.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "import random\n\ndef start_number_game():\n number = random.randint(1, 10)\n\n user_name = input('What is your name?')\n\n number_guesses = 0;\n\n print('Alright, ' + user_name + ' I guessed a number: ')\n\n while number_guesses < 5:\n guess = int(input())\n number_guesses += 1\n if guess < number:\n print('Too low!')\n if guess > number:\n print('Too high!')\n if guess == number:\n break\n\n if guess == number:\n print('YOU GOT IT! Took ' + str(number_guesses) + ' tries')\n else:\n print('YOU FAILED! The number was ' + str(number))" }, { "alpha_fraction": 0.5500505566596985, "alphanum_fraction": 0.5652173757553101, "avg_line_length": 28.939393997192383, "blob_id": "6f068e0958616f197295fc0135fe240a0b2cc67b", "content_id": "a89550af449066297ed0e4aefa700b3c5a15cc22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 989, "license_type": "no_license", "max_line_length": 78, "num_lines": 33, "path": "/ciphers.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "\ndef convert_cipher():\n type = input('What type of cipher? ')\n if type == 'b':\n convert_binary_cipher()\n elif type == 'u':\n convert_unicode_cipher()\n else:\n print('Cipher type not supported')\n \ndef convert_binary_cipher():\n file_content = open('cipher1.txt', 'r')\n result_text = ''\n ascii_value = 0\n multVal = 128\n while 1:\n binary_character = file_content.read(1)\n if not binary_character:\n break\n ascii_value += int(binary_character) * int(multVal)\n if multVal == 1:\n result_text += chr(ascii_value)\n multVal = 128\n ascii_value = 0\n else:\n multVal /= 2\n print('Decoded Text: ' + result_text)\n file_content.close() \n\ndef convert_unicode_cipher():\n file_content = open('cipher2.txt', 'r')\n result_text = file_content.read().encode('utf-8').decode('unicode-escape')\n print('Decoded Text: ' + result_text)\n file_content.close() " }, { "alpha_fraction": 0.5975460410118103, "alphanum_fraction": 0.6049079895019531, "avg_line_length": 37.83333206176758, "blob_id": "dd01d23461342ea67b88ec749fc1606ce275d4a0", "content_id": "a3e0395baf6a0fa080a5795ffa7ca42f78bdcfa1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1630, "license_type": "no_license", "max_line_length": 132, "num_lines": 42, "path": "/rockpaperscissors.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "from random import randint\n\ndef compare_selections(choices, choice_names, player_selection, ai_selection, total_wins, total_losses):\n player_index = choices.index(player_selection)\n ai_index = choices.index(ai_selection)\n is_player_win = (player_index > ai_index or (player_index == 0 and ai_index == 2)) and not (player_index == 2 and ai_index == 0)\n if is_player_win:\n print('You win! ' + choice_names[player_index] + ' beats ' + choice_names[ai_index])\n else:\n print('You lose! ' + choice_names[ai_index] + ' beats ' + choice_names[player_index])\n return is_player_win\n\ndef start_rock_paper_scissors_game():\n\n choices = ['r', 'p', 's']\n \n choice_names = ['Rock', 'Paper', 'Scissors']\n\n ai_selection = choices[randint(0,2)]\n\n player_selection = None\n \n total_wins = 0\n total_losses = 0\n\n while player_selection == None:\n player_selection = input(\"Rock, Paper, Scissors? \").lower()\n if player_selection == ai_selection:\n player_index = choices.index(player_selection)\n print('Both played ' + choice_names[player_index])\n elif player_selection in choices:\n is_win = compare_selections(choices, choice_names, player_selection, ai_selection, total_wins, total_losses)\n if is_win:\n total_wins += 1\n else:\n total_losses += 1\n else:\n print('Invalid choice, try again')\n \n print('Current Record: Wins = ' + str(total_wins) + ' Losses = ' + str(total_losses))\n player_selection = None\n ai_selection = choices[randint(0,2)]" }, { "alpha_fraction": 0.5692883729934692, "alphanum_fraction": 0.584269642829895, "avg_line_length": 31.393939971923828, "blob_id": "3b127ad8ff58d6784ea438875295342e95d3c882", "content_id": "6926d2a16161ee76315765de4537b870a5c4c68d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1068, "license_type": "no_license", "max_line_length": 65, "num_lines": 33, "path": "/csvmanipulation.py", "repo_name": "redwingsdan/python-tests", "src_encoding": "UTF-8", "text": "import csv\n\ndef writer (header, data, filename, option):\n with open (filename, 'w', newline = '') as csvfile:\n if option == 'write':\n pizza_places = csv.writer(csvfile)\n pizza_places.writerow(header)\n for data_row in data:\n pizza_places.writerow(data_row)\n elif option == 'update':\n writer = csv.DictWriter(csvfile, fieldnames = header)\n writer.writeheader()\n writer.writerows(data)\n else:\n print('Unknown option')\n\ndef updater(filename):\n with open(filename, 'r', newline = '') as csvfile:\n readData = [row for row in csv.DictReader(csvfile)]\n readData[0]['Rating'] = '9.2'\n readHeader = readData[0].keys()\n writer(readHeader, readData, filename, 'update')\n\ncsvFileName = 'csv_pizza_ratings.csv'\ncsvHeader = ('Rank', 'Rating', 'Pizza Place')\ncsvData = [\n (1, 9.4, 'Di Faras'),\n (2, 8.8, 'Frank Pepes'),\n (3, 7.3, 'Pizza District'),\n (4, 6.9, 'Poppa Ginos')\n]\nwriter(csvHeader, csvData, csvFileName, 'write')\nupdater(csvFileName)" } ]
10
vsskanand/Hello-World-
https://github.com/vsskanand/Hello-World-
e97088514afc0a76c469e4a68567771b613b5c02
077ff4fb7d6de6808592e86a16adc16c80c5b1a7
1f2004de1af8d3bd19eb40f07a6c158e218c3883
refs/heads/master
2020-12-24T18:03:25.613281
2015-02-20T15:47:00
2015-02-20T15:47:00
30,999,876
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7749999761581421, "alphanum_fraction": 0.7749999761581421, "avg_line_length": 40, "blob_id": "459c6334069473d7f4faea21cb692cbcf443fc2a", "content_id": "839835f75f8b096ae7f4515cbe3b491420409ea9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 40, "license_type": "no_license", "max_line_length": 40, "num_lines": 1, "path": "/HelloWorld.py", "repo_name": "vsskanand/Hello-World-", "src_encoding": "UTF-8", "text": "print \"Hello, world! in Python language\"" }, { "alpha_fraction": 0.6944444179534912, "alphanum_fraction": 0.6944444179534912, "avg_line_length": 36, "blob_id": "d457cd3b28fb3601b4793d862f105fdc287bd9aa", "content_id": "8b5f7a6879a197ab9b8bd7bb76ae1bf2d55c2516", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "R", "length_bytes": 36, "license_type": "no_license", "max_line_length": 36, "num_lines": 1, "path": "/HelloWorld.r", "repo_name": "vsskanand/Hello-World-", "src_encoding": "UTF-8", "text": "cat('Hello, world! in R language\\n')" } ]
2
jslon/Ofuscador
https://github.com/jslon/Ofuscador
9f7f1f0d4d257478430b5a07fa6431620102327c
3b272988df42e7c1c49c639bd233557522d227b5
03a92a681a3612fd139bb087f2b3db7f1db696fa
refs/heads/master
2020-12-24T17:35:34.047296
2014-11-14T20:50:15
2014-11-14T20:50:15
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3492288589477539, "alphanum_fraction": 0.382910817861557, "avg_line_length": 25.24186134338379, "blob_id": "1398db64acce2c878026d96226ca42f5f2a391f3", "content_id": "35001ab52b4e25c036967b26963f5fe31883d3fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5641, "license_type": "no_license", "max_line_length": 97, "num_lines": 215, "path": "/Ofuscador.py", "repo_name": "jslon/Ofuscador", "src_encoding": "UTF-8", "text": "tokens = ('ID','NUM','LET', 'ALFNUM', 'ASG', 'IF', 'ELSE', 'SWITCH', 'CASE', 'WHILE', 'DEFAULT')\nids = []\ndic = {}\nt_NUM = r'[0-9]+'\nt_LET = r'[A-Za-z]+'\nt_ALFNUM= r'[A-Za-z0-9]+'\nt_ASG = r'='\n#t_ID = r'[a-z][a-zA-Z0-9]*'\nt_IF = r'if'\n\nliterals = ['+', '-', '*', '=', '<', '>', '=', '!', ':', ';', '(', ')', '{', '}', '&', '|']\n\ndef t_ID(t):\n r'[a-z][a-zA-Z0-9]*'\n return t\n\ndef ofuscarVar(id):\n new_id = id\n new_id +='X'\n return new_id\n\n#t_ignore = \" \\t\"\n\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += t.value.count(\"\\n\")\n\ndef t_error(t):\n print(\"Expresion mal definida '%s'\" % t.value[0])\n t.lexer.skip(1)\n\n\nimport ply.lex as lex\nlex.lex()\n\n#parser\ndef p_var(p):\n 'variable : ID ASG ID'\n if(p[1] in dic):\n n=ids[dic[p[1]]]\n else:\n ids.append(ofuscarVar(p[1]))\n dic[p[1]]=len(ids)-1\n n=ids[len(ids)-1]\n print (n)\n return n\n\ndef p_PLS(p): #PROGRAMA -> lista_sentencias\n 'P : LS'\n p[0] = p[1]\n\ndef p_LSLSS(p): #lista_sentencias -> lista_sentencias sentencia\n 'LS : LS S'\n p[0] = p[1]+p[2]\n\ndef p_LSS(p): #lista_sentencias -> sentencia\n 'LS : S'\n p[0] = p[1]\n\ndef p_SE(p): #sentencia -> E;\n 'S : E ;'\n p[0] = p[1]+p[2]\n\ndef p_SW(p): #sentencia -> WHILE\n 'S : W'\n p[0] = p[1]\n\ndef p_SIFE(p): #sentencia -> IF_ELSE\n 'S : IE'\n p[0] = p[1]\n\ndef p_SSWC(p): #sentencia -> SWITCH\n 'S : SW'\n p[0] = p[1]\n\ndef p_WWS(p): #WHILE -> while (condicion) sentencia ;\n 'W : while ( C ) S ;'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]\n\ndef p_WWLS(p): #WHILE -> while (condicion) { lista_sentencias }\n 'W : while ( C ) { LS }'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]+p[6]+p[7]\n\ndef p_IEIES(p): #IF_ELSE -> IF else sentencia;\n 'IE : I else S ;'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_IEIELS(p): #IF_ELSE -> IF else { lista_sentencias }\n 'IE : I else { LS }'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]\n\ndef p_IICS(p): #IF -> IF (condicion) sentencia\n 'I : IF ( C ) S'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]\n\ndef p_ICLS(p): #IF-> IF (condicion) {lista_sentencias}\n 'I : IF ( C ) { LS }'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]+p[6]+p[7]\n\ndef p_SWSWILC(p): #SWITCH -> SWITCH(ID) {lista_case}\n 'SW : switch ( ID ) { LC }'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]+p[6]+p[7]\n\ndef p_SWSWILCD(p): #SWITCH -> SWITCH(ID) {lista_case DEFAULT}\n 'SW : switch ( ID ) { LC } DF'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]+p[6]+p[7]+p[8]\n\ndef p_LCC(p): #lista_case -> CASE\n 'LC : CA'\n p[0] = p[1]\n\ndef p_LCLCC(p): #lista_case -> lista_case CASE\n 'LC : LC CA'\n p[0] = p[1]+p[2]\n\ndef p_CACAIDSE(p): #CASE -> CASE ID : sentencia\n 'CA : case ID : S'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]+p[6]\n\ndef p_CACAIDLS(P): #CASE -> CASE ID : { lista_sentencias }\n 'CA : case ID : { LS }'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]+p[6]+p[7]+p[8]\n\ndef p_DFDFS(p): #DEFAULT -> DEFAULT : sentencia\n 'DF : default : S'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_DFDFLS(p): #DEFAULT -> DEFAULT : { lista_sentencias }\n 'DF : default : { LS }'\n p[0] = p[1]+p[2]+p[3]+p[4]+p[5]+p[6]\n\ndef p_CCL(p): #CONDICION -> CONDICION_LOGICA\n 'C : CL'\n p[0] = p[1]\n\ndef p_CCA(p): #CONDICION -> AND\n 'C : AND'\n p[0] = p[1]\n\ndef p_CCO(p): #CONDICION -> OR\n 'C : OR'\n p[0] = p[1]\n\ndef p_AND(p): #AND -> CONDICION_LOGICA && CONDICION_LOGICA\n 'AND : CL && CL'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_OR(p): #OR -> CONDICION_LOGICA || CONDICION_LOGICA\n 'OR : CL || CL'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_CL0(p): #CONDICION_LOGICA -> E > E\n 'CL : E > E'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_CL1(p): #CONDICION_LOGICA -> E < E\n 'CL : E < E'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_CL2(p): #CONDICION_LOGICA -> E >= E\n 'CL : E > = E'\n p[0] = p[1]+p[2]+p[3]+p[4]\n\ndef p_CL3(p): #CONDICION_LOGICA -> E <= E\n 'CL : E < = E'\n p[0] = p[1]+p[2]+p[3]+p[4]\n\ndef p_CL4(p): #CONDICION_LOGICA -> E == E\n 'CL : E == E'\n p[0] = p[1]+p[2]+p[3]+p[4]\n\ndef p_CL5(p): #CONDICION_LOGICA -> E != E\n 'CL : E != E'\n p[0] = p[1]+p[2]+p[3]+p[4]\n\ndef p_EET(p): #E -> E+T\n 'E : E + T'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_EET2(p): #E -> E-T\n 'E : E - T'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_ET(p): #E -> T\n 'E : T'\n p[0] = p[1]\n\ndef p_TTID(p): #T-> T*ID\n 'T : T * ID'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_TTID1(p): #T-> T/ID\n 'T : T/ID'\n p[0] = p[1]+p[2]+p[3]\n\ndef p_TID(p): #T -> ID\n 'T : ID'\n p[0] = p[1]\n\ndef p_error(p):\n if p:\n print(\"Error de sintaxis en '%s'\" % p.value)\n else:\n print(\">.>\")\n\nimport ply.yacc as yacc\nyacc.yacc()\n\nwhile 1:\n try:\n s = input('Inserte expresion > ')\n except EOFError:\n break\n if not s: continue\n yacc.parse(s)" } ]
1
liuchaorun/RISCVCPU
https://github.com/liuchaorun/RISCVCPU
576de59bcde80c54be0c365e33b05133729af72d
081e955e5e4fc42cb6af9007b6440ac812ccceae
d00d71f7cdcfad1bd11494079bf0ef8e47907e8b
refs/heads/main
2023-06-19T16:51:15.798155
2021-07-17T15:13:29
2021-07-17T15:13:29
377,493,844
3
0
null
null
null
null
null
[ { "alpha_fraction": 0.3100961446762085, "alphanum_fraction": 0.36057692766189575, "avg_line_length": 23.52941131591797, "blob_id": "183a5e1b6e1557905ebe13677b677b6abf1389cf", "content_id": "01ba80616b6dea41ecc09f6d6887564cb6c96651", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 436, "license_type": "no_license", "max_line_length": 50, "num_lines": 17, "path": "/test_program/1.0/BubbleSort/BubbleSort.c", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main() {\n int n = 10;\n int array[] = {10, 9, 8, 7, 6, 1, 2 ,3, 4, 5};\n for (int i = 0; i < n - 1; i++) {\n for (int j = i; j < n - 1; j++) {\n if (array[j] >= array[j+1]) {\n int temp = array[j+1];\n array[j+1] = array[j];\n array[j] = temp;\n }\n }\n }\n printf(\"数组中第一个元素是%d。\", array[0]);\n return 0;\n}" }, { "alpha_fraction": 0.5642317533493042, "alphanum_fraction": 0.5944584608078003, "avg_line_length": 23.060606002807617, "blob_id": "84bf4be9792dd725c7efdcebf1e304276fafb869", "content_id": "629830599c1e32795b9573b09ab64a9fe52cbf8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1588, "license_type": "no_license", "max_line_length": 83, "num_lines": 66, "path": "/test_program/2.0/四个测试程序/instruction_get.py", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "instruction = []\ninstruction16 = []\n\nbubble_sort_ins = open(\"./BubbleSort.txt\", \"r\")\n\nlines = bubble_sort_ins.readlines()\n\nfor line in lines:\n temp = line.split()\n if len(temp) >= 3 and temp[0][len(temp[0]) - 1] == \":\" and temp[2] != \"format\":\n instruction.append(temp[2])\n if len(temp[1]) == 4:\n instruction16.append(temp[2])\n\nbubble_sort_ins.close()\n\nbubble_sort_ins = open(\"./BubbleSort_ass.txt\", \"r\")\n\nlines = bubble_sort_ins.readlines()\n\nfor line in lines:\n temp = line.split()\n if len(temp) >= 3 and temp[0][len(temp[0]) - 1] == \":\" and temp[2] != \"format\":\n instruction.append(temp[2])\n if len(temp[1]) == 4:\n instruction16.append(temp[2])\n\nbubble_sort_ins.close()\n\nfibonacci_ins = open(\"./Fibonacci.txt\", \"r\")\n\nlines = fibonacci_ins.readlines()\n\nfor line in lines:\n temp = line.split()\n if len(temp) >= 3 and temp[0][len(temp[0]) - 1] == \":\" and temp[2] != \"format\":\n instruction.append(temp[2])\n if len(temp[1]) == 4:\n instruction16.append(temp[2])\n\nfibonacci_ins.close()\n\nfibonacci_ins = open(\"./Fibonacci_ass.txt\", \"r\")\n\nlines = fibonacci_ins.readlines()\n\nfor line in lines:\n temp = line.split()\n if len(temp) >= 3 and temp[0][len(temp[0]) - 1] == \":\" and temp[2] != \"format\":\n instruction.append(temp[2])\n if len(temp[1]) == 4:\n instruction16.append(temp[2])\n\nfibonacci_ins.close()\n\nprint(len(set(instruction)))\n\nprint(set(instruction))\n\nprint(set(instruction16))\n\nresult = set(instruction)\n\nw = open('instruction.txt', 'w')\n\nw.write(','.join(result))\n" }, { "alpha_fraction": 0.7324414849281311, "alphanum_fraction": 0.7658863067626953, "avg_line_length": 53.45454406738281, "blob_id": "bd0202d02e1f12276a1026f2eb30f9bad525b025", "content_id": "8a40047a5b2a35c62dfab9a87cf8b496be086a6a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 598, "license_type": "no_license", "max_line_length": 64, "num_lines": 11, "path": "/test_program/2.0/四个测试程序/README.MD", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "./riscv32-unknown-elf-gcc -E Fibonacci.c -o Fibonacci.i\n./riscv32-unknown-elf-gcc -S Fibonacci.i -o Fibonacci.s\n./riscv32-unknown-elf-gcc -c Fibonacci.s -o Fibonacci.o\n./riscv32-unknown-elf-gcc -static Fibonacci.o -o Fibonacci.out\n./riscv32-unknown-elf-objdump -S Fibonacci.out > Fibonacci.txt\n\n./riscv32-unknown-elf-gcc -E BubbleSort.c -o BubbleSort.i\n./riscv32-unknown-elf-gcc -S BubbleSort.i -o BubbleSort.s\n./riscv32-unknown-elf-gcc -c BubbleSort.s -o BubbleSort.o\n./riscv32-unknown-elf-gcc -static BubbleSort.o -o BubbleSort.out\n./riscv32-unknown-elf-objdump -S BubbleSort.out > BubbleSort.txt" }, { "alpha_fraction": 0.6081871390342712, "alphanum_fraction": 0.6608186960220337, "avg_line_length": 33.20000076293945, "blob_id": "5948d65b56979e7033d59ede23190dfd461667cf", "content_id": "286fb4d4308ce68212a43de775bdf71a95814ff4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 171, "license_type": "no_license", "max_line_length": 78, "num_lines": 5, "path": "/homework/3rd week/第三周实验附件/RISCV/RISCV.runs/synth_1/.vivado.begin.rst", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "<?xml version=\"1.0\"?>\n<ProcessHandle Version=\"1\" Minor=\"0\">\n <Process Command=\"vivado.bat\" Owner=\"X\" Host=\"LABDESKTOP-XSY\" Pid=\"20988\">\n </Process>\n</ProcessHandle>\n" }, { "alpha_fraction": 0.29916897416114807, "alphanum_fraction": 0.3434903025627136, "avg_line_length": 21.625, "blob_id": "1c43dfcc08a2cfb35bf8c2dfcca840e5baa2ed13", "content_id": "9fc53225be2b013d919eae839dcf9e0031a8956d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 361, "license_type": "no_license", "max_line_length": 41, "num_lines": 16, "path": "/homework/2nd week/代码/test_program/BubbleSort/BubbleSort.c", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main() {\n int n = 7;\n int array[] = {10,5,7,3,4,2,1};\n for (int i = 0; i < n - 1; i++) {\n for (int j = i; j < n - 1; j++) {\n if (array[j] < array[j+1]) {\n int temp = array[j+1];\n array[j+1] = array[j];\n array[j] = temp;\n }\n }\n }\n return 0;\n}" }, { "alpha_fraction": 0.7852050065994263, "alphanum_fraction": 0.832442045211792, "avg_line_length": 26.365854263305664, "blob_id": "b07efdb78caae1952f971397705ae1e7b0479881", "content_id": "b364c60717197a067436c068b328786898784932", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 1122, "license_type": "no_license", "max_line_length": 34, "num_lines": 41, "path": "/homework/2nd week/代码/RISCV/RISCV.sim/sim_1/behav/xsim/xsim.dir/TOP_behav/xsimSettings.ini", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "[General]\nARRAY_DISPLAY_LIMIT=1024\nRADIX=hex\nTIME_UNIT=ns\nTRACE_LIMIT=2147483647\nVHDL_ENTITY_SCOPE_FILTER=true\nVHDL_PACKAGE_SCOPE_FILTER=false\nVHDL_BLOCK_SCOPE_FILTER=true\nVHDL_PROCESS_SCOPE_FILTER=false\nVHDL_PROCEDURE_SCOPE_FILTER=false\nVERILOG_MODULE_SCOPE_FILTER=true\nVERILOG_PACKAGE_SCOPE_FILTER=false\nVERILOG_BLOCK_SCOPE_FILTER=false\nVERILOG_TASK_SCOPE_FILTER=false\nVERILOG_PROCESS_SCOPE_FILTER=false\nINPUT_OBJECT_FILTER=true\nOUTPUT_OBJECT_FILTER=true\nINOUT_OBJECT_FILTER=true\nINTERNAL_OBJECT_FILTER=true\nCONSTANT_OBJECT_FILTER=true\nVARIABLE_OBJECT_FILTER=true\nSCOPE_NAME_COLUMN_WIDTH=208\nSCOPE_DESIGN_UNIT_COLUMN_WIDTH=75\nSCOPE_BLOCK_TYPE_COLUMN_WIDTH=75\nOBJECT_NAME_COLUMN_WIDTH=235\nOBJECT_VALUE_COLUMN_WIDTH=139\nOBJECT_DATA_TYPE_COLUMN_WIDTH=75\nPROCESS_NAME_COLUMN_WIDTH=75\nPROCESS_TYPE_COLUMN_WIDTH=75\nFRAME_INDEX_COLUMN_WIDTH=75\nFRAME_NAME_COLUMN_WIDTH=75\nFRAME_FILE_NAME_COLUMN_WIDTH=75\nFRAME_LINE_NUM_COLUMN_WIDTH=235\nLOCAL_NAME_COLUMN_WIDTH=139\nLOCAL_VALUE_COLUMN_WIDTH=75\nINPUT_LOCAL_FILTER=1\nOUTPUT_LOCAL_FILTER=1\nINOUT_LOCAL_FILTER=1\nINTERNAL_LOCAL_FILTER=1\nCONSTANT_LOCAL_FILTER=1\nVARIABLE_LOCAL_FILTER=1\n" }, { "alpha_fraction": 0.5585442781448364, "alphanum_fraction": 0.5680379867553711, "avg_line_length": 16.58333396911621, "blob_id": "4cbad98edfcbc6c8a3efa59ff66b150e40487dc7", "content_id": "1ff7365836ac37823d813076de5aae7df1b267da", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 632, "license_type": "no_license", "max_line_length": 49, "num_lines": 36, "path": "/homework/5th week/附件/test_program/trap_get.py", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "# trap = {}\n\n# bubble_sort_ins = open(\"./trap.txt\", \"r\")\n\n# lines = bubble_sort_ins.readlines()\n\n# for line in lines:\n# temp = line.split()\n# if temp[0] == \"core\": \n# if temp[2][2] == \"8\":\n# trap[temp[2]] = line\n\n# bubble_sort_ins.close()\n\n# keys = sorted(trap.keys())\n\n# for key in keys:\n# print(trap[key])\n\n# for dict_key, dict_value in trap.items(): \n# print(dict_value)\n\ntrap = []\n\nbubble_sort_ins = open(\"./trap_program.txt\", \"r\")\n\nlines = bubble_sort_ins.readlines()\n\nfor line in lines:\n temp = line.split()\n trap.append(temp[1])\n\nbubble_sort_ins.close()\n\nfor t in trap:\n print(t)" }, { "alpha_fraction": 0.42965778708457947, "alphanum_fraction": 0.45627376437187195, "avg_line_length": 14.969696998596191, "blob_id": "50dc3baf893371813f45a0dd547711b2746b64f8", "content_id": "dff778b9a36b08e5adb967e1d8b1803af43a0e74", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 578, "license_type": "no_license", "max_line_length": 45, "num_lines": 33, "path": "/homework/2nd week/代码/test_program/Fibonacci/Fibonacci.c", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint ReFib(int n){\n if(n == 1) return 0;\n if(n == 2) return 1;\n return ReFib(n-1) + ReFib(n-2);\n}\n\nint ItFib(int n){\n if(n == 1) return 0;\n if(n == 2) return 1;\n\n int i = 0;\n int j = 1;\n int k, fib;\n for(k = 3; k <= n; k++){\n fib = i + j;\n i = j;\n j = fib;\n }\n return fib;\n}\n\nint main(){\n int n = 5;\n\n int ReFibN = ReFib(n);\n\n int ItFibN = ItFib(n);\n\n printf(\"(递归)第%d个斐波那契数为:%d\\n\", n, ReFibN);\n printf(\"(迭代)第%d个斐波那契数为:%d\\n\", n, ItFibN);\n}" }, { "alpha_fraction": 0.7200000286102295, "alphanum_fraction": 0.7749999761581421, "avg_line_length": 14.461538314819336, "blob_id": "6dfcba1e5f24b985971c690200ec3d86802acd69", "content_id": "85cdbb73ae4cc6c411a99ef8919daa09e7bae2ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 312, "license_type": "no_license", "max_line_length": 45, "num_lines": 13, "path": "/homework/2nd week/代码/README.md", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "# RISCVCPU\n\n代码位于 RISCVCPU\\RISCV\\RISCV.srcs\\sources_1\\new下\n\n开发环境:vivado 2018.3\n\n## 使用方法\n\n1. 使用vivado打开RISCV项目文件\n2. 点击TOP->if_unit:IF->instMem\n3. 选择加载Fibonacci.coe文件加载后\n4. 点击运行仿真\n5. 若仿真正确,寄存器和RAM值如文档中所示" }, { "alpha_fraction": 0.5421686768531799, "alphanum_fraction": 0.5602409839630127, "avg_line_length": 19.8125, "blob_id": "1fca2d0e9f7dad5fc10622dccf09210543c308cb", "content_id": "32cda3246b3f19e9ab947c2fe0ea58e4f39cec54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "no_license", "max_line_length": 43, "num_lines": 16, "path": "/test_program/3.0/trap_get.py", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "trap = {}\n\nbubble_sort_ins = open(\"./trap.txt\", \"r\")\n\nlines = bubble_sort_ins.readlines()\n\nfor line in lines:\n temp = line.split()\n if temp[0] == \"core\": \n if temp[2][2] == \"8\":\n trap[temp[2]] = temp[3]\n\nbubble_sort_ins.close()\n\nfor dict_key, dict_value in trap.items(): \n print(dict_key,'->',dict_value)" }, { "alpha_fraction": 0.2961876690387726, "alphanum_fraction": 0.32258063554763794, "avg_line_length": 15.285714149475098, "blob_id": "16a8df7e8863368f6db0eb9f599741ee832b65a5", "content_id": "994442b34adb5ccf498d5ac769157e3355e65aa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 359, "license_type": "no_license", "max_line_length": 38, "num_lines": 21, "path": "/test_program/1.0/Fibonacci/Fibonacci.c", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n\nint main(){\n int n = 5;\n int fib = 0;\n \n if(n == 1) fib = 0;\n else if(n == 2) fib = 1;\n else {\n int i = 0;\n int j = 1;\n int k;\n for(k = 3; k <= n; k++){\n fib = i + j;\n i = j;\n j = fib;\n }\n }\n\n printf(\"第%d个斐波那契数为:%d\\n\", n, fib);\n}" }, { "alpha_fraction": 0.5738498568534851, "alphanum_fraction": 0.6222760081291199, "avg_line_length": 20.736841201782227, "blob_id": "b38c3b9d84664e38292bff86e1a039d5356cc534", "content_id": "4f859bb34dccd2ae0c6a887b6ea1bdf395e9e9e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "no_license", "max_line_length": 83, "num_lines": 19, "path": "/test_program/3.0/instruction.py", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "instruction = []\n\nfor i in range(0,16413):\n instruction.append(\"00000000\")\n\nfibonacci_ins = open(\"./Fibonacci.txt\", \"r\")\n\nlines = fibonacci_ins.readlines()\n\nfor line in lines:\n temp = line.split()\n if len(temp) >= 3 and temp[0][len(temp[0]) - 1] == \":\" and temp[2] != \"format\":\n instruction.append(temp[1])\n\nfibonacci_ins.close()\n\nw = open('instruction.txt', 'w')\n\nw.write('\\n'.join(instruction))\n" }, { "alpha_fraction": 0.7704917788505554, "alphanum_fraction": 0.7991803288459778, "avg_line_length": 19.41666603088379, "blob_id": "df250bbee4b56abbcccf6b3c1a520f43a75b4cb9", "content_id": "46a7a7ef37a4b3355de8ae910822ae947dafb53b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 406, "license_type": "no_license", "max_line_length": 47, "num_lines": 12, "path": "/README.md", "repo_name": "liuchaorun/RISCVCPU", "src_encoding": "UTF-8", "text": "# RISCVCPU\n\n代码位于 RISCVCPU\\RISCV\\RISCV.srcs\\sources_1\\new下\n\n## 使用方法\n\n1. 使用vivado打开RISCV项目文件\n2. 点击TOP->if_unit:IF->instMem\n3. 选择加载Fibonacci.coe文件(位于test_program四个文件夹下)加载后\n4. 修改ram中mem初始化文件位置(位于test_program四个文件夹下)\n5. 点击运行仿真\n6. 若仿真正确,寄存器和RAM值如文档中所示" } ]
13
prefontaine/python-playtime-pbandj
https://github.com/prefontaine/python-playtime-pbandj
6870ca0a34a3511d8e611c5b9294c2afa9d6adae
e3876600728593d231bb9aa3690ee2b80f2f2a06
456d30008927b8056ad450babb73eff4e83ba687
refs/heads/master
2016-05-30T17:38:34.141838
2014-02-01T03:23:58
2014-02-01T03:23:58
16,427,429
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6625514626502991, "alphanum_fraction": 0.6872428059577942, "avg_line_length": 23.299999237060547, "blob_id": "dbedab06075c16ada1bf6957f4ef261e66a60720", "content_id": "328c291f453a46b1e00a00fd145b52e0c14316a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 243, "license_type": "no_license", "max_line_length": 54, "num_lines": 10, "path": "/pbandj-goal1.py", "repo_name": "prefontaine/python-playtime-pbandj", "src_encoding": "UTF-8", "text": "print \"Okay, I have a plate and a knife.\"\n\nbread = 7\njelly = 4\npeanut_butter = 5\n\nif bread >= 2 and peanut_butter >= 1 and jelly >= 1:\n\tprint \"I can make a peanut butter and jelly sandwich\"\nelse:\n\tprint \"Looks like I don't have a lunch today\"\n" }, { "alpha_fraction": 0.6705202460289001, "alphanum_fraction": 0.6936416029930115, "avg_line_length": 27.91666603088379, "blob_id": "15885a6b595e636fe6a26590880dea720b4a61e9", "content_id": "dddb6d32fd0b24634a8bfdcdafc16774e278e27e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 346, "license_type": "no_license", "max_line_length": 78, "num_lines": 12, "path": "/pbandj-goal3.py", "repo_name": "prefontaine/python-playtime-pbandj", "src_encoding": "UTF-8", "text": "print \"Okay, I have a plate and a knife.\"\n\nbread = 7\njelly = 4\npeanut_butter = 5\n\nif bread >= 2 and peanut_butter >= 1 and jelly >= 1:\n\tsandwiches = bread / 2 \n\tprint \"I can make this many sandwiches:\",sandwiches, \n\tprint \"\\nI can also make this many of open-faced sandwiches:\",sandwiches % 2,\nelse:\n\tprint \"Looks like I don't have a lunch today\"" }, { "alpha_fraction": 0.6874427199363708, "alphanum_fraction": 0.7011915445327759, "avg_line_length": 37.32143020629883, "blob_id": "949ed44ba5ca900cc7517714566e4d3da037f39c", "content_id": "af495e0ec2f9ca2b417fb9a931d255cfd0060bdd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1091, "license_type": "no_license", "max_line_length": 181, "num_lines": 28, "path": "/pbandj-goal5.py", "repo_name": "prefontaine/python-playtime-pbandj", "src_encoding": "UTF-8", "text": " \n # To satisfy the fifth goal:\n # Continue from the fourth goal, but this time if you have enough bread and peanut butter but no jelly, print a message that tells you that you can make a peanut butter sandwich\n # Or if you have more peanut butter and bread than jelly, that you can make a certain number of peanut butter & jelly sandwiches and a certain number of peanut butter sandwiches\n\n # NOTE: This one isn't done yet!!\n\n\nbread = 9\njelly = 0\npeanut_butter = 3\n\nprint \"Okay, I have a plate and a knife.\"\n\nif bread == 0:\n\tprint \"But I don't have bread.\"\nif peanut_butter == 0:\n\tprint \"But I don't have peanut butter.\"\nif jelly == 0:\n\tprint \"But I don't have jelly.\"\n\nif bread >= 2 and peanut_butter >= 1 and jelly >= 1:\n\tsandwiches = bread / 2 \n\tprint \"I can make this many PB&J sandwiches:\",sandwiches, \n\tprint \"\\nI can also make this many of open-faced PB&Js sandwiches:\",sandwiches % 2,\n\nif bread >= 2 and peanut_butter >= 1 and jelly == 0:\n\tpeanut_butter_sandwiches = bread / 2 \n\tprint \"I can make this many peanut butter sandwiches:\",peanut_butter_sandwiches, \n\n\n\n\n\n\n\n\n\n\n\n\n\n " }, { "alpha_fraction": 0.6265060305595398, "alphanum_fraction": 0.6265060305595398, "avg_line_length": 19.75, "blob_id": "c701c85f3c22923354793c19a82c60bd824890bd", "content_id": "1c82b4907a7d42b0bc23093946bef4ac27518b22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 83, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/README.md", "repo_name": "prefontaine/python-playtime-pbandj", "src_encoding": "UTF-8", "text": "python-playtime-pbandj\n======================\n\nPlaying with conditional statements\n" }, { "alpha_fraction": 0.6481876373291016, "alphanum_fraction": 0.6716417670249939, "avg_line_length": 28.25, "blob_id": "a4e9d15993e0d9e7da870ca747a68599282b5876", "content_id": "9713e5db3a4a4a3d740944a635c8077dba14b18e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 469, "license_type": "no_license", "max_line_length": 78, "num_lines": 16, "path": "/pbandj-goal4.py", "repo_name": "prefontaine/python-playtime-pbandj", "src_encoding": "UTF-8", "text": "print \"Okay, I have a plate and a knife.\"\n \nbread = 7\njelly = 0\npeanut_butter = 0\n \nif bread >= 2 and peanut_butter >= 1 and jelly >= 1:\n\tsandwiches = bread / 2 \n\tprint \"I can make this many sandwiches:\",sandwiches, \n\tprint \"\\nI can also make this many of open-faced sandwiches:\",sandwiches % 2,\nif bread == 0:\n\tprint \"But I don't have any bread.\"\nif peanut_butter == 0:\n\tprint \"But I don't have any peanut butter.\"\nif jelly == 0:\n\tprint \"But I don't have any jelly.\"\n " }, { "alpha_fraction": 0.6529850959777832, "alphanum_fraction": 0.6791045069694519, "avg_line_length": 23.454545974731445, "blob_id": "473f23e2884d74368b25191529f9dcccbb61241f", "content_id": "22841e80927385fd06b6b049abc04499f1d9b57c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 268, "license_type": "no_license", "max_line_length": 53, "num_lines": 11, "path": "/pbandj-goal2.py", "repo_name": "prefontaine/python-playtime-pbandj", "src_encoding": "UTF-8", "text": "print \"Okay, I have a plate and a knife.\"\n \nbread = 7\njelly = 4\npeanut_butter = 5\n \nif bread >= 2 and peanut_butter >= 1 and jelly >= 1:\n\tsandwiches = bread / 2 \n\tprint \"I can make this many sandwiches:\",sandwiches,\nelse:\n\tprint \"Looks like I don't have a lunch today\"" } ]
6
anindyabrata/Sea-level-prediction
https://github.com/anindyabrata/Sea-level-prediction
bcd2e56ac59606521fa8fedc2c999ba34a7e595f
390b635ba95342f7d0b53f4ab7f2d51e89933f67
e10df086fe3ece6c03140ce118b17bbe88623edf
refs/heads/master
2020-04-14T12:30:45.414029
2019-01-02T13:09:34
2019-01-02T13:09:34
163,842,374
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8253968358039856, "avg_line_length": 30.5, "blob_id": "ff570dcd649c0086242dc4bc92cacc57628df631", "content_id": "819b7eef504d9766d497c0a6cb8f3ecabdd61263", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 63, "license_type": "no_license", "max_line_length": 39, "num_lines": 2, "path": "/README.md", "repo_name": "anindyabrata/Sea-level-prediction", "src_encoding": "UTF-8", "text": "# Sea-level-prediction\nsea level prediction comparing 5 models\n" }, { "alpha_fraction": 0.6608030796051025, "alphanum_fraction": 0.6894334554672241, "avg_line_length": 34.41592788696289, "blob_id": "c820d16428c14c67fe709693a959caff1cea0ff4", "content_id": "a8a7dd865f9ce6cbe5f815c9bede8da101a0d4e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8243, "license_type": "no_license", "max_line_length": 101, "num_lines": 226, "path": "/Sealevelprediction.py", "repo_name": "anindyabrata/Sea-level-prediction", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 5 22:46:01 2018\r\n\r\n\"\"\"\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.ensemble import RandomForestRegressor\r\nfrom sklearn.ensemble import ExtraTreesRegressor\r\nfrom sklearn.tree import DecisionTreeRegressor\r\nfrom sklearn.ensemble import AdaBoostRegressor\r\nfrom sklearn import svm\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.metrics import r2_score\r\nfrom sklearn.metrics import explained_variance_score, mean_squared_error,mean_squared_log_error \r\n \r\ndata = pd.read_csv('E:\\Mypythoncodes\\Global_Warming_Indicator.csv')\r\n'''\r\nsealevel = data['Adjusted sea level']\r\nfeatures= data.drop('Adjusted sea level ', axis = 1)\r\n'''\r\nfeatures = data.iloc[:,0:3]\r\nfeature = np.array(features)\r\nsealevels = data.iloc[:,[3]]\r\nsealevel = np.array(sealevels)\r\n\r\nprint(' dataset has {} data points with {} variables each.'.format(*data.shape))\r\n\r\n\r\nminimum_sealevel = np.min(sealevel)\r\nmaximum_sealevel = np.max(sealevel)\r\nmean_sealevel = np.mean(sealevel)\r\nmedian_sealevel = np.median(sealevel)\r\nstd_sealevel = np.std(sealevel)\r\nprint(\"Statistics for Carbon emition,Temperature, Adjusted sea level dataset:\")\r\nprint(\"Minimum Adjusted sea level : {:,.2f} inchs\".format(minimum_sealevel))\r\nprint(\"Maximum Adjusted sea level : {:,.2f} inchs\".format(maximum_sealevel))\r\nprint(\"Mean Adjusted sea level : {:,.2f} inchs\".format(mean_sealevel))\r\nprint(\"Median Adjusted sea level {:,.2f} inchs\".format(median_sealevel))\r\nprint(\"Standard deviation of Adjusted sea level : {:,.2f} inchs\".format(std_sealevel))\r\n\r\n\r\nsum_exs1=sum_ms1=sum_r21=sum_msle1=0; \r\nsum_exs2=sum_ms2=sum_r22=sum_msle2=0; \r\nsum_exs3=sum_ms3=sum_r23=sum_msle3=0;\r\nsum_exs4=sum_ms4=sum_r24=sum_msle4=0; \r\nsum_exs5=sum_ms5=sum_r25=sum_msle5=0; \r\n\r\ndef performance_measure(y_test,y_pred):\r\n \r\n explained_variance = explained_variance_score(y_test, y_pred)\r\n mean_squared = mean_squared_error(y_test, y_pred)\r\n mean_squared_log = mean_squared_log_error(y_test, y_pred)\r\n r_squared = r2_score(y_test, y_pred)\r\n print(\"Performance Metric...\")\r\n print('explained variance = {}'.format(explained_variance))\r\n print('mse = {}'.format(mean_squared))\r\n print('r2 = {}'.format(r_squared))\r\n print('msle = {}'.format(mean_squared_log))\r\n \r\n return explained_variance,mean_squared,mean_squared_log,r_squared\r\n \r\n'''\r\ndef sum_of_performance_metric(explained_variance,mean_squared,mean_squared_log,r_squared):\r\n \r\n sum_exs=sum_ms=sum_r2=sum_msle=0; \r\n sum_exs = sum_exs + mean_squared\r\n sum_ms = sum_ms + explained_variance\r\n sum_r2 = sum_r2 + mean_squared_log\r\n sum_msle = sum_msle + r_squared\r\n \r\n return sum_exs,sum_ms,sum_r2,sum_msle\r\n''' \r\n\r\nfrom sklearn.preprocessing import StandardScaler\r\nscaler =StandardScaler().fit(feature)\r\nfeature= scaler.transform(feature) \r\n \r\nX = np.array(features)\r\ny = np.array(sealevel) \r\nkf=KFold(n_splits=5, random_state=None, shuffle=True)\r\n\r\nfor train_index, test_index in kf.split(X,y):\r\n \r\n #print(\"TRAIN:\", train_index, \"TEST:\", test_index)\r\n X_train, X_test = X[train_index], X[test_index]\r\n y_train, y_test = y[train_index], y[test_index]\r\n \r\n \r\n regressor = RandomForestRegressor(n_estimators=500)\r\n regressor.fit(X_train, y_train)\r\n y_pred = regressor.predict(X_test)\r\n explained_variance1,mean_squared1,mean_squared_log1,r_squared1 = performance_measure(y_test,y_pred)\r\n #sum_of_performance_metric(explained_variance1,mean_squared1,mean_squared_log1,r_squared1)\r\n sum_exs1 = sum_exs1 + explained_variance1 \r\n sum_ms1 = sum_ms1 + mean_squared1\r\n sum_r21 = sum_r21 + r_squared1 \r\n sum_msle1 = sum_msle1 + mean_squared_log1\r\n \r\n regressor = ExtraTreesRegressor(n_estimators=500)\r\n regressor.fit(X_train, y_train)\r\n y_pred = regressor.predict(X_test)\r\n explained_variance2,mean_squared2,mean_squared_log2,r_squared2 = performance_measure(y_test,y_pred)\r\n\r\n sum_exs2 = sum_exs2 + explained_variance2\r\n sum_ms2 = sum_ms2 + mean_squared2\r\n sum_r22 = sum_r22 + r_squared2\r\n sum_msle2 = sum_msle2 + mean_squared_log2\r\n\r\n \r\n regressor = DecisionTreeRegressor()\r\n regressor.fit(X_train, y_train)\r\n y_pred = regressor.predict(X_test)\r\n explained_variance3,mean_squared3,mean_squared_log3,r_squared3 = performance_measure(y_test,y_pred)\r\n\r\n sum_exs3 = sum_exs3 + explained_variance3\r\n sum_ms3 = sum_ms3 + mean_squared3\r\n sum_r23 = sum_r23 + r_squared3\r\n sum_msle3 = sum_msle3 + mean_squared_log3\r\n \r\n regressor = svm.SVR()\r\n regressor.fit(X_train, y_train)\r\n y_pred = regressor.predict(X_test)\r\n explained_variance4,mean_squared4,mean_squared_log4,r_squared4 = performance_measure(y_test,y_pred)\r\n\r\n sum_exs4 = sum_exs4 + explained_variance4\r\n sum_ms4 = sum_ms4 + mean_squared4\r\n sum_r24 = sum_r24 + r_squared4\r\n sum_msle4 = sum_msle4 + mean_squared_log4\r\n \r\n regressor = AdaBoostRegressor()\r\n regressor.fit(X_train, y_train)\r\n y_pred = regressor.predict(X_test)\r\n explained_variance5,mean_squared5,mean_squared_log5,r_squared5 = performance_measure(y_test,y_pred)\r\n\r\n sum_exs5 = sum_exs5 + explained_variance5\r\n sum_ms5 = sum_ms5 + mean_squared5\r\n sum_r25 = sum_r25 + r_squared5\r\n sum_msle5 = sum_msle5 + mean_squared_log5\r\n \r\nprint(\" ..........Average of 5 fold performance............ \") \r\nprint(\"Model 1: RandomForestRegressor\") \r\navg_RandomForest_exs = (sum_exs5)/5\r\navg_RandomForest_ms = (sum_ms5)/5\r\navg_RandomForest_r2 = (sum_r25)/5\r\navg_RandomForest_msle = (sum_msle5)/5\r\n\r\nprint('explained variance = {}'.format(avg_RandomForest_exs))\r\nprint('mean squared error = {}'.format(avg_RandomForest_ms))\r\nprint('r2 = {}'.format(avg_RandomForest_r2))\r\nprint('mean squared log error = {}'.format(avg_RandomForest_msle))\r\n\r\n\r\nprint(\"Model 2: ExtraTreesRegressor \")\r\navg_ExtraTrees_exs = (sum_exs2)/5\r\navg_ExtraTrees_ms = (sum_ms2)/5\r\navg_ExtraTrees_r2 = (sum_r22)/5\r\navg_ExtraTrees_msle = (sum_msle2)/5\r\n\r\nprint('explained variance = {}'.format(avg_ExtraTrees_exs))\r\nprint('mean squared error = {}'.format(avg_ExtraTrees_ms))\r\nprint('r2 = {}'.format(avg_ExtraTrees_r2))\r\nprint('mean squared log error = {}'.format(avg_ExtraTrees_msle))\r\n\r\n\r\nprint(\"Model 3: DecisionTreeRegressor \")\r\navg_DecisionTree_exs = (sum_exs3)/5\r\navg_DecisionTree_ms = (sum_ms3)/5\r\navg_DecisionTree_r2 = (sum_r23)/5\r\navg_DecisionTree_msle = (sum_msle3)/5\r\n\r\nprint('explained variance = {}'.format(avg_DecisionTree_exs))\r\nprint('mean squared error = {}'.format(avg_DecisionTree_ms))\r\nprint('r2 = {}'.format(avg_DecisionTree_r2))\r\nprint('mean squared log error = {}'.format(avg_DecisionTree_msle))\r\n\r\n\r\nprint(\"Model 4: SupportVectorMachine \")\r\navg_SupportVector_exs = (sum_exs4)/5\r\navg_SupportVector_ms = (sum_ms4)/5\r\navg_SupportVector_r2 = (sum_r24)/5\r\navg_SupportVector_msle = (sum_msle4)/5\r\n\r\nprint('explained variance = {}'.format(avg_SupportVector_exs))\r\nprint('mean squared error = {}'.format(avg_SupportVector_ms))\r\nprint('r2 = {}'.format(avg_SupportVector_r2))\r\nprint('mean squared log error = {}'.format(avg_SupportVector_msle))\r\n\r\n \r\nprint(\"Model 5: AdaBoostRegressor \")\r\navg_AdaBoost_exs = (sum_exs5)/5\r\navg_AdaBoost_ms = (sum_ms5)/5\r\navg_AdaBoost_r2 = (sum_r25)/5\r\navg_AdaBoost_msle = (sum_msle5)/5\r\n\r\nprint('explained variance = {}'.format(avg_AdaBoost_exs))\r\nprint('mean squared error = {}'.format(avg_AdaBoost_ms))\r\nprint('r2 = {}'.format(avg_AdaBoost_r2))\r\nprint('mean squared log error = {}'.format(avg_AdaBoost_msle)) \r\n \r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\ncorrmat = features[['Temperature ','Concentration of carbon','Temperature anomaly ']]\r\ncorrmat = corrmat.corr()\r\nf, ax = plt.subplots(figsize=(7,7))\r\nsns.heatmap(corrmat, vmin=-.9, vmax=.9,annot=True,fmt=\".2f\",square=True, cmap = 'coolwarm')\r\nplt.show() \r\n\r\n\r\n'''\r\n\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\ncorrmat = features[['Temperature ','Concentration of carbon','Temperature anomaly ']]\r\ncorrmat = corrmat.corr()\r\nf, ax = plt.subplots(figsize=(7,7))\r\nsns.heatmap(corrmat, vmin=-.9, vmax=.9,annot=True,fmt=\".2f\",square=True, cmap = 'coolwarm')\r\nplt.show()\r\n\r\nfrom sklearn import tree \r\nclf = tree.DecisionTreeClassifier()\r\nclf = clf.fit(features,sealevels)\r\ntree.export_graphviz(clf, out_file='tree.dot') \r\n\r\n\r\n'''\r\n\r\n\r\n\r\n\r\n \r\n" } ]
2
ctrlcctrlv/WhergBot
https://github.com/ctrlcctrlv/WhergBot
46bf882074010e32d4109760811292ca7ef81a46
af6c8a03926b8db8aaeb3f8ee00ac538849ac102
b5923374008e840f9a10ce934ec0420bb06a5398
refs/heads/master
2021-01-15T21:14:17.461261
2013-03-26T01:10:07
2013-03-26T01:10:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6949458718299866, "alphanum_fraction": 0.6994584798812866, "avg_line_length": 38.46428680419922, "blob_id": "92123b4095ab932f414f3114f7921416e0250c7f", "content_id": "3f36f51fca0eac24990301ec47dc6098e129f89f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1108, "license_type": "no_license", "max_line_length": 131, "num_lines": 28, "path": "/Plugins/LastSeen/lastseen.py", "repo_name": "ctrlcctrlv/WhergBot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport sqlite3\nimport time\n\nclass Seen(object):\n\tdef __init__(self, database=\":memory:\"):\n\t\tself.database = database\n\t\tself.Conn = sqlite3.connect(self.database, check_same_thread = False)\n\t\tself.Cursor = self.Conn.cursor()\n\t\tself.Cursor.execute(\"CREATE TABLE IF NOT EXISTS lastseen (nick TEXT PRIMARY KEY, channel TEXT, last_msg TEXT, timestamp DATE)\")\n\n\tdef getLastSeen(self, nick):\n\t\tresults = self.Cursor.execute(\"SELECT channel, last_msg, timestamp FROM lastseen WHERE nick=?\", [nick])\n\t\ttry:\n\t\t\tchannel, last_msg, timestamp = results.fetchone()\n\t\t\treturn (nick, channel, last_msg, timestamp)\n\t\texcept TypeError:\n\t\t\treturn None\n\n\tdef addLastSeen(self, nick, channel, last_msg):\n\t\ttimestamp = time.time()\n\t\tx = self.Cursor.execute(\"SELECT COUNT(0) FROM lastseen WHERE nick=?\", [nick])\n\t\tif x.fetchone()[0] == 0:\n\t\t\tself.Cursor.execute(\"INSERT INTO lastseen VALUES (?, ?, ?, ?)\", [nick, channel, last_msg, timestamp])\n\t\telse:\n\t\t\tself.Cursor.execute(\"UPDATE lastseen SET channel=?, last_msg=?, timestamp=? WHERE nick=?\", [channel, last_msg, timestamp, nick])\n\t\tself.Conn.commit()\n\n\n\n" }, { "alpha_fraction": 0.5194174647331238, "alphanum_fraction": 0.5436893105506897, "avg_line_length": 40.20000076293945, "blob_id": "bfad7fc0945b643d96d648a4e94228cfb0dba53c", "content_id": "6e8a9e23da02ce2d43fab5124eb7c6ed3ac947cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 206, "license_type": "no_license", "max_line_length": 63, "num_lines": 5, "path": "/Plugins/LastSeen/Settings.py", "repo_name": "ctrlcctrlv/WhergBot", "src_encoding": "UTF-8", "text": "Settings = {\"database\": \"LastSeen.sql3\"\n\t\t,\"timestamp\": \"%h %d, %Y around %I:%M:%S %p\" # 12 hr w/ am/pm\n#\t\t,\"timestamp\": \"%h %d, %Y around %H:%M:%S\" # 24 hr format\n\t\t,\"blacklist\": [\"#opers\", \"#services\"]\n}\n" }, { "alpha_fraction": 0.5535714030265808, "alphanum_fraction": 0.5681818127632141, "avg_line_length": 27, "blob_id": "7879ee97592233029aec39c134d358b152db2313", "content_id": "36aaebd0def7c3d6fd0e3b240fa843e9314e6b0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 616, "license_type": "no_license", "max_line_length": 75, "num_lines": 22, "path": "/Plugins/Gentbot/Settings.py", "repo_name": "ctrlcctrlv/WhergBot", "src_encoding": "UTF-8", "text": "Settings = {\n\t'allowed':['[email protected]']\n\t,'gentbot': {\n\t\t'replyrate': 15\n\t\t,\"data_dir\": \"Plugins/Gentbot/data/\" #data dir\n\t\t,\"num_contexts\": 0 # Total word contextx\n\t\t,\"num_words\": 0 # Total unique words known\n\t\t,\"max_words\": 12000 # Max limit in the number of words known\n\t\t,\"learning\": True # Allow the bot to learn?\n\t\t,\"ignore_list\": ['!.', '?.', \"'\", ',', ';', 'asl', 'h'] # Words to ignore\n\t\t,\"no_save\": False # If true, dont save to disk\n\t}\n\t,'twitter': {\n\t\t'use': False,\n\t\t'oauth-keys': {\n\t\t\t\"consumer_key\": 'h',\n\t\t\t\"consumer_secret\": 'h',\n\t\t\t\"access_token_key\": 'h',\n\t\t\t\"access_token_secret\": 'h'\n\t\t}\n\t}\n}\n" }, { "alpha_fraction": 0.6697819232940674, "alphanum_fraction": 0.6853582262992859, "avg_line_length": 25.75, "blob_id": "b8ab4020759de1d5868524a16af9f4d7ea02649c", "content_id": "ad75bdfa37d0c332902dcf50ca10490981c83f00", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2568, "license_type": "no_license", "max_line_length": 84, "num_lines": 96, "path": "/Plugins/Gentbot/Main.py", "repo_name": "ctrlcctrlv/WhergBot", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\nfrom time import sleep\nfrom threading import Thread\ntry:\n\timport queue\nexcept ImportError:\n\timport Queue as queue\n\nfrom . import pyborg\nfrom .Settings import Settings\n\nclass TwitterOutput(object):\n\tdef __init__(self, oauth_keys):\n\t\ttwitter = __import__('twitter')\n\t\tself.apiHandle = twitter.Api(**oauth_keys)\n\n\tdef tweet(self, message):\n\t\tif (len(message) < 8):\n\t\t\treturn\n\t\telse:\n\t\t\tif len(message.strip()) > 140:\n\t\t\t\ttweet = message.strip()[0:136]+'...'\n\t\t\telse:\n\t\t\t\ttweet = message.strip()\n\t\t\ttry:\n\t\t\t\tself.apiHandle.PostUpdate(tweet)\n\t\t\texcept Exception:\n\t\t\t\tpass # until there is proper logging\n\nclass Main(object):\n\tdef __init__(self, Name, Parser):\n\t\tself.__name__ = Name\n\t\tself.Parser = Parser\n\t\tself.IRC = self.Parser.IRC\n\t\tself.Queue = queue.Queue()\n\n\t\tif Settings.get('twitter').get('use'):\n\t\t\ttry:\n\t\t\t\tself.twitter = TwitterOutput(Settings.get('twitter').get('oauth-keys'))\n\t\t\t\tself.isTweeting = True\n\t\t\texcept (ImportError, KeyError):\n\t\t\t\tself.isTweeting = False\n\t\telse:\n\t\t\tself.isTweeting = False\n\n\t\tself.Pyborg = pyborg.pyborg(settings=Settings.get('gentbot'))\n\t\tself.Learning = Settings.get('gentbot').get('learning')\n\t\tself.Replyrate = Settings.get('gentbot').get('replyrate')\n\n\t\tself.Main = Thread(target=self.processForever)\n\t\tself.Main.daemon = True\n\t\tself.Main.start()\n\n\tdef Load(self):\n\t\tself.Parser.hookCommand(\"PRIVMSG\", self.__name__, {\".*\": self.process})\n\tdef Unload(self):\n\t\tself.save()\n\t\tdel self.Parser.loadedPlugins[self.__name__]\n\tdef Reload(self):\n\t\tpass\n\n\tdef save(self):\n\t\tself.Pyborg.save_all()\n\n\tdef output(self, message, data):\n\t\tif self.isTweeting and \"\\x19\\x08\\x15\\x21\\x10\\x15\\x20\\x01\\x03\\x08\\x09\" not in data:\n\t\t\t# This is a horrible hack, but it would be more accurate than checking for\n\t\t\t# admin output with regexes\n\t\t\tself.twitter.tweet(message)\n\t\tself.IRC.say(data[2], message)\n\n\tdef process(self, data):\n\t\tbody = \" \".join(data[3:])[1:]\n\t\towner = 1 if data[0] in Settings.get(\"allowed\") else 0\n\t\treplyrate = 100 if self.IRC.getnick() in body else self.Replyrate\n\t\tif body.startswith(\"@\"):\n\t\t\tpass\n\t\telse:\n\t\t\targs = (self, body, replyrate, self.Learning, data, owner)\n\t\t\tself.addToQueue(args)\n\n\tdef addToQueue(self, args):\n\t\tself.Queue.put_nowait(args)\n\tdef getFromQueue(self):\n\t\treturn self.Queue.get()\n\n\tdef processForever(self):\n\t\twhile True:\n\t\t\tt = Thread(target=self.Pyborg.process_msg, args=self.getFromQueue())\n\t\t\tt.daemon = True\n\t\t\tt.start()\n\t\t\tsleep(.2)\n\n# find out what I can do to minimize threads\n# change command handling to @gentbot <command> <args>\n# use pyborg.py to convert databases\n" }, { "alpha_fraction": 0.6284693479537964, "alphanum_fraction": 0.6433085799217224, "avg_line_length": 29.325000762939453, "blob_id": "481204cb4c0da3be72ac4802b531965a2845f893", "content_id": "1491f9adf3ba2f37ddef6ed3b0c32f2e04bd851f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3639, "license_type": "no_license", "max_line_length": 149, "num_lines": 120, "path": "/Plugins/UrbanDictionary/Main.py", "repo_name": "ctrlcctrlv/WhergBot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport requests\nimport re\nimport json\nfrom html import entities as htmlentitydefs\nimport logging\nlogger = logging.getLogger(\"UrbanDictionary\")\n\nfrom Parser import Locker\nLocker = Locker(5)\n\nfrom .Settings import Settings\n\ndef convert(text):\n\t\"\"\"Decode HTML entities in the given text.\"\"\"\n\ttry:\n\t\tif type(text) is str:\n\t\t\tuchr = chr\n\t\telse:\n\t\t\tuchr = lambda value: value > 255 and chr(value) or chr(value)\n\t\tdef entitydecode(match, uchr=uchr):\n\t\t\tentity = match.group(1)\n\t\t\tif entity.startswith('#x'):\n\t\t\t\treturn uchr(int(entity[2:], 16))\n\t\t\telif entity.startswith('#'):\n\t\t\t\treturn chr(int(entity[1:]))\n\t\t\telif entity in htmlentitydefs.name2codepoint:\n\t\t\t\treturn chr(htmlentitydefs.name2codepoint[entity])\n\t\t\telse:\n\t\t\t\treturn match.group(0)\n\t\tcharrefpat = re.compile(r'&(#(\\d+|x[\\da-fA-F]+)|[\\w.:-]+);?')\n\t\ttext = charrefpat.sub(entitydecode, text)\n\t\treturn text\n\texcept Exception as e:\n\t\tlogger.exception(\"Error'd on convert()\")\n\t\treturn text\n\n# http://www.urbandictionary.com/tooltip.php?term= <-- Thank god for this url.\n# http://api.urbandictionary.com/v0/define?term= <-- Even better,\nclass Main(object):\n\tdef __init__(self, Name, Parser):\n\t\tself.__name__ = Name\n\t\tself.Parser = Parser\n\t\tself.IRC = self.Parser.IRC\n\n\t\tself.CacheFile = Settings.get(\"CacheFile\", \"Plugins/UrbanDictionary/Cache.txt\")\n\n\t\t# create it if it doesnt exist.\n\t\ttry:\n\t\t\tc = open(self.CacheFile, 'r')\n\t\texcept IOError:\n\t\t\tc = open(self.CacheFile, 'w')\n\t\tc.close()\n\t\tdel c\n\n\n\tdef checkCacheForDef(self, word):\n\t\twith open(self.CacheFile, 'r') as c:\n\t\t\tcache = c.read().split('\\n')\n\t\t\tfor line in cache:\n\t\t\t\tif line.startswith(word.lower()):\n\t\t\t\t\treturn line.split(\" : \")[1]\n\t\t\telse:\n\t\t\t\treturn False\n\n\tdef addWordToCache(self, word, definition=''):\n\t\twith open(self.CacheFile, 'a') as c:\n\t\t\tlogger.info('Adding word {0}'.format(word))\n\t\t\tc.write(\"{0} : {1}\\n\".format(word, definition))\n\n\tdef Main(self, data):\n\t\tif Locker.Locked:\n\t\t\tself.IRC.notice(data[0].split(\"!\")[0], \"Please wait a little bit longer before using this command.\")\n\t\t\treturn None\n\t\tword = ' '.join(data[4:])\n\t\tcheckCache = self.checkCacheForDef(word)\n\t\tif checkCache:\n\t\t\tlogger.info(\"Sending cached word.\")\n\t\t\tself.IRC.say(data[2], \"\\x02[UrbanDict]\\x02 {0}: {1}\".format(word, checkCache))\n\t\t\tLocker.Lock()\n\t\t\treturn None\n\n\t\tlogger.info(\"Polling UrbanDictionary.\")\n\t\turl = \"http://www.urbandictionary.com/tooltip.php?term={0}\".format(word.replace(\" \",\"%20\"))\n\t\ttry:\n\t\t\thtml = requests.get(url).text\n\t\texcept requests.HTTPError:\n\t\t\tlogger.exception(\"Failed to connect.\")\n\t\t\tself.IRC.say(data[2], \"Failed to connect to Urban Dictionary.\")\n\t\t\treturn None\n\n\t\thtml = html.replace(\"\\\\u003C\", \"<\").replace(\"\\\\u003E\",\">\")\n\t\thtml = json.loads(html)['string']\n\n\t\ttry:\n\t\t\tresult = re.sub(r'[\\r\\n\\t]', \"\", html)\n\t\t\tresult, other = re.search(\"<div>\\s*<b>.*?</b></div><div>\\s*(?:.*?<br/><br/>)?(.*?)</div>(?:<div class='others'>\\s*(.*?)</div>)?\", result).groups()\n\t\texcept Exception as e:\n\t\t\tlogger.exception(\"Error parsing html\")\n\t\t\tresult = None\n\t\tif not result or result is None or result == '':\n\t\t\tself.IRC.say(data[2], \"\\x02[UrbanDict]\\x02 {0} has not yet been defined.\".format(word))\n\t\t\treturn None\n\n\t\tresults = []\n\t\tfor x in re.split(\"<br/>\", result):\n\t\t\tif x == \" \" or x == \"\":\n\t\t\t\tcontinue\n\t\t\tx = x.replace('&quot;', '\"').replace('<b>', '\\x02').replace('</b>', '\\x02').replace('<br/>', '')\n\t\t\tresults.append(x)\n\t\t\tself.IRC.say(data[2], \"\\x02[UrbanDict]\\x02 {0}: {1}\".format(word, x))\n\t\tLocker.Lock()\n\t\tself.addWordToCache(word.lower(), \" \".join(results))\n\n\tdef Load(self):\n\t\tself.Parser.hookCommand(\"PRIVMSG\", self.__name__, {\"^@ud .*?$\": self.Main})\n\n\tdef Unload(self):\n\t\tpass\n" }, { "alpha_fraction": 0.5051903128623962, "alphanum_fraction": 0.5238754153251648, "avg_line_length": 16.609756469726562, "blob_id": "ee78593b9124de29a96277d2e52834fcca7305ba", "content_id": "dcd8078e442d9e774c5cb5b160d85d379b946ccb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 70, "num_lines": 82, "path": "/Config.py", "repo_name": "ctrlcctrlv/WhergBot", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\nGlobal = {\n\t\"unwantedchars\": \"\\x03(?:[0-9]{1,2})?(?:,[0-9]{1,2})?|\\x02|\\x07|\\x1F\"\n\t}\n\nServers = {\n\t\"DatNode\":\n\t\t{\"host\": \"mempsimoiria.datnode.net\"\n\t\t,\"port\": 6697\n\t\t,\"nick\": \"Wherg\"\n\t\t,\"realname\": \"WhergBot 2.0 [Ferus]\"\n\t\t,\"ident\": \"Wherg\"\n\t\t,\"channels\": \"#boats\"\n\t\t,\"ssl\": True\n\t\t,\"enabled\": True\n\t\t,\"quitmessage\": \"h\"\n\t\t,\"plugins\": [\n\t\t\t'Services'\n\t\t\t,'CleverBot'\n\t\t\t,'Omegle'\n\t\t\t,'Oper'\n\t\t\t,'Plinko'\n\t\t\t,'Misc'\n\t\t\t,'Quit'\n\t\t\t,'Matix'\n\t\t\t,'Fapget'\n\t\t\t,'GuessingGame'\n\t\t\t,'PyFileServ'\n\t\t\t,'Quotes'\n\t\t\t,'EightBall'\n\t\t\t,'Wikipedia'\n\t\t\t,'Told'\n\t\t\t,'Uptime'\n\t\t\t,'SloganMaker'\n\t\t\t,'Exec'\n\t\t\t,'Asl'\n\t\t\t,'Meme'\n\t\t\t,'Etymology'\n\t\t\t,'Slap'\n\t\t\t,'YouTube'\n\t\t\t,'Tinyboard'\n\t\t\t,'Ermahgerd'\n\t\t\t,'Wordnik'\n\t\t\t,'UrbanDictionary'\n\t\t\t,'InsultGenerator'\n\t\t\t,'FuckMyLife'\n\t\t\t,'Imgur'\n\t\t\t,'General'\n\t\t\t,'Weather'\n\t\t\t,'Roulette'\n#\t\t\t,'PyMpd'\n\t\t\t,'WhatStatus'\n\t\t\t,'WheelofFortune'\n\t\t\t,'UrlAnnounce'\n\t\t\t]\n\t\t,\"owner\": {\"nicks\": [\"Ferus\", \"Ferrous\", \"^\"]\n\t\t\t,\"hosts\": [\"the.interwebs\", \"ur.messages\"]\n\t\t\t,\"idents\": [\"anonymous\", \"carroting\"]\n\t\t}\n\t}\n\n\t,\"GentBot\":\n\t\t{\"host\": \"mempsimoiria.datnode.net\"\n\t\t,\"port\": 6697\n\t\t,\"nick\": \"gentbot|h\"\n\t\t,\"realname\": \"WhergBot 2.0 [Ferus]\"\n\t\t,\"ident\": \"gentbot\"\n\t\t,\"channels\": \"#boats\"\n\t\t,\"ssl\": True\n\t\t,\"enabled\": False\n\t\t,\"quitmessage\": 'h'\n\t\t,\"plugins\": [\n\t\t\t'General'\n\t\t\t,'GentBot'\n\t\t\t,'Services'\n\t\t\t]\n\t\t,\"owner\": {\"nicks\": [\"Ferus\"]\n\t\t\t,\"hosts\": [\"the.interwebs\"]\n\t\t\t,\"idents\": [\"anonymous\"]\n\t\t\t}\n\t\t}\n}\n\n" } ]
6
DiscOH/FileDragGui
https://github.com/DiscOH/FileDragGui
f8acaca3c160281398fee091952a75941d3db833
d83b5c9ddbdfa88c4007616386a3da6b37ac9878
20f0f81a5b30886606292b9dfdc937d29967aabf
refs/heads/master
2021-05-07T16:45:59.113355
2017-10-28T00:27:25
2017-10-28T00:27:25
108,603,836
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5661764740943909, "alphanum_fraction": 0.5735294222831726, "avg_line_length": 21.83333396911621, "blob_id": "9e9b32a3236314846166e749de72ea9d9a3171a0", "content_id": "b7bf1e33f274a096505c186f85f76cb879e83380", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 136, "license_type": "no_license", "max_line_length": 36, "num_lines": 6, "path": "/main.py", "repo_name": "DiscOH/FileDragGui", "src_encoding": "UTF-8", "text": "from sys import argv as sys_argv\n\nif __name__ == \"__main__\":\n\twith open('sample.txt', 'w+') as t:\n\t\tfor s in sys_argv[1:]:\n\t\t\tt.write(s)" } ]
1
arifjamal89/eserta
https://github.com/arifjamal89/eserta
d70da24073a7806ddf42ebbb339071a00515593b
908c349ba17e8333670c089c536f5d99b029ff2f
5e5842913962b99a45fd4e26703ab2325bc56ed6
refs/heads/master
2020-04-02T13:06:51.261184
2018-10-30T09:04:47
2018-10-30T09:04:47
154,467,792
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6626794338226318, "alphanum_fraction": 0.7105262875556946, "avg_line_length": 37.09090805053711, "blob_id": "90329a8675bfb681f4a58510f2f516951950d523", "content_id": "e51332cc0e2f55200a7752a9cf3dd44eb49a189e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 418, "license_type": "no_license", "max_line_length": 81, "num_lines": 11, "path": "/penganjur/urls.py", "repo_name": "arifjamal89/eserta", "src_encoding": "UTF-8", "text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n\t#http://127.0.0.1:8000/penganjur/\n\tpath('', views.home, name='home_penganjur'),\n\t#http://127.0.0.1:8000/penganjur/aktiviti/add/\n\tpath('aktiviti/add/', views.addaktiviti, name='add_aktiviti'),\n\tpath('aktiviti/<int:pk>/edit/', views.editaktiviti, name='edit_aktiviti'),\n\tpath('aktiviti/<int:pk>/delete', views.delete_aktiviti, name='delete_aktiviti'),\n]" }, { "alpha_fraction": 0.7129202485084534, "alphanum_fraction": 0.7191826105117798, "avg_line_length": 26.590909957885742, "blob_id": "599d61f6ca76cfd83bcc7fa1b9fd264bb4d6825d", "content_id": "871ce557e5469971880cba99f16cc11bf4ad3df1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3034, "license_type": "no_license", "max_line_length": 86, "num_lines": 110, "path": "/penganjur/views.py", "repo_name": "arifjamal89/eserta", "src_encoding": "UTF-8", "text": "from django.shortcuts import render,redirect,get_object_or_404\nfrom .models import Aktiviti\nfrom .forms import AktivitiForm\nfrom django.urls import reverse_lazy\n\n# Create your views here.\n\n# Home penganjur\ndef home(request):\n\n\t# aktivitiid = request.GET['aktivitiid']\n\t#print(request.GET['aktivitiid'])\t\t\t\t#sama macam get php id\n\n\t#List of record\n\ta = Aktiviti.objects.all()\t\t\t\t\t\t#semua object/data letak dalam a\n\t#print(a.tajuk) \n\t# for ak in a:\t\t\t\t\t\t\t\t\t#Papar data di cmd\n\t# \tprint (ak.tajuk,ak.tempat,ak.penceramah)\n\n\treturn render(request,'penganjur/home.html',{'aktiviti': a}) \n\n#update aktiviti\ndef update_penganjur(request,pk):\n\t#dapatkan id aktiviti dan cari rekod\n\taktiviti = get_object_or_404(Aktiviti,pk)\n\taktiviti = Aktiviti(tajuk='Not Cheddar Update',tempat='Anyplace update',\n\t\tpenceramah='Anybody Update',hadpeserta=20)\n\taktiviti.save()\n\n\treturn render(request,'penganjur/home.html') \n\n#tambah aktiviti\ndef add_penganjur(request):\n\n\t#tambah aktiviti setiap kali request\n\takt = Aktiviti(tajuk='Not',tempat='Anyplaces',\n\t\tpenceramah='Anybody',hadpeserta=55)\n\takt.save() #Tambah Data\n\n\treturn render(request,'penganjur/home.html') \n\n#delete penganjur\ndef delete_penganjur(request,pk):\n\t#get id aktiviti dan cari rekod\n\taktiviti = get_object_or_404(Aktiviti,pk)\n\n\t#confirm delete\n\taktiviti.delete()\n\n\treturn render(request,'penganjur/home.html') \n\n\n#tambah aktiviti forms py\ndef addaktiviti(request):\n\n\tif request.method == \"POST\":\n\t\t\n\t\tform = AktivitiForm(request.POST) \t\t\t#value akan submit ke form\n\n\t\tif form.is_valid(): \t\t\t\t\t\t\t\t#validate semak semua dah isi\n\t\t\taktiviti = form.save(commit=False) \t\t\t\t#simpan dalam memori\n\t\t\taktiviti.save() \t\t\t\t\t\t\t\t#save ke db\n\t\t\treturn redirect(reverse_lazy('home_penganjur'))\n\t\t#print(\"POST DAH MASUK\") \t\t\t\t\t\t\t#ini macam echo nak semak masuk POST ke x\n\n\n\telse:\n\t\tform= AktivitiForm()\n\t\t#print(form)\n\n\treturn render(request,'penganjur/tambahaktiviti.html',{'form' : form})\n\n#hapus aktiviti guna form\ndef delete_aktiviti(request,pk):\n\n\taktiviti = get_object_or_404(Aktiviti,pk=pk)\n\n\tif request.method == 'POST':\n\n\t\tif request.POST.get(\"submit_yes\"):\n\t\t\tprint(request.method)\n\t\t\taktiviti.delete()\n\t\t\treturn redirect(reverse_lazy('home_penganjur'))\n\n\t#View page confirm delete\t\n\treturn render(request,'penganjur/confirm_delete_aktiviti.html',{'aktiviti':aktiviti})\n\n#edit aktiviti forms py\ndef editaktiviti(request,pk):\n\n\t#Dapatkan rekod berdasarkan pk yang dihantar\n\taktiviti= get_object_or_404(Aktiviti,pk=pk)\n\n\n\tif request.method == \"POST\":\n\t\t\n\t\tform = AktivitiForm(request.POST,instance=aktiviti) #value akan submit ke form\n\n\t\tif form.is_valid(): \t\t\t\t\t\t\t\t#validate semak semua dah isi\n\t\t\taktiviti = form.save(commit=False) \t\t\t\t#simpan dalam memori\n\t\t\taktiviti.save() \t\t\t\t\t\t\t\t#save ke db\n\t\t\treturn redirect(reverse_lazy('home_penganjur'))\n\t\t#print(\"POST DAH MASUK\") \t\t\t\t\t\t\t#ini macam echo nak semak masuk POST ke x\n\n\n\telse:\n\t\tform= AktivitiForm(instance=aktiviti) #yang ni dapatkan id untuk papar\n\t\t#print(form)\n\n\treturn render(request,'penganjur/editaktiviti.html',{'form' : form})" }, { "alpha_fraction": 0.8345323801040649, "alphanum_fraction": 0.8345323801040649, "avg_line_length": 30, "blob_id": "eff1091f281d2e4001d4069b0cc267f447e40000", "content_id": "8a1c9abf205a88ce587e1003d56eaab6fcb30dc3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 278, "license_type": "no_license", "max_line_length": 54, "num_lines": 9, "path": "/penganjur/admin.py", "repo_name": "arifjamal89/eserta", "src_encoding": "UTF-8", "text": "from import_export.admin import ImportExportModelAdmin\nfrom django.contrib import admin\nfrom .models import Aktiviti #import table aktiviti\n\n# Register your models here.\n#admin.site.register(Aktiviti) \[email protected](Aktiviti)\nclass AktivitiAdmin(ImportExportModelAdmin):\n\tpass" } ]
3
rakesh329/Simulating-a-disease-spread-and-visualizing-curve-using-python
https://github.com/rakesh329/Simulating-a-disease-spread-and-visualizing-curve-using-python
133eb33273e2df245b0ce05b0163184bd78e4af5
d4b0cc8e1753d3d3251b257cf73c4001ebb71275
41ef2850609ee84c175c3c21252e665390e468ce
refs/heads/main
2023-07-09T17:52:24.097938
2021-08-02T03:01:48
2021-08-02T03:01:48
388,018,793
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6466395258903503, "alphanum_fraction": 0.6583502888679504, "avg_line_length": 37.509803771972656, "blob_id": "d8898e65fae51461a7b7b080de1abb4a97657431", "content_id": "cea9103303ab89227b6656221abffa9a9ada9c0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1964, "license_type": "no_license", "max_line_length": 117, "num_lines": 51, "path": "/Social_connections.py", "repo_name": "rakesh329/Simulating-a-disease-spread-and-visualizing-curve-using-python", "src_encoding": "UTF-8", "text": "\"\"\"\nWritten by : Rakesh Namballa\nStarted date : 23/05/2020\nLast edited: 08/06/2020\nDescription: \" Representing social connections \"\nIn this code we create objects for all the people and add friends to each person depending on the sample txt file.\nSample file consist of all the Person names along with their respective friends.\n\n\"\"\"\n\n\nclass Person:\n def __init__(self, first_name, last_name):\n self.friend_list = [] # List for all the friends\n self.first_name = first_name\n self.last_name = last_name\n\n def add_friend(self, friend_person):\n self.friend_list.append(friend_person)\n\n def get_name(self):\n return str(self.first_name + \" \" + self.last_name) # Concatenating first name and last name\n\n def get_friends(self):\n return self.friend_list\n\n\ndef load_people():\n all_personObjects = {} # Each person name and object address stored as a Key:Value pairs.\n all_lines = []\n f = open(\"sample_set.txt\", 'r') # Open the file and read each line.\n for line in f:\n line = line.rstrip() # Removes the /n tag from each line\n all_lines.append(line) # Append each line into a list(all_lines)\n person_name = line.split(\": \") # Separate the Person with friends\n person = Person(person_name[0].split(\" \")[0], person_name[0].split(\" \")[1]) # Splits the first and last name\n all_personObjects[person_name[0]] = person # Person is added into the dictionary along with object address\n\n f.close()\n\n for line in all_lines:\n person_name = line.split(\": \") # Separate the fiends with person\n friend_name = person_name[1].split(\", \") # Separate all the friends\n for friend in friend_name:\n all_personObjects[person_name[0]].add_friend(all_personObjects[friend]) # Add friend object to person\n\n return list(all_personObjects.values()) # return list of all Person objects from the file records\n\n\nif __name__ == '__main__':\n load_people()\n" }, { "alpha_fraction": 0.6673251390457153, "alphanum_fraction": 0.6831291913986206, "avg_line_length": 44.17856979370117, "blob_id": "bcd4d67735c5537e3a4ee38411834a54bd8e7397", "content_id": "2cbbeeabdb0ef16ee35bd379d66f6b5a7ec8a886", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2531, "license_type": "no_license", "max_line_length": 121, "num_lines": 56, "path": "/Visualise_curve.py", "repo_name": "rakesh329/Simulating-a-disease-spread-and-visualizing-curve-using-python", "src_encoding": "UTF-8", "text": "\"\"\"\nWritten by : Rakesh Namballa \nStarted date : 23/05/2020\nLast edited: 08/06/2020\nDescription: \" Visualise the curve \"\nIn this code we create a count vs days graph and visualise the graph\n\"\"\"\n\"\"\"\nTest scenario A: An uncontained outbreak \nNumber of days: 30\nMeeting probability: 0.6 \nPatient zero health: 25 health points \nIn this case as the patient zero health is less he infect more viral load to the friends he meet and the probability of \nmeeting is also more.\nThough running through multiple case the spread for the first few days start slowly but as patients meet regularly the \nviral load gets infected to multiple people fast and at the end of 30 days all the patients are completely effected with \nvirus.\n------------------------------------------------------------------------------------------------------------------------\nTest scenario B: an unpredictable situation \nNumber of days: 60 \nMeeting probability: 0.25 \nPatient zero health: 49 health points \nThis is an unpredictable case where the patient zero health has a mild symptoms and the meeting probability also less.\n* In few cases on first day virus spreads for few people and from second day all patients gets recovers after sleep.\n* In few cases it keeps on increasing and many patients gets infected.\n------------------------------------------------------------------------------------------------------------------------\nTest scenario C: flattening the curve \nNumber of days: 90 \nMeeting probability: 0.18 \nPatient zero health: 40 health points \nIn this cse as the meeting probability is less and the patient zero health is less effected, the increase in the virus \nis less\n* In few cases the patient recovers after few days\n* In few cases patients gets infected but increases slowly \n\"\"\"\n\n\nfrom matplotlib import pyplot as plt # import libraries to plot a graph\nfrom Simulate_disease_spread import run_simulation\n\n\ndef visual_curve(days, meeting_probability, patient_zero_health):\n data_series = run_simulation(days, meeting_probability, patient_zero_health) # storing the list of day_count\n plt.plot(list(range(1, days + 1)), data_series)\n plt.title(\"Virus spread simulation\")\n plt.xlabel(\"Days\")\n plt.ylabel(\"Count\")\n plt.show()\n\n\nif __name__ == '__main__':\n # Take inputs from the user\n days = int(input(\"Enter number of days:\"))\n meeting_probability = float(input(\"Enter meeting probability:\"))\n patient_zero_health = int(input(\"Enter patient zero health:\"))\n visual_curve(days, meeting_probability, patient_zero_health)\n\n" }, { "alpha_fraction": 0.7709367871284485, "alphanum_fraction": 0.7778881192207336, "avg_line_length": 57.567962646484375, "blob_id": "53440cc96d909f7c9c668a90bdd95516efb82ff9", "content_id": "d2ba88b8655f0592fab4599dbe4d160883febfd3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 12140, "license_type": "no_license", "max_line_length": 143, "num_lines": 206, "path": "/README.md", "repo_name": "rakesh329/Simulating-a-disease-spread-and-visualizing-curve-using-python", "src_encoding": "UTF-8", "text": "## Simulating-a-disease-spread-and-visualizing-curve-using-python\n\nThis project is to create the necessary data structure to simulate social links and disease transmission\nbetween people, simulate infections among the population over a period of time, and plot graphs to determine\nwhether an outbreak is contained or not.\n\nWe surveyed 200 fake people, all with unique names, and asked them to provide the names of their friends in the\ngroup who they are in regular contact with. You may assume that each person has specified at least one friend, and\neach of the person’s friends has also named that person as a friend. All the details are present on the sample_set.txt.\n\nThe data file consists of 200 records. Each record is recorded on its own line in the file, and consists of a person’s\nname, together with all the names of that person’s friends. The real file is 200 lines long, but to illustrate the file\nformat, just the first two lines of the file are shown here as a sample:\n> Gill Bates: Jodee Killam, Natacha Osterhoudt, Jom Tones, Verdie Tong, Ossie Digangi\n; Jom Tones: Marry Blakely, Masako Miguel, Gill Bates\n\n**Text file Explaination:**\n\n- The first line in the file is the record for Gill Bates. Gill Bates has named the following people as her social\nconnections: Jodee Killam, Natacha Osterhoudt, Jom Tones, Verdie Tong, and Ossie Digangi. This means that\nif Gill Bates is contagious (able to spread the virus), Gill Bates may infect the people she has named, and if\nher friends are contagious, they may infect Gill Bates.\n\n- On the next line, Jom Tones has named his friends in a similar way, and so on.\n- Note that Gill Bates has named Jom Tones as one of her friends. This means that Jom Tones must also name\nGill Bates as one of his friends. It’s not unusual that may both visit each other, and the virus may travel from\neither person to the other. You can assume that this rule is followed for all records in the file.\n\n## How the virus spreads\n\n**Health of each person**\n\nEach person has a number of health points which changes over time depending on a person’s health.\nThe number of health points is used to check if a patient is contagious (i.e. able to infect other people) or not:\n\n\n>| Health Points | |Description |\n| -------------- | ----------- |\n| 76-100 | |Perfect Health, Not contagious|\n| 75 || Average Health, Not contagious |\n| 50-74 || Fair Health, Not contagious |\n| 30-49 || **contagious** |\n| 0-49 || Poor Health, **contagious** |\n\nWhen sleeping after each day, each person’s immune system will naturally add 5 health points to that person, up to\na maximum of 100 health points.\n\n**Meeting probability**\n\nEach day, a person may or may not visit another person for a meeting. For each person, the probability that they will\ntravel to visit one of their friends depends on social distancing regulations. A single meeting probability parameter\nwill be applied to all people in the group to determine the effect of a certain level of social distancing. This\nprobability is a fraction of 1. \n- For example, running the simulation with a meeting probability of 1.0 means that every\nday, every person will leave home to visit all of their friends, and all their friends will also travel to visit them during\nthe same day. A probability of 0.0 means nobody can leave home to visit anyone else, and a probability of 0.333\nmeans there is a 33.3% random chance of each visit happening.\n\n**Viral load**\n\nThe virus spreads when a contagious person2 passes a viral load to a person they are visiting, or a person who has\nvisited them. The term ‘viral load’ is a measure of the quantity of virus in the air which the other person breathes in\nwhen they are visiting and/or being visited by any contagious person. A person can be affected by a viral load even if\nthey are already partly sick.\n\n**Effect of infection**\n\nWhen a contagious person produces a viral load, every person they meet when visiting (or being visited) will be\ninfected by their viral load. If the viral load is small, or a person is healthy, the person who is infected might not\nbecome sick, and they will quickly recover their health later when they sleep.\n\n\n## Program Explaination\n\nComplete projects is done in three different python files:\n1. Social_connections.py\n2. Simulate_disease_spread.py\n3. Visualise_curve.py\n\n**1. Social_connections.py**\n\nIn this code we create objects for all the people and add friends to each person depending on the sample txt file.\nSample file consist of all the Person names along with their respective friends.\n\n**Person class**\nCreate a Python program that defines a Person class with the following methods.:\n- **__init__(first_name, last_name):**\nConstructor method to create a new Person object.\nwhere first_name and last_name are strings containing the person’s name\n- **add_friend(friend_person):**\nThis method should add a new social connection to be stored in this Person object.\nfriend_person is a reference to another Person object.\n- **get_name():**\nThis method returns a string containing the person’s first and last name concatenated together;\ne.g. “Jom Tones”\n- **get_friends():**\nThis method returns a list of Person objects for the social connections that have been added.\n\nThe purpose of the Person class is to represent a person who is linked to other people by social connections. The\nabove description specifies what methods and form the Person class required to have, but not how to code them.\nTherefore each Person object must be able to store a set of references to other Person objects. (You will need to\nthink about a suitable data type for storing a set of objects, and how you would need to initialize the empty set\nwithin the class definition.) In addition to storing the person’s friends, your Person class should also contain\ninstance variables to keep track of the person’s name.\n\n**2. Simulate_disease_spread.py**\n\nIn this code we create objects for all the patients and add friends to each person depending on the sample txt file.\nWe run a simulation to check the no:of effected people and return a count for each day. This is the most important part in the \nproject as this code contins all the calculation that checks wheather the person is contagious or not.\n\n**Patient class (a subclass of Person)**\n\nThe Person class you defined in Social_connections.py is fine for mapping social connections, but it does not contain appropriate\nmethods for simulating disease spread or health of the people in our group.\nBefore you move to writing the simulation, define a Patient class which inherits the methods of\nthe Person class through inheritance. Your Patient class should add the following methods:\n- **__init__(first_name, last_name, health):**\nConstructor method to create a new Patient object by inheriting from the Person class.\nwhere first_name and last_name are strings containing the person’s name and health is the initial starting value of the person’s health points.\n- **get_health():**\nThis method returns the patient’s current health points.\n- **set_health(new_health):**\nThis method changes the patient’s current health points directly.\n- **is_contagious():**\nThis method should return a Boolean result of True if the person’s health points are in the range of\nbeing contagious able to spread disease. It should return False if the\nperson is not currently contagious.\n- **infect(viral_load):**\nThis method infects the Patient object with a viral load. It causes the patient to receive the viral\nload specified in the method’s argument given as a floating point number.\nAfter receiving a viral load, the person may or may not become sick enough to be contagious.\nCalling this method should adjust the person’s health points according to the rules defined in section\nNote that the person’s health cannot go below 0.\n- **sleep():**\nCalling this method causes the person to recover some health points one night’s sleep.\n\n\n**load_patients function ()**\n\nYou will also need to write a slightly different version of the function you wrote to load data from the file, since we\nreally need a list of Patient objects, not a list of Person objects. Write a function named\nload_patients(default_health) which does the following: \n1. Reads from the file sample_set.txt.\n2. Creates a new Patient object for each record (line) in the file, which contains the name of the person\nrepresented by that record. For each Patient object created, you should assign the health value given by\nthe default_health argument, since the initial health of each person is not listed in the file.\n3. Where a person’s record indicates that they have friends, you should use the inherited add_friend\nmethod to add each friend to that Person object.\n4. Finally, return a list of all the Patient objects that have been created from the file records.\nIn other words, this function should do the same thing as load_people, except that it should create Patient\nobjects (with a specified default health value) instead of Person objects.\n\n\n**run_simulation function – implement the simulation logic**\n\nNow implement a run_simulation(days, meeting_probability, patient_zero_health) function\nwhich should implement the following behaviour:\n1. Take in the following arguments:\n- days: the integer number of days the simulation should run for.\n- meeting_probability: the fractional probability that any person may visit a certain friend on\na certain day. 0.0 means 0% chance, 1.0 means 100% chance. (This was explained in section 2.)\n- patient_zero_health: the initial health of the first person in the file. (See below.) If the\n(rounded) initial health is less than or equal to 49, this person is contagious and there may be\nthe chance of a disease outbreak.\n2. Use your load_patients function to load patient data from the disk. The first patient in the returned\nlist (who we will call ‘patient zero’) should be given the starting health value specified in the\npatient_zero_health argument. The remaining patients should be given an initial health value of\n75, which is the average health of the population from section 2.\n3. Run through each day of the simulation. For each day, do the following:\n- For each patient in the group, look at each of the person’s friends, and randomize whether the\nperson should meet that friend today. 7 The probability for this to happen is given by the\nmeeting_probability argument. If the meeting takes place, each person in that pair who is\ncontagious8 should spread a viral load to the other person, by calling the infect() method on\nthe other person. You will need to calculate what viral load to infect each friend with according\nto the rules in section 2.\n- After all meetings have completed for the day, check how many people are now contagious in\nthe simulation.\n\n- After the end of each day, all people should sleep() to recover some health.\n4. Finally, the function should return a list with the daily number of contagious cases through the duration\nof the simulation. For example, if your simulation runs for 30 days, the list should\ncontain 30 integers containing the number of people who were contagious at the end of each day, from\nthe first day of the simulation (element [0]) to the last day of the simulation.\n\n**3. Visualise_curve.py**\n\n**visual_curve function**\n\nWrite a function named visual_curve(days, meeting_probability, patient_zero_health) which runs\nthe simulation using the specified arguments, and then does the following:\n1. Runs the simulation by calling the run_simulation function with the specified arguments for days,\nmeeting_probability, patient_zero_health.\n2. After the simulation is complete, prints the whole daily list of contagious patient counts from the returned\ndata.\n3. Then, using functionality from either the matplotlib or pandas library, plot a curve showing the daily\nnumber of contagious patients over the number of days of the simulation. The days of the simulation should\nbe on the X axis and the contagious patient count on the Y axis. Your graph should have the X and Y axis\nlabelled accordingly.\n\n> The output diagrams are provided for different senarious\n![alt text](scenario_A.png)\n\n![alt text](scenario_B.png)\n\n![alt text](scenario_c.png)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5868647694587708, "alphanum_fraction": 0.6031920909881592, "avg_line_length": 43.317073822021484, "blob_id": "c6ff8977046873143fcfc411dab2897e9b2a36ae", "content_id": "c142f37e0e6c0e8e30bac013f5afa34d5fb24325", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5455, "license_type": "no_license", "max_line_length": 119, "num_lines": 123, "path": "/Simulate_disease_spread.py", "repo_name": "rakesh329/Simulating-a-disease-spread-and-visualizing-curve-using-python", "src_encoding": "UTF-8", "text": "\"\"\"\nWritten by : Rakesh Namballa\nStarted date : 26/05/2020\nLast edited: 08/06/2020\nDescription: \" Simulate disease spread \"\nIn this code we create objects for all the patients and add friends to each person depending on the sample txt file.\nWe run a simulation to check the no:of effected people and return a count for each day.\n\"\"\"\nimport random\n\nfrom Social_connections import Person\n\n\nclass Patient(Person):\n def __init__(self, first_name, last_name, health):\n super().__init__(first_name, last_name)\n self.friend_list = []\n self.first_name = first_name\n self.last_name = last_name\n self.health = set_health_boundary(health) # Initial starting person’s health point values\n\n def get_health(self):\n return round(self.health) # Returns the patient’s current health points\n\n def set_health(self, new_health):\n self.health = set_health_boundary(round(new_health)) # Changes health points\n\n def is_contagious(self):\n if self.health < 50:\n return True\n else:\n return False\n\n def infect(self, viral_load):\n if self.health <= 29:\n self.health = set_health_boundary(round(self.health - (0.1 * viral_load)))\n return\n elif self.health < 50:\n self.health = set_health_boundary(round(self.health - (1.0 * viral_load)))\n return\n elif self.health >= 50:\n self.health = set_health_boundary(round(self.health - (2.0 * viral_load)))\n return\n\n def sleep(self):\n self.health = set_health_boundary(self.health + 5) # Add 5 heath points after sleep\n\n\ndef set_health_boundary(value): # Method to set the min and max health points\n if value <= 0:\n return 0\n elif value >= 100:\n return 100\n else:\n return value\n\n\ndef run_simulation(days, meeting_probability, patient_zero_health):\n all_PatientObjects = load_patients(75) # Set all the patients with initial health by calling load_patient()\n all_PatientObjects[0].set_health(patient_zero_health) # Specify the zero patient health\n\n events = [\"meet\", \"don'tmeet\"] # List for the use in random.choices()\n not_meeting_probability = round(1 - meeting_probability, 2)\n day_count = []\n for i in range(0, days):\n for patient in all_PatientObjects:\n for friend in patient.get_friends(): # Gets all the friend for that patient object\n # random.choices() returns a list with randomly selected from the specified sequence\n toMeet = random.choices(events, weights=[meeting_probability, not_meeting_probability])[0]\n if toMeet == \"meet\":\n # Checks if both patient and meeting friend are contagious\n if friend.is_contagious() and patient.is_contagious():\n friend_health = friend.get_health()\n # from given viral load formula\n friend_viral_load = (((friend_health - 25) * (friend_health - 25)) / 62) + 5\n person_health = patient.get_health()\n person_viral_load = (((person_health - 25) * (person_health - 25)) / 62) + 5\n friend.infect(person_viral_load)\n patient.infect(friend_viral_load)\n # Enter the condition if only friend is contagious\n elif friend.is_contagious():\n friend_health = friend.get_health()\n friend_viral_load = (((friend_health - 25) * (friend_health - 25)) / 62) + 5\n patient.infect(friend_viral_load)\n # Enter the condition if only patient is contagious\n elif patient.is_contagious():\n person_health = patient.get_health()\n person_viral_load = (((person_health - 25) * (person_health - 25)) / 62) + 5\n friend.infect(person_viral_load)\n\n count = 0\n for patient in all_PatientObjects:\n if patient.is_contagious():\n count = count + 1 # count for no:of infected patients each day\n patient.sleep()\n day_count.append(count)\n return day_count # return the list of day_count\n\n\ndef load_patients(initial_health):\n all_PatientObjects = {} # Each patient name and object address stored as a Key:Value pairs.\n all_lines = []\n f = open(\"a2_sample_set.txt\", 'r') # Open the file and read each line.\n for line in f:\n line = line.rstrip() # Removes the /n tag from each line\n all_lines.append(line) # Append each line into a list\n patient_name = line.split(\": \") # Separate the patient with friends\n patient = Patient(patient_name[0].split(\" \")[0], patient_name[0].split(\" \")[1], initial_health)\n all_PatientObjects[patient_name[0]] = patient # Patient is added into the dictionary along with object address\n\n f.close()\n\n for line in all_lines:\n patient_name = line.split(\": \") # Separate the fiends with patient\n friend_names = patient_name[1].split(\", \") # Separate all the friends\n for friend in friend_names:\n all_PatientObjects[patient_name[0]].add_friend(all_PatientObjects[friend])\n\n return list(all_PatientObjects.values()) # return list of all Patient objects from the file records\n\n\nif __name__ == '__main__':\n run_simulation(40, 1, 1)\n" } ]
4
amansh45/Neural-Network
https://github.com/amansh45/Neural-Network
e8b7d47693b47ce227b70ff5a369009729809beb
2b73e7e36fe331fade85a3e4e19d953037034d7a
9cb6127df37fce863b6c351d7e03b756b78414bd
refs/heads/master
2020-05-01T04:19:53.387374
2019-03-23T09:49:14
2019-03-23T09:49:14
177,271,188
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.544753909111023, "alphanum_fraction": 0.5538918972015381, "avg_line_length": 36.84166717529297, "blob_id": "ae58ad3a21fa2ff4df622d7c3d61c0064ecb8e4b", "content_id": "5b48980fda9fc44e4f66ff9a2d944095dbd893ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9083, "license_type": "no_license", "max_line_length": 147, "num_lines": 240, "path": "/src/neural_net.py", "repo_name": "amansh45/Neural-Network", "src_encoding": "UTF-8", "text": "import numpy as np\nimport math\nimport copy\nimport pandas as pd\nimport os\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils.extmath import softmax\nfrom scipy.special import expit\nimport time\nfrom matplotlib import pyplot as plt\n\nclass Layer:\n def __init__(self, num_neurons = None, activation = None, batch_size = None):\n self.num_neurons = num_neurons\n self.activation = activation\n self.input = np.zeros((batch_size, num_neurons))\n self.output = np.zeros((batch_size, num_neurons))\n self.delta = np.zeros((batch_size, num_neurons))\n\nclass Model:\n def __init__(self, batch):\n self.layers = []\n self.weights = {}\n self.weight_labels = []\n self.loss = None\n self.learn_rate = None\n self.batch = batch\n\n def initialize_weights(self, input_layer_len):\n self.num_weights = len(self.layers)\n num_neurons = []\n for layer in self.layers:\n num_neurons.append(layer.num_neurons)\n weight_mat_dimensions = []\n weight_mat_dimensions.append([input_layer_len, num_neurons[0]])\n self.weight_labels.append(\"i_h0\")\n for i in range(len(num_neurons)-1):\n weight_mat_dimensions.append([num_neurons[i], num_neurons[i+1]])\n self.weight_labels.append(\"h\"+str(i)+\"_h\"+str(i+1))\n \n for i in range(len(weight_mat_dimensions)):\n self.weights[self.weight_labels[i]] = np.random.rand(weight_mat_dimensions[i][0],weight_mat_dimensions[i][1])\n\n for i in range(len(weight_mat_dimensions)):\n self.weights[self.weight_labels[i]] = self.weights[self.weight_labels[i]] * math.sqrt(2.0/self.weights[self.weight_labels[i]].shape[0])\n\n\n def apply_activation(self, in_arr, activation):\n if activation == \"sigmoid\":\n return 1.0 / (1 + np.exp(-in_arr))\n elif activation == \"relu\":\n out_arr = np.maximum(0,in_arr)\n return out_arr\n elif activation == \"softmax\":\n return softmax(in_arr)\n elif activation == 'tanh':\n return np.tanh(in_arr)\n\n def derivative_of_activation(self, activation, in_data):\n derived_data = []\n if activation == \"sigmoid\":\n return self.apply_activation(in_data, 'sigmoid') * (1 - self.apply_activation(in_data, 'sigmoid'))\n elif activation == \"relu\":\n derived_data = copy.deepcopy(in_data)\n derived_data[derived_data <= 0] = 0\n derived_data[derived_data > 0] = 1\n return derived_data\n elif activation == \"softmax\":\n for x in in_data:\n x_data = []\n sqr_sum = 0\n for neuron in x:\n sqr_sum += math.e**(neuron)\n sqr_sum = sqr_sum ** 2\n\n for i in range(len(x)):\n num = math.e**(x[i])\n num_sum = 0\n for j in range(len(x)):\n if i==j:\n continue\n else:\n num_sum += math.e**(x[j])\n num = num * num_sum\n x_data.append(num/sqr_sum)\n derived_data.append(x_data)\n return derived_data\n elif activation == 'tanh':\n tanh_z = np.tanh(in_data)\n return 1 - (tanh_z)**2\n \n def add(self, neurons = None, activation = None):\n layer = Layer(num_neurons = neurons, activation = activation, batch_size = self.batch)\n self.layers.append(layer)\n\n def compile(self, loss = \"categorical_crossentropy\", learn_rate = 0.01):\n self.loss = loss\n self.learn_rate = learn_rate\n\n def calculate_loss(self, labels):\n if self.loss == \"categorical_crossentropy\":\n return (self.layers[-1].output - labels)\n\n def forward_propagate(self, input_sample):\n new_input = np.array([])\n for i, lab in enumerate(self.weight_labels):\n if i == 0:\n t = np.dot(input_sample, self.weights[lab])\n else:\n t = np.dot(new_input, self.weights[lab])\n self.layers[i].input = copy.deepcopy(t)\n self.layers[i].output = self.apply_activation(t, self.layers[i].activation)\n new_input = self.layers[i].output\n\n\n def back_propagation(self, sample, lab):\n i = len(self.layers)-1\n dE_dW = {}\n yminus_yhat = self.calculate_loss(lab)\n while i>=0:\n if i == len(self.layers)-1:\n weights_name = self.weight_labels[i]\n self.layers[i].delta = yminus_yhat\n exp_output = copy.deepcopy(self.layers[i-1].output)\n delta_weights = np.dot(exp_output.T, yminus_yhat)\n dE_dW[weights_name] = delta_weights\n else:\n weights_name = self.weight_labels[i]\n previous_delta = copy.deepcopy(self.layers[i+1].delta)\n din_dout = self.weights[self.weight_labels[i+1]]\n\n dout_din = self.derivative_of_activation(self.layers[i].activation, self.layers[i].input)\n\n dcost_dah = np.dot(previous_delta, din_dout.T)\n if i == 0:\n din_dW = sample\n else:\n din_dW = self.layers[i-1].output\n self.layers[i].delta = np.multiply(dcost_dah, dout_din)\n \n dE_dW[weights_name] = np.dot(din_dW.T, self.layers[i].delta)\n\n i-=1\n for j in range(len(self.layers)):\n weights_name = self.weight_labels[j]\n self.weights[weights_name] = self.weights[weights_name] - np.multiply(dE_dW[weights_name], self.learn_rate)\n \n\n def predict(self, test_x):\n self.forward_propagate(np.array(test_x))\n return self.layers[len(self.layers)-1].output\n\n def accuracy(self, f, s):\n true = 0\n for i in range(len(f)):\n if f[i] == s[i]:\n true += 1\n return true/len(f)\n\n def convert_encoding(self, labels, flag):\n if flag:\n new_labs = []\n for lab in labels:\n max_index = 0\n max_prob = lab[0]\n for i in range(len(lab)):\n if lab[i] > max_prob:\n max_prob = lab[i]\n max_index = i\n new_labs.append(max_index)\n return np.array(new_labs)\n elif flag == False:\n new_labs = []\n for lab in labels:\n test_lab = np.zeros(len(np.unique(labels))).tolist()\n test_lab[int(lab)] = 1\n new_labs.append(test_lab)\n return np.array(new_labs)\n\n\n def fit(self, train_x, train_labels, epochs = 10):\n self.initialize_weights(len(train_x[0]))\n one_hat_vectors = self.convert_encoding(train_labels, False)\n print(\"Train samples count: \",len(train_x))\n\n for j in range(epochs):\n num_batches = math.ceil(len(train_x)/self.batch)\n for i in range(num_batches):\n batch = train_x[i*self.batch:(i+1)*self.batch]\n batch_lab = one_hat_vectors[i*self.batch:(i+1)*self.batch]\n self.forward_propagate(np.array(batch))\n self.back_propagation(np.array(batch), np.array(batch_lab))\n predictions = self.predict(train_x)\n predictions = self.convert_encoding(predictions, True)\n accuracy = self.accuracy(predictions, train_labels)\n print(\"Epoch count:\", j,\" accuracy over training data:\", accuracy)\n\n\ndef load_data():\n global lab_mean\n l = os.getcwd().split('/')\n l.pop()\n data_csv = '/'.join(l) + \"/input_data/apparel-trainval.csv\"\n raw_data = pd.read_csv(data_csv, header=0)\n raw_data = raw_data.astype('float64')\n complete_array = raw_data.values\n Y_array = complete_array[:, 0]\n X_array = np.delete(complete_array, (0), axis=1)\n\n X_array = (X_array - np.mean(X_array, axis=0)) / np.std(X_array, axis=0)\n\n split_size = 0.20\n seed = 1\n\n X_train, X_val, Y_train, Y_val = train_test_split(X_array, Y_array, test_size=split_size)\n return (X_train, Y_train) , (X_val, Y_val)\n\ndef load_test():\n l = os.getcwd().split('/')\n l.pop()\n data_csv = '/'.join(l) + \"/input_data/apparel-test.csv\"\n test_dataset = pd.read_csv(data_csv)\n test_dataset = test_dataset.values\n X_array = test_dataset.astype('float64')\n X_array = (X_array - np.mean(X_array, axis=0)) / np.std(X_array, axis=0)\n return X_array\n\ntrain, validation = load_data()\n\n\nm = Model(batch = 100)\nm.add(neurons = 128, activation = \"relu\")\nm.add(neurons = 10, activation = \"softmax\")\nm.compile(loss = \"categorical_crossentropy\", learn_rate = 0.001)\nm.fit(train[0], train[1], epochs = 5)\n\nm.forward_propagate(validation[0])\nval_predictions = m.layers[-1].output\nval_predictions = m.convert_encoding(val_predictions, True)\nprint(\"Accuracy over the validation dataset is: \", m.accuracy(val_predictions, validation[1]))\n\n" } ]
1
elmoneto/geoproc-ufsm
https://github.com/elmoneto/geoproc-ufsm
b48848ba631ce7fb2628e3843c742907db25db0b
558b859dd13cad54d3c7036380fc4da98252a746
2f49aac2b3642f51e368fb57f943bba457d6bf75
refs/heads/master
2022-10-12T09:26:43.520615
2019-01-16T11:56:58
2019-01-16T11:56:58
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.559792697429657, "alphanum_fraction": 0.5860792398452759, "avg_line_length": 37.58571243286133, "blob_id": "da1d1a94edf9dd2f4e6b01c2704a2f0bbbdc830a", "content_id": "5a771077f9f5af980b9fae6a6551f83b5dd04f0a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5403, "license_type": "permissive", "max_line_length": 115, "num_lines": 140, "path": "/2018-1/codigo_carta_v2.py", "repo_name": "elmoneto/geoproc-ufsm", "src_encoding": "UTF-8", "text": "import math\n\n__author__ = \"Elmo Neto\"\n__email__ = \"[email protected]\"\n\n\ndef carta_milionesimo(arglat, arglon):\n codigo_faixas = list(\"ABCDEFGHIJKLMNOPQRSTUV\")\n if arglat >= 0:\n cod_carta.append('N')\n else:\n cod_carta.append('S')\n\n cod_faixa = math.floor(abs(arglat) / 4)\n if arglat < 0 and arglat % 4 == 0 :\n cod_faixa -= 1\n cod_carta.append(codigo_faixas[cod_faixa])\n\n cod_fuso = (math.ceil((arglon + 180) / 6)) % 60\n if arglon % 6 == 0:\n cod_fuso += 1\n cod_carta.append(cod_fuso)\n\n limite_inf_faixa = ((math.floor(arglat / 4)) * 4) * 1.0\n limite_sup_faixa = limite_inf_faixa + 4\n limite_esq_fuso = ((math.floor(arglon / 6)) * 6) * 1.0\n limite_dir_fuso = limite_esq_fuso + 6\n\n ponto_a = {'x': limite_esq_fuso, 'y': limite_inf_faixa}\n ponto_b = {'x': limite_esq_fuso, 'y': limite_sup_faixa}\n ponto_c = {'x': limite_dir_fuso, 'y': limite_sup_faixa}\n ponto_d = {'x': limite_dir_fuso, 'y': limite_inf_faixa}\n novos_pontos = {'pto_inf_esq': ponto_a, 'pto_sup_esq': ponto_b, 'pto_sup_dir': ponto_c, 'pto_inf_dir': ponto_d}\n return novos_pontos\n\n\ndef amplia(linhax1, linhay1, linhax2, linhay2):\n ponto_a = {'x': linhax1, 'y': linhay1}\n ponto_b = {'x': linhax1, 'y': linhay2}\n ponto_c = {'x': linhax2, 'y': linhay2}\n ponto_d = {'x': linhax2, 'y': linhay1}\n novos_pontos = {'pto_inf_esq': ponto_a, 'pto_sup_esq': ponto_b, 'pto_sup_dir': ponto_c, 'pto_inf_dir': ponto_d}\n return novos_pontos\n\n\ndef amplia_4reg(arglat, arglon, pontos, codigos):\n ponto_medio_x = (pontos['pto_inf_esq']['x'] + pontos['pto_inf_dir']['x']) / 2\n ponto_medio_y = (pontos['pto_inf_esq']['y'] + pontos['pto_sup_esq']['y']) / 2\n\n if (arglat >= ponto_medio_y) and (arglon < ponto_medio_x):\n cod_carta.append(codigos[\"NO\"])\n novos_pontos = amplia(pontos['pto_inf_esq']['x'], ponto_medio_y, ponto_medio_x, pontos['pto_sup_esq']['y'])\n return novos_pontos\n\n if (arglat >= ponto_medio_y) and (arglon >= ponto_medio_x):\n cod_carta.append(codigos[\"NE\"])\n novos_pontos = amplia(ponto_medio_x, ponto_medio_y, pontos['pto_sup_dir']['x'], pontos['pto_sup_dir']['y'])\n return novos_pontos\n\n if (arglat < ponto_medio_y) and (arglon < ponto_medio_x):\n cod_carta.append(codigos[\"SO\"])\n novos_pontos = amplia(pontos['pto_inf_esq']['x'], pontos['pto_inf_esq']['y'], ponto_medio_x, ponto_medio_y)\n return novos_pontos\n\n if (arglat < ponto_medio_y) and (arglon >= ponto_medio_x):\n cod_carta.append(codigos[\"SE\"])\n novos_pontos = amplia(ponto_medio_x, pontos['pto_inf_esq']['y'], pontos['pto_inf_dir']['x'], ponto_medio_y)\n return novos_pontos\n\n\ndef amplia_6reg(arglat, arglon, pontos):\n temp = (pontos['pto_inf_dir']['x'] - pontos['pto_inf_esq']['x']) / 3\n pmx1 = pontos['pto_inf_esq']['x'] + temp\n pmx2 = pmx1 + temp\n pmy = (pontos['pto_inf_esq']['y'] + pontos['pto_sup_esq']['y']) / 2\n if (arglat >= pmy) and (arglon < pmx1):\n cod_carta.append(\"I\")\n novos_pontos = amplia(pontos['pto_sup_esq']['x'], pmy, pmx1, pontos['pto_sup_esq']['y'])\n return novos_pontos\n if (arglat >= pmy) and (arglon < pmx2):\n cod_carta.append(\"II\")\n novos_pontos = amplia(pmx1, pmy, pmx2, pontos['pto_sup_esq']['y'])\n return novos_pontos\n if (arglat >= pmy) and (arglon >= pmx2):\n cod_carta.append(\"III\")\n novos_pontos = amplia(pmx2, pmy, pontos['pto_sup_dir']['x'], pontos['pto_sup_dir']['y'])\n return novos_pontos\n if (arglat < pmy) and (arglon < pmx1):\n cod_carta.append(\"IV\")\n novos_pontos = amplia(pontos['pto_inf_esq']['x'], pontos['pto_inf_esq']['y'], pmx1, pmy)\n return novos_pontos\n if (arglat < pmy) and (arglon < pmx2):\n cod_carta.append(\"V\")\n novos_pontos = amplia(pmx1, pontos['pto_inf_esq']['y'], pmx2, pmy)\n return novos_pontos\n if (arglat < pmy) and (arglon >= pmx2):\n cod_carta.append(\"VI\")\n novos_pontos = amplia(pmx2, pontos['pto_inf_esq']['y'], pontos['pto_inf_dir']['x'], pmy)\n return novos_pontos\n\n\nlat = float(input(\"Latitude (em formato decimal): \"))\nlon = float(input(\"Longitude (em formato decimal): \"))\npontos_limite = {}\ndicio_um_500_mil = {\"NO\": \"V\", \"NE\": 'X', \"SO\": 'Y', \"SE\": \"Z\"}\ndicio_um_250_mil = {\"NO\": \"A\", \"NE\": \"B\", \"SO\": \"C\", \"SE\": \"D\"}\ndicio_um_50_mil = {\"NO\": 1, \"NE\": 2, \"SO\": 3, \"SE\": 4}\ndicio_um_25_mil = {\"NO\": \"NO\", \"NE\": \"NE\", \"SO\": \"SO\", \"SE\": \"SE\"}\n\ncod_carta = []\n\nprint(\"Informe a escala da carta desejada: \")\nprint(\"(1) - 1:1.000.000\")\nprint(\"(2) - 1:500.000\")\nprint(\"(3) - 1:250.000\")\nprint(\"(4) - 1:100.000\")\nprint(\"(5) - 1:50.000\")\nprint(\"(6) - 1:25:000\")\nnivel = int(input(\"\"))\n\nif nivel >= 1:\n pontos_limite = carta_milionesimo(lat, lon)\n# print(pontos_limite)\nif nivel >= 2:\n pontos_limite = amplia_4reg(lat, lon, pontos_limite, dicio_um_500_mil)\n# print(pontos_limite)\nif nivel >= 3:\n pontos_limite = amplia_4reg(lat, lon, pontos_limite, dicio_um_250_mil)\n# print(pontos_limite)\nif nivel >= 4:\n pontos_limite = amplia_6reg(lat, lon, pontos_limite)\n# print(pontos_limite)\nif nivel >= 5:\n pontos_limite = amplia_4reg(lat, lon, pontos_limite, dicio_um_50_mil)\n# print(pontos_limite)\nif nivel == 6:\n pontos_limite = amplia_4reg(lat, lon, pontos_limite, dicio_um_25_mil)\n print(pontos_limite)\nprint(\"\\nCódigo da carta: \")\nprint(cod_carta)\n" }, { "alpha_fraction": 0.5363288521766663, "alphanum_fraction": 0.5546128153800964, "avg_line_length": 37.38532257080078, "blob_id": "233789b8c35f71050b538c9996dbdba71278cf3f", "content_id": "4558448b039c0259f5e9caef1562b809791ec8b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8368, "license_type": "permissive", "max_line_length": 115, "num_lines": 218, "path": "/2018-1/codigo_carta_milionesimo.py", "repo_name": "elmoneto/geoproc-ufsm", "src_encoding": "UTF-8", "text": "import math\n\n\n__author__ = \"Elmo Neto\"\n__email__ = \"[email protected]\"\n\n\ndef carta_milionesimo(lat, lon):\n codigo_faixas = list(\"ABCDEFGHIJKLMNOPQRSTUV\")\n if (lat > 0):\n cod_carta.append('N')\n else:\n cod_carta.append('S')\n\n cod_faixa = math.floor(abs(lat) / 4)\n cod_carta.append(codigo_faixas[cod_faixa])\n\n cod_fuso = math.ceil((lon + 180) / 6)\n cod_carta.append(cod_fuso)\n\n limite_inf_faixa = ((math.floor(lat / 4)) * 4) * 1.0\n limite_sup_faixa = ((math.ceil(lat / 4)) * 4) * 1.0\n limite_esq_fuso = ((math.floor(lon / 6)) * 6) * 1.0\n limite_dir_fuso = ((math.ceil(lon / 6)) * 6) * 1.0\n\n ponto_a = {'x': limite_esq_fuso, 'y': limite_inf_faixa}\n ponto_b = {'x': limite_esq_fuso, 'y': limite_sup_faixa}\n ponto_c = {'x': limite_dir_fuso, 'y': limite_sup_faixa}\n ponto_d = {'x': limite_dir_fuso, 'y': limite_inf_faixa}\n novos_pontos = {'pto_inf_esq': ponto_a, 'pto_sup_esq': ponto_b, 'pto_sup_dir': ponto_c, 'pto_inf_dir': ponto_d}\n return novos_pontos\n\n\ndef amplia_no(pto_medio_x, pto_medio_y, ptos):\n pto_a = {'x': ptos['pto_inf_esq']['x'], 'y': pto_medio_y}\n pto_b = ptos['pto_sup_esq']\n pto_c = {'x': pto_medio_x, 'y': ptos['pto_sup_dir']['y']}\n pto_d = {'x': pto_medio_x, 'y': pto_medio_y}\n novos_ptos = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return novos_ptos\n\n\ndef amplia_ne(pto_medio_x, pto_medio_y, ptos):\n pto_a = {'x': pto_medio_x, 'y': pto_medio_y}\n pto_b = {'x': pto_medio_x, 'y': ptos['pto_sup_dir']['y']}\n pto_c = {'x': ptos['pto_sup_dir']['x'], 'y': ptos['pto_sup_dir']['y']}\n pto_d = {'x': ptos['pto_sup_dir']['x'], 'y': pto_medio_y}\n temp = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return temp\n\n\ndef amplia_so(pto_medio_x, pto_medio_y, ptos):\n pto_a = {'x': ptos['pto_inf_esq']['x'], 'y': ptos['pto_inf_esq']['y']}\n pto_b = {'x': ptos['pto_inf_esq']['x'], 'y': pto_medio_y}\n pto_c = {'x': pto_medio_x, 'y': pto_medio_y}\n pto_d = {'x': pto_medio_x, 'y': ptos['pto_inf_esq']['y']}\n temp = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return temp\n\n\ndef amplia_se(pto_medio_x, pto_medio_y, ptos):\n pto_a = {'x': pto_medio_x, 'y': ptos['pto_inf_dir']['y']}\n pto_b = {'x': pto_medio_x, 'y': pto_medio_y}\n pto_c = {'x': ptos['pto_inf_dir']['x'], 'y': pto_medio_y}\n pto_d = {'x': ptos['pto_inf_dir']['x'], 'y': ptos['pto_inf_dir']['y']}\n novos_ptos = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return novos_ptos\n\n\ndef amplia_i(pmx1, pmy, pontos):\n pto_a = {'x': pontos['pto_inf_esq']['x'], 'y': pmy}\n pto_b = {'x': pontos['pto_sup_esq']['x'], 'y': pontos['pto_sup_esq']['y']}\n pto_c = {'x': pmx1, 'y': pontos['pto_sup_esq']['y']}\n pto_d = {'x': pmx1, 'y': pmy}\n novos_pontos = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return novos_pontos\n\n\ndef amplia_ii(pmx1, pmx2, pmy, pontos):\n pto_a = {'x': pmx1, 'y': pmy}\n pto_b = {'x': pmx1, 'y': pontos['pto_sup_esq']['y']}\n pto_c = {'x': pmx2, 'y': pontos['pto_sup_esq']['y']}\n pto_d = {'x': pmx2, 'y': pmy}\n novos_pontos = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return novos_pontos\n\n\ndef amplia_iii(pmx2, pmy, pontos):\n pto_a = {'x': pmx2, 'y': pmy}\n pto_b = {'x': pmx2, 'y': pontos['pto_sup_dir']['y']}\n pto_c = {'x': pontos['pto_sup_dir']['x'], 'y': pontos['pto_sup_dir']['y']}\n pto_d = {'x': pontos['pto_sup_dir']['x'], 'y': pmy}\n novos_pontos = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return novos_pontos\n\n\ndef amplia_iv(pmx1, pmy, pontos):\n pto_a = {'x': pontos['pto_inf_esq']['x'], 'y': pontos['pto_inf_esq']['y']}\n pto_b = {'x': pontos['pto_inf_esq']['x'], 'y': pmy}\n pto_c = {'x': pmx1, 'y': pmy}\n pto_d = {'x': pmx1, 'y': pontos['pto_inf_esq']['y']}\n novos_pontos = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return novos_pontos\n\n\ndef amplia_v(pmx1, pmx2, pmy, pontos):\n pto_a = {'x': pmx1, 'y': pontos['pto_inf_esq']['y']}\n pto_b = {'x': pmx1, 'y': pmy}\n pto_c = {'x': pmx2, 'y': pmy}\n pto_d = {'x': pmx2, 'y': pontos['pto_inf_esq']['y']}\n novos_pontos = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return novos_pontos\n\n\ndef amplia_vi(pmx2,pmy,pontos):\n pto_a = {'x': pmx2, 'y': pontos['pto_inf_esq']['y']}\n pto_b = {'x': pmx2, 'y': pmy}\n pto_c = {'x': pontos['pto_sup_dir']['x'], 'y': pmy}\n pto_d = {'x': pontos['pto_inf_dir']['x'], 'y': pontos['pto_inf_dir']['y']}\n novos_pontos = {'pto_inf_esq': pto_a, 'pto_sup_esq': pto_b, 'pto_sup_dir': pto_c, 'pto_inf_dir': pto_d}\n return novos_pontos\n\n\ndef amplia_4reg(lat, lon, pontos, codigos):\n ponto_medio_x = (pontos['pto_inf_esq']['x'] + pontos['pto_inf_dir']['x']) / 2\n ponto_medio_y = (pontos['pto_inf_esq']['y'] + pontos['pto_sup_esq']['y']) / 2\n\n if (lat > ponto_medio_y) and (lon <= ponto_medio_x):\n cod_carta.append(codigos[\"NO\"])\n novos_pontos = amplia_no(ponto_medio_x, ponto_medio_y, pontos)\n return novos_pontos\n\n if (lat > ponto_medio_y) and (lon > ponto_medio_x):\n cod_carta.append(codigos[\"NE\"])\n novos_pontos = amplia_ne(ponto_medio_x, ponto_medio_y, pontos)\n return novos_pontos\n\n if (lat <= ponto_medio_y) and (lon <= ponto_medio_x):\n cod_carta.append(codigos[\"SO\"])\n novos_pontos = amplia_so(ponto_medio_x, ponto_medio_y, pontos)\n return novos_pontos\n\n if (lat <= ponto_medio_y) and (lon > ponto_medio_x):\n cod_carta.append(codigos[\"SE\"])\n novos_pontos = amplia_se(ponto_medio_x, ponto_medio_y, pontos)\n return novos_pontos\n\n\ndef amplia_6reg(lat, lon, pontos):\n temp = (pontos['pto_inf_dir']['x'] - pontos['pto_inf_esq']['x']) / 3\n pmx1 = pontos['pto_inf_esq']['x'] + temp\n pmx2 = pmx1 + temp\n pmy = (pontos['pto_inf_esq']['y'] + pontos['pto_sup_esq']['y']) / 2\n print(pmx1, pmx2, pmy)\n if (lat > pmy) and (lon <= pmx1):\n cod_carta.append(\"I\")\n novos_pontos = amplia_i(pmx1, pmy, pontos)\n return novos_pontos\n if (lat > pmy) and (lon <= pmx2):\n cod_carta.append(\"II\")\n novos_pontos = amplia_ii(pmx1, pmx2, pmy, pontos)\n return novos_pontos\n if (lat > pmy) and (lon > pmx2):\n cod_carta.append(\"III\")\n novos_pontos = amplia_iii(pmx2, pmy, pontos)\n return novos_pontos\n if (lat <= pmy) and (lon <= pmx1):\n cod_carta.append(\"IV\")\n novos_pontos = amplia_iv(pmx1, pmy, pontos)\n return novos_pontos\n if (lat <= pmy) and (lon <= pmx2):\n cod_carta.append(\"V\")\n novos_pontos = amplia_v(pmx1, pmx2, pmy, pontos)\n return novos_pontos\n if (lat <= pmy) and (lon > pm2):\n cod_carta.append(\"VI\")\n novos_pontos = amplia_vi(pmx2, pmy, pontos)\n return novos_pontos\n\n\nlat = float(input(\"Informe a latitude: \"))\nlon = float(input(\"Informe a longitude: \"))\npontos_limite = {}\ndicio_um_500_mil = {\"NO\": \"V\", \"NE\": 'X', \"SO\": 'Y', \"SE\": \"Z\"}\ndicio_um_250_mil = {\"NO\": \"A\", \"NE\": \"B\", \"SO\": \"C\", \"SE\": \"D\"}\ndicio_um_50_mil = {\"NO\": 1, \"NE\": 2, \"SO\": 3, \"SE\": 4}\ndicio_um_25_mil = {\"NO\": \"NO\", \"NE\": \"NE\", \"SO\": \"SO\", \"SE\": \"SE\"}\n\ncod_carta = []\n\nprint(\"Informe a escala da carta desejada: \")\nprint(\"(1) - 1:1.000.000\")\nprint(\"(2) - 1:500.000\")\nprint(\"(3) - 1:250.000\")\nprint(\"(4) - 1:100.000\")\nprint(\"(5) - 1:50.000\")\nprint(\"(6) - 1:25:000\")\nnivel = int(input(\"\"))\n\nif (nivel >= 1):\n pontos_limite = carta_milionesimo(lat, lon)\n# print(pontos_limite)\nif (nivel >= 2):\n pontos_limite = amplia_4reg(lat, lon, pontos_limite, dicio_um_500_mil)\n# print(pontos_limite)\nif (nivel >= 3):\n pontos_limite = amplia_4reg(lat, lon, pontos_limite, dicio_um_250_mil)\n# print(pontos_limite)\nif (nivel >= 4):\n pontos_limite = amplia_6reg(lat, lon, pontos_limite)\n# print(pontos_limite)\nif (nivel >= 5):\n pontos_limite = amplia_4reg(lat, lon, pontos_limite, dicio_um_50_mil)\n# print(pontos_limite)\nif nivel == 6:\n pontos_limite = amplia_4reg(lat, lon, pontos_limite, dicio_um_25_mil)\n print(pontos_limite)\nprint(cod_carta)\n" }, { "alpha_fraction": 0.78899085521698, "alphanum_fraction": 0.78899085521698, "avg_line_length": 14.571428298950195, "blob_id": "4f0336ec503f982ae17eb58fe5ba5ab5fef8edf0", "content_id": "115c1a5f83b011e537b7bb4504d7a8478671a9dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 113, "license_type": "permissive", "max_line_length": 35, "num_lines": 7, "path": "/README.md", "repo_name": "elmoneto/geoproc-ufsm", "src_encoding": "UTF-8", "text": "# Curso Técnico em Geoprocessamento\n\n- Anotações de aula\n\n- Material extraclasse\n\n- Códigos-fonte auxiliares\n" }, { "alpha_fraction": 0.7340043187141418, "alphanum_fraction": 0.742631196975708, "avg_line_length": 22.183332443237305, "blob_id": "2416e3bd2d5ee3fd8c2abc76b275f916fbb8ccf2", "content_id": "1eb5d646a97f0d6bf70d5cf7497be8d1801c32e6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1400, "license_type": "permissive", "max_line_length": 105, "num_lines": 60, "path": "/links.md", "repo_name": "elmoneto/geoproc-ufsm", "src_encoding": "UTF-8", "text": "# Links Úteis\n\n[Curso Técnico em Geoprocessamento da UFSM](http://politecnico.ufsm.br/geotec)\n\n[Curso Tecnólogo em Geoprocessamento da UFSM](http://politecnico.ufsm.br/geosuperior)\n\n---\n# Software\n\n[OSGeo Live](https://live.osgeo.org/en/index.html)\n\n[QGIS](https://qgis.org)\n\n[PostGIS](https://postgis.net/)\n\n[pgRouting](https://pgrouting.org/)\n\n[OpenLayers](https://openlayers.org/)\n\n[PROJ.4](https://proj4.org/)\n\n---\n\n# Materiais de Estudo\n\n## Introdução ao PostGIS\n\n[Boundless Geo](http://workshops.boundlessgeo.com/postgis-intro/welcome.html)\n\n[PostGIS Documentation](https://postgis.net/docs/postgis_introduction.html)\n\n## Desenvolvimento de aplicações no QGIS\n\n[Guia de desenvolvimento para Python](https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/)\n\n---\n\n# Eventos\n\n[FOSS4G 2018](https://2018.foss4g.org/)\n\n[Congresso Brasileiro de Cartografia](http://www.cartografia.org.br/cbc/)\n\n---\n\n# Ferramentas e Fontes de Dados\n\n[Downloads - Geociências IBGE](https://www.ibge.gov.br/geociencias-novoportal/downloads-geociencias.html)\n\n[Portal de Mapas do IBGE](https://portaldemapas.ibge.gov.br/portal.php)\n\n[Overpass Turbo](https://overpass-turbo.eu/)\n\n[Topodata - Mapa Índice](http://www.webmapit.com.br/inpe/topodata/)\n\n[Natural Earth Data](https://www.naturalearthdata.com/downloads/)\n\n[Spatial Reference](http://www.spatialreference.org/)\n\n[geojson.io](http://geojson.io)\n" } ]
4
aludvik/sawtooth-core
https://github.com/aludvik/sawtooth-core
0c7363f6fc08fd2bc2cb30bceda4e7a5763dc6cd
d50264f8867f0aa78c81b8db6d10062c67dc5a03
ae50b29876a2a91193b93f7e94dd12b8dd946473
refs/heads/engine-prototype-dev
2021-01-11T18:40:37.126417
2018-06-14T23:04:06
2018-06-14T23:04:06
79,595,660
0
0
Apache-2.0
2017-01-20T20:30:42
2018-06-14T23:04:08
2018-07-26T21:48:23
Python
[ { "alpha_fraction": 0.6293874382972717, "alphanum_fraction": 0.6371279954910278, "avg_line_length": 33.689815521240234, "blob_id": "0097cd0040eb259fd6e16a36b7c7bbfd1954c4af", "content_id": "1a684b29d42ed505fee88603e0fa614f24cae9d7", "detected_licenses": [ "CC-BY-4.0", "Apache-2.0", "Zlib", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7493, "license_type": "permissive", "max_line_length": 80, "num_lines": 216, "path": "/integration/sawtooth_integration/tests/test_consensus_engine_api.py", "repo_name": "aludvik/sawtooth-core", "src_encoding": "UTF-8", "text": "# Copyright 2017 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------------\n\nimport json\nimport time\nimport unittest\nimport urllib\n\nfrom sawtooth_sdk.protobuf import validator_pb2\nfrom sawtooth_sdk.protobuf import consensus_pb2\nfrom sawtooth_sdk.messaging.stream import Stream\n\nfrom sawtooth_intkey.intkey_message_factory import IntkeyMessageFactory\n\nfrom sawtooth_integration.tests.integration_tools import wait_for_rest_apis\n\n\nREST_API_URL = \"http://rest-api:8008\"\nINTERBLOCK_PERIOD = 1\nWAIT = 300\nBATCH_KEYS = 'abcd'\n\n\nclass TestConsensusEngineAPI(unittest.TestCase):\n def setUp(self):\n wait_for_rest_apis([REST_API_URL])\n self.stream = Stream(\"tcp://validator:5005\")\n\n def tearDown(self):\n self.stream.close()\n\n def test_consensus_engine_api(self):\n chain_head = self.head()\n\n batches = make_batches(BATCH_KEYS)\n committed = 0\n\n for batch in batches:\n batch_response = self.publish_block(batch)\n\n self.commit_block()\n\n # Wait for the validator to respond that the batch was committed\n wait_for_batch(batch_response)\n committed += 1\n\n self.assertEqual(committed, len(batches))\n blocks = query_rest_api('/blocks')\n self.assertEqual(\n len(blocks['data']),\n len(BATCH_KEYS) + 1)\n\n def publish_block(self, batch):\n # Initialize a new block\n status = self._initialize()\n\n # Submit a batch and wait\n response = post_batch(batch)\n time.sleep(INTERBLOCK_PERIOD)\n\n # Finalize the block\n while True:\n status = self._finalize()\n if status == consensus_pb2.\\\n ConsensusFinalizeBlockResponse.BLOCK_NOT_READY:\n time.sleep(1)\n else:\n self.assertEqual(\n status,\n consensus_pb2.ConsensusFinalizeBlockResponse.OK)\n break\n\n return response\n\n def commit_block(self):\n block_id = self._receive_new()\n self._check_and_commit(block_id)\n\n def _receive_new(self):\n new_update = self._receive_update(\n validator_pb2.Message.CONSENSUS_NOTIFY_BLOCK_NEW,\n consensus_pb2.ConsensusNotifyBlockNew)\n return new_update.block.block_id\n\n def _check_and_commit(self, block_id):\n self._check(block_id)\n valid_update = self._receive_update(\n validator_pb2.Message.CONSENSUS_NOTIFY_BLOCK_VALID,\n consensus_pb2.ConsensusNotifyBlockValid)\n self.assertEqual(\n block_id,\n valid_update.block_id)\n self._commit(block_id)\n commit_update = self._receive_update(\n validator_pb2.Message.CONSENSUS_NOTIFY_BLOCK_COMMIT,\n consensus_pb2.ConsensusNotifyBlockCommit)\n self.assertEqual(\n block_id,\n commit_update.block_id)\n\n def _check(self, block_id):\n future = self.stream.send(\n validator_pb2.Message.CONSENSUS_CHECK_BLOCKS_REQUEST,\n consensus_pb2.ConsensusCheckBlocksRequest(block_ids=[block_id])\n .SerializeToString())\n result = future.result()\n self.assertEqual(\n result.message_type,\n validator_pb2.Message.CONSENSUS_CHECK_BLOCKS_RESPONSE)\n response = consensus_pb2.ConsensusCheckBlocksResponse()\n response.ParseFromString(result.content)\n return response.status\n\n def _commit(self, block_id):\n future = self.stream.send(\n validator_pb2.Message.CONSENSUS_COMMIT_BLOCK_REQUEST,\n consensus_pb2.ConsensusCommitBlockRequest(block_id=block_id)\n .SerializeToString())\n result = future.result()\n self.assertEqual(\n result.message_type,\n validator_pb2.Message.CONSENSUS_COMMIT_BLOCK_RESPONSE)\n response = consensus_pb2.ConsensusCommitBlockResponse()\n response.ParseFromString(result.content)\n return response.status\n\n def head(self):\n future = self.stream.send(\n validator_pb2.Message.CONSENSUS_CHAIN_HEAD_GET_REQUEST,\n consensus_pb2.ConsensusChainHeadGetRequest()\n .SerializeToString())\n result = future.result()\n self.assertEqual(\n result.message_type,\n validator_pb2.Message.CONSENSUS_CHAIN_HEAD_GET_RESPONSE)\n response = consensus_pb2.ConsensusChainHeadGetResponse()\n response.ParseFromString(result.content)\n return response.status\n\n def _initialize(self):\n future = self.stream.send(\n validator_pb2.Message.CONSENSUS_INITIALIZE_BLOCK_REQUEST,\n consensus_pb2.ConsensusInitializeBlockRequest()\n .SerializeToString())\n result = future.result()\n self.assertEqual(\n result.message_type,\n validator_pb2.Message.CONSENSUS_INITIALIZE_BLOCK_RESPONSE)\n response = consensus_pb2.ConsensusInitializeBlockResponse()\n response.ParseFromString(result.content)\n return response.status\n\n def _finalize(self):\n future = self.stream.send(\n validator_pb2.Message.CONSENSUS_FINALIZE_BLOCK_REQUEST,\n consensus_pb2.ConsensusFinalizeBlockRequest(data=b\"Devmode\")\n .SerializeToString())\n result = future.result()\n self.assertEqual(\n result.message_type,\n validator_pb2.Message.CONSENSUS_FINALIZE_BLOCK_RESPONSE)\n response = consensus_pb2.ConsensusFinalizeBlockResponse()\n response.ParseFromString(result.content)\n return response.status\n\n def _receive_update(self, update_type, update_class):\n message = self.stream.receive().result()\n self.stream.send_back(\n validator_pb2.Message.CONSENSUS_NOTIFY_ACK,\n message.correlation_id,\n consensus_pb2.ConsensusNotifyAck().SerializeToString())\n self.assertEqual(message.message_type, update_type)\n update = update_class()\n update.ParseFromString(message.content)\n return update\n\n\ndef post_batch(batch):\n headers = {'Content-Type': 'application/octet-stream'}\n response = query_rest_api(\n '/batches', data=batch, headers=headers)\n return response\n\n\ndef wait_for_batch(post_response):\n response = submit_request('{}&wait={}'.format(post_response['link'], WAIT))\n return response\n\n\ndef query_rest_api(suffix='', data=None, headers=None):\n if headers is None:\n headers = {}\n url = REST_API_URL + suffix\n return submit_request(urllib.request.Request(url, data, headers))\n\n\ndef submit_request(request):\n response = urllib.request.urlopen(request).read().decode('utf-8')\n return json.loads(response)\n\n\ndef make_batches(keys):\n imf = IntkeyMessageFactory()\n return [imf.create_batch([('set', k, 0)]) for k in keys]\n" }, { "alpha_fraction": 0.5689468383789062, "alphanum_fraction": 0.5698999166488647, "avg_line_length": 36.90311813354492, "blob_id": "915d67304835eb1da9a4377eaa9203cbb69df552", "content_id": "92a3aec45a4fd1f267468c9afb672e1a253a032d", "detected_licenses": [ "CC-BY-4.0", "Apache-2.0", "Zlib", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 23083, "license_type": "permissive", "max_line_length": 80, "num_lines": 609, "path": "/validator/sawtooth_validator/journal/chain_ce.py", "repo_name": "aludvik/sawtooth-core", "src_encoding": "UTF-8", "text": "# Copyright 2017 Intel Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ------------------------------------------------------------------------------\n\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nimport logging\nimport queue\nfrom threading import RLock\n\nfrom sawtooth_validator.concurrent.thread import InstrumentedThread\nfrom sawtooth_validator.journal.block_wrapper import BlockStatus\nfrom sawtooth_validator.journal.block_wrapper import NULL_BLOCK_IDENTIFIER\nfrom sawtooth_validator.journal.block_validator import BlockValidationFailure\nfrom sawtooth_validator.protobuf.transaction_receipt_pb2 import \\\n TransactionReceipt\nfrom sawtooth_validator import metrics\n\n\nLOGGER = logging.getLogger(__name__)\nCOLLECTOR = metrics.get_collector(__name__)\n\n\nclass BuildForkError(Exception):\n \"\"\"\n Indication that an error occured during fork resolution.\n \"\"\"\n\n\nclass BuildForkResult:\n def __init__(self, block):\n self.block = block\n self.chain_head = None\n self.new_chain = []\n self.current_chain = []\n self.committed_batches = []\n self.uncommitted_batches = []\n # NOTE: The following are for all blocks validated in order to validate\n # this block, i.e., all blocks on this block's fork\n self.execution_results = []\n self.transaction_count = 0\n\n def __bool__(self):\n return self.block.status == BlockStatus.Valid\n\n def __str__(self):\n keys = (\"block\", \"valid\", \"chain_head\", \"new_chain\", \"current_chain\",\n \"committed_batches\", \"uncommitted_batches\",\n \"execution_results\", \"transaction_count\")\n\n out = \"{\"\n for key in keys:\n out += \"%s: %s,\" % (key, self.__getattribute(key))\n return out[:-1] + \"}\"\n\n\nclass ChainObserver(object, metaclass=ABCMeta):\n @abstractmethod\n def chain_update(self, block, receipts):\n \"\"\"This method is called by the ChainController on block boundaries.\n\n Args:\n block (:obj:`BlockWrapper`): The block that was just committed.\n receipts (dict of {str: receipt}): Map of transaction signatures to\n transaction receipts for all transactions in the block.\"\"\"\n raise NotImplementedError()\n\n\nclass _ChainThread(InstrumentedThread):\n def __init__(self, chain_controller, block_queue, block_cache):\n super().__init__(name='_ChainThread')\n self._chain_controller = chain_controller\n self._block_queue = block_queue\n self._block_cache = block_cache\n self._exit = False\n\n def run(self):\n try:\n while True:\n try:\n block = self._block_queue.get(timeout=1)\n self._chain_controller.on_block_received(block)\n except queue.Empty:\n # If getting a block times out, just try again.\n pass\n\n if self._exit:\n return\n # pylint: disable=broad-except\n except Exception:\n LOGGER.exception(\"ChainController thread exited with error.\")\n\n def stop(self):\n self._exit = True\n\n\nclass _CommitThread(InstrumentedThread):\n def __init__(self, commit_queue, commit_fn):\n super().__init__(name='_CommitThread')\n self._commit_queue = commit_queue\n self._commit_fn = commit_fn\n self._exit = False\n\n def run(self):\n while True:\n try:\n block = self._commit_queue.get(timeout=1)\n LOGGER.warning(\"Got %s\", block)\n self._commit_fn(block)\n except queue.Empty:\n # If getting a block times out, just try again.\n pass\n\n if self._exit:\n return\n\n def stop(self):\n self._exit = True\n\n\nclass ChainController(object):\n \"\"\"\n To evaluating new blocks to determine if they should extend or replace\n the current chain. If they are valid extend the chain.\n \"\"\"\n\n def __init__(self,\n block_cache,\n block_validator,\n state_view_factory,\n chain_head_lock,\n on_chain_updated,\n consensus_notifier,\n chain_id_manager,\n identity_signer,\n data_dir,\n config_dir,\n chain_observers):\n \"\"\"Initialize the ChainController\n Args:\n block_cache: The cache of all recent blocks and the processing\n state associated with them.\n block_validator: The object to use for submitting block validation\n work.\n state_view_factory: A factory that can be used to create read-\n only views of state for a particular merkle root, in\n particular the state as it existed when a particular block\n was the chain head.\n chain_head_lock: Lock to hold while the chain head is being\n updated, this prevents other components that depend on the\n chain head and the BlockStore from having the BlockStore change\n under them. This lock is only for core Journal components\n (BlockPublisher and ChainController), other components should\n handle block not found errors from the BlockStore explicitly.\n on_chain_updated: The callback to call to notify the rest of the\n system the head block in the chain has been changed.\n chain_id_manager: The ChainIdManager instance.\n identity_signer: A cryptographic signer for signing blocks.\n data_dir: path to location where persistent data for the\n consensus module can be stored.\n config_dir: path to location where config data for the\n consensus module can be found.\n chain_observers (list of :obj:`ChainObserver`): A list of chain\n observers.\n Returns:\n None\n \"\"\"\n self._lock = RLock()\n self._chain_head_lock = chain_head_lock\n self._consensus_notifier = consensus_notifier\n self._block_cache = block_cache\n self._block_store = block_cache.block_store\n self._state_view_factory = state_view_factory\n self._notify_on_chain_updated = on_chain_updated\n self._identity_signer = identity_signer\n self._data_dir = data_dir\n self._config_dir = config_dir\n\n self._chain_id_manager = chain_id_manager\n\n self._chain_head = None\n\n self._chain_observers = chain_observers\n\n self._chain_head_gauge = COLLECTOR.gauge('chain_head', instance=self)\n self._committed_transactions_gauge = COLLECTOR.gauge(\n 'committed_transactions_gauge', instance=self)\n self._committed_transactions_gauge.set_value(0)\n self._committed_transactions_count = COLLECTOR.counter(\n 'committed_transactions_count', instance=self)\n self._block_num_gauge = COLLECTOR.gauge('block_num', instance=self)\n self._blocks_considered_count = COLLECTOR.counter(\n 'blocks_considered_count', instance=self)\n\n self._moved_to_fork_count = COLLECTOR.counter(\n 'chain_head_moved_to_fork_count', instance=self)\n\n self._block_queue = queue.Queue()\n self._chain_thread = None\n\n self._block_validator = block_validator\n\n self._commit_queue = queue.Queue()\n self._commit_thread = None\n\n # Only run this after all member variables have been bound\n self._set_chain_head_from_block_store()\n\n def _set_chain_head_from_block_store(self):\n try:\n self._chain_head = self._block_store.chain_head\n if self._chain_head is not None:\n LOGGER.info(\"Chain controller initialized with chain head: %s\",\n self._chain_head)\n self._chain_head_gauge.set_value(\n self._chain_head.identifier[:8])\n except Exception:\n LOGGER.exception(\n \"Invalid block store. Head of the block chain cannot be\"\n \" determined\")\n raise\n\n def start(self):\n self._set_chain_head_from_block_store()\n self._notify_on_chain_updated(self._chain_head)\n\n self._chain_thread = _ChainThread(\n chain_controller=self,\n block_queue=self._block_queue,\n block_cache=self._block_cache)\n self._chain_thread.start()\n self._commit_thread = _CommitThread(\n commit_queue=self._commit_queue,\n commit_fn=self._commit_block)\n self._commit_thread.start()\n\n def stop(self):\n if self._chain_thread is not None:\n self._chain_thread.stop()\n self._chain_thread = None\n if self._commit_thread is not None:\n self._commit_thread.stop()\n self._commit_thread = None\n\n def queue_block(self, block):\n \"\"\"\n New block has been received, queue it with the chain controller\n for processing.\n \"\"\"\n self._block_queue.put(block)\n\n @property\n def chain_head(self):\n return self._chain_head\n\n def submit_blocks_for_verification(self, blocks):\n self._block_validator.submit_blocks_for_verification(\n blocks, self.on_block_validated)\n\n def on_block_validated(self, block):\n \"\"\"Message back from the block validator, that the validation is\n complete\n Args:\n commit_new_block (Boolean): whether the new block should become the\n chain head or not.\n result (Dict): Map of the results of the fork resolution.\n Returns:\n None\n \"\"\"\n LOGGER.warning(\"on_block_validated\")\n self._blocks_considered_count.inc()\n try:\n if block.status == BlockStatus.Valid:\n self._consensus_notifier.notify_block_valid(\n block.header_signature)\n else:\n self._consensus_notifier.notify_block_invalid(\n block.header_signature)\n\n # pylint: disable=broad-except\n except Exception:\n LOGGER.exception(\n \"Unhandled exception in ChainController.on_block_validated()\")\n\n def ignore_block(self, block):\n LOGGER.info(\"Ignoring block %s\", block)\n\n def fail_block(self, block):\n with self._lock:\n LOGGER.info(\"Failing block %s\", block)\n block.status = BlockStatus.Invalid\n\n def commit_block(self, block):\n self._commit_queue.put(block)\n\n def _commit_block(self, block):\n with self._lock:\n try_again = True\n while try_again:\n # Get the current chain_head\n chain_head = self._block_cache.block_store.chain_head\n\n result = self._build_fork(block, chain_head)\n\n with self._chain_head_lock:\n if self._check_chain_head_updated(chain_head, block):\n continue\n\n try_again = False\n\n self._chain_head = block\n\n # update the the block store to have the new chain\n self._block_store.update_chain(result.new_chain,\n result.current_chain)\n\n LOGGER.info(\n \"Chain head updated to: %s\",\n self._chain_head)\n\n self._chain_head_gauge.set_value(\n self._chain_head.identifier[:8])\n\n self._committed_transactions_gauge.set_value(\n self._block_store.get_transaction_count())\n\n self._committed_transactions_count.inc(\n result.transaction_count)\n\n self._block_num_gauge.set_value(\n self._chain_head.block_num)\n\n # tell the BlockPublisher else the chain is updated\n self._notify_on_chain_updated(\n self._chain_head,\n result.committed_batches,\n result.uncommitted_batches)\n\n for batch in block.batches:\n if batch.trace:\n LOGGER.debug(\"TRACE %s: %s\",\n batch.header_signature,\n self.__class__.__name__)\n\n for blk in reversed(result.new_chain):\n receipts = self._make_receipts(blk.execution_results)\n # Update all chain observers\n for observer in self._chain_observers:\n observer.chain_update(blk, receipts)\n\n self._consensus_notifier.notify_block_commit(\n block.header_signature)\n\n def _check_chain_head_updated(self, chain_head, block):\n # The validity of blocks depends partially on whether or not\n # there are any duplicate transactions or batches in the block.\n # This can only be checked accurately if the block store does\n # not update during validation. The current practice is the\n # assume this will not happen and, if it does, to reprocess the\n # validation. This has been experimentally proven to be more\n # performant than locking the chain head and block store around\n # duplicate checking.\n if chain_head is None:\n return False\n\n current_chain_head = self._block_cache.block_store.chain_head\n if chain_head.identifier != current_chain_head.identifier:\n LOGGER.warning(\n \"Chain head updated from %s to %s while resolving\"\n \" fork for block %s. Reprocessing resolution.\",\n chain_head, current_chain_head, block)\n return True\n\n return False\n\n def _build_fork(self, block, chain_head):\n result = BuildForkResult(block)\n LOGGER.info(\"Starting fork resolution of : %s\", block)\n\n # Create new local variables for current and new block, since\n # these variables get modified later\n current_block = chain_head\n new_block = block\n\n try:\n # Get all the blocks since the greatest common height from the\n # longer chain.\n if self._compare_chain_height(current_block, new_block):\n current_block, result.current_chain =\\\n self._build_fork_diff_to_common_height(\n current_block, new_block)\n else:\n new_block, result.new_chain =\\\n self._build_fork_diff_to_common_height(\n new_block, current_block)\n\n # Add blocks to the two chains until a common ancestor is found\n # or raise an exception if no common ancestor is found\n self._extend_fork_diff_to_common_ancestor(\n new_block, current_block,\n result.new_chain, result.current_chain)\n\n except BuildForkError as err:\n LOGGER.error(\n 'Encountered an error while resolving a fork with head %s:'\n ' %s', block, err)\n return False, result\n\n for blk in reversed(result.new_chain):\n result.transaction_count += blk.num_transactions\n\n LOGGER.info(\n \"Comparing current chain head '%s' against new block '%s'\",\n chain_head, new_block)\n for i in range(max(\n len(result.new_chain), len(result.current_chain)\n )):\n cur = new = num = \"-\"\n if i < len(result.current_chain):\n cur = result.current_chain[i].header_signature[:8]\n num = result.current_chain[i].block_num\n if i < len(result.new_chain):\n new = result.new_chain[i].header_signature[:8]\n num = result.new_chain[i].block_num\n LOGGER.info(\n \"Fork comparison at height %s is between %s and %s\",\n num, cur, new)\n\n commit, uncommit =\\\n self._get_batch_commit_changes(\n result.new_chain, result.current_chain)\n result.committed_batches = commit\n result.uncommitted_batches = uncommit\n\n if result.new_chain[0].previous_block_id \\\n != chain_head.identifier:\n self._moved_to_fork_count.inc()\n\n LOGGER.info(\"Finished building fork result for: %s\", block)\n return result\n\n @staticmethod\n def _compare_chain_height(head_a, head_b):\n \"\"\"Returns True if head_a is taller, False if head_b is taller, and\n True if the heights are the same.\"\"\"\n return head_a.block_num - head_b.block_num >= 0\n\n def _build_fork_diff_to_common_height(self, head_long, head_short):\n \"\"\"Returns a list of blocks on the longer chain since the greatest\n common height between the two chains. Note that the chains may not\n have the same block id at the greatest common height.\n\n Args:\n head_long (BlockWrapper)\n head_short (BlockWrapper)\n\n Returns:\n (list of BlockWrapper) All blocks in the longer chain since the\n last block in the shorter chain. Ordered newest to oldest.\n\n Raises:\n BlockValidationError\n The block is missing a predecessor. Note that normally this\n shouldn't happen because of the completer.\"\"\"\n fork_diff = []\n\n last = head_short.block_num\n blk = head_long\n\n while blk.block_num > last:\n if blk.previous_block_id == NULL_BLOCK_IDENTIFIER:\n break\n\n fork_diff.append(blk)\n try:\n blk = self._block_cache[blk.previous_block_id]\n except KeyError:\n raise BuildForkError(\n 'Failed to build fork diff: block {} missing predecessor'\n .format(blk))\n\n return blk, fork_diff\n\n def _extend_fork_diff_to_common_ancestor(\n self, new_blkw, cur_blkw, new_chain, cur_chain\n ):\n \"\"\" Finds a common ancestor of the two chains. new_blkw and cur_blkw\n must be at the same height, or this will always fail.\n \"\"\"\n while cur_blkw.identifier != new_blkw.identifier:\n if (cur_blkw.previous_block_id == NULL_BLOCK_IDENTIFIER\n or new_blkw.previous_block_id == NULL_BLOCK_IDENTIFIER):\n # We are at a genesis block and the blocks are not the same\n for b in new_chain:\n b.status = BlockStatus.Invalid\n raise BuildForkError(\n 'Block {} rejected due to wrong genesis {}'.format(\n cur_blkw, new_blkw))\n\n new_chain.append(new_blkw)\n try:\n new_blkw = self._block_cache[new_blkw.previous_block_id]\n except KeyError:\n raise BuildForkError(\n 'Block {} rejected due to missing predecessor {}'.format(\n new_blkw, new_blkw.previous_block_id))\n\n cur_chain.append(cur_blkw)\n cur_blkw = self._block_cache[cur_blkw.previous_block_id]\n\n @staticmethod\n def _get_batch_commit_changes(new_chain, cur_chain):\n \"\"\"\n Get all the batches that should be committed from the new chain and\n all the batches that should be uncommitted from the current chain.\n \"\"\"\n committed_batches = []\n for blkw in new_chain:\n for batch in blkw.batches:\n committed_batches.append(batch)\n\n uncommitted_batches = []\n for blkw in cur_chain:\n for batch in blkw.batches:\n uncommitted_batches.append(batch)\n\n return (committed_batches, uncommitted_batches)\n\n def on_block_received(self, block):\n try:\n with self._lock:\n if self.has_block(block.header_signature):\n # do we already have this block\n return\n\n if self.chain_head is None:\n self._set_genesis(block)\n return\n\n self._block_cache[block.identifier] = block\n\n self._consensus_notifier.notify_block_new(block)\n\n # pylint: disable=broad-except\n except Exception:\n LOGGER.exception(\n \"Unhandled exception in ChainController.on_block_received()\")\n\n def has_block(self, block_id):\n with self._lock:\n if block_id in self._block_cache:\n return True\n\n if self._block_validator.has_block(block_id):\n return True\n\n return False\n\n def _set_genesis(self, block):\n # This is used by a non-genesis journal when it has received the\n # genesis block from the genesis validator\n if block.previous_block_id == NULL_BLOCK_IDENTIFIER:\n chain_id = self._chain_id_manager.get_block_chain_id()\n if chain_id is not None and chain_id != block.identifier:\n LOGGER.warning(\"Block id does not match block chain id %s. \"\n \"Cannot set initial chain head.: %s\",\n chain_id[:8], block.identifier[:8])\n else:\n try:\n self._block_validator.validate_block(block)\n except BlockValidationFailure as err:\n LOGGER.warning(\n 'Cannot set chain head; '\n 'genesis block %s is not valid: %s',\n block, err)\n return\n\n if chain_id is None:\n self._chain_id_manager.save_block_chain_id(\n block.identifier)\n self._block_store.update_chain([block])\n self._chain_head = block\n self._notify_on_chain_updated(self._chain_head)\n\n else:\n LOGGER.warning(\"Cannot set initial chain head, this is not a \"\n \"genesis block: %s\", block)\n\n def _make_receipts(self, results):\n receipts = []\n for result in results:\n receipt = TransactionReceipt()\n receipt.data.extend([data for data in result.data])\n receipt.state_changes.extend(result.state_changes)\n receipt.events.extend(result.events)\n receipt.transaction_id = result.signature\n receipts.append(receipt)\n return receipts\n" }, { "alpha_fraction": 0.5527523159980774, "alphanum_fraction": 0.5622542500495911, "avg_line_length": 27.523365020751953, "blob_id": "d9d805dd53125ca531d7b2e5fb902d7e68997c4b", "content_id": "216049ac0c876d85e96ab62b6b3419dcb51537e2", "detected_licenses": [ "CC-BY-4.0", "Apache-2.0", "Zlib", "MIT" ], "is_generated": false, "is_vendor": false, "language": "Rust", "length_bytes": 3052, "license_type": "permissive", "max_line_length": 89, "num_lines": 107, "path": "/validator/src/database/lmdb_ffi.rs", "repo_name": "aludvik/sawtooth-core", "src_encoding": "UTF-8", "text": "/*\n * Copyright 2018 Intel Corporation\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ------------------------------------------------------------------------------\n */\nuse database::lmdb::*;\nuse std::ffi::CStr;\nuse std::os::raw::{c_char, c_void};\nuse std::path::Path;\nuse std::slice;\n\n#[repr(u32)]\n#[derive(Debug)]\npub enum ErrorCode {\n Success = 0,\n NullPointerProvided = 0x01,\n InvalidFilePath = 0x02,\n InvalidIndexString = 0x03,\n\n InitializeContextError = 0x11,\n InitializeDatabaseError = 0x12,\n}\n\n#[no_mangle]\npub extern \"C\" fn lmdb_database_new(\n path: *const c_char,\n file_size: usize,\n indexes: *const *const c_char,\n indexes_len: usize,\n db_ptr: *mut *const c_void,\n) -> ErrorCode {\n if path.is_null() {\n return ErrorCode::NullPointerProvided;\n }\n\n if indexes_len > 0 && indexes.is_null() {\n return ErrorCode::NullPointerProvided;\n }\n\n let indexes: Result<Vec<&str>, ErrorCode> = if indexes_len > 0 {\n unsafe { slice::from_raw_parts(indexes, indexes_len) }\n .iter()\n .map(|c_str| {\n unsafe { CStr::from_ptr(*c_str).to_str() }\n .map_err(|_| ErrorCode::InvalidIndexString)\n })\n .collect()\n } else {\n Ok(Vec::with_capacity(0))\n };\n\n if indexes.is_err() {\n return indexes.unwrap_err();\n }\n\n let db_path = unsafe {\n match CStr::from_ptr(path).to_str() {\n Ok(s) => s,\n Err(_) => return ErrorCode::InvalidFilePath,\n }\n };\n\n let ctx = match LmdbContext::new(Path::new(&db_path), indexes_len, Some(file_size)) {\n Ok(ctx) => ctx,\n Err(err) => {\n error!(\n \"Unable to create LMDB context for db at {}: {:?}\",\n db_path, err\n );\n return ErrorCode::InitializeContextError;\n }\n };\n\n match LmdbDatabase::new(ctx, &(indexes.unwrap())) {\n Ok(db) => {\n unsafe {\n *db_ptr = Box::into_raw(Box::new(db)) as *const c_void;\n }\n ErrorCode::Success\n }\n Err(err) => {\n error!(\"Unable to create Database at {}: {:?}\", db_path, err);\n ErrorCode::InitializeDatabaseError\n }\n }\n}\n\n#[no_mangle]\npub extern \"C\" fn lmdb_database_drop(lmdb_database: *mut c_void) -> ErrorCode {\n if lmdb_database.is_null() {\n return ErrorCode::NullPointerProvided;\n }\n\n unsafe { Box::from_raw(lmdb_database as *mut LmdbDatabase) };\n ErrorCode::Success\n}\n" } ]
3
Epizana/ebay_scrape
https://github.com/Epizana/ebay_scrape
cea1b7f133a4563591a64594a44dbc39e8e5a733
a1e168d8da86ac91b882c9348692f9f5dbfad38a
3753f7a8aa2fa3334e17a88ca63be47c349bf799
refs/heads/master
2020-08-11T01:26:44.366390
2019-10-15T07:13:37
2019-10-15T07:13:37
214,462,164
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6096291542053223, "alphanum_fraction": 0.629364550113678, "avg_line_length": 42.05607604980469, "blob_id": "6c0498c7ae9e764967de4366e7aaeed9d9c16fd0", "content_id": "69568aa63e0eeb0bb9a9521c4262f3abcafbce5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4611, "license_type": "no_license", "max_line_length": 104, "num_lines": 107, "path": "/ebay/ebayhelp.py", "repo_name": "Epizana/ebay_scrape", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\n\ndef ebay_helper(ebay1):\n \n ebay1.loc[ebay1['bids'] == 0, 'format'] = 'BIN'\n ebay1.loc[ebay1['bids'] > 0, 'format'] = 'Auction'\n ebay1['brand']=ebay1['brand'].fillna('Unspecified')\n ebay1['title']=ebay1['title'].str.lower()\n \n #Process Hasbro\n hasre='Hasbro|hasbro|HASBRO|Toy Biz|Transformers|G1|ToyBiz|G.I. Joe|GI Joe|Hasbri|HABRO|H a s b r o'\n ebay1['brand'] = np.where(ebay1['brand'].str.contains(hasre,regex = True), 'Hasbro',ebay1['brand'])\n \n #Process Mattel\n matre = 'Mattel|MATTEL|Barbie|Masters of the Universe|Matel|motu|MOTU'\n ebay1['brand'] = np.where(ebay1['brand'].str.contains(matre,regex = True), 'Mattel',ebay1['brand'])\n \n #Process more brands: McFarlane\n macre = 'Mcfarlane|McFarlane'\n ebay1['brand'] = np.where(ebay1['brand'].str.contains(macre, regex = True), 'McFarlane Toys',\\\n ebay1['brand'])\n \n #Process more brands: Playmates\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Playmates|PLAYMATES', regex = True),\\\n 'Playmates Toys',ebay1['brand'])\n \n #Process more brands: Takara Tomy\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('TAKARA|Takara|takara|TOMY|Tomy',\\\n regex = True), 'Takara TOMY',ebay1['brand'])\n \n #Process more brands: Bandai\n banre = 'Bandai|BANDAI|Tamashii Nations|SHF|Figuarts'\n ebay1['brand'] = np.where(ebay1['brand'].str.contains(banre, regex = True), 'Bandai',ebay1['brand'])\n \n #Process more brands: DC\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('DC'), 'DC',ebay1['brand'])\n \n #Process more brands: Fisher Price\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Fisher Price|Fisher-Price|FISHER PRICE',\\\n regex = True), 'Fisher Price',ebay1['brand'])\n \n #Process more brands: Funko\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('FUNKO|Funko',regex = True),\\\n 'Funko',ebay1['brand'])\n \n #Process more brands: Jakks\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('JAKKS|Jakks',regex = True),\\\n 'Jakks Pacific',ebay1['brand'])\n \n #Process more brands: Sideshow\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Slideshow|Sideshow|SIDESHOW',regex = True),\\\n 'Sideshow Collectibles',ebay1['brand'])\n \n #Process more brands: Diamond\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('DIAMOND|Diamond',regex = True),\\\n 'Diamond Select',ebay1['brand'])\n \n #Process more brands: WWE\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('WWE|WWF',regex = True),\\\n 'WWE',ebay1['brand'])\n \n #Process more brands: Kenner\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Kenner'), 'Kenner',ebay1['brand'])\n \n #Process more brands: Medicom\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('MEDICOM|Medicom|Medicos', regex = True),\\\n 'MEDICOM',ebay1['brand'])\n \n #Process more brands: Hot Toys\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('HOT TOYS|Hot Toys', regex = True),\\\n 'Hot Toys',ebay1['brand'])\n \n #Process more brands: Mezco\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Mezco'), 'Mezco',ebay1['brand'])\n \n #Process more brands: NECA\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('NECA|NEC|neca', regex = True),\\\n 'NECA',ebay1['brand'])\n \n #Process more brands: Star Wars\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Star Wars'), 'Star Wars', ebay1['brand'])\n \n #Process more brands: Unbranded\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Unbranded|Unbrand|UNBRANDED|Unbrander',\\\n regex = True), 'Unbranded', ebay1['brand'])\n \n #Process more brands: Fanstoys\n fanre = 'Fan Toys|Fans Toys|Fanstoys|Fan toys|Fans toys'\n ebay1['brand'] = np.where(ebay1['brand'].str.contains(fanre, regex = True),'Fanstoys',\\\n ebay1['brand'])\n \n #Process more brands: Super7\n suprex = 'Super7|Super 7'\n ebay1['brand'] = np.where(ebay1['brand'].str.contains(suprex,regex = True),'Super7',ebay1['brand'])\n \n #Process more brands: Marvel\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Marvel|MARVEL', regex = True),\\\n 'Marvel', ebay1['brand'])\n \n #Process more brands: X-Plus\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('X- Plus|X-Plus', regex = True),\\\n 'X-Plus', ebay1['brand'])\n \n #Process more brands: Maketoys\n ebay1['brand'] = np.where(ebay1['brand'].str.contains('Make Toys|Maketoys', regex = True),\\\n 'Maketoys', ebay1['brand'])\n " }, { "alpha_fraction": 0.6324200630187988, "alphanum_fraction": 0.6335616707801819, "avg_line_length": 24.05714225769043, "blob_id": "09e8007cea3c2af15b9bde3fba3cd6cff0dd217c", "content_id": "91ce8d11aafa08ae669fd199bf43233612dd4719", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 876, "license_type": "no_license", "max_line_length": 52, "num_lines": 35, "path": "/ebay/ebay/items.py", "repo_name": "Epizana/ebay_scrape", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\n# Define here the models for your scraped items\n#\n# See documentation in:\n# https://doc.scrapy.org/en/latest/topics/items.html\n\nimport scrapy\nimport re\n\n\nclass EbayItem(scrapy.Item):\n # define the fields for your item here like:\n # name = scrapy.Field()\n \n #ebay_id = scrapy.Field()\n title = scrapy.Field()\n item_num = scrapy.Field()\n #description = scrapy.Field()\n condition = scrapy.Field()\n #product = scrapy.Field()\n price = scrapy.Field()\n bids = scrapy.Field()\n quantity_sold = scrapy.Field()\n category = scrapy.Field()\n brand = scrapy.Field()\n #seller_id = scrapy.Field()\n year = scrapy.Field()\n era = scrapy.Field()\n franchise = scrapy.Field()\n character = scrapy.Field()\n toy_type = scrapy.Field()\n sell_date = scrapy.Field()\n size = scrapy.Field()\n gender = scrapy.Field()" }, { "alpha_fraction": 0.7967574000358582, "alphanum_fraction": 0.8002316355705261, "avg_line_length": 122.35713958740234, "blob_id": "27962a3a902f49499b09a6ea7f836a13a56e7b5f", "content_id": "7fbee5c3a74a9a1f29819668e1bfcf63bdf9ee67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1727, "license_type": "no_license", "max_line_length": 643, "num_lines": 14, "path": "/README.md", "repo_name": "Epizana/ebay_scrape", "src_encoding": "UTF-8", "text": "# ebay_scrape\nScraping snapshot of sales from ebay's action figure cateogry. The purpose of the project is to take a brief look at the sales volume for different brands/IPs (if possible, based on user-provided data).\n\nThe crawler aims to scrape sold listings form eBay's action figure category for details including selling price, title, brand, franchise/IP, number of bids, quantity sold, and a few other categorical features. Because eBay sold listings follow 3 general \"formats\" (auction, buy-it-now/BIN, and \"dutch\" style auctions, where a given quantity is offered for sale and the actual listing page is only qualified as completed/sold when the whole batch is sold out; until that occurs the page remains \"live\") coupled with the item specifics data being largely user/seller populated, many values for the categorical features may or may not be present.\n\nExcept for title and price, all other categories will populate based on a combination of user input and/or auction format.\n\nFor example, BIN formats will have 0 for number of bids, while \"dutch\" style auctions will most likely not list a sell date, as the actual listing itself remains live even though some of the offered quantity has sold. The brand/'character family' value-which will be used for the sales volume analysis for a given brand-is unfortunately user provided information and may or may not be populated.\n\nv1.0\nAt this time, there is no functionality yet to consider text from seller-provided descriptions, as well as capturing dutch-style auction listings.\n\nv2.0\nUpdated with format, and scraped an additional day. Final jupyter ipython file named \"ebay_final\" pushed. Includes interactive plotly graphs...which I couldn't export to the final pdf.\n" }, { "alpha_fraction": 0.5389564037322998, "alphanum_fraction": 0.5503931641578674, "avg_line_length": 33.75776290893555, "blob_id": "68840c5f5dd138aa277b0ba46d1362c3a91b1948", "content_id": "f11f7f5c9ba48015090e88c7999d9752ef601fe3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5596, "license_type": "no_license", "max_line_length": 158, "num_lines": 161, "path": "/ebay/ebay/spiders/ebay_spider.py", "repo_name": "Epizana/ebay_scrape", "src_encoding": "UTF-8", "text": "from scrapy import Spider, Request\nfrom ebay.items import EbayItem\nimport re\n\n\nclass EbaySpider (Spider):\n name = 'ebay_spider' #this must always be a unqiue name!!!!!!\n allowed_domains = ['www.ebay.com']\n start_urls = ['https://www.ebay.com/sch/i.html?_dcat=246&_fsrp=1&_nkw=toys&_sacat=246&_from=R40&LH_Complete=1&rt=nc&LH_Sold=1&Type=Action%2520Figure']\n\n\n def parse(self, response):\n \n #get the total number of pages from the hit summary on the left-hand side.\n #hit_string = response.xpath('//h1[@class=\"srp-controls__count-heading\"]/span/text()').extract_first()\n #total_hits = int(''.join(re.findall('\\d+(?:\\.\\d+)?',hit_string)))\n #per_page = 50 #ebay seems to default responses to 50 per page. \n #number_pages = total_hits // per_page\n\n \n #store long url, and construct all the urls for the resulting pages.\n temp = 'https://www.ebay.com/sch/i.html?_dcat=246&_fsrp=1&_nkw=toys&_sacat=246&_from=R40&LH_Complete=1&rt=nc&LH_Sold=1&Type=Action%2520Figure&_pgn={}'\n\n page_urls = [temp.format(x) for x in range(1,260)] #try 250\n\n \n for url in page_urls: #yield 2 for now\n yield Request(url=url, callback = self.parse_result_page)\n\n def parse_result_page(self, response):\n\n\n item_urls = response.xpath('//a[@class=\"s-item__link\"]/@href').extract()\n #print(len(item_urls)) #print how many urls gathered per page. Apparently default is 50?\n #print('='*50)\n\n for url in item_urls:\n yield Request(url, callback=self.parse_item_page)\n\n def parse_item_page(self, response):\n\n title = response.xpath('//span[@id=\"vi-lkhdr-itmTitl\"]/text()').extract_first()\n \n item_num = int(response.xpath('//div[@class=\"u-flL iti-act-num itm-num-txt\"]/text()').extract_first())\n\n try:\n condition = response.xpath('//div[@itemprop=\"itemCondition\"]/text()').extract_first()\n except:\n condition = 'None'\n\n\n #BIN page has different xpath from auction page. Try BIN, exception is auction.\n\n try:\n price1 = response.xpath('//span[@class=\"notranslate\"]/text()').extract_first().lstrip()\n except:\n price1 = response.xpath('//span[@class=\"notranslate vi-VR-cvipPrice\" or @id=\"mm-saleDscPrc\"]/text()').extract_first()\n \n #process either BIN or auction price with below:\n price = float(''.join(re.findall('\\d+(?:\\.\\d+)?',price1)))\n \n #not all results will be auction format. 0 bids is BIN/dutch auction.\n\n try:\n bids = int(response.xpath('//a[@class=\"vi-bidC\"]/span/text()').extract_first())\n except:\n bids = 0\n\n #dutch-style auctions show quantity sold. If not dutch style, quant_sold = 1.\n\n try:\n quant_sold = response.xpath('//a[@class=\"vi-txt-underline\"]/text()').extract_first()\n quant_sold = quant_sold = int(''.join(re.findall('\\d+',quant_sold)))\n except:\n quant_sold = 1\n\n try:\n category = response.xpath('//td[@style=\"vertical-align:top;\"]/table/tr/td/ul/li[5]//text()').extract_first()\n except:\n category = ''\n\n\n #store pages with multiple quantities will not have a sold date on the results page\n #as long as there is item stock.\n try:\n sell_date = response.xpath('//span[@id=\"bb_tlft\"]/text()').extract_first().lstrip()\n except:\n sell_date = ''\n\n #++++++++++++++process Item specifics box++++++++++++++++\n \n #overall xpath for the table\n temp = response.xpath('//div[@class=\"itemAttr\"]')\n #xpath for the categories and their text values, yields messy list.\n item_specifics = temp.xpath('.//table//tr//td//text()').extract()\n #process the messy list\n specs = list(filter(lambda s: s != '',list(map(lambda s: s.strip(),item_specifics))))\n \n #dict comprehension for key/value assignment; list --> dict\n item_dict = {specs[i][:-1]:specs[i+1] for i in range (0,len(specs)-1) if ':' in specs[i]}\n\n #user-provided individual specifics may or may not be populated on a given page.\n \n try:\n brand = response.xpath('//h2[@itemprop=\"brand\"]/span/text()').extract_first()\n except:\n brand = ''\n\n try:\n year = item_dict['Year']\n except:\n year = ''\n\n try:\n era = item_dict['Era']\n except:\n era = ''\n\n try:\n franchise = item_dict['Character Family']\n except:\n franchise = ''\n \n try:\n character = item_dict['Character']\n except:\n character = ''\n\n try:\n toy_type = item_dict['Type']\n except:\n toy_type = ''\n\n try:\n size = item_dict['Size']\n except:\n size = ''\n\n #+++++++++++++assign items++++++++++++++++\n \n item = EbayItem()\n item['title'] = title\n item['item_num'] = item_num\n item['condition'] = condition\n item['price'] = price\n item['bids'] = bids\n item['quantity_sold'] = quant_sold\n item['category'] = category\n item['brand'] = brand\n item['year'] = year\n item['era'] = era\n item['franchise'] = franchise\n item['character'] = character\n item['toy_type'] = toy_type\n item['sell_date'] = sell_date\n item['size'] = size\n yield item\n\n\n\n #print('+'*20,'Processed', title,'+'*20)\n" } ]
4
kooyeun/mysql-practice
https://github.com/kooyeun/mysql-practice
ee22797c11f3d7c969ecb122d01568d8c2fd5dc2
6b507b19370b280776493021dbafabf5b64eccca
54354cad4441082334de9f0915ed3040f7e7c167
refs/heads/master
2023-03-27T03:24:35.456349
2021-04-01T08:51:04
2021-04-01T08:51:04
352,852,160
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5609022378921509, "alphanum_fraction": 0.5684210658073425, "avg_line_length": 19.121212005615234, "blob_id": "5dbe51560b3f285a89924c9ea2fd2e96aa6b670d", "content_id": "4de82eff53f565cbe09d3c1a2250efcb13cccc1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 665, "license_type": "no_license", "max_line_length": 80, "num_lines": 33, "path": "/mysqlclient-practices/selecttest.py", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "\nfrom MySQLdb import connect, OperationalError\nfrom MySQLdb.cursors import DictCursor\n\n\ntry:\n # connection\n db = connect(user='webdb',\n password='webdb',\n host='localhost',\n port=3306,\n db='webdb',\n charset='utf8')\n\n # cusor\n cursor = db.cursor(DictCursor)\n\n # SQL\n sql = 'select no,first_name,last_name,email from emaillist order by no desc'\n cursor.execute(sql)\n\n # result\n results = cursor.fetchall()\n\n #\n cursor.close()\n db.close()\n\n #\n for result in results:\n print(result)\n\nexcept OperationalError as e:\n print(f'error : {e}')\n" }, { "alpha_fraction": 0.5156909227371216, "alphanum_fraction": 0.5736832618713379, "avg_line_length": 25.70098114013672, "blob_id": "23de16a0bc7338a1ca0a13917b0c4c810f3466ab", "content_id": "ca7ea899006be17b57d69d5c72e5f7c57f28ccfa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 5925, "license_type": "no_license", "max_line_length": 81, "num_lines": 204, "path": "/sql-practices/practice04/practice04.sql", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "-- 서브 쿼리\n\n\n-- ex1)\n-- 현재 Fai Bale 이 근무하는 부서의 전체 직원의 사번과 이름을 출력하세요\n\n-- ex1-sol1)\nselect dept_no\nfrom dept_emp a, employees b\nwhere a.emp_no = b.emp_no\nand a.to_date='9999-01-01'\nand concat(b.first_name,' ',b.last_name) = 'Fai Bale';\n\n-- ex1-sol2)\nselect *\nfrom dept_emp\nwhere to_date='9999-01-01'\nand dept_no='d004';\n\n\n-- 개별 쿼리로 해결 -> 가능하면 하나의 쿼리로 해결\nselect a.emp_no,b.first_name\nfrom dept_emp a, employees b\nwhere a.emp_no = b.emp_no\nand to_date='9999-01-01'\nand dept_no=(select dept_no\n\t\t\t\tfrom dept_emp a, employees b\n\t\t\t\twhere a.emp_no = b.emp_no\n\t\t\t\tand a.to_date='9999-01-01'\n\t\t\t\tand concat(b.first_name,' ',b.last_name) = 'Fai Bale');\n\n\n\n\n-- where 절의 조건식에 서브쿼리를 사용하고 결과가 단일행인 경우 :\n-- =, !=, >, <, >=, <=\n\n-- ex2)\n-- 현재 전체 사원의 평균 연봉보다 적은 급여를 받는 사원들의 이름, 급여를 출력하세요\n\n\nselect b.first_name,a.salary\nfrom salaries a, employees b\nwhere a.emp_no=b.emp_no\nand a.to_date='9999-01-01'\nand a.salary < (select avg(salary)\n\t\t\t\tfrom salaries\n\t\t\t\twhere to_date='9999-01-01');\n\n-- where 절의 조건식에 서브쿼리를 사용하고 결과가 다중행인 경우 :\n-- in(not in)\n-- any: =any(in 동일), >any, <any, ,<>any(!=any 동일), <=any, >=any\n-- all: =all, >all, <all, <>all(!=all, not in), <=all, >=all\n\n-- ex3)\n-- 현재 급여가 50000 이상인 직원의 이름과 급여를 출력하세요\n\n-- ex3-sol1)join\nselect a.first_name,b.salary\nfrom employees a, salaries b\nwhere a.emp_no=b.emp_no\nand b.to_date='9999-01-01'\nand b.salary >= 50000\norder by b.salary;\n\n-- ex3-sol2) subquery (멀티 행/열)\nselect a.first_name,b.salary\nfrom employees a, salaries b\nwhere a.emp_no=b.emp_no\nand b.to_date='9999-01-01';\n\nselect *\nfrom salaries\nwhere to_date='9999-01-01'\nand salary > 50000;\n\n\nselect a.first_name,b.salary\nfrom employees a, salaries b\nwhere a.emp_no=b.emp_no\nand b.to_date='9999-01-01'\nand (a.emp_no,b.salary) =any (select emp_no,salary\n\t\t\t\t\t\t\tfrom salaries\n\t\t\t\t\t\t\twhere to_date='9999-01-01'\n\t\t\t\t\t\t\tand salary > 50000);\n\n \n-- ex3-sol3) subquery (멀티 행/열)\nselect a.first_name,b.salary\nfrom employees a, salaries b\nwhere a.emp_no=b.emp_no\nand b.to_date='9999-01-01'\nand (a.emp_no,b.salary) in (select emp_no,salary\n\t\t\t\t\t\t\tfrom salaries\n\t\t\t\t\t\t\twhere to_date='9999-01-01'\n\t\t\t\t\t\t\tand salary > 50000); \n\n\n-- ex3-sol4) subquery (멀티 행/열)\nselect a.first_name, b.salary\n\tfrom employees a,\n (select emp_no, salary\n from salaries\n\t\t where to_date='9999-01-01'\n and salary > 50000) b\n where a.emp_no = b.emp_no\norder by b.salary;\n\n\n-- ex4) 현재 가장 적은 평균급여의 직책과 그 평균급여를 출력해보세요\n-- ex4-sol1)\n select b.title, round(avg(salary)) as avg_salary \n from salaries a, titles b\n where a.emp_no = b.emp_no\n\tand a.to_date='9999-01-01'\n and b.to_date='9999-01-01'\ngroup by b.title\n having avg_salary = ( select min(avg_salary)\n\t\t\t\t\t\t\tfrom ( select b.title, round(avg(salary)) as avg_salary\n\t\t\t\t\t\t\t\t\t from salaries a, titles b\n\t\t\t\t\t\t\t\t\t where a.emp_no = b.emp_no\n\t and a.to_date='9999-01-01'\n and b.to_date='9999-01-01'\n group by b.title) a); \n\n-- ex4-sol2) top-k\n select b.title, avg(salary) as avg_salary\n from salaries a, titles b\n where a.emp_no = b.emp_no\n and a.to_date='9999-01-01'\n and b.to_date='9999-01-01'\ngroup by b.title\norder by avg_salary asc\n limit 0, 1;\n \n\n-- ex5) 현재 각 부서별로 최고 급여를 받는 사원의 이름과 급여를 출력해보세요\n-- 부서별로 최고 급여를 구해야\n select a.dept_no, max(b.salary) as max_salary\n from dept_emp a, salaries b\n where a.emp_no = b.emp_no\n and a.to_date = '9999-01-01'\n and b.to_date = '9999-01-01'\ngroup by a.dept_no; \n\n-- ex5-sol1) from절 subquery\nselect a.first_name, b.dept_no, d.dept_name, c.salary\n from employees a,\n dept_emp b,\n salaries c,\n departments d,\n ( select a.dept_no, max(b.salary) as max_salary\n\t\t from dept_emp a, salaries b\n where a.emp_no = b.emp_no\n and a.to_date = '9999-01-01'\n and b.to_date = '9999-01-01'\n group by a.dept_no) e\n where a.emp_no = b.emp_no\n and b.emp_no = c.emp_no\n and b.dept_no = d.dept_no\n and b.dept_no = e.dept_no\n and c.salary = e.max_salary\n and b.to_date = '9999-01-01'\n and c.to_date = '9999-01-01'\norder by c.salary desc; \n \n-- ex5-sol1) where절 subquery\nselect a.first_name, b.dept_no, d.dept_name, c.salary\n from employees a,\n dept_emp b,\n salaries c,\n departments d\n where a.emp_no = b.emp_no\n and b.emp_no = c.emp_no\n and b.dept_no = d.dept_no\n and b.to_date = '9999-01-01'\n and c.to_date = '9999-01-01'\n and (b.dept_no, c.salary) in (select a.dept_no, max(b.salary) as max_salary\n from dept_emp a, salaries b\n where a.emp_no = b.emp_no\n and a.to_date = '9999-01-01'\n and b.to_date = '9999-01-01'\n\t\t\t\t\t\t\t\t group by a.dept_no)\norder by c.salary desc;\n\n\n---------------------------------------------------------------------------------\n---------------------------------------------------------------------------------\n\n\nselect a.title,b.emp_no,max(b.salary) as max_salary\nfrom titles a, salaries b\nwhere a.emp_no = b.emp_no\nand a.to_date='9999-01-01'\ngroup by a.title;\n\n\nselect d.first_name,c.max_salary\nfrom employees d,(select a.title,b.empo_no,max(b.salary) as max_salary\n\t\t\t\t\tfrom titles a, salaries b\n\t\t\t\t\twhere a.emp_no = b.emp_no\n and a.to_date='9999-01-01'\n\t\t\t\t\tgroup by a.title) c\nwhere d.emp_no = c.emp_no;\n\n\n" }, { "alpha_fraction": 0.6355572938919067, "alphanum_fraction": 0.6895487904548645, "avg_line_length": 21.929203033447266, "blob_id": "281d5e741ad4580a3aebbe953a2c51559f3900bd", "content_id": "8b0e0d30d89713f991088ed403c66cfc034b4e10", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 2997, "license_type": "no_license", "max_line_length": 58, "num_lines": 113, "path": "/sql-practices/practice03/practice03.sql", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "-- 현재 근무하고 있는 여직원의 이름과 직책을 직원 이름 순으로 출력하세요\nselect a.first_name,b.title\nfrom employees a, titles b\nwhere a.emp_no = b.emp_no -- join condition\nand b.to_date='9999-01-01' -- select condition\nand a.gender='F' -- select condition\norder by a.first_name;\n\n-- 부서별로 현재 직책이 Engineer 인 직원들에 대해서만 평균 급여를 구하세요\nselect a.dept_no, d.dept_name, avg(b.salary) as avg_salary\nfrom dept_emp a, salaries b, titles c, departments d\nwhere a.emp_no = b.emp_no\nand b.emp_no = c.emp_no\nand a.dept_no = d.dept_no\nand a.to_date='9999-01-01'\nand b.to_date='9999-01-01'\nand c.to_date='9999-01-01'\nand c.title='Engineer'\ngroup by a.dept_no\norder by avg_salary desc;\n\n-- 현재 직책별로 급여의 총합을 구하되 Engineer 직책은 제외 하세요\n-- 단 총합이 2,000,000,000 이상인 직책만 나타내며\n-- 급여의 총합에 대해서는 내림차순(DESC)으로 정렬하세요\nselect a.title, sum(b.salary)\nfrom titles a, salaries b\nwhere a.emp_no = b.emp_no\nand NOT a.title IN('Engineer')\nand a.to_date='9999-01-01'\nand b.to_date='9999-01-01'\ngroup by a.title\nhaving sum(b.salary) >= 2000000000\norder by sum(b.salary) desc;\n\n\n--\n-- ANSI/ISO SQL 1999 JOIN 문법\n--\n-- join ~ on\n-- 현재 근무하고 있는 여직원의 이름과 직책을 직원 이름 순으로 출력하세요\nselect a.first_name,b.title\nfrom employees a\njoin titles b\n on a.emp_no = b.emp_no -- join condition\nwhere b.to_date='9999-01-01' -- select condition\nand a.gender='F' -- select condition\norder by a.first_name;\n\n-- natural join\nselect a.first_name,b.title\nfrom employees a\nnatural join titles b\nwhere b.to_date='9999-01-01' -- select condition\nand a.gender='F' -- select condition\norder by a.first_name;\n\n-- natural join 단점\nselect count(*)\nfrom titles a\njoin salaries b\non a.emp_no = b.emp_no\nwhere a.to_date='9999-01-01'\nand b.to_date='9999-01-01';\n\nselect count(*)\nfrom titles a\nnatural join salaries b\nwhere a.to_date='9999-01-01'\nand b.to_date='9999-01-01';\n\n\n-- join ~ using\nselect count(*)\nfrom titles a\njoin salaries b\nusing (emp_no)\nwhere a.to_date='9999-01-01'\nand b.to_date='9999-01-01';\n\n\n-- outer join\n\n-- 테스트 데이터 넣기\ninsert into dept values(null,'총무');\ninsert into dept values(null,'개발');\ninsert into dept values(null,'영업');\ninsert into emp values(null,'둘리',2);\ninsert into emp values(null,'마이콜',3);\ninsert into emp values(null,'또치',2);\ninsert into emp values(null,'도우넛',3);\ninsert into emp values(null,'길동',null);\n\n\nselect * from emp;\nselect * from dept;\n\n-- 현재 회사의 직원의 이름과 부서이름을 출력하세요\nselect a.name,b.name\nfrom emp a\njoin dept b\non a.dept_no=b.no;\n\n-- left join\nselect a.name,ifnull(b.name,'없음')\nfrom emp a\nleft join dept b\non a.dept_no=b.no;\n\n-- right join\nselect ifnull(a.name,'직원없음'),b.name\nfrom emp a\nright join dept b\non a.dept_no=b.no;\n\n\n" }, { "alpha_fraction": 0.6390977501869202, "alphanum_fraction": 0.7034252285957336, "avg_line_length": 18.590164184570312, "blob_id": "249ca2e829ca87c8000d9f24b75a3e8adddc6b28", "content_id": "f16f11e40198668671b04e3a42f651849008fb0f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1709, "license_type": "no_license", "max_line_length": 55, "num_lines": 61, "path": "/sql-practices/practice02/practice02.sql", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "-- 집계함수\n\n-- 예제1\n-- salaries 테이블에서 현재 전체 직원의 평균급여 출력\nselect avg(salary),max(salary)\nfrom salaries\nwhere to_date = '9999-01-01';\n-- 왜 null 로 나오지??\n\n-- 예제2\n-- salaries 테이블에서 사번이 10060인 직원의 급여 평균과 총합ㄱalterㅖ를 출력\nselect avg(salary),sum(salary)\nfrom salaries\nwhere emp_no=10060;\n\n-- 예제3\n-- 이 예제 직원의 최저 임금을 받은 시기와 최대 임금을 \"받은 시기\"를 각 각 출력해보세요\n-- select 절에 집계함수가 있으면 다른 컬럼은 올 수 없다\n-- 따라서 \"받은 시기\"는 조인이나 서브쿼리를 통해서 구해야 한다\nselect max(salary),min(salary)\nfrom salaries\nwhere emp_no=10060;\n\n-- 예제4\n-- dept_emp 테이블에서 d008에 근무하는 인원수는\nselect count(*)\nfrom dept_emp\nwhere dept_no='d008'\nand to_date='9999-01-01';\n\n-- 예제5\n-- 각 사원별로 평균연봉 출력\nselect emp_no,avg(salary) as avg_salary\nfrom salaries\ngroup by emp_no\norder by avg_salary desc;\n\n-- 예제6\n-- salaries 테이블에서 현재 전체 직원별로 평균급여가 35000 이상인 직원의 평균 급여를\n-- 큰 순서로 출력\nselect emp_no,avg(salary)\nfrom salaries\nwhere to_date='9999-01-01'\ngroup by emp_no\nhaving avg(salary) >= 35000\norder by avg(salary) desc;\n\n-- 예제7\n-- 사원별로 몇 번의 직책 변경이 있었는지 조회해보세요\nselect emp_no,count(*)\nfrom titles\ngroup by emp_no;\n\n-- 예제8\n-- 현재 직책별로 직원수를 구하되 직원수가 100명 이상인 직책만 출력하세요\nselect title, count(*) as cnt\nfrom titles\nwhere to_date='9999-01-01'\ngroup by title\nhaving cnt >= 100\norder by cnt desc;\n\n\n" }, { "alpha_fraction": 0.625539243221283, "alphanum_fraction": 0.6600517630577087, "avg_line_length": 17.109375, "blob_id": "c1311d697dddc680d4d227726b3d58b8939dc2db", "content_id": "0a2f3ac7c728a7b09f51388f9de7541530e2d94a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 1771, "license_type": "no_license", "max_line_length": 58, "num_lines": 64, "path": "/sql-practices/practice01/practice01.sql", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "-- 문제1\n-- 사번이 10944인 사원의 이름은(전체 이름)\nselect concat(last_name,' ',first_name) as name\nfrom employees\nwhere emp_no=10944;\n\n-- 문제2. \n-- 전체 직원의 다음 정보를 조회하세요.\n-- 가장 선임부터 출력이 되도록 하세요.\n-- 출력은 이름, 성별, 입사일 순서이고 이름, 성별, 입사일 로 컬럼 이름을 대체해 보세요.\nselect last_name as '이름',gender as '성별',hire_date as '입사일'\nfrom employees\norder by hire_date;\n\n\n-- 문제3.\n-- 여직원과 남직원은 각 각 몇 명이나 있나요?\nselect count(*) as '남직원 수'\nfrom employees\nwhere gender='M';\n\nselect count(*) as '여직원 수'\nfrom employees\nwhere gender='F';\n\n\n-- 문제4.\n-- 현재 근무하고 있는 직원 수는 몇 명입니까? (salaries 테이블을 사용합니다.) \n\n\n-- 문제5.\n-- 부서는 총 몇 개가 있나요?\nselect count(distinct dept_name) as '부서의 총 개수'\nfrom departments;\n\n-- 문제6.\n-- 현재 부서 매니저는 몇 명이나 있나요?\n\n\n-- 문제7.\n-- 전체 부서를 출력하려고 합니다. 순서는 부서이름이 긴 순서대로 출력해 보세요.\nselect distinct dept_name\nfrom departments\norder by length(dept_name) desc;\n\n-- 문제8.\t\n-- 현재 급여가 120,000이상 받는 사원은 몇 명이나 있습니까?\nselect count(*)\nfrom salaries\nwhere salary >= 120000;\n\n-- 문제9.\n-- 어떤 직책들이 있나요? 중복 없이 이름이 긴 순서대로 출력해 보세요.\n select distinct title, length(title)\n from titles\n order by length(title) desc;\n \n\n-- 문제10\n-- 현재 Enginner 직책의 사원은 총 몇 명입니까?\n\n\n-- 문제11\n-- 사번이 13250(Zeydy)인 지원이 직책 변경 상황을 시간순으로 출력해보세요.\n" }, { "alpha_fraction": 0.6451612710952759, "alphanum_fraction": 0.6612903475761414, "avg_line_length": 14.75, "blob_id": "6c0eddcaa16586e81a7c737fc9f1d91279d973fc", "content_id": "4b947e8371987986175105f5c051673d95319038", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 70, "license_type": "no_license", "max_line_length": 37, "num_lines": 4, "path": "/readme.md", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "# MySQL 연습\n\n## 1. SQL 연습\n## Pyton MySQL Lib : mysqlclient test" }, { "alpha_fraction": 0.6448467969894409, "alphanum_fraction": 0.6991643309593201, "avg_line_length": 22.933332443237305, "blob_id": "b03c3b7a896f913c501c121462e53f6d519cc3be", "content_id": "89ccc0e300f68feee63dafb9e866367b0d840901", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 764, "license_type": "no_license", "max_line_length": 78, "num_lines": 30, "path": "/sql-practices/01.basic-sql-practices.sql", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "\n-- pets table 생성\ncreate table pets(\nname varchar(20),\nowner varchar(20),\nspecies varchar(20),\ngender char(1),\nbirth date,\ndeath date\n);\n\n-- table schema 확인\ndesc pets;\n\n-- insert(C)\ninsert into pets values('성탄이','kickscar','dog','m','2010-12-25',null);\ninsert into pets(owner,name,species,gender,birth) \nvalues('kickscar','choco','cat','m','2010-12-25');\ninsert into pets values('마음이','kickscar','dog','m','2010-12-25','2021-03-30');\n\n-- select(R)\nselect * from pets;\nselect name,birth from pets;\nselect name,birth from pets order by birth asc;\nselect count(*) from pets; -- null이 있는 row 세지않는다는 것을 주의\nselect count(*) from pets where death is not null;\n\n-- update(U)\nupdate pets\nset species='monkey'\nwhere name='choco';" }, { "alpha_fraction": 0.5017300844192505, "alphanum_fraction": 0.512110710144043, "avg_line_length": 17.612903594970703, "blob_id": "3aa22952d9e11d76739907c64b8ebb11840183e8", "content_id": "dfa0a9b2b6842fb78ae9a6744b1fc4ff021ac8a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 584, "license_type": "no_license", "max_line_length": 65, "num_lines": 31, "path": "/mysqlclient-practices/inserttest.py", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "\nfrom MySQLdb import connect, OperationalError\n\n\ntry:\n # connection\n db = connect(user='webdb',\n password='webdb',\n host='localhost',\n port=3306,\n db='webdb',\n charset='utf8')\n\n # cusor\n cursor = db.cursor()\n\n # SQL\n sql = \"insert into emaillist values(null,'마','이콜','[email protected]')\"\n count = cursor.execute(sql)\n\n # commit\n db.commit()\n\n #\n cursor.close()\n db.close()\n\n #\n print(f'result : {count==1}')\n\nexcept OperationalError as e:\n print(f'error : {e}')\n" }, { "alpha_fraction": 0.5566714406013489, "alphanum_fraction": 0.6398852467536926, "avg_line_length": 14.840909004211426, "blob_id": "c90f20a22fa8c82c41733483cad0039b8f2ae122", "content_id": "1e0c4ec33ab6419e01838d75a203e378aafa94f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1033, "license_type": "no_license", "max_line_length": 51, "num_lines": 44, "path": "/sql-practices/practice01/readme.md", "repo_name": "kooyeun/mysql-practice", "src_encoding": "UTF-8", "text": "#문제를 풀면서\n\n##4,6,10\n\"현재\" 에 대해서 표현할 줄 몰랐다\n답안에는 \nwhere to_date = '9999-01-01'\n전부 이렇게 나와있는데 납득이 잘 가지 않으니 물어봐야겠다\n\n\n\n##11\ntitles 테이블에 대한 이해가 부족해서 활용하지 못했다\n(10,11 문제)\n\n\n## 답안\n-- 문제4.\n-- 현재 근무하고 있는 직원 수는 몇 명입니까? (salaries 테이블을 사용합니다.) \nselect count(*)\n from salaries\n where to_date = '9999-01-01';\n\n\n-- 문제6.\n-- 현재 부서 매니저는 몇 명이나 있나요?(역임 매너저는 제외)\n\tselect count(*) \n from dept_manager\n where to_date = '9999-01-01';\n\n\n-- 문제10\n-- 현재 Enginner 직책의 사원은 총 몇 명입니까?\nselect count(*)\n from titles\n where title = 'Engineer'\n and to_date = '9999-01-01';\n\n\n-- 문제11\n-- 사번이 13250(Zeydy)인 지원이 직책 변경 상황을 시간순으로 출력해보세요.\nselect title, from_date, to_date \n from titles\n where emp_no = 13250\norder by from_date asc; " } ]
9
NHSCubsRobotics/Finnovators-python
https://github.com/NHSCubsRobotics/Finnovators-python
102c73c88da73c2c28ac0dc8bfbbb417e5fa1bd9
13c2c325384044abef21b24af9c393556d2d9d33
4808baec3a17f3131e9e1c570f4cfb9d0ca2c1ad
refs/heads/master
2020-05-29T14:11:22.422473
2017-06-08T19:44:09
2017-06-08T19:44:09
82,593,396
0
2
null
2017-02-20T19:19:04
2017-02-20T21:55:29
2017-03-20T03:53:17
Python
[ { "alpha_fraction": 0.7678571343421936, "alphanum_fraction": 0.7976190447807312, "avg_line_length": 20.125, "blob_id": "23a677e5b5c92b9056b9436bebdf89ff7a854696", "content_id": "d0896c4dafa80800935254d7aedb5cb7692f987a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 168, "license_type": "permissive", "max_line_length": 42, "num_lines": 8, "path": "/README.md", "repo_name": "NHSCubsRobotics/Finnovators-python", "src_encoding": "UTF-8", "text": "# Finnovators\nCode for Finnovators team.\n\n# intallation\n1 intall pycharm\n2 install python 3+\n3 intall pygame and pyserial using command\n pip3 install pygame pyserial" }, { "alpha_fraction": 0.588556706905365, "alphanum_fraction": 0.612557590007782, "avg_line_length": 31.12413787841797, "blob_id": "736bb555e4f2f93f385daa5801724b24e230686e", "content_id": "5afc6d1245a8cc7b4eae42cec970c4a8493cd238", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9333, "license_type": "permissive", "max_line_length": 100, "num_lines": 290, "path": "/FourMotorVector3.py", "repo_name": "NHSCubsRobotics/Finnovators-python", "src_encoding": "UTF-8", "text": "import pygame\nimport math\nimport serial\nimport RPi.GPIO as GPIO\nfrom numpy import matrix, nan_to_num\n\n# Define some colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\n\nSERIAL_MARKER = 128\nVECTOR_MOTORS_IDNT = 0\nUP_DOWN_MOTOR_IDNT = 2\nLIGHT_TOGGLE_IDNT = 5\nCLAW_OPEN_CLOSE_IDNT = 4\nCLAW_SPIN_IDNT = 3\nCLAW_OPEN_CLOSE_GPIO_PIN = 2\nTRIPPLE_ROTATE_RIGHT_IDNT = 6\nTRIPPLE_ROTATE_LEFT_IDNT = 7\n\nVirt = 0\n\ndef pmap( value, istart, istop, ostart, ostop):\n return ostart + (ostop - ostart) * ((value - istart) / (istop - istart))\ndef sendSerial(serialPort , data):\n serialPort.write(data)\n\ndef vset(nvalue):\n global Virt\n Virt = nvalue\n\n##### CONFIGURE T HESE AXES #####\nX_AXIS = 0\nY_AXIS = 1\nYAW_AXIS = 3\nINVERT_X = False\nINVERT_Y = False\nINVERT_Yaw = False\n################################\n\n# Define some motor control matrices\nY_AXIS_MATRIX = matrix('-1, -1; 1, 1')\nX_AXIS_MATRIX = matrix('1, -1; 1, -1')\nYAW_MATRIX = matrix('1, -1; -1, 1')\n\n# This is a simple class that will help us print to the screen\n# It has nothing to do with the joysticks, just outputting the\n# information.\nclass TextPrint:\n def __init__(self):\n self.reset()\n self.font = pygame.font.Font(None, 20)\n\n def printScreen(self, screen, textString):\n textBitmap = self.font.render(textString, True, BLACK)\n screen.blit(textBitmap, [self.x, self.y])\n self.y += self.line_height\n\n def print2DMatrix(self, screen, matrix):\n array = matrix.getA()\n for row in array:\n self.printScreen(screen, \"[{0:07.3f}, {1:07.3f}]\".format(row[0].item(), row[1].item()))\n\n def reset(self):\n self.x = 10\n self.y = 10\n self.line_height = 15\n\n def indent(self):\n self.x += 10\n\n def unindent(self):\n self.x -= 10\n\n\npygame.init()\n\n#Opens Serial port on Rasberry PI3\nser = serial.Serial('/dev/ttyS0', 38400, timeout=5)\n\n#Setup GPIO for claw open/close relay\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(CLAW_OPEN_CLOSE_GPIO_PIN, GPIO.OUT)\nclawClosed = True\n\nclawSpin = 0\n\n# Set the width and height of the screen [width,height]\nsize = [200, 600]\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption(\"Four Motor Demo\")\n\n# Loop until the user clicks the close button.\ndone = False\n\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\n\n# Initialize the joysticks\npygame.joystick.init()\n\n# Get ready to print\ntextPrint = TextPrint()\n\n# -------- Main Program Loop -----------\nwhile done == False:\n # EVENT PROCESSING STEP\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n if (event.type == pygame.KEYDOWN):\n print (\"key pressed \" + pygame.key.name(event.key))\n keys = 0\n idnt = 255\n\n if (event.key == pygame.K_c and pygame.key.get_mods() & pygame.KMOD_SHIFT):\n idnt = TRIPPLE_ROTATE_RIGHT_IDNT\n keys = 1\n if (event.key == pygame.K_z and pygame.key.get_mods() & pygame.KMOD_SHIFT):\n idnt = TRIPPLE_ROTATE_LEFT_IDNT\n keys = 1\n\n if (event.key == pygame.K_l):\n idnt = LIGHT_TOGGLE_IDNT\n keys = 1\n if (event.key == pygame.K_j):\n idnt = CLAW_OPEN_CLOSE_IDNT\n keys = 1\n GPIO.output(CLAW_OPEN_CLOSE_GPIO_PIN, GPIO.HIGH if clawClosed else GPIO.LOW)\n clawClosed = not clawClosed\n print(\"Setting claw: \" + (\"GPIO.HIGH\" if clawClosed else \"GPIO.LOW\"))\n\n if (event.key == pygame.K_d):\n clawSpin += 1\n if (event.key == pygame.K_a):\n clawSpin -= 1\n\n keyBytes = bytes([SERIAL_MARKER, idnt, keys])\n sendSerial(ser, keyBytes)\n\n if (event.type == pygame.KEYUP):\n if (event.key == pygame.K_d):\n clawSpin -= 1\n print (\"key released \" + pygame.key.name(event.key))\n if (event.key == pygame.K_a):\n clawSpin += 1\n print (\"key released \" + pygame.key.name(event.key))\n\n # DRAWING STEP\n # First, clear the screen to white. Don't put other drawing commands\n # above this, or they will be erased with this command.\n screen.fill(WHITE)\n textPrint.reset()\n\n if (clawSpin != 0):\n spinBytes = bytes([SERIAL_MARKER, CLAW_SPIN_IDNT, clawSpin % 256])\n sendSerial(ser, spinBytes)\n ser.read(1)\n\n try:\n # Get joystick to work with.\n joystick = pygame.joystick.Joystick(0)\n except pygame.error:\n print('Please connect a controller')\n exit(1)\n joystick.init()\n\n # Print axis values.\n for i in range (joystick.get_numaxes()):\n Throttle= pmap(joystick.get_axis(5), -1, 1, 0, 127)\n if i == 5:\n textPrint.printScreen(screen, \"Axis {0} value: {1:07.3f}\".format(i, Throttle))\n continue\n axis = joystick.get_axis(i)\n axis = pmap(math.fabs(axis), math.sqrt(2 * math.pow(0.17, 2)), 1, 0, 1)\n axis = max(0, axis)\n axis = math.copysign(axis, joystick.get_axis(i))\n textPrint.printScreen(screen, \"Axis {0} value: {1:07.3f}\".format(i, axis))\n textPrint.printScreen(screen, \"\")\n\n # Get axes to work with.\n # Set tolerance\n axisX = joystick.get_axis(X_AXIS)\n axisX = pmap(math.fabs(axisX), math.sqrt(2 * math.pow(0.17, 2)), 1, 0, 1)\n axisX = max(0, axisX)\n axisX = math.copysign(axisX, joystick.get_axis(X_AXIS))\n\n axisY = joystick.get_axis(Y_AXIS)\n axisY = pmap(math.fabs(axisY), math.sqrt(2 * math.pow(0.17, 2)), 1, 0, 1)\n axisY = max(0, axisY)\n axisY = math.copysign(axisY, joystick.get_axis(Y_AXIS))\n\n axisYaw = joystick.get_axis(YAW_AXIS)\n axisYaw = pmap(math.fabs(axisYaw), math.sqrt(2 * math.pow(0.17, 2)), 1, 0, 1)\n axisYaw = max(0, axisYaw)\n axisYaw = math.copysign(axisYaw, joystick.get_axis(YAW_AXIS))\n\n xAxis = axisX * (-1 if INVERT_X else 1)\n yAxis = axisY * (-1 if INVERT_Y else 1)\n yawAxis = axisYaw * (-1 if INVERT_Yaw else 1)\n\n # Construct individual thrust matrices.\n xMatrix = (X_AXIS_MATRIX * xAxis)\n yMatrix = (Y_AXIS_MATRIX * yAxis)\n yawMatrix = (YAW_MATRIX * yawAxis)\n # Combine individual thrust matrices into complete motor thrust matrix.\n motorMatrix = (xMatrix + yMatrix + yawMatrix)\n\n # Calculate thrust matrix scaling factor.\n maxInputMag = max(abs(xAxis), abs(yAxis), abs(yawAxis))\n maxThrust = max(abs(motorMatrix.min()), motorMatrix.max())\n motorScalar = nan_to_num(maxInputMag / maxThrust)\n\n #Set Throttle\n Throttle = pmap(joystick.get_axis(5), -1, 1, 0, 128)\n\n # Scale thrust matrix down to within motor thrust range.\n motorMatrix = (motorMatrix * motorScalar) * Throttle\n # Clip off thrust matrix values less than -127.\n motorMatrix = motorMatrix.clip(min=-127)\n # Cast matrix values to integers.\n motorMatrix = motorMatrix.astype(int)\n\n # Print matrices to screen.\n textPrint.printScreen(screen, \"xMatrix: \")\n textPrint.print2DMatrix(screen, xMatrix)\n textPrint.printScreen(screen, \"\")\n textPrint.printScreen(screen, \"yMatrix: \")\n textPrint.print2DMatrix(screen, yMatrix)\n textPrint.printScreen(screen, \"\")\n textPrint.printScreen(screen, \"yawMatrix: \")\n textPrint.print2DMatrix(screen, yawMatrix)\n textPrint.printScreen(screen, \"\")\n textPrint.printScreen(screen, \"motorMatrix: \")\n textPrint.print2DMatrix(screen, motorMatrix)\n textPrint.printScreen(screen, \"\")\n\n # Print motor values.\n textPrint.printScreen(screen, \"Fore-Port Motor: {:03d}\".format(motorMatrix.item(0)))\n textPrint.printScreen(screen, \"Fore-Starboard Motor: {:03d}\".format(motorMatrix.item(1)))\n textPrint.printScreen(screen, \"Aft-Port Motor: {:03d}\".format(motorMatrix.item(2)))\n textPrint.printScreen(screen, \"Aft-Starboard Motor: {:03d}\".format(motorMatrix.item(3)))\n textPrint.printScreen(screen, \"\")\n\n\n FPM = motorMatrix.item(0) % 256\n FSM = motorMatrix.item(1) % 256\n APM = motorMatrix.item(2) % 256\n ASM = motorMatrix.item(3) % 256\n\n axisBytes = bytes([SERIAL_MARKER, VECTOR_MOTORS_IDNT , FPM, FSM, APM, ASM])\n sendSerial(ser, axisBytes)\n\n buttons = joystick.get_numbuttons()\n\n for i in range(buttons):\n button = joystick.get_button(i)\n button_a = joystick.get_button(0)\n button_b = joystick.get_button(1)\n if (button_a + button_b) == 0:\n vset(0)\n if (button_a + button_b) == 2:\n vset(0)\n if button_a == 0 and button_b == 1:\n vset (127)\n if button_a == 1 and button_b == 0:\n vset(-127)\n #textPrint.print(screen, \"Virtical value: {}\".format(Virt))\n\n axisBytes = bytes([SERIAL_MARKER, UP_DOWN_MOTOR_IDNT, Virt % 256])\n sendSerial(ser, axisBytes)\n\n\n #for i in range(hats):\n #hat = joystick.get_hat(i)\n\n\n # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT\n\n # Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n\n # Limit to 20 frames per second\n clock.tick(20)\n\n# Close the window and quit.\n# If you forget this line, the program will 'hang'\n# on exit if running from IDLE.\npygame.quit()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.560146689414978, "alphanum_fraction": 0.5814180970191956, "avg_line_length": 31.196849822998047, "blob_id": "eb150b95ed1dd01a8079b4ff9864c69862c95254", "content_id": "eb2e598bc4edb3448d3b598b15b78f04f6470fe6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8180, "license_type": "permissive", "max_line_length": 103, "num_lines": 254, "path": "/MainNoMode.py", "repo_name": "NHSCubsRobotics/Finnovators-python", "src_encoding": "UTF-8", "text": "import pygame\nimport math\nimport serial\nimport RPi.GPIO as GPIO\n# Define some colors\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nSERIAL_MARKER = 128\nLEFT_MOTOR_IDNT = 0\nRIGHT_MOTOR_IDNT = 1\nUP_DOWN_MOTOR_IDNT = 2\nLIGHT_TOGGLE_IDNT = 5\nCLAW_OPEN_CLOSE_IDNT = 4\nCLAW_SPIN_IDNT = 3\nCLAW_OPEN_CLOSE_GPIO_PIN = 2\nTRIPPLE_ROTATE_RIGHT_IDNT = 6\nTRIPPLE_ROTATE_LEFT_IDNT = 7\ndef pmap( value, istart, istop, ostart, ostop):\n return ostart + (ostop - ostart) * ((value - istart) / (istop - istart))\ndef sendSerial(serialPort , data):\n serialPort.write(data)\n\n#things needed to send over serial:\n#claw spin (A/D) - max 7 bits\n#claw open/close (J)\n#light on/off (L)\n#2 motors forward/back - 8 bits each\n#motors up/down - 8 bits\n#drill thingy(K)\n#10 bits\n\n# This is a simple class that will help us print to the screen\n# It has nothing to do with the joysticks, just outputing the\n# information.\nclass TextPrint:\n def __init__(self):\n self.reset()\n self.font = pygame.font.Font(None, 20)\n\n def print(self, screen, textString):\n textBitmap = self.font.render(textString, True, BLACK)\n screen.blit(textBitmap, [self.x, self.y])\n self.y += self.line_height\n\n def reset(self):\n self.x = 10\n self.y = 10\n self.line_height = 15\n\n def indent(self):\n self.x += 10\n\n def unindent(self):\n self.x -= 10\n\n\npygame.init()\n#Opens Serial port on Rasberry PI3\nser = serial.Serial('/dev/ttyS0', 19200, timeout=5)\n\n#Setup GPIO for claw open/close relay\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(CLAW_OPEN_CLOSE_GPIO_PIN, GPIO.OUT)\nclawClosed = True\n\nclawSpin = 0\n\n# Set the width and height of the screen [width,height]\nsize = [500, 700]\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption(\"My Game\")\n\n# Loop until the user clicks the close button.\ndone = False\n\n# Used to manage how fast the screen updates\nclock = pygame.time.Clock()\n\n# Initialize the joysticks\npygame.joystick.init()\n\n# Get ready to print\ntextPrint = TextPrint()\n\n# -------- Main Program Loop -----------\nwhile done == False:\n # EVENT PROCESSING STEP\n for event in pygame.event.get(): # User did something\n if event.type == pygame.QUIT: # If user clicked close\n done = True # Flag that we are done so we exit this loop\n\n # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN JOYBUTTONUP JOYHATMOTION\n if event.type == pygame.JOYBUTTONDOWN:\n print(\"Joystick button pressed.\")\n if event.type == pygame.JOYBUTTONUP:\n print(\"Joystick button released.\")\n\n if (event.type == pygame.KEYDOWN):\n print (\"key pressed \" + pygame.key.name(event.key))\n keys = 0\n idnt = 255\n \n\n if (event.key == pygame.K_c and pygame.key.get_mods() & pygame.KMOD_SHIFT):\n idnt = TRIPPLE_ROTATE_RIGHT_IDNT\n keys = 1\n if (event.key == pygame.K_z and pygame.key.get_mods() & pygame.KMOD_SHIFT):\n idnt = TRIPPLE_ROTATE_LEFT_IDNT\n keys = 1\n\n if (event.key == pygame.K_l):\n idnt = LIGHT_TOGGLE_IDNT\n keys = 1\n if (event.key == pygame.K_j):\n idnt = CLAW_OPEN_CLOSE_IDNT\n keys = 1\n GPIO.output(CLAW_OPEN_CLOSE_GPIO_PIN, GPIO.HIGH if clawClosed else GPIO.LOW)\n clawClosed = not clawClosed\n print(\"Setting claw: \" + (\"GPIO.HIGH\" if clawClosed else \"GPIO.LOW\"))\n\n if (event.key == pygame.K_d):\n clawSpin += 1\n if (event.key == pygame.K_a):\n clawSpin -= 1\n\n keyBytes = bytes([SERIAL_MARKER, idnt, keys])\n sendSerial(ser, keyBytes)\n\n if (event.type == pygame.KEYUP):\n if (event.key == pygame.K_d):\n clawSpin -= 1\n print (\"key released \" + pygame.key.name(event.key))\n if (event.key == pygame.K_a):\n clawSpin += 1\n print (\"key released \" + pygame.key.name(event.key))\n\n # DRAWING STEP\n # First, clear the screen to white. Don't put other drawing commands\n # above this, or they will be erased with this command.\n screen.fill(WHITE)\n textPrint.reset()\n\n # Get count of joysticks\n joystick_count = pygame.joystick.get_count()\n\n textPrint.print(screen, \"Number of joysticks: {}\".format(joystick_count))\n textPrint.indent()\n\n if (clawSpin != 0):\n spinBytes = bytes([SERIAL_MARKER, CLAW_SPIN_IDNT, clawSpin % 256])\n sendSerial(ser, spinBytes)\n ser.read(1)\n\n # For each joystick:\n for i in range(joystick_count):\n joystick = pygame.joystick.Joystick(i)\n joystick.init()\n\n textPrint.print(screen, \"Joystick {}\".format(i))\n textPrint.indent()\n\n # Get the name from the OS for the controller/joystick\n name = joystick.get_name()\n textPrint.print(screen, \"Joystick name: {}\".format(name))\n\n # Usually axis run in pairs, up/down for one, and left/right for\n # the other.\n axes = joystick.get_numaxes()\n textPrint.print(screen, \"Number of axes: {}\".format(axes))\n textPrint.indent()\n\n for i in range(axes):\n if i == 0 or i == 3 or i == 5:\n continue\n #find number of axes, build tolerance around neutral position, get sign of axis back,\n #map axis between -127 and 127\n axis = joystick.get_axis(i)\n axis = pmap(math.fabs(axis), math.sqrt(2 * math.pow(0.17,2)), 1, 0, 1)\n axis = max(0, axis)\n axis = math.copysign(axis , joystick.get_axis(i))\n axis = pmap(axis, -1, 1, -127, 127)\n axis = int(axis)\n\n #Since on Linux there are 6 axes, axes 2 and 5 are combined\n if i== 2 and axes >= 6:\n #get same information about axis 5\n axis5 = joystick.get_axis(5)\n axis5 = pmap(math.fabs(axis5), math.sqrt(2 * math.pow(0.17, 2)), 1, 0, 1)\n axis5 = max(0, axis5)\n axis5 = math.copysign(axis5, joystick.get_axis(5))\n axis5 = pmap(axis5, -1, 1, 0, -127)\n axis5 = int(axis5)\n\n #map axis 2 from -127 threw 127 to 0 threw 127\n axis = pmap(axis, -127, 127, 0, 127)\n axis = int(axis)\n\n #combine axes 2 and 5\n axis = (axis + axis5)\n\n textPrint.print(screen, \"Axis {} value: {:>6.3f}\".format(i, axis))\n\n #define the identification number axis-motorcontrol\n idnt = 255\n if i == 1:\n idnt = LEFT_MOTOR_IDNT\n if i == 4:\n idnt = RIGHT_MOTOR_IDNT\n if i == 2:\n idnt = UP_DOWN_MOTOR_IDNT\n\n #Convert axis information and identification number to byte array, send bytes over serial\n axisBytes = bytes ([SERIAL_MARKER, idnt , axis % 256])\n sendSerial(ser , axisBytes)\n textPrint.unindent()\n\n\n\n buttons = joystick.get_numbuttons()\n textPrint.print(screen, \"Number of buttons: {}\".format(buttons))\n textPrint.indent()\n\n for i in range(buttons):\n button = joystick.get_button(i)\n textPrint.print(screen, \"Button {:>2} value: {}\".format(i, button))\n textPrint.unindent()\n\n # Hat switch. All or nothing for direction, not like joysticks.\n # Value comes back in an array.\n hats = joystick.get_numhats()\n textPrint.print(screen, \"Number of hats: {}\".format(hats))\n textPrint.indent()\n\n for i in range(hats):\n hat = joystick.get_hat(i)\n textPrint.print(screen, \"Hat {} value: {}\".format(i, str(hat)))\n textPrint.unindent()\n\n textPrint.unindent()\n\n # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT\n\n # Go ahead and update the screen with what we've drawn.\n pygame.display.flip()\n\n # Limit to 20 frames per second\n clock.tick(20)\n\n# Close the window and quit.\n# If you forget this line, the program will 'hang'\n# on exit if running from IDLE.\nGPIO.cleanup()\npygame.quit()\n\n\n" } ]
3
saikatbsk/MLforDummies
https://github.com/saikatbsk/MLforDummies
d4a0bf3468e78a06884cac06ba050d63b95f0be1
0ad44c1b08344a7b6ceb31f9a32e997a7fbec07c
f51f27117952df54017215d98bf117cf5b9e0bf2
refs/heads/master
2017-09-10T23:02:50.172414
2017-08-06T18:13:25
2017-08-06T18:13:25
96,035,898
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5726495981216431, "alphanum_fraction": 0.5840455889701843, "avg_line_length": 28.87234115600586, "blob_id": "ad3c667e7adeda8e2229c2d07278d0b3d62af993", "content_id": "877f9f279b235d773bb7d5ce61d8d458521aafda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1404, "license_type": "no_license", "max_line_length": 81, "num_lines": 47, "path": "/linear-classifier/utils/cifar10_utils.py", "repo_name": "saikatbsk/MLforDummies", "src_encoding": "UTF-8", "text": "import os\nimport glob\nimport pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef vector_to_image(X, nb_samples):\n return X.reshape(nb_samples, 3, 32, 32).transpose(0, 2, 3, 1).astype(\"float\")\n\ndef load_cifar_batch(filename):\n with open(filename, 'rb') as f:\n datadict = pickle.load(f, encoding='bytes')\n X = datadict[b'data']\n Y = datadict[b'labels']\n Y = np.array(Y)\n return X, Y\n\ndef load_cifar10(root):\n xs = []\n ys = []\n batch_files = glob.glob(os.path.join(root, 'data_batch_*'))\n for file in batch_files:\n x, y = load_cifar_batch(file)\n xs.append(x)\n ys.append(y)\n X_train = np.concatenate(xs)\n Y_train = np.concatenate(ys)\n x, y = None, None\n xs, ys = None, None\n X_test, Y_test = load_cifar_batch(os.path.join(root, 'test_batch'))\n return X_train, Y_train, X_test, Y_test\n\ndef visualize(X, Y, classes, samples_per_class=10):\n nb_classes = len(classes)\n\n for y, cls in enumerate(classes):\n idxs = np.flatnonzero(Y == y)\n idxs = np.random.choice(idxs, samples_per_class, replace=False)\n\n for i, idx in enumerate(idxs):\n plt_idx = i * nb_classes + y + 1\n plt.subplot(samples_per_class, nb_classes, plt_idx)\n plt.imshow(X[idx].astype('uint8'))\n plt.axis('off')\n if i == 0:\n plt.title(cls)\n plt.show()\n" } ]
1
scyyx1/Chatbot
https://github.com/scyyx1/Chatbot
6505b59905c8c8b7477da1fc4149b6bc5edc1a7e
24ce7736dfbd68b9f7f16920a41fcdc70d09f676
3072b8b5984d3cfaee1a69256a92a5ab4880efa6
refs/heads/master
2023-08-17T08:40:50.611472
2021-10-09T23:36:22
2021-10-09T23:36:22
415,444,112
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6498697400093079, "alphanum_fraction": 0.6571369767189026, "avg_line_length": 39.97190856933594, "blob_id": "9cd464efec05e4dd96fbac1b9774bd978c3007eb", "content_id": "c6677a9a797ccdac195d1740c60dddf11ecb2b4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14586, "license_type": "no_license", "max_line_length": 114, "num_lines": 356, "path": "/chatbot.py", "repo_name": "scyyx1/Chatbot", "src_encoding": "UTF-8", "text": "import nltk\nfrom scipy import spatial\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk.stem.snowball import SnowballStemmer\nimport random\nimport csv\nimport re\nimport math\n\n# Dictionary of Word with index\nphrase_word2index = {}\nname_input_word2index = {}\nquestion_word2index = {}\ntalk_input_word2index = {}\n\n# Threshold Value\nintent_threshold = 0.74\nquestion_threshold = 0.85\n\n# Key Phrases Database\ntalk_phrase_corpus = {}\nname_phrase_corpus = {}\n\n# Intent Database\ntalk_input_corpus = {}\ntalk_answer_database = {}\nname_input_corpus = {}\nname_input_label_database = {}\nquestion_corpus = {}\nanswer_database = {}\n\n# Initialise system variables\nnum_word_in_phrase = 0\nstemmer = SnowballStemmer(\"english\")\nlemmatizer = WordNetLemmatizer()\nuser = \"\"\nname_intent_stopwords = [\"hi\", \"please\", \"hello\", \"pls\", \"hey\"]\nposmap = {\n 'ADJ': 'a',\n 'ADV': 'r',\n 'NOUN': 'n',\n 'VERB': 'v'\n}\n\n# Download package\n#nltk.download('wordnet')\n#nltk.download('averaged_perceptron_tagger')\n#nltk.download('universal_tagset')\n\n# Compute Term Log Frequency\ndef compute_TF(word_dict):\n tf_dict = {}\n for word, frequency in word_dict.items():\n tf_dict[word] = math.log10(1 + frequency)\n return tf_dict\n\n# Compute Inverse Document Frequency\ndef compute_IDF(doc_list):\n num_doc = len(doc_list)\n idf_dict = dict.fromkeys(doc_list[0].keys(), 0)\n for doc in doc_list:\n for word, val in doc.items():\n if val > 0:\n idf_dict[word] += 1\n for word, val in idf_dict.items():\n idf_dict[word] = math.log10(num_doc / float(val))\n return idf_dict\n\n# Compute Term Frequency-Inverse Document Frequency\ndef compute_TFIDF(tf, idfs):\n tfidf = {}\n for word, tf_value in tf.items():\n tfidf[word] = tf_value * idfs[word]\n return tfidf\n\n# Remove punctuation in word\ndef remove_punc_in_sentence(list):\n new_list = []\n for word in list:\n new = re.sub(r'[^\\w\\s]', '', word)\n if new != \"\":\n new_list.append(new)\n return new_list\n\n# Lemmatization and exclude the word with punctuation\ndef lemmatizing_sentence(sentence, remove_punc):\n tokens = word_tokenize(sentence)\n if remove_punc:\n tokens = remove_punc_in_sentence(tokens)\n post = nltk.pos_tag(tokens, tagset='universal')\n normalized_word_in_sentence = []\n for token in post:\n word = token[0].lower()\n tag = token[1]\n if tag in posmap.keys():\n normalized_word_in_sentence.append(lemmatizer.lemmatize(word, posmap[tag]))\n else:\n normalized_word_in_sentence.append(lemmatizer.lemmatize(word))\n return normalized_word_in_sentence\n\n# Add word in phrase to dictionary\ndef add_phrase_word(word, word2index):\n global num_word_in_phrase\n if word not in word2index:\n word2index[word] = num_word_in_phrase\n num_word_in_phrase += 1\n\n# Add word in question to dictionary\ndef add_question_word(word, word2index, num_word_question):\n if word not in question_word2index:\n word2index[word] = num_word_question\n\n# Read name phrase and small talk phrase dataset using stemmer, create vocabulary\ndef read_phrase_file(file, corpus):\n with open(file, 'r', encoding='utf-8') as f:\n first_line = True\n readCSV = csv.reader(f, delimiter=',')\n num_phrases = 0\n for row in readCSV:\n if first_line:\n first_line = False\n continue\n key_phrase = row[0]\n tokens_without_punc = remove_punc_in_sentence(word_tokenize(key_phrase))\n normalized_word_phrase = [stemmer.stem(word.lower()) for word in tokens_without_punc]\n corpus[num_phrases] = normalized_word_phrase\n num_phrases += 1\n for word in normalized_word_phrase:\n add_phrase_word(word, phrase_word2index)\n\n# Read name intent and small talk intent dataset using lemmatizing, create vocabulary\ndef read_intent_file(file, question_corpus, extra_database, word2index, question_index, extra_index):\n with open(file, 'r', encoding='utf-8') as f:\n first_line = True\n num_question = 0\n unique_word_question = 0\n readCSV = csv.reader(f, delimiter=',')\n for row in readCSV:\n if first_line:\n first_line = False\n continue\n question = row[question_index]\n normalized_word_in_question = lemmatizing_sentence(question, remove_punc=True)\n question_corpus[num_question] = normalized_word_in_question\n extra_database[num_question] = row[extra_index]\n num_question += 1\n for word in normalized_word_in_question:\n add_question_word(word, word2index, unique_word_question)\n unique_word_question += 1\n\n# Use dictionary to create the term-document matrix of the corpus for easy implementation\ndef setup_term_document_matrix(corpus, word2index):\n term_document_dict = []\n for index, que in corpus.items():\n word_dict = dict.fromkeys(word2index.keys(), 0)\n for word in corpus[index]:\n word_dict[word] += 1\n term_document_dict.append(word_dict)\n return term_document_dict\n\n# For each items in term document matrix, compute the cosine similarity with the query\n# return items in highest similarity\ndef get_highest_similarity_item(query_doc, dict):\n similarity = {}\n for i in range(len(dict)):\n doc = [num for num in dict[i].values()]\n sim = 1 - spatial.distance.cosine(query_doc, doc)\n similarity[i] = sim\n similarity = sorted(similarity.items(), key=lambda x: x[1], reverse=True)\n max_val = similarity[0][1]\n selected_item = [item for item in similarity if item[1] == max_val]\n return max_val, selected_item\n\n# Handle name intent\ndef handle_name(normalized_word_in_query, original_query):\n # Map search query on the name inputs collection-induced vector space\n query_dict = dict.fromkeys(name_input_word2index.keys(), 0)\n for word in normalized_word_in_query:\n if word in query_dict:\n query_dict[word] += 1\n # Apply tf-idf weighting to the tokens in query\n tf_dict = compute_TF(query_dict)\n query_dict = compute_TFIDF(tf_dict, name_input_idfs)\n query_doc = [num for num in query_dict.values()]\n value, selected_question = get_highest_similarity_item(query_doc, name_input_term_doc_dict)\n index = selected_question[0][0]\n global user\n if name_input_label_database[index] == '1':\n if user == \"\":\n return \"You currently don't have a name. Can you tell me your name, please? \"\n return \"Your name is {name}. Anything you would like to know? \".format(name=user)\n else:\n # Name Extraction\n tokenize_query = remove_punc_in_sentence(word_tokenize(original_query))\n tokens_without_sw = [word for word in tokenize_query if not word.lower() in name_intent_stopwords]\n detect_pos_tag = nltk.pos_tag(tokens_without_sw)\n is_name = False\n name = \"\"\n for index, tag in enumerate(detect_pos_tag):\n if is_name:\n if tag[0] == 'am' and index != len(detect_pos_tag) - 1:\n continue\n if tag[0] == 'm' and index != len(detect_pos_tag) - 1:\n continue\n name = tag[0]\n break\n if tag[1] == 'TO' or tag[1] == 'PRP' or tag[1] == 'VBZ':\n is_name = True\n if name == \"\":\n return \"Please input a valid name \"\n else:\n user = name\n totalNameResponse = []\n totalNameResponse.append(\"Hello {name}, how can I help you? \".format(name=user))\n totalNameResponse.append(\"Hi {name}, nice to meet you. \".format(name=user))\n totalNameResponse.append(\"Hello {name}, how's everything going? \".format(name=user))\n totalNameResponse.append(\"Hi {name}, how can I help you? \".format(name=user))\n return random.choice(totalNameResponse)\n\n# Handle small talk intent\ndef handle_talk(normalized_word_in_query):\n # Map search query on the small talk inputs collection-induced vector space\n query_dict = dict.fromkeys(talk_input_word2index.keys(), 0)\n for word in normalized_word_in_query:\n if word in query_dict:\n query_dict[word] += 1\n # Apply tf-idf weighting to the tokens in query\n tf_dict = compute_TF(query_dict)\n query_dict = compute_TFIDF(tf_dict, talk_input_idfs)\n query_doc = [num for num in query_dict.values()]\n value, selected_question = get_highest_similarity_item(query_doc, talk_input_term_doc_dict)\n if len(selected_question) > 1:\n random_answer = random.choice(selected_question)\n response = talk_answer_database[random_answer[0]] + \" \"\n else:\n answer = selected_question[0]\n response = talk_answer_database[answer[0]] + \" \"\n return response\n\n# Handle question answering intent\ndef answer_question(normalized_word_in_query):\n # Map search query on the question collection-induced vector space\n query_dict = dict.fromkeys(question_word2index.keys(), 0)\n for word in normalized_word_in_query:\n if word in query_dict:\n query_dict[word] += 1\n # Apply tf-idf weighting to the tokens in query\n tf_dict = compute_TF(query_dict)\n query_dict = compute_TFIDF(tf_dict, question_idfs)\n query_doc = [num for num in query_dict.values()]\n if len(query_doc) != query_doc.count(0):\n value, selected_question = get_highest_similarity_item(query_doc, question_term_doc_dict)\n if value >= question_threshold:\n if len(selected_question) > 1:\n random_answer = random.choice(selected_question)\n response = answer_database[random_answer[0]] + \" \"\n else:\n answer = selected_question[0]\n response = answer_database[answer[0]] + \" \"\n else:\n response = \"I am not able to answer this question at the moment. \"\n else:\n response = \"I am not able to answer this question at the moment. \"\n return response\n\n\n# Setup data corpus, add to word2index\nread_phrase_file('talk_intent_key_phrases.csv', talk_phrase_corpus)\nprint(\"----Talk Phrases Dataset Setup----\")\nread_phrase_file('name_intent_key_phrases.csv', name_phrase_corpus)\nprint(\"----Name Phrases Dataset Setup----\")\nread_intent_file('name_dataset.csv', name_input_corpus, name_input_label_database, name_input_word2index, 0, 1)\nprint(\"----Name Intent Dataset Setup----\")\nread_intent_file('small_talk_dataset.csv', talk_input_corpus, talk_answer_database, talk_input_word2index, 0, 1)\nprint(\"----Small Talk Intent Dataset Setup----\")\nread_intent_file(\"COMP3074-CW1-Dataset.csv\", question_corpus, answer_database, question_word2index, 1, 2)\nprint(\"----Provided Question Answering Intent Setup----\")\n\n# Use the vocabulary to compute the term-document matrix of the corpus\ntalk_phrases_term_doc_dict = setup_term_document_matrix(talk_phrase_corpus, phrase_word2index)\nname_phrases_term_doc_dict = setup_term_document_matrix(name_phrase_corpus, phrase_word2index)\nname_input_term_doc_dict = setup_term_document_matrix(name_input_corpus, name_input_word2index)\ntalk_input_term_doc_dict = setup_term_document_matrix(talk_input_corpus, talk_input_word2index)\nquestion_term_doc_dict = setup_term_document_matrix(question_corpus, question_word2index)\n\n# Apply TF-IDF weighting to the term-document matrix\nphrase_idfs = compute_IDF(talk_phrases_term_doc_dict + name_phrases_term_doc_dict)\nfor i in range(len(talk_phrases_term_doc_dict)):\n tf_dict = compute_TF(talk_phrases_term_doc_dict[i])\n talk_phrases_term_doc_dict[i] = compute_TFIDF(tf_dict, phrase_idfs)\nfor i in range(len(name_phrases_term_doc_dict)):\n tf_dict = compute_TF(name_phrases_term_doc_dict[i])\n name_phrases_term_doc_dict[i] = compute_TFIDF(tf_dict, phrase_idfs)\n\nquestion_idfs = compute_IDF(question_term_doc_dict)\nfor i in range(len(question_term_doc_dict)):\n tf_dict = compute_TF(question_term_doc_dict[i])\n question_term_doc_dict[i] = compute_TFIDF(tf_dict, question_idfs)\n\nname_input_idfs = compute_IDF(name_input_term_doc_dict)\nfor i in range(len(name_input_term_doc_dict)):\n tf_dict = compute_TF(name_input_term_doc_dict[i])\n name_input_term_doc_dict[i] = compute_TFIDF(tf_dict, name_input_idfs)\n\ntalk_input_idfs = compute_IDF(talk_input_term_doc_dict)\nfor i in range(len(talk_input_term_doc_dict)):\n tf_dict = compute_TF(talk_input_term_doc_dict[i])\n talk_input_term_doc_dict[i] = compute_TFIDF(tf_dict, talk_input_idfs)\n\nprint(\"All preparation is done!\")\nprint(\"----------------------------------Chatbot Start----------------------------------------------------------\")\n\n# Handling query\nstop = False\nconversation_string = \"Hi! What is your name? \"\nwhile not stop:\n # Handle User Input\n query = input(conversation_string)\n if query == \"\":\n conversation_string = \"Please input something. \"\n continue\n if query == \"bye\":\n stop = True\n\n # Query Normalisation\n query_token_without_punctuation = remove_punc_in_sentence(word_tokenize(query))\n normalized_word_in_query = [stemmer.stem(word.lower()) for word in query_token_without_punctuation]\n\n # Map query on the phrase collection-induced vector space\n query_dict = dict.fromkeys(phrase_word2index.keys(), 0)\n for word in normalized_word_in_query:\n if word in query_dict:\n query_dict[word] += 1\n\n # Apply TF-IDF weighting to the tokens in query\n tf_dict = compute_TF(query_dict)\n query_dict = compute_TFIDF(tf_dict, phrase_idfs)\n query_doc = [num for num in query_dict.values()]\n\n # Compare similarity between query and phrases in name and small talk intent\n sim_with_name = 0\n sim_with_talk = 0\n\n # Check whether the input query contains certain dictionary words, if not set similarity to 0\n if len(query_doc) != query_doc.count(0):\n sim_with_name, _ = get_highest_similarity_item(query_doc, name_phrases_term_doc_dict)\n sim_with_talk, _ = get_highest_similarity_item(query_doc, talk_phrases_term_doc_dict)\n\n # Match the query to intents\n if sim_with_name >= intent_threshold and sim_with_name >= sim_with_talk:\n conversation_string = handle_name(lemmatizing_sentence(query, remove_punc=True), query)\n elif sim_with_talk >= intent_threshold:\n conversation_string = handle_talk(lemmatizing_sentence(query, remove_punc=True))\n else:\n conversation_string = answer_question(lemmatizing_sentence(query, remove_punc=True))\n" } ]
1
kaz96/DeepLearning-Sound-Recognition
https://github.com/kaz96/DeepLearning-Sound-Recognition
c9b02000b522bb1aabe8e3f569fbeadf29ec4c22
2c425b558f7f5e7f285cd37e6a9f9856778b1532
d3dd20f14cdd8233f65e6b9d715c269ac6360a93
refs/heads/master
2020-03-29T01:58:30.318141
2018-10-17T16:47:36
2018-10-17T16:47:36
149,415,824
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6404787302017212, "alphanum_fraction": 0.6627282500267029, "avg_line_length": 25.58367347717285, "blob_id": "289174e76bcb02a32d350f261560898a827c21fc", "content_id": "f2c7d96adf19ca462eada5558184657d0c372d3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6517, "license_type": "no_license", "max_line_length": 114, "num_lines": 245, "path": "/SoundRecognition.py", "repo_name": "kaz96/DeepLearning-Sound-Recognition", "src_encoding": "UTF-8", "text": "\n\n\n\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport os\nfrom os.path import isdir, join\nfrom pathlib import Path\nfrom tqdm import tqdm\nimport time\n\nimport numpy as np\nfrom scipy.fftpack import fft\nfrom scipy import signal\nfrom scipy.io import wavfile\nimport librosa\nimport IPython.display as ipd\nfrom tensorflow.python.platform import gfile\nfrom keras.utils import np_utils\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Conv2D, MaxPooling2D, Flatten\nfrom keras import optimizers\nfrom sklearn.model_selection import train_test_split\nimport plotly.offline as py\npy.init_notebook_mode(connected=True)\nimport plotly.graph_objs as go\nimport pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\n\n\n\n#train_audio_path_test = '/Users/Kaz/Desktop/tst'\ntrain_audio_path = '/Users/Kaz/Desktop/tst/audio_path/'\n\nfilename = '/left.wav'\nnew_sample_rate = 8000\n\n\n#sample_rate, samples = wavfile.read(str(train_audio_path_test) + filename)\nsamples1, sample_rate1 = librosa.load(str(train_audio_path_test) + filename, res_type='kaiser_fast')\n\nmfcc = librosa.feature.mfcc(samples1, sr=16000)\n#mfccs = np.mean(librosa.feature.mfcc(y=samples1, sr=\"8000\", n_mfcc=13).T, axis=0)\n\n#print(sample_rate,samples)\n\n\n\n# LOG SPECTOGRAM - NOT USED ANYMORE\n#def log_specgram(audio, sample_rate, window_size=20,\n# step_size=10, eps=1e-10):\n# #nperseg = int(round(window_size * sample_rate / 1e3))\n# #noverlap = int(round(step_size * sample_rate / 1e3))\n# freqs, times, spec = signal.spectrogram(audio,\n# fs=sample_rate,\n# window='hann',\n# nperseg=None,\n# noverlap=None,\n# detrend=False)\n# # if ( spec. == 0 ):\n# # print(\"ZERO\")\n#\n#\n# return freqs, times, np.log(spec)\n\n\n#resampled = signal.resample(samples, int(new_sample_rate/sample_rate * samples.shape[0]))\n\n\n#freqs, times, spectrogram = log_specgram(samples, sample_rate)\n#\n#freqs1, times1, spectrogram1 = log_specgram(resampled, new_sample_rate)\n\n\n\n\n\n#normalize\n\n#mean = np.mean(spectrogram, axis=0)\n#std = np.std(spectrogram, axis=0)\n#spectrogram = (spectrogram - mean) / std\n\n\n\n# get name of each of the labels, e.g. dog, eight, follow, foward, bird\ndirs = [f for f in os.listdir(train_audio_path) if isdir(join(train_audio_path, f))]\n\n# soft in alphabetical order\ndirs.sort()\n\n\nprint('Total Number of Labels in Directory: ' + str(len(dirs)))\n\nnumber_of_recordings = []\n# for loop to get every file in each folder\nfor direct in dirs:\n waves = [f for f in os.listdir(join(train_audio_path, direct)) if f.endswith('.wav')]\n number_of_recordings.append(len(waves))\n\n\n\n#Print histogram\ndata = [go.Histogram(x=dirs, y=number_of_recordings)]\ntrace = go.Bar(\n x=dirs,\n y=number_of_recordings,\n marker=dict(color = number_of_recordings, colorscale='Viridis', showscale=True\n ),\n)\n\nlayout = go.Layout(\n title='Number of recordings in given label',\n xaxis = dict(title='Words'),\n yaxis = dict(title='Number of recordings')\n)\n#py.plot(go.Figure(data=[trace], layout=layout))\n\n\n\n# IMPLEMENTATION\nto_keep = 'down left up'.split()\ndirs = [d for d in dirs if d in to_keep]\n\nnumber=0\nlabels = []\nlabelsarray = []\ntrainingsetlabelarray = []\n\ntrainingset = []\nprint(\"Begin Reading Files\")\n#for each folder e.g. left\nlabelno = 0\n\ngetfromfile = False\n\nif (getfromfile):\n for index,direct in enumerate(dirs):\n # Get individual file e.g. audio_path/left/032jd2.wav\n print(\"Processing Values For: \", direct, \" [\",index+1,\"/\",len(dirs),\"]\")\n waves = [f for f in os.listdir(join(train_audio_path, direct)) if f.endswith('.wav')]\n no = 0\n for wav in tqdm(waves, total= len(waves)):\n\n wave, sr = librosa.load(train_audio_path + direct + '/' + wav, mono=True, sr=None)\n wave = wave[::3]\n mfcc = librosa.feature.mfcc(wave, sr=16000)\n pad_width = 11 - mfcc.shape[1]\n mfcc = np.pad(mfcc, pad_width=((0, 0), (0, pad_width)), mode='constant')\n\n # y = np.append(y, np.full(x.shape[0], fill_value=(i + 1)))\n\n trainingsetlabelarray.append(mfcc)\n labelsarray.append(direct)\n no += 1\n labelno += 1\n\n\n #translate to numpy array\n trainingset = np.array(trainingsetlabelarray)\n labels = np.array(labelsarray)\n\n #Save as a npy file\n np.save('trainingset.npy', trainingset)\n np.save('labels.npy', labels,)\n\nprint(\"LOAD FROM FILE\")\n#load from file\ntrainingset = np.load('trainingset.npy')\nlabels = np.load('labels.npy')\n\nprint(\"LOAD FROM FILE1\")\n\n#normalizaation\ntrainingset = (trainingset - np.mean(trainingset,axis=0)) / np.std(trainingset, axis=0)\ny = np.zeros(trainingset.shape[0])\n\n\n#Encode labels into vectors e.g. up = [1,0,0], down = [0,1,0]\nlb = LabelEncoder()\n\ny = np_utils.to_categorical(lb.fit_transform(labels))\n\n\n# Split into Train, and validation 60/40 split\nX_train, X_test, y_train, y_test = train_test_split(trainingset, y, test_size= .40, random_state=44, shuffle=True)\nX_train = X_train.reshape(X_train.shape[0], 20, 11, 1)\nX_test = X_test.reshape(X_test.shape[0], 20, 11, 1)\n\n\n\n\n\n\n\n\n\n\n# Deep Learning Model\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(2, 2), activation='relu', input_shape=(20, 11, 1)))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.25))\nmodel.add(Dense(3, activation='softmax'))\nmodel.compile(loss=\"categorical_crossentropy\",\n optimizer=optimizers.Adadelta(),\n metrics=['accuracy'])\n\n\nmodel.fit(X_train, y_train, batch_size=100, epochs=10, verbose=1, validation_data=(X_test, y_test))\n\n\n\n# PREDICTION\npredict = []\n\nwave, sr = librosa.load(\"/Users/Kaz/Desktop/tst/up1.wav\", mono=True, sr=None)\nwave = wave[::3]\nmfcc = librosa.feature.mfcc(wave, sr=16000)\npad_width = 11 - mfcc.shape[1]\nmfcc = np.pad(mfcc, pad_width=((0, 0), (0, pad_width)), mode='constant')\nsample_reshaped = mfcc.reshape(1, 20, 11, 1)\n\n\npredict.append(sample_reshaped)\n\noutput = model.predict(np.array(sample_reshaped))\nmodel.evaluate()\n\n\n\nprint(model.summary())\n\nprint(output)\n\nprint(np.argmax(model.predict(np.array(sample_reshaped))))\n\noutput = np.argmax(model.predict(np.array(sample_reshaped)))\nif(output == 0):\n print(\"OUTPUT: Down\")\nif(output == 1):\n print(\"OUTPUT: Up\")\nif(output == 2):\n print(\"OUTPUT: Left\")\nprint(\"end\")\n" } ]
1
5l1v3r1/SpamDi
https://github.com/5l1v3r1/SpamDi
2c0bf624338842b4986af586cc908583ab82c3a6
9d3565ce713481b43885cdcde39c7b5f0c6bfa7d
f94f9bfec51feef0f400a02ca41d0323e0ee7ddc
refs/heads/master
2022-10-23T21:46:45.010376
2020-06-22T22:04:14
2020-06-22T22:04:14
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6405529975891113, "alphanum_fraction": 0.6451612710952759, "avg_line_length": 13.87804889678955, "blob_id": "0a127499259398d92768df44ec0071f0ceb4611d", "content_id": "b15b3e565ea76eca926282f12ad73cc3a390c4df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 651, "license_type": "no_license", "max_line_length": 94, "num_lines": 41, "path": "/README.md", "repo_name": "5l1v3r1/SpamDi", "src_encoding": "UTF-8", "text": "# SpamDi\r\n\r\nSpamDi is an Python 3 library that's allow you to do spam in discord using multiples accounts.\r\n\r\n## How To Use\r\n\r\n1- Download the file , and put it in the same location of your python file.\r\n\r\n2- Import library to your python file.\r\n\r\n## Examples:\r\n\r\n**Join Server:**\r\n\r\n```py\r\nimport SpamDi\r\n\r\nSpamDi.Join(\"Invite_Code\",\"Authorization\")\r\n```\r\n\r\n**Spam Messages:**\r\n\r\n```py\r\nimport SpamDi\r\n\r\nwhile True:\r\n SpamDi.Spam_M(\"Channel_Id\",\"Authorization\")\r\n\r\n```\r\n\r\n**Spam Reactions:**\r\n\r\n```py\r\nimport SpamDi\r\n\r\nwhile True:\r\n SpamDi.Spam_E(\"Channel_Id\",\"Message_Id\",\"Authorization\")\r\n\r\n```\r\n\r\n**Ps: Authorization Means Account Token.**\r\n" }, { "alpha_fraction": 0.5325042605400085, "alphanum_fraction": 0.5935556888580322, "avg_line_length": 40.62650680541992, "blob_id": "3a331571a55f8884401fc6c6d69c04bdf507ec9b", "content_id": "2ebe646a79f349fce07bd8e6b1fb9a204c2b9490", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3538, "license_type": "no_license", "max_line_length": 460, "num_lines": 83, "path": "/SpamDi.py", "repo_name": "5l1v3r1/SpamDi", "src_encoding": "UTF-8", "text": "# Created By AhmedViruso\r\n\r\nimport random,string,random,time,os,sys\r\n\r\nLib = (\"\")\r\n\r\ntry:\r\n import requests\r\n from requests.packages.urllib3.exceptions import InsecureRequestWarning\r\nexcept:\r\n Lib = False\r\n\r\nif (Lib == False):\r\n print(\"Trying to install requests library.\")\r\n Response = os.system('{} -m pip install -U '.format(sys.executable) + \"requests\" + \" -q\")\r\n\r\n if (Response != 0):\r\n sys.exit(\"Couldn't Install The requests Library, Please Install it Manually.\")\r\n else:\r\n print(\"Done.\")\r\n import requests\r\n from requests.packages.urllib3.exceptions import InsecureRequestWarning\r\n\r\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\r\n\r\nDomain = (\"https://discordapp.com\")\r\n\r\ndef Headers(Pr):\r\n return {'Authorization':Pr,'Content-Type':'application/json','User-Agent':'Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) discord/0.0.306 Chrome/78.0.3904.130 Electron/7.1.11 Safari/537.36'}\r\n\r\ndef Join(Invite,Token):\r\n try:\r\n R = requests.post(Domain + \"/api/v6/invites/{}\".format(Invite),headers=Headers(Token) ,verify=False)\r\n if(R.status_code == 200):\r\n print(\"Ok ({})\".format(R.status_code))\r\n else:\r\n print(\"Not Ok [Server Response {}] [{}]\".format(R.status_code,Token) )\r\n time.sleep(3)\r\n except:\r\n print(\"An error occurred during function execution\")\r\n exit()\r\n\r\ndef Spam_M(Channel,Token):\r\n try:\r\n Random = random.randint(10, 80)\r\n \r\n Chars = string.ascii_uppercase + string.ascii_lowercase + string.digits\r\n Chars = ''.join( random.sample(Chars*Random, Random) )\r\n\r\n R = requests.post(Domain + \"/api/v6/channels/{}/messages\".format(Channel), headers=Headers(Token) ,json={'content':Chars} ,verify=False)\r\n Rs = R.status_code\r\n\r\n if(Rs == 200):\r\n print(\"Ok ({})\".format(Rs))\r\n elif(Rs == 429):\r\n print(\"{} Too Many Requests , Sleep(3)\".format(Rs) )\r\n time.sleep(3)\r\n else:\r\n print(\"Not Ok [Server Response {}] [{}]\".format(Rs,Token) )\r\n time.sleep(2)\r\n except:\r\n print(\"An error occurred during function execution\")\r\n exit()\r\n\r\ndef Spam_E(Channel,Message,Token):\r\n try:\r\n ListEmojis = [\"%F0%9F%98%A2\",\"%F0%9F%98%81\",\"%F0%9F%A4%A4\",\"%F0%9F%98%AC\",\"%F0%9F%91%A8%E2%80%8D%F0%9F%A6%AF\",\"%F0%9F%A4%AA\",\"%F0%9F%98%98\",\"%F0%9F%90%B9\",\"%F0%9F%91%A8%E2%80%8D%F0%9F%94%A7\",\"%F0%9F%A6%B7\",\"%F0%9F%A7%99%E2%80%8D%E2%99%80%EF%B8%8F\",\"%F0%9F%91%A8%E2%80%8D%F0%9F%8F%AB\",\"%F0%9F%A4%A7\",\"%F0%9F%A4%9B\",\"%F0%9F%A7%A0\",\"%F0%9F%98%B6\",\"%F0%9F%92%87%E2%80%8D%E2%99%80%EF%B8%8F\",\"%F0%9F%95%B5%EF%B8%8F%E2%80%8D%E2%99%82%EF%B8%8F\",\"%F0%9F%90%AC\"]\r\n Random = random.randint(0, 18)\r\n\r\n R = requests.put(Domain + \"/api/v6/channels/{}/messages/{}/reactions/{}/@me\".format(Channel,Message,ListEmojis[Random]), headers=Headers(Token) ,verify=False)\r\n R1 = requests.delete(Domain + \"/api/v6/channels/{}/messages/{}/reactions/{}/@me\".format(Channel,Message,ListEmojis[Random]), headers=Headers(Token) ,verify=False)\r\n \r\n Frist = R.status_code\r\n Second = R1.status_code\r\n \r\n if(Frist + Second == 408):\r\n print(\"Ok\")\r\n else:\r\n print(\"Not Ok , Sleep(2) [Put Emoji Response ({})] [Delete Emoji Response ({})] [{}]\".format(Frist,Second,Token) )\r\n time.sleep(2)\r\n except:\r\n print(\"An error occurred during function execution\")\r\n exit()\r\n" } ]
2
yesEric/tytorn
https://github.com/yesEric/tytorn
6993a8aacaa815e5759c5237f3eac901c8973ba1
a0c65a658802145ff1df011a2363ef97c26aaf7f
b6cf6401b4234faed6928717067b9eb9ed9aa7c5
refs/heads/master
2020-12-30T23:10:17.977254
2016-05-07T04:02:32
2016-05-07T04:02:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6584867238998413, "alphanum_fraction": 0.6912065148353577, "avg_line_length": 21.272727966308594, "blob_id": "e9c009f58e034ca2060af589412fc42c18fef2a3", "content_id": "c7e83850878745c5f3db534b9436baea36c7776f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 503, "license_type": "no_license", "max_line_length": 69, "num_lines": 22, "path": "/handlers/main.py", "repo_name": "yesEric/tytorn", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@version: 1.0.0\n@author: whitney\n@file: index.py\n@time: 2016/4/22 15:42\n\"\"\"\n\n# from models.test import test\nfrom handlers.base import MainBaseHandler\nimport tornado.web\nimport tornado.gen\n\n\nclass IndexHandler(MainBaseHandler):\n @tornado.web.asynchronous\n @tornado.gen.coroutine\n def get(self):\n # article = yield self.QueryNoParam(\"select * FROM articles\")\n # print article[0]['title']\n self.write('恭喜你成功部署tytorn!')" } ]
1
jla497/snpoverlap
https://github.com/jla497/snpoverlap
e7f420ede996dda2e0aa81b19d6642b8a3fd5468
b9a1d75c207cf0d2e7f81f1f7ed7a8e7c5b12699
d70d806cfee3b5d85b5aa6154e411b2efab2217e
refs/heads/master
2021-01-21T04:04:15.027769
2017-08-30T17:34:15
2017-08-30T17:34:15
97,995,200
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6330332159996033, "alphanum_fraction": 0.6497982144355774, "avg_line_length": 53.61016845703125, "blob_id": "3d01110408ce651aeff57388600d0be8f7482a88", "content_id": "ae2f73fcfd545cec97b61ebecefd12749e6e6813", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3221, "license_type": "no_license", "max_line_length": 142, "num_lines": 59, "path": "/README.txt", "repo_name": "jla497/snpoverlap", "src_encoding": "UTF-8", "text": "README\n----------------------------------------------------------------------------------------\n!!! The application needs minimum ~15GB of free disk space to download and process the bed files from the NCBI ftp server!!!\n\n-----------------USAGE------------------------------------------------------------------\n1. runme_first.sh downloads hg19 snp bed files from ncbi ftp server, run md5checksum on all files then sort them before being used.\n i. If running in Windows:\n\ta. go to https://cygwin.com/install.html\n\tb. Install Cygwin by running setup-x86_(32 bit or 64bit).exe \n\tc. In the Select Packages phase during setup, search for 'wget' in 'Not Installed' view. \n\td. Install the Web category package (check Bin?)\n\te. Click 'yes' to all further prompts and finish the installation\n\tf. Run cygwin. CD into the application directory and run ./runme_first.sh\n\t\n ii. If running in Linux:\n\ta. Go to CLI and cd into the application directory \n\tb. Run ./runme_first.sh\n\n\n2.\tIf input bed file uses Hg38 assembly and you need to convert genome coordinates and annotations to Hg19:\n\t\n\t\tWeb version of LiftOver is available at this address: http://genome.ucsc.edu/cgi-bin/hgLiftOver\n\t\n4. The script will download all 24 chromosome bed files containing snps, check MD5 sums, and sort them by chromosome end positions\n\t\n5. Once script is finished, type ./wrapper.sh -i1[first_input_bedfile] -i2[second_input_bedfile]\n\t\n----------INPUT FILE FORMAT------------------------------------------------------------------\nEach row has three columns. \nFirst column must start with the prefix 'chr' followed by number from 1-22 or Y or Y or M or MT\nSecond column must be an integer value of the chromosome start position\nSecond column must be an integer value of the chromosome end position\nEach column is tab delimited\n\n|--Chromosome Number --|--Chromosome Start Position--|--Chromosome End Position--|\ne.g Chr1\t\t\ttab delimited\t\t12345\t\t\t\ttab delimited\t\t\t54321\ne.g ChrM\t\t\t\t\t123\t\t\t\t\t\t\t\t345\n----------OUTPUT FILES------------------------------------------------------------------\n\nsnps1.rs - contains all snps that are in chromosome range from input1 bed file\n\nsnps2.rs - contains all snps that are in chromosome range from input2 bed file\n\nmatchedSnps_remapped.rs - contains matchingSnps based on the latest snp merge history\n\n---------CORNER CASE-------------------------------------------------------------------\nFew rsIDs (maybe they are not SNPs) have chromosome ranges longer than our scan range\n\n|---------------------| (rs range)\n |--------------| (chromosome range we want to scan)\n \nThese corner cases are ignored\n\n----------- Overview of the application------------------------------------------------\n1. The java app sorts all chromosome ranges that we want to scan\n2. Linear search is possible because both the chromosome ranges that we want to scan and the bed files are sorted by chromosome end positions\n3. The tool is multithreaded and will simulateneously launch 4 threads in parallel\n4. The snps found in the scan ranges from both input files are 'lifted' based on the latest merge history file downloaded from NCBI ftp server\n5. The overlapping set of snps between both list of snps is returned as the final output" }, { "alpha_fraction": 0.5555555820465088, "alphanum_fraction": 0.5816091895103455, "avg_line_length": 21.842105865478516, "blob_id": "0d63521e1df8ff4b2805941d9e0ad7a03e501e2f", "content_id": "d2435012b1b46e7f1c3d7bf10f05fb11b73353bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 85, "num_lines": 57, "path": "/output/checkBed.py", "repo_name": "jla497/snpoverlap", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys, os\n\ndef usage():\n print(\"%s file: lift over rs number. \" % sys.argv[0] )\n print(\"file should look like:\")\n print(\"11111\")\n print(\"11112\")\n print(\"...\")\ndef myopen(fn):\n import gzip\n try:\n h = gzip.open(fn)\n ln = h.read(2) # read arbitrary bytes so check if @param fn is a gzipped file\n except:\n # cannot read in gzip format\n return open(fn)\n h.close()\n return gzip.open(fn)\n\nRS_Ref = set()\nRS_Input = set() # store rs\nRS_CHROM = dict() # high_rs -> (lower_rs, current_rs)\nexm = set()\nexm_chrom=dict()\nif __name__ == '__main__':\n \n\timport re\n\trsPattern = re.compile(r'^[0-9]+$')\n\t\n\tfor ln in myopen(sys.argv[1]):\n\t\trs = ln.strip()\n\t\tif not rsPattern.match(rs):\n\t\t\tprint 'ERROR: rs number should be like \"1000\"'\n\t\t\tsys.exit(2)\n\t\t\t\n\t\tRS_Ref.add(rs)\n\n\tfor ln in myopen(sys.argv[2]):\n\t\trs = ln.strip()\n\t\tif not rsPattern.match(rs):\n\t\t\tprint 'ERROR: rs number should be like \"1000\"'\n\t\t\tsys.exit(2)\n\t\t# rs number not appear in RS_MERGE -> there is no merge on this rs\n\t\tRS_Input.add(rs)\t\n\t\n\tRS_Diff = RS_Ref.difference(RS_Input)\n\t\n\tfor ln in myopen(sys.argv[3]):\n\t\tln = ln.strip()\n\t\tfd = ln.split(\"\\t\")\n\t\tif len(fd) < 3:\n\t\t\tcontinue\n\t\trs = fd[3][2:]\n\n\t\tif rs in RS_Diff:\n\t\t\tprint fd[0],\"\\t\",fd[1],\"\\t\",fd[2], \"\\t\",fd[3]\n\t\t\t" }, { "alpha_fraction": 0.7844638824462891, "alphanum_fraction": 0.7888402342796326, "avg_line_length": 29.46666717529297, "blob_id": "f96d1bbb9fe16a1d4951c225b78763106d9f12a4", "content_id": "55505bf0527ff58df412d262f128e988e8600e39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 914, "license_type": "no_license", "max_line_length": 79, "num_lines": 30, "path": "/src/main/java/com/daleylab/AppConfig.java", "repo_name": "jla497/snpoverlap", "src_encoding": "UTF-8", "text": "/*\n * To change this license header, choose License Headers in Project Properties.\n * To change this template file, choose Tools | Templates\n * and open the template in the editor.\n */\npackage com.daleylab;\n\n/**\n * Configuration for ThreadPool\n * @author JLee05\n */\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.ComponentScan;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.scheduling.annotation.EnableAsync;\nimport org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;\n\n@Configuration\n@ComponentScan(basePackages = {\"com.mkyong\"})\npublic class AppConfig {\n \n @Bean\n\tpublic ThreadPoolTaskExecutor taskExecutor() {\n\t\tThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();\n\t\tpool.setCorePoolSize(4);\n\t\tpool.setMaxPoolSize(6);\n\t\tpool.setWaitForTasksToCompleteOnShutdown(true);\n\t\treturn pool;\n\t}\n}\n" }, { "alpha_fraction": 0.5595736503601074, "alphanum_fraction": 0.5839360356330872, "avg_line_length": 23.33333396911621, "blob_id": "30349310b25c30e7e5e880d5348cd93eba74df32", "content_id": "3c3a9b54a8eeee4d76120b6929b84af4fd85f765", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2627, "license_type": "no_license", "max_line_length": 85, "num_lines": 108, "path": "/test/read_exom_rsid.py", "repo_name": "jla497/snpoverlap", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys, os\n\ndef usage():\n print(\"%s file: lift over rs number. \" % sys.argv[0] )\n print(\"file should look like:\")\n print(\"11111\")\n print(\"11112\")\n print(\"...\")\ndef myopen(fn):\n import gzip\n try:\n h = gzip.open(fn)\n ln = h.read(2) # read arbitrary bytes so check if @param fn is a gzipped file\n except:\n # cannot read in gzip format\n return open(fn)\n h.close()\n return gzip.open(fn)\n\nRS_Ref = set()\nRS_Input = set() # store rs\nRS_CHROM = dict() # high_rs -> (lower_rs, current_rs)\nexm = set()\nexm_chrom=dict()\nexm_rs = dict()\n\nif __name__ == '__main__':\n \n\timport re\n\trsPattern = re.compile(r'^[0-9]+$')\n\trsP2 = re.compile(r'chr1$')\n\trsP3 = re.compile(r'^rs*|.$')\n\trsP4 = re.compile(r'^exm*')\n\t#input InfiniumExome-24v1-0_A1_b138_rsids.txt\n\tfor ln in myopen(sys.argv[1]):\n\t\tln = ln.strip()\n\t\tfd = ln.split(\"\\t\")\n\t\tif not rsP3.match(fd[1]):\n\t\t\tprint fd[1],\"not matching\"\n\t\t\tsys.exit(2)\n\t\t\n\t\tif not rsP4.match(fd[0]):\n\t\t\tprint fd[0],\"not matching\"\n\t\t\tsys.exit(2)\n\t\t\n\t\tif fd[1].find(','):\n\t\t\trses= fd[1].split(',')\n\t\t\texm_rs[fd[0].strip()] = rses\n\t\telse:\n\t\t\texm_rs[fd[0].strip()] = fd[1].strip()\n\t\t\n\t\t#print fd[0],fd[1]\n\t#input InfiniumExome-24v1-0_A1.bed\n\tfor ln in myopen(sys.argv[2]):\n\t\tln = ln.strip()\n\t\t\n\t\tfd = ln.split(\"\\t\")\n\t\texm = fd[3].strip()\n\t\t#print fd[3]\n\t\tif exm in exm_rs:\n\t\t\trs = exm_rs[exm]\n\t\t\tif isinstance(rs,list):\n\t\t\t\tfor x in rs:\n\t\t\t\t\tRS_CHROM[x]= fd[0],fd[1],fd[2]\n\t\t\telse:\n\t\t\t\tRS_CHROM[rs]= fd[0],fd[1],fd[2]\n\t#chhavi's infi_rs_final_sorted2.txt\n\tfor ln in myopen(sys.argv[3]):\n\t\trsFound = false\n\t\trs = ln.strip()\n\t\tif rs not in RS_CHROM:\n\t\t\tprint rs+\" not found in RS_CHROM\"\n\t\t\t\n\t\t\n\t\tchrNum, chrStart, chrEnd = RS_CHROM[rs]\n\t\tchrNum = chrNum[3:]\n\t\t\n\t\tfileName=\"sorted_bed_chr_\"+chrNum+\".bed\"\n\t\t#print rs\n\t\tprint fileName\n\t\twith open(fileName) as f:\n\t\t\tfor ln in f:\n\t\t\t\trsP5 = re.compile(r'chr*')\n\t\t\t\tif not rsP5.match(ln):\n\t\t\t\t\tcontinue\n\n\t\t\t\tln = ln.strip()\n\t\t\t\tfd = ln.split(\"\\t\")\n\t\t\t\trsRef = fd[3].strip()\n\t\t\t\tr_chrStart = fd[1].strip()\n\t\t\t\tr_chrEnd = fd[2].strip()\n\t\t\t\tprint rsRef\n\t\t\t\tif rsRef == rs:\n\t\t\t\t\trsFound = true\n\t\t\t\t\tif not r_chrStart == chrStart:\n\t\t\t\t\t\tprint rs+\" does not have matching chromosome start positions:\"\n\t\t\t\t\t\t#print \"r_chrStart=\",r_chrStart,\"chrStart=\",chrStart\n\t\t\t\t\t\t#print rs\n\t\t\t\t\n\t\t\t\t\tif not r_chrEnd == chrEnd:\n\t\t\t\t\t\tprint rs+\" does not have matching chromosome end positions:\"\n\t\t\t\t\t\t#print \"r_chrEnd=\",r_chrEnd,\"chrEnd=\",chrEnd\n\t\t\t\t\t\t#print rs\n\t\t\t\t\t#else:\n\t\t\t\t\t\t#print rs,\"start and end positions match\"\n\t\t\t\tif rsFound == false:\n\t\t\t\t\tprint rs,\"wasn't found in bed file\" #rs not found in bed file" }, { "alpha_fraction": 0.6459032297134399, "alphanum_fraction": 0.6923813819885254, "avg_line_length": 21.419355392456055, "blob_id": "304eaf24915335073be34c14120363fbe4282051", "content_id": "39501f6c6a30ff20a85710e1aabe2872bff042b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 2087, "license_type": "no_license", "max_line_length": 169, "num_lines": 93, "path": "/wrapper.sh", "repo_name": "jla497/snpoverlap", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#wrapper script for running the chromosome to snp mapping and overlap functions\n\nwhile [[ $# -gt 1 ]]\n\tdo\n\tkey=\"$1\"\n\t\n\tcase $key in\n\t\t-i1|--input1)\n\t\tINPUT1=\"$2\"\n\t\tshift\n\t\t;;\n\t\t-i2|--input2) \n\t\tINPUT2=\"$2\"\n\t\t;;*)\n\t\t\n\t\t;;\n\tesac\n\tshift\ndone\n\n\n\necho INPUT1 =\"${INPUT1}\"\n\necho INPUT2 =\"${INPUT2}\"\n\nmkdir ${PWD}/output\n\necho mapping chromosome ranges to snps...\n\njava -jar target/chromosome_to_snp-1.0.jar \"${INPUT1}\" \"${INPUT2}\"\n\ncp snps1.rs snps2.rs ${PWD}/output\n\nmv snps1.rs snps2.rs ${PWD}/snpLift\n\ncd ${PWD}/snpLift\n\nrm *.md5\n\nrm *.gz\n\n wget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nlm.nih.gov/snp/organisms/human_9606_b150_GRCh38p7/database/data/organism_data/SNPHistory.bcp.gz \n wget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nlm.nih.gov/snp/organisms/human_9606_b150_GRCh38p7/database/data/organism_data/SNPHistory.bcp.gz.md5 \n wget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nlm.nih.gov/snp/organisms/human_9606_b150_GRCh38p7/database/data/organism_data/RsMergeArch.bcp.gz\n wget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nlm.nih.gov/snp/organisms/human_9606_b150_GRCh38p7/database/data/organism_data/RsMergeArch.bcp.gz.md5 \n \nfor f in *.gz\n\tdo\n\n\tmd5Check=$(md5sum \"${f}\" | awk '{print $1}') \n\t\n\tmd5Ref=$(cat ${f}.md5 | sed -e 's/MD5('\"$f\"')=//' | tr -d '[:space:]') \n\n\tif [ $md5Check != $md5Ref ];\n\tthen\n\t\techo md5sum for file $f does not match\n\t\texit 1\n\tfi\n\ndone\n\necho running liftRsNumber.py for snps1.rs...\n\npython LiftRsNumber.py snps1.rs > snps1_remapped.rs \n\nparentdir=\"$(dirname \"$(PWD)\")\"\n\ncp snps1_remapped.rs $parentdir/output\n\nrm snps1.rs\n\necho running liftRsNumber.py for snps2.rs...\n\n\npython LiftRsNumber.py snps2.rs > snps2_remapped.rs \n\ncp snps2_remapped.rs $parentdir/output\n\nrm snps2.rs\n\ncat snps1_remapped.rs | awk '{print $2}'| sort -o sorted_snp1.rs \n\ncat snps2_remapped.rs | awk '{print $2}'| sort -o sorted_snp2.rs \n\nrm snps1_remapped.rs snps2_remapped.rs\n\ncomm -12 sorted_snp1.rs sorted_snp2.rs > matchedSnps_remapped.rs\n\ncp matchedSnps_remapped.rs $parentdir/output\n\nrm *.rs\n\n\n" }, { "alpha_fraction": 0.5405405163764954, "alphanum_fraction": 0.569431483745575, "avg_line_length": 21.33333396911621, "blob_id": "23d9007362796e883bac1191340fc541b470d357", "content_id": "49dbd2bdbfde0be05635dfeec5b901b2b108b0ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1073, "license_type": "no_license", "max_line_length": 85, "num_lines": 48, "path": "/output/matchingsnps.py", "repo_name": "jla497/snpoverlap", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\nimport sys, os\n\ndef usage():\n print(\"%s file: lift over rs number. \" % sys.argv[0] )\n print(\"file should look like:\")\n print(\"11111\")\n print(\"11112\")\n print(\"...\")\ndef myopen(fn):\n import gzip\n try:\n h = gzip.open(fn)\n ln = h.read(2) # read arbitrary bytes so check if @param fn is a gzipped file\n except:\n # cannot read in gzip format\n return open(fn)\n h.close()\n return gzip.open(fn)\n\nRS_Ref = set()\nRS_Input = set() # store rs\nRS_CHROM = dict() # high_rs -> (lower_rs, current_rs)\nexm = set()\nexm_chrom=dict()\nexm_rs = dict()\nexm_snp = dict()\nif __name__ == '__main__':\n \n\timport re\n\trsPattern = re.compile(r'^[0-9]+$')\n\trsP2 = re.compile(r'chr1$')\n\trsP3 = re.compile(r'^rs*')\n\trsP4 = re.compile(r'^exm*')\n\tfor ln in myopen(sys.argv[1]):\n\t\tln = ln.strip()\n\t\tfd = ln.split(\"\\t\")\n\t\tif not rsP3.match(fd[1]):\n\t\t\tprint fd[1],\"not matching\"\n\t\t\tsys.exit(2)\n\t\t\n\t\tif not rsP4.match(fd[0]):\n\t\t\tprint fd[0],\"not matching\"\n\t\t\tsys.exit(2)\n\t\t\n\t\texm_rs[fd[0].strip()] = fd[1].strip()\n\t\t\n\t\tprint fd[0],fd[1]\n\t" }, { "alpha_fraction": 0.8148148059844971, "alphanum_fraction": 0.8222222328186035, "avg_line_length": 26.200000762939453, "blob_id": "34a48022b61df04d0009e84c445d0fa44dc9b5c2", "content_id": "6e99b31e0008322fa312aaa74d8675d7f747f4f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 135, "license_type": "no_license", "max_line_length": 35, "num_lines": 5, "path": "/target/classes/application.properties", "repo_name": "jla497/snpoverlap", "src_encoding": "UTF-8", "text": "outputfile=matchingSnps.txt\ninput.file.delimiter=\\t\ninput.file.chrom.column=0\nbed.file.delimiter=\\t\nbed.filename.prefix=sorted_bed_chr_" }, { "alpha_fraction": 0.6397820115089417, "alphanum_fraction": 0.6986376047134399, "avg_line_length": 33, "blob_id": "fb219230c99392ab772caf2fe8c5b34c50e7c51e", "content_id": "4018a53cdb68398910faac2ed0f6e9bce1491ab2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1835, "license_type": "no_license", "max_line_length": 140, "num_lines": 54, "path": "/runme_first.sh", "repo_name": "jla497/snpoverlap", "src_encoding": "UTF-8", "text": "#!/bin/bash\n#This script downloads human snp bed files from the NCBI ftp server and \n#sorts each bed files by the third column of each row (chromosome end position)\n\nfor ((var=1;var<=22;var++))\n\tdo\n\t\twget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b150_GRCh37p13/BED/bed_chr_${var}.bed.gz\n\t\twget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b150_GRCh37p13/BED/bed_chr_${var}.bed.gz.md5\n\tdone\n\nwget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b150_GRCh37p13/BED/bed_chr_X.bed.gz\nwget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b150_GRCh37p13/BED/bed_chr_X.bed.gz.md5\nwget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b150_GRCh37p13/BED/bed_chr_Y.bed.gz\nwget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b150_GRCh37p13/BED/bed_chr_Y.bed.gz.md5\nwget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b150_GRCh37p13/BED/bed_chr_MT.bed.gz\nwget --user=anonymous --password='[email protected]' ftp://ftp.ncbi.nih.gov/snp/organisms/human_9606_b150_GRCh37p13/BED/bed_chr_MT.bed.gz.md5\n\t\necho finished downloading all bed.gz files...\n\necho checking md5sum...\n\nfor f in *.bed.gz\n\tdo\n\n\tmd5Check=$(md5sum \"${f}\" | awk '{print $1}') \n\t\n\tmd5Ref=$(cat ${f}.md5 | sed -e 's/MD5('\"$f\"')=//' | tr -d '[:space:]') \n\n\tif [ $md5Check != $md5Ref ];\n\tthen\n\t\techo md5sum for file $f does not match\n\t\texit 1\n\tfi\n\ndone\n\nrm *.md5\n\necho unzipping all bed.gz files...\n\ngunzip *.bed.gz \n\necho finished unzipping all .gz files...\n\nfor f in *.bed\n\tdo\n\t\tsort -nk3 ${f} -o r_sorted_${f}\n\t\trm ${f}\n\t\techo sorted ${f}\n\tdone\n\nmkdir ${PWD}/bedfiles\nmv *.bed ${PWD}/bedfiles\necho done" } ]
8
davidwah/Praktik-Kelas
https://github.com/davidwah/Praktik-Kelas
0553e9c4676be9610b4eb2d5834034215e0fed64
1a0908ea658a3e7c33b5d025bcd3b010825c1595
9ad9ac8f92930e8cd44e871724400056ff57e1a5
refs/heads/master
2020-06-26T07:37:42.686591
2019-07-30T04:25:26
2019-07-30T04:25:26
199,573,679
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5925925970077515, "alphanum_fraction": 0.6424501538276672, "avg_line_length": 17, "blob_id": "6237d49a42491cfd8b67bd20b37dd8cd2593fb25", "content_id": "737c652bc1be812e3c834b724789542c31bb0034", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 702, "license_type": "no_license", "max_line_length": 54, "num_lines": 39, "path": "/10_ESP32_LoRa_Sender/10_ESP32_LoRa_Sender.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "#include <SPI.h>\n#include <LoRa.h>\n\n#define ss 10 //5\n#define rst 14\n#define dio0 2\n\nint counter = 0;\n\nvoid setup() {\n // put your setup code here, to run once:\n Serial.begin(115200);\n while(!Serial);\n Serial.println(\"Lora Sender\");\n\n LoRa.setPins(ss, rst, dio0);\n while (!LoRa.begin(433E6)) //433 diganti dengan 915 \n {\n Serial.println(\".\");\n delay(500);\n }\n LoRa.setSyncWord(0xF5);\n Serial.println(\"LoRa Initializing OK!\");\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n Serial.print(\"Sending packet: \");\n Serial.println(counter);\n\n LoRa.beginPacket();\n LoRa.print(\"Haloo Senin !!\");\n LoRa.print(counter);\n LoRa.endPacket();\n\n counter++;\n delay(10000);\n\n}\n" }, { "alpha_fraction": 0.6197478771209717, "alphanum_fraction": 0.680672287940979, "avg_line_length": 17.30769157409668, "blob_id": "705d666831127d00a7b8c2b4c7859b78a803e1c3", "content_id": "9b1207271d5b2e1c95deb714b429e36b172b924e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 476, "license_type": "no_license", "max_line_length": 43, "num_lines": 26, "path": "/06_AnalogRead/06_AnalogRead.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "const int ledPin1 = 2;\n//const int Pot = 34;\n\nint potValue = 0;\n\nconst int freq = 5000;\nconst int ledChannel = 0;\nconst int resolution = 12;\n\nvoid setup() {\n Serial.begin(115200);\n delay(1000);\n // put your setup code here, to run once:\n ledcSetup(ledChannel, freq, resolution);\n ledcAttachPin(ledPin1, ledChannel);\n}\n\nvoid loop() {\n\n //channel 1\n uint16_t dutycycle = analogRead(A0);\n ledcWrite(ledChannel, dutycycle);\n Serial.println(dutycycle);\n delay(15);\n \n}\n" }, { "alpha_fraction": 0.6224489808082581, "alphanum_fraction": 0.6358418464660645, "avg_line_length": 23.5, "blob_id": "72a37ccd9c327af39e42a9f329d6cd436f78bdd4", "content_id": "cd2faf180f86f0e57f507acccb1ea25248ff8c2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1580, "license_type": "no_license", "max_line_length": 77, "num_lines": 64, "path": "/12_thinkspeak_ESP32/12_thinkspeak_ESP32.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "//#ifdef __cplusplus\n//extern \"C\" {\n//#endif\n//uint8_t temprature_sens_read();\n//#ifdef __cplusplus\n//}\n//#endif\n//uint8_t temprature_sens_read();\n#include <WiFi.h>\n#include <PubSubClient.h>\n\n\nString apiKey = \"W7ZAEX8K7MM41KW5\"; // Enter your Write API key from ThingSpeak\nconst char *ssid = \"Ashish\"; // replace with your wifi ssid and password\nconst char *pass = \"12345678\";\nconst char* server = \"api.thingspeak.com\";\nWiFiClient client;\n\nvoid setup() {\n // put your setup code here, to run once:\n Serial.begin(9600);\n delay(10);\n Serial.println(\"Connecting to \");\n Serial.println(ssid);\n WiFi.begin(ssid, pass);\n while (WiFi.status() != WL_CONNECTED){\n delay(500);\n Serial.print(\".\");\n }​​​​​​\n Serial.println(\"\");\n Serial.println(\"WiFi connected\");\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n\n int h = 0;\n float t = 0;\n h = hallRead();\n t = ((temperature_sensor()-32)/1.8);\n\n String postStr = apiKey;\n postStr +=\"&field1=\";\n postStr += String(h);\n postStr += \"&field2=\";\n postStr += String(t);\n postStr += \"\\r\\n\\r\\n\";\n\n\n client.print(\"POST /update HTTP/1.1\\n\");\n client.print(\"Host: api.thingspeak.com\\n\");\n client.print(\"Connection: close\\n\");\n client.print(\"X-THINGSPEAKAPIKEY: \"+apiKey+\"\\n\");\n client.print(\"Content-Type: application/x-www-form-urlencoded\\n\");\n client.print(\"Content-Length: \");\n client.print(postStr.length()); \n client.print(\"\\n\\n\");\n client.print(postStr);\n Serial.print(\"Hall: \");\n Serial.println(h);\n Serial.print(\"Temperature:\");\n Serial.print(t);\n Serial.println(\" C\");\n}\n" }, { "alpha_fraction": 0.6393162608146667, "alphanum_fraction": 0.7025641202926636, "avg_line_length": 39.344825744628906, "blob_id": "7a690246419cfbfe535a2ecaeb2fdd31cdea0e90", "content_id": "94ebfeeaeebe6832f0f11e6baebc00d8937fa70e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 98, "num_lines": 29, "path": "/03_full_step/03_full_step.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "int buttonState = 0;\nvoid setup() {\n // put your setup code here, to run once:\n pinMode(15, OUTPUT);\n pinMode(2, OUTPUT);\n pinMode(0, OUTPUT);\n pinMode(4, OUTPUT);\n pinMode(17, INPUT);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n buttonState = digitalRead(17);\n if (buttonState == HIGH) {\n // turn LED on:\n digitalWrite(15,HIGH);digitalWrite(2,LOW);digitalWrite(0,LOW);digitalWrite(4,LOW); delay(100);\n digitalWrite(15,LOW);digitalWrite(2,HIGH);digitalWrite(0,LOW);digitalWrite(4,LOW); delay(100);\n digitalWrite(15,LOW);digitalWrite(2,LOW);digitalWrite(0,HIGH);digitalWrite(4,LOW); delay(100);\n digitalWrite(15,LOW);digitalWrite(2,LOW);digitalWrite(0,LOW);digitalWrite(4,HIGH); delay(100);\n\n } else {\n // turn LED off:\n digitalWrite(15,LOW);digitalWrite(2,LOW);digitalWrite(0,LOW);digitalWrite(4,HIGH); delay(100);\n digitalWrite(15,LOW);digitalWrite(2,LOW);digitalWrite(0,HIGH);digitalWrite(4,LOW); delay(100);\n digitalWrite(15,LOW);digitalWrite(2,HIGH);digitalWrite(0,LOW);digitalWrite(4,LOW); delay(100);\n digitalWrite(15,HIGH);digitalWrite(2,LOW);digitalWrite(0,LOW);digitalWrite(4,LOW); delay(100);\n\n }\n}\n" }, { "alpha_fraction": 0.5657418370246887, "alphanum_fraction": 0.6537997722625732, "avg_line_length": 25.70967674255371, "blob_id": "474aec1a522b324f8f74ce8d44b86e4b4d54c423", "content_id": "2f05c4467c9a5a4b13e848a38e9b4905854f9b08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 829, "license_type": "no_license", "max_line_length": 48, "num_lines": 31, "path": "/less01/less01.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "\nvoid setup() {\n // put your setup code here, to run once:\n pinMode(15, OUTPUT);\n pinMode(2, OUTPUT);\n pinMode(0, OUTPUT);\n pinMode(4, OUTPUT);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n //kanan \n digitalWrite(15,HIGH); delay(100);\n digitalWrite(15,LOW); delay(100);\n digitalWrite(2,HIGH); delay(100);\n digitalWrite(2,LOW); delay(100);\n digitalWrite(0,HIGH); delay(100);\n digitalWrite(0,LOW); delay(100);\n digitalWrite(4,HIGH); delay(100);\n digitalWrite(4,LOW); delay(100);\n digitalWrite(4,HIGH); delay(100);\n digitalWrite(4,LOW); delay(100);\n digitalWrite(0,HIGH); delay(100);\n digitalWrite(0,LOW); delay(100);\n digitalWrite(2,HIGH); delay(100);\n digitalWrite(2,LOW); delay(100);\n digitalWrite(15,HIGH); delay(100);\n digitalWrite(15,LOW); delay(100);\n\n //kiri\n \n}\n" }, { "alpha_fraction": 0.5605428218841553, "alphanum_fraction": 0.6242170929908752, "avg_line_length": 25.61111068725586, "blob_id": "cae37e406578b3e53c7ac6db13244910c15bc9ae", "content_id": "86f34d5f857406115a5021ed5528f3415517157d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 958, "license_type": "no_license", "max_line_length": 94, "num_lines": 36, "path": "/07_LM35/07_LM35.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "const int analogPin = 36; //initializes/defines the output pin of the LM35 temperature sensor\n //this sets the ground pin to LOW and the input voltage pin to high\nint value;\nvoid setup()\n{\n Serial.begin(115200);\n}\n\nvoid loop() //main loop\n{\n// value = analogRead(analogPin);\n//// float mv = (value / 1024)*3300;/\n// float temp = ((value * (3300/1023)));\n//// float celc = temp / 10;/\n//// float farh = (celc*9)/5 + /32;\n//\n// Serial.print(\"Temperature = \");\n// Serial.print(temp);\n// Serial.print(\"*C\");\n// Serial.println();\n// delay(500);\n\n\n \n int analogValue = analogRead(analogPin);\n float millivolts = (analogValue/1024.0) * 3300; //3300 is the voltage provided by NodeMCU\n float celsius = millivolts/10;\n Serial.print(\"in DegreeC= \");\n Serial.println(celsius);\n delay(500);\n//\n// float fahrenheit = ((celsius * 9)/5 + 32);\n// Serial.print(\"in Farenheit= \");\n// Serial.println(fahrenheit);\n// delay(1000);\n}\n" }, { "alpha_fraction": 0.75, "alphanum_fraction": 0.75, "avg_line_length": 15, "blob_id": "7af02cdd9e0bdc4810a60b481b70468cf48a73be", "content_id": "bc874086625671483655805e5a4a5889a2d62764", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 16, "license_type": "no_license", "max_line_length": 15, "num_lines": 1, "path": "/README.md", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "# Praktik-Kelas\n" }, { "alpha_fraction": 0.5691906213760376, "alphanum_fraction": 0.6279373168945312, "avg_line_length": 24.53333282470703, "blob_id": "34cb044995bd79655e67d2ee86c3448018598e56", "content_id": "571c377fe8f0f3412284c30c87cab2df05337f78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 766, "license_type": "no_license", "max_line_length": 65, "num_lines": 30, "path": "/07_LM35_02_/07_LM35_02_.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "const int analogIn = 36;\n \nint RawValue= 0;\ndouble Voltage = 0;\ndouble tempC = 0;\ndouble tempF = 0;\n \nvoid setup(){\nSerial.begin(115200);\n}\n \nvoid loop(){\n RawValue = analogRead(analogIn);\n Voltage = (RawValue / 1023.0) * 3300; // 5000 to get millivots.\n// Voltage = (RawValue * (3300/1023));\n tempC = Voltage * 0.1;\n// tempF = (tempC * 1.8) + 32; // conver to F\n Serial.print(\"Raw Value = \" ); // shows pre-scaled value\n Serial.print(RawValue);\n Serial.print(\"\\n\");\n Serial.print(\"milli volts = \"); // shows the voltage measured\n Serial.print(Voltage,0); //\n Serial.print(\"\\n\");\n Serial.print(\"Temperature in C = \");\n Serial.print(tempC,1);\n Serial.print(\"\\n\");\n// Serial.print(\"\\t Temperature in F = \");\n// Serial.println(tempF,1);\n delay(500);\n}\n" }, { "alpha_fraction": 0.6258205771446228, "alphanum_fraction": 0.6827133297920227, "avg_line_length": 17.280000686645508, "blob_id": "48b1eb6b5523b254ac21ad5ff95c6e6482129eea", "content_id": "089c29e62d31857b41cab16e76d77de5ca92f8be", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 457, "license_type": "no_license", "max_line_length": 80, "num_lines": 25, "path": "/08_Servo/08_Servo.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "//#include <UnoWiFiDevEd.h>\n\n#include <ESP32Servo.h>\n\n//#include <Servo.h>\n\nstatic const int servoPin = 13;\nstatic const int potPin = 36;\n\nServo myservo;\n//int pos = 0; \n\nvoid setup() {\n Serial.begin(115200);\n myservo.attach(servoPin); // attaches the servo on pin 13 to the servo object\n \n}\n\nvoid loop() {\n int servoPosition = map(analogRead(potPin), 0, 4096, 0, 180);\n myservo.write(servoPosition);\n Serial.println(servoPosition);\n delay(20);\n\n}\n" }, { "alpha_fraction": 0.7358185052871704, "alphanum_fraction": 0.7390599846839905, "avg_line_length": 24.75, "blob_id": "8c565458cfce31ce264524ae22bd8c9443474188", "content_id": "a0d782a65b4c734e5d04be8ecfd0782612f002b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 617, "license_type": "no_license", "max_line_length": 106, "num_lines": 24, "path": "/13_MQTT/Subscribe.py", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as paho\nimport time\nimport sys\nimport datetime\nimport time\n\nbroker = \"localhost\" #bisa disesuaikan dengan Server Broker. Free Server Broker Public \"broker.hivemq.com\"\ntopic = \"yuhu\" # \"yuhu\" = topic, bisa diganti dengan topic yang lainnya\n\ndef on_message(client, userdata, message):\n print(\"recived data is: \")\n print(str(message.payload.decode(\"utf-8\")))\n print(\"\")\n\nclient = paho.Client(\"user\")\nclient.on_message=on_message\n\nprint(\"Connecting to broker host\", broker)\nclient.connect(broker)\nprint(\"subscribing begins here\")\nclient.subscribe(topic)\n\nwhile 1:\n client.loop_start()" }, { "alpha_fraction": 0.5802781581878662, "alphanum_fraction": 0.6207332611083984, "avg_line_length": 18.292682647705078, "blob_id": "218d39dd743b1b9ee262e04b0e4502db52f88652", "content_id": "ed014f73688d8f9fdce1fd54e6b4388be76f5b46", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 791, "license_type": "no_license", "max_line_length": 54, "num_lines": 41, "path": "/11_ESP32_LoRa_Recive/11_ESP32_LoRa_Recive.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "#include <SPI.h>\n#include <LoRa.h>\n\n#define ss 5 //5\n#define rst 14\n#define dio0 2\n\nint counter = 0;\n\nvoid setup() {\n // put your setup code here, to run once:\n Serial.begin(115200);\n while(!Serial);\n delay(500);\n Serial.println(\"Lora Receiver\");\n \n\n LoRa.setPins(ss, rst, dio0);\n while (!LoRa.begin(915E6)) //433 diganti dengan 915 \n {\n Serial.println(\".\");\n delay(500);\n }\n LoRa.setSyncWord(0xF3);\n Serial.println(\"LoRa Initializing OK!\");\n}\n\nvoid loop() {\n int packetSize = LoRa.parsePacket();\n if (packetSize) {\n Serial.print(\"Recived packet: \");\n\n //Read packet data\n while (LoRa.available()) {\n String LoRaData = LoRa.readString();\n Serial.print(LoRaData); \n }\n Serial.print(\"' with RSSI \");\n Serial.println(LoRa.packetRssi());\n }\n}\n" }, { "alpha_fraction": 0.6256983280181885, "alphanum_fraction": 0.6610800623893738, "avg_line_length": 21.375, "blob_id": "8ca593a7912a1aa5c664924de41e53dc424e9311", "content_id": "1e47c3eeefd0c259a4fa2dbdd0707d644b87f178", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 537, "license_type": "no_license", "max_line_length": 57, "num_lines": 24, "path": "/04_PWM/04_PWM.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "const int ledPin = 2;\n\nconst int freq = 2000;\nconst int ledChannel = 0;\nconst int resolution = 8;\n\nvoid setup() {\n // put your setup code here, to run once:\n ledcSetup(ledChannel, freq, resolution);\n ledcAttachPin(ledPin, ledChannel);\n}\n\nvoid loop() {\n // put your main code here, to run repeatedly:\n for(int dutyCycle = 0; dutyCycle <= 255; dutyCycle++) {\n ledcWrite(ledChannel, dutyCycle);\n delay(15);\n }\n\n for(int dutyCycle = 255; dutyCycle <= 0; dutyCycle++) {\n ledcWrite(ledChannel, dutyCycle);\n delay(15);\n }\n}\n" }, { "alpha_fraction": 0.6372548937797546, "alphanum_fraction": 0.6612200140953064, "avg_line_length": 26, "blob_id": "344da1f63b99824177e814a058cd735942047d2d", "content_id": "c71f721b217d6eb67b9eaaf2374d765fccd8c5fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 918, "license_type": "no_license", "max_line_length": 100, "num_lines": 34, "path": "/13_MQTT/Publish.py", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "import paho.mqtt.client as paho\nimport os\nimport json\nimport time\nfrom datetime import datetime\n\nbroker = \"localhost\" #bisa disesuaikan dengan Server Broker\nport = 1883\n\ndef on_publish(client, userdata, result):\n print(\"data published to broker \\n\")\n pass\nclient1= paho.Client(\"control1\")\nclient1.on_publish = on_publish\nclient1.connect(broker,port, keepalive=60)\n\nwhile True:\n payload=\"{\"\n payload+=\"\\\"humidity\\\":60,\";\n payload+=\"\\\"temperature\\\":22\";\n payload+=\"}\"\n ret = client1.publish(\"yuhu\", payload) # \"yuhu\" = topic, bisa diganti dengan topic yang lainnya\n print(\"Kirim Data!!!\")\n print(payload);\n time.sleep(2)\n\n payload=\"{\"\n payload+=\"\\\"humidity\\\":40,\";\n payload+=\"\\\"temperature\\\":32\";\n payload+=\"}\"\n ret = client1.publish(\"yuhu\", payload) # \"yuhu\" = topic, bisa diganti dengan topic yang lainnya\n print(\"Kirim Data!!!\")\n print(payload);\n time.sleep(1)\n" }, { "alpha_fraction": 0.591472327709198, "alphanum_fraction": 0.615160346031189, "avg_line_length": 21.491804122924805, "blob_id": "8250976ba19f57c361e706ec68a438ed4a481488", "content_id": "84b5b725cea8b465a9ef711b20fdeb4d4a6b84de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2744, "license_type": "no_license", "max_line_length": 69, "num_lines": 122, "path": "/11_ESP32_LoRa_Recive_WebServer/11_ESP32_LoRa_Recive_WebServer.ino", "repo_name": "davidwah/Praktik-Kelas", "src_encoding": "UTF-8", "text": "#include <SPI.h>\n#include <LoRa.h>\n\n#include <WiFi.h>\n#include <WiFiClient.h>\n#include <WebServer.h>\n#include <ESPmDNS.h>\n\n#define ss 5 //5\n#define rst 14\n#define dio0 2\n\nconst char* ssid = \"POSKO INTERNET\";\nconst char* password = \"yuhusaja\";\n\nWebServer server(80);\n\nString LoRaData;\n\nint counter = 0;\n\n\n//void handle_OnConnect() {\n// server.send(200, \"text/html\", SendHTML(loradata));\n//}\n\n//void handle_led1on() {\n// led1status = HIGH;\n// server.send(200, \"text/html\", SendHTML(led1status));\n// Serial.println(\"LED dinyalakan.\");\n//}\n\n//void handle_led1off() {\n//// led1status = LOW;\n// server.send(200, \"text/html\", SendHTML(led1status));\n// Serial.println(\"LED dimatikan.\");\n//}\n\nvoid handleNotFound() {\n String message = \"File Not Found\\n\\n\";\n message += \"URI: \";\n message += server.uri();\n message += \"\\nMethod: \";\n message += (server.method() == HTTP_GET) ? \"GET\" : \"POST\";\n message += \"\\nArguments: \";\n message += server.args();\n message += \"\\n\";\n for (uint8_t i = 0; i < server.args(); i++) {\n message += \" \" + server.argName(i) + \": \" + server.arg(i) + \"\\n\";\n }\n server.send(404, \"text/plain\", message);\n}\n\nvoid setup() {\n // put your setup code here, to run once:\n Serial.begin(115200);\n while(!Serial);\n delay(500);\n Serial.println(\"Lora Receiver\");\n WiFi.mode(WIFI_STA);\n WiFi.begin(ssid, password);\n Serial.println(\"\");\n\n // Wait for connection\n while (WiFi.status() != WL_CONNECTED) {\n delay(500);\n Serial.print(\".\");\n }\n Serial.println(\"\");\n Serial.print(\"Connected to \");\n Serial.println(ssid);\n Serial.print(\"IP address: \");\n Serial.println(WiFi.localIP());\n\n if (MDNS.begin(\"esp32\")) {\n Serial.println(\"MDNS responder started\");\n }\n//// server.on(\"/\", handle_OnConnect);\n// server.on(\"/led1on\", handle_led1on);\n// server.on(\"/led1off\", handle_led1off);\n// server.onNotFound(handleNotFound);\n\n server.begin();\n Serial.println(\"HTTP server started\");\n \n\n LoRa.setPins(ss, rst, dio0);\n while (!LoRa.begin(915E6)) //433 diganti dengan 915 \n {\n Serial.println(\".\");\n delay(500);\n }\n LoRa.setSyncWord(0xF3);\n Serial.println(\"LoRa Initializing OK!\");\n}\n\nvoid loop() {\n// LoRaData = LoRa.readString();\n int packetSize = LoRa.parsePacket();\n if (packetSize) {\n Serial.print(\"Recived packet: \");\n\n //Read packet data\n while (LoRa.available()) {\n String LoRaData = LoRa.readString();\n Serial.print(LoRaData); \n }\n Serial.print(\"' with RSSI \");\n Serial.println(LoRa.packetRssi());\n }\n}\n\nString SendHTML(uint8_t loradata) {\n String teks = \"<!DOCTYPE html> <html>\\n\";\n teks += \"<head><meta http-equiv=\\\"refresh\\\" content=\\\"6\\\"></head>\";\n\n teks = teks + \"<p> loradata = \"+ LoRaData +\"</p>\";\n\n teks += \"</html>\";\n \n return teks;\n}\n" } ]
14
danghualong/stock
https://github.com/danghualong/stock
f87b262e691fbc2571849bfe51582781051d4c80
36ecb25044162070431de42ab55a97be17e0f03e
35a5ffad073e2266812861adf56ab3511e6862ad
refs/heads/master
2023-03-26T09:10:26.858585
2021-03-28T14:00:05
2021-03-28T14:00:05
339,403,083
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6069231033325195, "alphanum_fraction": 0.6169230937957764, "avg_line_length": 31.33333396911621, "blob_id": "5f63b4e8348b421282d95ef8fce998630e06c7e9", "content_id": "07caf8693537ababf2b8b8c5c677cb9081b02b1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1300, "license_type": "no_license", "max_line_length": 86, "num_lines": 39, "path": "/src/cron/service/add_history_service.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...constant import urls\r\nfrom ...db import dboper\r\nfrom ..parsers import historyParser\r\nfrom ...logger import currentLogger\r\nimport datetime\r\nimport requests\r\n\r\n\r\ndef addHistoryDaily(days=300):\r\n stocks = dboper.getStocks()\r\n if (stocks is None or len(stocks)<=0):\r\n currentLogger.warn(\"no stock fetched\")\r\n return\r\n\r\n stop = datetime.datetime.now().strftime(\"%Y%m%d\")\r\n start = (datetime.datetime.now() -\r\n datetime.timedelta(days=days)).strftime(\"%Y%m%d\")\r\n currentLogger.info(\"{0}-{1} records will be inserted\".format(start, stop))\r\n index=0\r\n for stock in stocks:\r\n details = _getDetails(stock.code, start, stop)\r\n index += 1\r\n if (details is None):\r\n continue\r\n for detail in details:\r\n dboper.insertDaily(detail)\r\n currentLogger.info(\"-------{2}/{3}---{0}:{1} insert all daily records\".format(\r\n stock.code, stock.name,index,len(stocks)))\r\n\r\ndef _getDetails(code, start, stop):\r\n url = urls.HISTORY_PRICE_URL.format(code, start, stop)\r\n resp = requests.get(url)\r\n content = resp.text\r\n details=None\r\n try:\r\n details = historyParser.parse(content)\r\n except Exception as ex:\r\n currentLogger.error(\"code:{0} error \\n%s\",ex)\r\n return details\r\n" }, { "alpha_fraction": 0.7424242496490479, "alphanum_fraction": 0.7424242496490479, "avg_line_length": 26.428571701049805, "blob_id": "8f882072cdd12728558aa243e7520ac23eb7231e", "content_id": "b6aa11caebf3322f9616c2fe42ed556e4328ecc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 57, "num_lines": 7, "path": "/src/stat/__init__.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from flask import Blueprint\r\n\r\nstat_bp = Blueprint(\"stat\", __name__, url_prefix=\"/stat\")\r\n\r\nfrom .controller import break_point\r\nfrom .controller import stock_filter\r\nfrom .controller import stocks " }, { "alpha_fraction": 0.5805168747901917, "alphanum_fraction": 0.5825049877166748, "avg_line_length": 27.705883026123047, "blob_id": "a58f69341a7b45c3f1734611dc14ba12221fd0ed", "content_id": "d1398b4ba3ec560bc49d31cb459f5bd003e26b1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 521, "license_type": "no_license", "max_line_length": 52, "num_lines": 17, "path": "/src/stat/view/trends.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...db import dboper\r\nfrom . import table\r\nfrom ..service import trait_service as TraitService \r\n\r\ndef showCurrentTrends():\r\n stocks = dboper.getStocks()\r\n if (stocks is None or len(stocks)<=0):\r\n print(\"no stock fetched\")\r\n return\r\n for stock in stocks:\r\n traits=TraitService.getTraits(stock.code)\r\n table.showMAAndATR(traits, stock)\r\n word = input(\"点击q退出,其他键继续...\\n\")\r\n if (word == 'q'):\r\n break\r\n else:\r\n print(word)" }, { "alpha_fraction": 0.41033434867858887, "alphanum_fraction": 0.4607902765274048, "avg_line_length": 19.9743595123291, "blob_id": "e0902377a775fc6b8c5297910bb5c17b5969640b", "content_id": "4850819d41e87e662f50ca92da1a4b91452cf2fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1717, "license_type": "no_license", "max_line_length": 133, "num_lines": 78, "path": "/src/model/model.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "import time\n\n\nclass Synchronizable(object):\n update_at = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time.time()))\n\n\nclass Stock(Synchronizable):\n code = ''\n name = ''\n prefix = 'sh'\n\nclass Daily(Synchronizable):\n code = \"\"\n date = \"\"\n open = \"\"\n last_close = \"\"\n current = \"\"\n high = \"\"\n low = \"\"\n quantity = \"\"\n amount = \"\"\n bid1 = \"\"\n bid1_amount = \"\"\n bid2 = \"\"\n bid2_amount = \"\"\n bid3 = \"\"\n bid3_amount = \"\"\n bid4 = \"\"\n bid4_amount = \"\"\n bid5 = \"\"\n bid5_amount = \"\"\n ask1 = \"\"\n ask1_amount = \"\"\n ask2 = \"\"\n ask2_amount = \"\"\n ask3 = \"\"\n ask3_amount = \"\"\n ask4 = \"\"\n ask4_amount = \"\"\n ask5 = \"\"\n ask5_amount = \"\"\n turnover = \"\"\n\nclass Trait(object):\n date = \"\"\n # # 移动平均线\n # MA = {}\n # # 平均真实波动幅度\n # ATR={}\n close = 0.0\n high = 0.0\n last_close=0.0\n low = 0.0\n open = 0.0\n quantity = 0.0\n amount = 0.0\n\n def __init__(self):\n # 移动平均线\n self.MA = {}\n # 平均真实波动幅度\n self.ATR = {}\n \n # 获取当日真实波动幅度\n def getTrueRange(self):\n return max(self.high - self.low, abs(self.high - self.last_close), abs(self.low - self.last_close))\n\n def __str__(self):\n return \"----{8}----,atr10:{0},atr20:{1},ma5:{2},ma10:{3},ma20:{4},ma30:{5},ma60:{6},ma120:{7}\".format(round(self.ATR[10], 3),\n round(self.ATR[20], 3),\n round(self.MA[5], 3),\n round(self.MA[10], 3),\n round(self.MA[20], 3),\n round(self.MA[30], 3),\n round(self.MA[60], 3),\n round(self.MA[120], 3),\n self.date)\n \n" }, { "alpha_fraction": 0.6434316635131836, "alphanum_fraction": 0.6434316635131836, "avg_line_length": 21.4375, "blob_id": "a7bb194e5c309cb0f0c60dc6858bc18ba520830b", "content_id": "39d3469a7541691e9fa8213f45b9bd06a5ec93ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "no_license", "max_line_length": 101, "num_lines": 16, "path": "/app.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from src import createApp\r\nimport os\r\nfrom src.tools.response_factory import create_response\r\n\r\napp = createApp()\r\n\r\n\r\[email protected](\"/\")\r\ndef index():\r\n mode=os.getenv(\"FLASK_ENV\", \"---\")\r\n items=[dict(path=i.rule,methods=list(i.methods),endpoint=i.endpoint) for i in app.url_map._rules]\r\n return create_response(items)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run()" }, { "alpha_fraction": 0.7076923251152039, "alphanum_fraction": 0.7076923251152039, "avg_line_length": 29.5, "blob_id": "211c8487ca1efe2d753b7753f76c04f602a16f90", "content_id": "eeb8182d4c427790bb6058f590b9deff26e97566", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 65, "license_type": "no_license", "max_line_length": 38, "num_lines": 2, "path": "/src/model/__init__.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from .model import Stock, Daily, Trait\r\nfrom .errors import *\r\n\r\n" }, { "alpha_fraction": 0.6171662211418152, "alphanum_fraction": 0.6267030239105225, "avg_line_length": 35.75, "blob_id": "0e6df0903752e4d49eb57484adfce216490bd7a9", "content_id": "96deb3c7ce4296ecc028969351845692f2494bec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 752, "license_type": "no_license", "max_line_length": 155, "num_lines": 20, "path": "/src/errorhandlers.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from .model import APIException, ServerError\nfrom werkzeug.exceptions import HTTPException\nfrom .logger import currentLogger\nfrom flask import request\n\ndef init_app(app):\n @app.errorhandler(Exception)\n def framework_error(e):\n currentLogger.error(\"url is {0},error info:{1}\".format(request.path,e) if isinstance(e, HTTPException) else \"error info:{0}\".format(e)) # 对错误进行日志记录\n if isinstance(e, APIException):\n return e\n if isinstance(e, HTTPException):\n msg = e.description\n error_code = 1007\n return APIException(error_code, msg)\n else:\n if not app.config['DEBUG']:\n return ServerError()\n else:\n return e" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.7453415989875793, "avg_line_length": 31.299999237060547, "blob_id": "5051f2e17339e32901f9caaa61b1ea86cb40cca8", "content_id": "17bbbaeb5a239eb5f0ba4c8de69d3fa8c7f17e7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 322, "license_type": "no_license", "max_line_length": 78, "num_lines": 10, "path": "/src/tools/response_factory.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from flask import make_response\nfrom .serializer import DHLEncoder\nimport json\n\ndef create_response(payload):\n result = dict(data=payload,error_code=0)\n content = json.dumps(result, cls=DHLEncoder, ensure_ascii=False, indent=4)\n resp = make_response(content)\n resp.mimetype = \"application/json\"\n return resp" }, { "alpha_fraction": 0.6329670548439026, "alphanum_fraction": 0.6329670548439026, "avg_line_length": 20.380952835083008, "blob_id": "7976bdd6e2255e4eeb61e9801f7581d786c3c47a", "content_id": "92aee0cecc56e4de9e653e5bff2abae9a954eccf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 511, "license_type": "no_license", "max_line_length": 53, "num_lines": 21, "path": "/src/stat/controller/stocks.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from .. import stat_bp\nfrom ...db import dboper\nfrom ...tools.response_factory import create_response\n\n@stat_bp.route(\"/\", methods=['GET'])\ndef getStocks():\n '''\n 获取所有的股票代码信息\n '''\n stocks = dboper.getStocks()\n return create_response(stocks)\n\n@stat_bp.route(\"/<key>\", methods=['GET'])\ndef getStocksByKey(key):\n '''\n 获取某支股票的信息\n\n key:股票代码 或者 名称\n '''\n stocks = dboper.getStocksByKey(key)\n return create_response(stocks)\n \n " }, { "alpha_fraction": 0.49716445803642273, "alphanum_fraction": 0.5122873187065125, "avg_line_length": 24.350000381469727, "blob_id": "e613ccc53c730427c382bd29f74421155951cb6b", "content_id": "737e2c089b4cb9c72ccf1e463fa42abf4195eb4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 83, "num_lines": 20, "path": "/src/stat/service/atr_service.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "\r\ndef calcATR(traits, N=20):\r\n '''\r\n 计算N日平均波动幅度\r\n\r\n traits:汇总特征数据集合\r\n N:均值的天数\r\n '''\r\n result=[]\r\n total = 0.0\r\n slowIndex = 0\r\n fastIndex = 0\r\n for fastIndex in range(len(traits)):\r\n trait=traits[fastIndex]\r\n if (fastIndex < N):\r\n total += trait.getTrueRange()\r\n trait.ATR[N]=total / (fastIndex + 1)\r\n else:\r\n total = total - traits[slowIndex].getTrueRange() + trait.getTrueRange()\r\n trait.ATR[N]=total/N\r\n slowIndex += 1\r\n" }, { "alpha_fraction": 0.6638298034667969, "alphanum_fraction": 0.6638298034667969, "avg_line_length": 25.647058486938477, "blob_id": "1be1bc3e2b5022e7ded4eb0ac6190058b6ad5f58", "content_id": "ad6f86d55d3649fb326753ef955f413aa00c56f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 57, "num_lines": 17, "path": "/src/__init__.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from flask import Flask\r\nimport os\r\nfrom .settings import configs\r\nfrom . import cron, logger, db, routers,errorhandlers\r\n\r\n\r\ndef createApp(configName=None):\r\n app = Flask(__name__)\r\n if configName == None:\r\n configName = os.getenv(\"FLASK_ENV\", \"production\")\r\n app.config.from_object(configs[configName])\r\n logger.init_app(app)\r\n errorhandlers.init_app(app)\r\n db.init_app(app)\r\n cron.init_app(app)\r\n routers.init_app(app)\r\n return app\r\n" }, { "alpha_fraction": 0.6113536953926086, "alphanum_fraction": 0.6113536953926086, "avg_line_length": 14.266666412353516, "blob_id": "3f00b0473159b2dadf3e0c53c12721969925377f", "content_id": "57adfca0c2c602e42856650c5ac0cfc7da1bb662", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "TOML", "length_bytes": 229, "license_type": "no_license", "max_line_length": 39, "num_lines": 15, "path": "/Pipfile", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "[[source]]\nname = \"pypi\"\nurl = \"https://pypi.douban.com/simple/\"\nverify_ssl = true\n\n[dev-packages]\npython-dotenv = \"*\"\n\n[packages]\nrequests = \"*\"\nmatplotlib = \"*\"\nflask = \"*\"\nflask-apscheduler = \"*\"\nwfastcgi = \"*\"\ngunicorn = \"*\"\n" }, { "alpha_fraction": 0.7446808218955994, "alphanum_fraction": 0.7446808218955994, "avg_line_length": 29.66666603088379, "blob_id": "2a29a374bcd88d8390c07f55d89877662ca56eaa", "content_id": "131a9177a9de500eb2ccfc5af6b39e8a418c0fdf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 188, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/src/stat/view/single_ma_view.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ..service import trait_service as TraitService\r\nfrom . import table\r\n\r\ndef ShowSingleMA(stock):\r\n traits = TraitService.getTraits(stock.code)\r\n table.showMA(traits, stock, True)" }, { "alpha_fraction": 0.7473683953285217, "alphanum_fraction": 0.7473683953285217, "avg_line_length": 30, "blob_id": "6e3361285fe48543d0ba925a0170f362595c0974", "content_id": "03028a58a8f373561e49a2446f8af6e8c80890d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 190, "license_type": "no_license", "max_line_length": 51, "num_lines": 6, "path": "/src/stat/view/single_atr_view.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ..service import trait_service as TraitService\r\nfrom . import table\r\n\r\ndef ShowSingleATR(stock):\r\n traits = TraitService.getTraits(stock.code)\r\n table.showATR(traits, stock, True)" }, { "alpha_fraction": 0.444638192653656, "alphanum_fraction": 0.48706769943237305, "avg_line_length": 28.860986709594727, "blob_id": "4e98b76dd0fabc71c7c280afff8608885a62ab74", "content_id": "24de379ba6c27a876b5c1a403b66df2168795f03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6890, "license_type": "no_license", "max_line_length": 97, "num_lines": 223, "path": "/src/db/dboper.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "import sqlite3\r\nimport os\r\nfrom ..model import Daily, Stock\r\nfrom ..settings import configs\r\nfrom ..logger import currentLogger\r\n\r\n\r\nDB_NAME = configs[os.getenv(\"FLASK_ENV\", \"production\")].SQLALCHEMY_DATABASE_URI\r\n\r\ndef insertStock(stock):\r\n try:\r\n conn = sqlite3.connect(DB_NAME)\r\n # print(\"insertStock connect db successfully\")\r\n cur = conn.cursor()\r\n cur.execute(\r\n 'insert or ignore into stock(code,name,prefix,update_at) values(?,?,?,?)',\r\n (\r\n stock.code,\r\n stock.name,\r\n stock.prefix,\r\n stock.update_at,\r\n ))\r\n conn.commit()\r\n except Exception as e:\r\n currentLogger.error(\"%s\",e)\r\n finally:\r\n if cur!=None:\r\n cur.close()\r\n if conn!=None:\r\n conn.close()\r\n\r\ndef getStocks():\r\n result = []\r\n try:\r\n conn = sqlite3.connect(DB_NAME)\r\n # print(\"getStocks connect db successfully\")\r\n cur = conn.cursor()\r\n cur.execute('select * from stock where type<9')\r\n items = cur.fetchall()\r\n for item in items:\r\n stock = Stock()\r\n stock.code = item[0]\r\n stock.name = item[1]\r\n stock.prefix = item[2]\r\n result.append(stock)\r\n except Exception as e:\r\n currentLogger.error(\"%s\",e)\r\n finally:\r\n if cur!=None:\r\n cur.close()\r\n if conn!=None:\r\n conn.close()\r\n return result\r\n\r\ndef getStocksByKey(keyword):\r\n result = []\r\n try:\r\n conn = sqlite3.connect(DB_NAME)\r\n # print(\"getStocks connect db successfully\")\r\n cur = conn.cursor()\r\n cur.execute(\"select * from stock where name like ? or code=?\",('%'+keyword+'%',keyword,))\r\n items = cur.fetchall()\r\n for item in items:\r\n stock = Stock()\r\n stock.code = item[0]\r\n stock.name = item[1]\r\n stock.prefix = item[2]\r\n result.append(stock)\r\n except Exception as e:\r\n currentLogger.error(\"%s\",e)\r\n finally:\r\n if cur!=None:\r\n cur.close()\r\n if conn!=None:\r\n conn.close()\r\n return result\r\n\r\n\r\ndef insertDaily(daily, replace=False):\r\n try:\r\n conn = sqlite3.connect(DB_NAME)\r\n # print(\"insertDaily connect db successfully\")\r\n cur = conn.cursor()\r\n cur.execute(\r\n '''insert or {0} into daily(\r\n code,date,open,last_close,current,high,low,quantity,amount,\r\n bid1,bid2,bid3,bid4,bid5,ask1,ask2,ask3,ask4,ask5,\r\n bid1_amount,bid2_amount,bid3_amount,bid4_amount,bid5_amount,\r\n ask1_amount,ask2_amount,ask3_amount,ask4_amount,ask5_amount,\r\n turnover,update_at) values\r\n (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)'''.\r\n format('replace' if replace else 'ignore'), (\r\n daily.code,\r\n daily.date,\r\n daily.open,\r\n daily.last_close,\r\n daily.current,\r\n daily.high,\r\n daily.low,\r\n daily.quantity,\r\n daily.amount,\r\n daily.bid1,\r\n daily.bid2,\r\n daily.bid3,\r\n daily.bid4,\r\n daily.bid5,\r\n daily.ask1,\r\n daily.ask2,\r\n daily.ask3,\r\n daily.ask4,\r\n daily.ask5,\r\n daily.bid1_amount,\r\n daily.bid2_amount,\r\n daily.bid3_amount,\r\n daily.bid4_amount,\r\n daily.bid5_amount,\r\n daily.ask1_amount,\r\n daily.ask2_amount,\r\n daily.ask3_amount,\r\n daily.ask4_amount,\r\n daily.ask5_amount,\r\n daily.turnover,\r\n daily.update_at,\r\n ))\r\n conn.commit()\r\n except Exception as e:\r\n currentLogger.error(\"%s\",e)\r\n finally:\r\n if cur!=None:\r\n cur.close()\r\n if conn!=None:\r\n conn.close()\r\n\r\ndef getDailys(code,N):\r\n result = []\r\n try:\r\n conn = sqlite3.connect(DB_NAME)\r\n cur = conn.cursor()\r\n cur.execute('select * from daily where code=? order by date desc limit ?',(code,N,))\r\n items = cur.fetchall()\r\n for item in items:\r\n daily = Daily()\r\n daily.code = item[0]\r\n daily.date = item[1]\r\n daily.open = item[2]\r\n daily.last_close = item[3]\r\n daily.current = item[4]\r\n daily.high = item[5]\r\n daily.low = item[6]\r\n daily.quantity = item[7]\r\n daily.amount = item[8]\r\n daily.bid1 = item[9]\r\n daily.bid1_amount = item[10]\r\n daily.bid2 = item[11]\r\n daily.bid2_amount = item[12]\r\n daily.bid3 = item[13]\r\n daily.bid3_amount = item[14]\r\n daily.bid4 = item[15]\r\n daily.bid4_amount = item[16]\r\n daily.bid5 = item[17]\r\n daily.bid5_amount = item[18]\r\n daily.ask1 = item[19]\r\n daily.ask1_amount = item[20]\r\n daily.ask2 = item[21]\r\n daily.ask2_amount = item[22]\r\n daily.ask3 = item[23]\r\n daily.ask3_amount = item[24]\r\n daily.ask4 = item[25]\r\n daily.ask4_amount = item[26]\r\n daily.ask5 = item[27]\r\n daily.ask5_amount = item[28]\r\n daily.turnover = item[30]\r\n result.append(daily)\r\n except Exception as e:\r\n currentLogger.error(\"%s\",e)\r\n finally:\r\n if cur!=None:\r\n cur.close()\r\n if conn!=None:\r\n conn.close()\r\n return result[::-1]\r\n\r\nif __name__ == \"__main__\":\r\n\r\n from model import Stock, Daily\r\n\r\n stock = Stock()\r\n stock.name = \"美的集团\"\r\n stock.code = \"000333\"\r\n stock.prefix = \"sz\"\r\n insertStock(stock)\r\n\r\n daily = Daily()\r\n daily.code = \"000333\"\r\n daily.date = \"2021-02-10\"\r\n daily.open = \"102.9\"\r\n daily.last_close = \"101.7\"\r\n daily.current = \"107.2\"\r\n daily.high = \"108\"\r\n daily.low = \"101.5\"\r\n daily.quantity = \"8654778686\"\r\n daily.amount = \"1545678968498786.01\"\r\n daily.bid1 = \"107.1\"\r\n daily.bid2 = \"107.0\"\r\n daily.bid3 = \"106.9\"\r\n daily.bid4 = \"106.7\"\r\n daily.bid5 = \"106.0\"\r\n daily.bid1_amount = \"3047\"\r\n daily.bid2_amount = \"3048\"\r\n daily.bid3_amount = \"3046\"\r\n daily.bid4_amount = \"3045\"\r\n daily.bid5_amount = \"3044\"\r\n daily.ask1 = \"107.2\"\r\n daily.ask2 = \"107.3\"\r\n daily.ask3 = \"107.4\"\r\n daily.ask4 = \"107.5\"\r\n daily.ask5 = \"107.6\"\r\n daily.ask1_amount = \"5041\"\r\n daily.ask2_amount = \"5042\"\r\n daily.ask3_amount = \"5043\"\r\n daily.ask4_amount = \"5044\"\r\n daily.ask5_amount = \"5045\"\r\n insertDaily(daily)\r\n" }, { "alpha_fraction": 0.7049180269241333, "alphanum_fraction": 0.7295082211494446, "avg_line_length": 90, "blob_id": "c88b7cb7bef0a0f0451770493524979d3c084f88", "content_id": "4a3a31dee718889bd00266501fd2d1b84849e86f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 145, "num_lines": 4, "path": "/src/constant/urls.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "DAILY_PRICE_URL = 'http://hq.sinajs.cn/list={0}' # sz表示深市,sh表示上市\r\nHISTORY_PRICE_URL = 'https://q.stock.sohu.com/hisHq?code=cn_{0}&start={1}&end={2}&stat=0&order=A&period=d&callback=historySearchHandler&rt=jsonp'\r\n# appkey从个人管理后台获取:https://www.jisuapi.com/api/stock/\r\nJISU_STOCK_URL='https://api.jisuapi.com/stock/list?classid=1&pagenum={0}&pagesize=40&appkey=9c9d121ac353b5c1'" }, { "alpha_fraction": 0.5574555397033691, "alphanum_fraction": 0.599179208278656, "avg_line_length": 36.52631759643555, "blob_id": "702f95fb54bc9da361fc97e8a08133807f6c8104", "content_id": "07519b00a15bb567eb4235143f9add3bd35c6719", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1462, "license_type": "no_license", "max_line_length": 72, "num_lines": 38, "path": "/src/stat/view/table.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\r\nplt.rcParams['font.family'] = ['sans-serif']\r\nplt.rcParams['font.sans-serif'] = ['SimHei']\r\n\r\ndef showMAAndATR(traits, stock):\r\n plt.subplot(2, 1, 1)\r\n showMA(traits, stock)\r\n plt.subplot(2, 1, 2)\r\n showATR(traits, stock)\r\n plt.show()\r\n\r\ndef showATR(traits, stock, autoShow=False): \r\n y1 = list(map(lambda p: p.ATR[10],traits))\r\n y2 = list(map(lambda p: p.getTrueRange(),traits))\r\n plt.plot(range(len(y1)), y1,marker='o',markersize=3,label='ATR10')\r\n plt.plot(range(len(y1)), y2, marker='*', markersize=3, label='TR')\r\n plt.legend()\r\n if (autoShow):\r\n plt.title(\"{0}({1})\".format(stock.name,stock.code))\r\n plt.show()\r\n\r\ndef showMA(traits,stock,autoShow=False):\r\n plt.title(\"{0}({1})\".format(stock.name,stock.code))\r\n y1 = list(map(lambda p: p.MA[5],traits))\r\n y2 = list(map(lambda p: p.MA[10],traits))\r\n y3 = list(map(lambda p: p.MA[20],traits))\r\n y4 = list(map(lambda p: p.MA[30],traits))\r\n y5 = list(map(lambda p: p.MA[60],traits))\r\n y6 = list(map(lambda p: p.MA[120],traits))\r\n plt.plot(range(len(y1)), y1,marker='o',markersize=3,label='MA05')\r\n plt.plot(range(len(y1)), y2,marker='*',markersize=3,label='MA10')\r\n plt.plot(range(len(y1)), y3, marker='^', markersize=3, label='MA20')\r\n plt.legend()\r\n # plt.plot(range(len(y1)), y4)\r\n # plt.plot(range(len(y1)), y5)\r\n # plt.plot(range(len(y1)), y6)\r\n if (autoShow):\r\n plt.show()" }, { "alpha_fraction": 0.6222222447395325, "alphanum_fraction": 0.6509804129600525, "avg_line_length": 25.321428298950195, "blob_id": "4a5e865584793c4fac04fa820c8c424868f50b02", "content_id": "02b2ea28b8c345f7bf851d9322be922787c7f512", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 813, "license_type": "no_license", "max_line_length": 49, "num_lines": 28, "path": "/src/stat/service/trait_service.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...db import dboper\r\nfrom ..util import trait_builder as TraitBuilder\r\nfrom . import atr_service as ATRService\r\nfrom . import ma_service as MAService\r\nimport math\r\n\r\ndef getTraits(code, days=50, N=120):\r\n '''\r\n 计算股票的汇总特征\r\n\r\n code:股票代码\r\n days:观察数据数量\r\n N:均值的天数\r\n '''\r\n dailys = dboper.getDailys(code, days + N - 1)\r\n traits=[]\r\n for daily in dailys:\r\n trait = TraitBuilder.populateTrait(daily)\r\n traits.append(trait)\r\n ATRService.calcATR(traits, 10)\r\n ATRService.calcATR(traits, 20)\r\n MAService.calcMA(traits, 5)\r\n MAService.calcMA(traits, 10)\r\n MAService.calcMA(traits, 20)\r\n MAService.calcMA(traits, 30)\r\n MAService.calcMA(traits, 60)\r\n MAService.calcMA(traits, 120)\r\n return traits[-days:]\r\n" }, { "alpha_fraction": 0.6754966974258423, "alphanum_fraction": 0.6900662183761597, "avg_line_length": 32.40909194946289, "blob_id": "fd978985cb6c9992e90fffc202363f62f1f90607", "content_id": "fbcc0fda0d8ae14b05675d7ce97c847433d8e0fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 755, "license_type": "no_license", "max_line_length": 116, "num_lines": 22, "path": "/src/logger.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "import logging\r\nimport os\r\nfrom logging.handlers import RotatingFileHandler\r\n\r\ndef init_app(app):\r\n baseDir=os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\r\n formatter = logging.Formatter('[%(asctime)s][%(levelname)s] %(filename)s--%(funcName)s(%(lineno)s):%(message)s')\r\n dir=os.path.join(baseDir,'logs')\r\n if(not os.path.exists(dir)):\r\n os.mkdir(dir)\r\n fh=RotatingFileHandler(os.path.join(dir,'mylog.log'),maxBytes=10*1024*1024,backupCount=5)\r\n fh.setLevel(logging.INFO)\r\n fh.setFormatter(formatter)\r\n currentLogger.addHandler(fh)\r\n app.logger = currentLogger\r\n\r\ndef _getLogger():\r\n logger = logging.getLogger(\"default\")\r\n logger.setLevel(logging.INFO)\r\n return logger\r\n\r\ncurrentLogger=_getLogger()" }, { "alpha_fraction": 0.645480215549469, "alphanum_fraction": 0.6581920981407166, "avg_line_length": 42.25, "blob_id": "ee51f7bb67fc6d02a968eb2e1b67ebdd3aaa3499", "content_id": "aae9767d6b823b20d2c9653645b1f73a67298eab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 238, "num_lines": 16, "path": "/src/stat/service/break_through_service.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "\r\ndef getBreakThroughPoint(traits, maFastDays, maSlowDays):\r\n '''\r\n 计算当前价格要变化到什么值能形成突破\r\n\r\n traits:汇总特征数据集合\r\n maFastDays:快线天数\r\n maSlowDays:慢线天数\r\n '''\r\n trait = traits[-2]\r\n size = len(traits)\r\n if(size>maSlowDays):\r\n return (trait.MA[maSlowDays] * maSlowDays * maFastDays - traits[-2 - maSlowDays + 1].close * maFastDays - trait.MA[maFastDays] * maFastDays * maSlowDays + traits[-2 - maFastDays + 1].close * maSlowDays) / (maSlowDays - maFastDays)\r\n elif (size > maFastDays):\r\n return (trait.MA[maSlowDays] * (size-1) *maFastDays-trait.MA[maFastDays]*maFastDays*size+traits[-2-maFastDays+1].close*size)/(size-maFastDays)\r\n else:\r\n return traits[-1].close" }, { "alpha_fraction": 0.48659002780914307, "alphanum_fraction": 0.5146871209144592, "avg_line_length": 25.964284896850586, "blob_id": "5a41e60ac93a5c33c6e3d6bf3b5e3c507fb44b9b", "content_id": "818f3afdbf415bcdeedac70bc1fb84726450f0d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 783, "license_type": "no_license", "max_line_length": 69, "num_lines": 28, "path": "/src/cron/parsers/historyParser.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...model import Daily\r\nimport re\r\nimport json\r\n\r\n\r\ndef parse(content):\r\n pattern = \"historySearchHandler\\(\\[(.*)\\]\\)\"\r\n pa = re.compile(pattern, re.S)\r\n arr = pa.findall(content)\r\n item = arr[0]\r\n item = json.loads(item)\r\n code = item[\"code\"]\r\n series = item[\"hq\"]\r\n dailys = []\r\n for d in series:\r\n daily = Daily()\r\n daily.date = d[0]\r\n daily.code = code[3:]\r\n daily.open = d[1]\r\n daily.current = d[2]\r\n daily.last_close = \"{:.2f}\".format(float(d[2]) - float(d[3]))\r\n daily.low = d[5]\r\n daily.high = d[6]\r\n daily.quantity = str(int(d[7]) * 100)\r\n daily.amount = \"{:.2f}\".format(float(d[8]) * 10000)\r\n daily.turnover = d[9]\r\n dailys.append(daily)\r\n return dailys\r\n" }, { "alpha_fraction": 0.652996838092804, "alphanum_fraction": 0.652996838092804, "avg_line_length": 26.81818199157715, "blob_id": "af7637475b707095160c90e247630ab150563107", "content_id": "91a6bd5589ee793cf8f12a720980de7b24312425", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 317, "license_type": "no_license", "max_line_length": 44, "num_lines": 11, "path": "/src/stat/util/trait_builder.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...model import Trait\r\n\r\ndef populateTrait(daily):\r\n trait = Trait()\r\n trait.date = daily.date\r\n trait.last_close=float(daily.last_close)\r\n trait.open = float(daily.open)\r\n trait.high = float(daily.high)\r\n trait.low = float(daily.low)\r\n trait.close = float(daily.current)\r\n return trait\r\n" }, { "alpha_fraction": 0.307552307844162, "alphanum_fraction": 0.42493176460266113, "avg_line_length": 29.399999618530273, "blob_id": "97d544acc1047f89d007316434e8b16d7524c1ac", "content_id": "faa1272d7d6afff46109b818dfa58c81c644b7b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1263, "license_type": "no_license", "max_line_length": 53, "num_lines": 35, "path": "/src/cron/service/add_stock_service.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...model import Stock\r\nfrom ...db import dboper\r\nfrom ...logger import currentLogger\r\n\r\ndef addStocks():\r\n stocks = [\r\n ('603288', \"海天味业\", \"sh\"),\r\n ('601012', \"隆基股份\", \"sh\"),\r\n ('600519', \"贵州茅台\", \"sh\"),\r\n ('600309', \"万华化学\", \"sh\"),\r\n ('600031', \"三一重工\", \"sh\"),\r\n ('600276', \"恒瑞医药\", \"sh\"),\r\n ('600887', \"伊利股份\", \"sh\"),\r\n ('601318', \"中国平安\", \"sh\"),\r\n ('601888', \"中国中免\", \"sh\"),\r\n ('603259', \"药明康德\", \"sh\"),\r\n ('600036', \"招商银行\", \"sh\"),\r\n ('002352', \"顺丰控股\", \"sz\"),\r\n ('002714', \"牧原股份\", \"sz\"),\r\n ('000858', \"五粮液\", \"sz\"),\r\n ('002475', \"立讯精密\", \"sz\"),\r\n ('000333', \"美的集团\", \"sz\"),\r\n ('002594', \"比亚迪\", \"sz\"),\r\n ('300015', \"爱尔眼科\", \"sz\"),\r\n ('300750', \"宁德时代\", \"sz\"),\r\n ('300760', \"迈瑞医疗\", \"sz\"),\r\n ('300059', \"东方财富\", \"sz\"),\r\n ]\r\n for item in stocks:\r\n stock = Stock()\r\n stock.code = item[0]\r\n stock.name = item[1]\r\n stock.prefix = item[2]\r\n dboper.insertStock(stock)\r\n currentLogger.info(\"add all stocks successfully\")\r\n" }, { "alpha_fraction": 0.561170220375061, "alphanum_fraction": 0.563829779624939, "avg_line_length": 19.88888931274414, "blob_id": "5a52a71f8163cb1e5e4761d5290849889ed097fa", "content_id": "44d999cab68a7de1ab86995d84147e5994a455fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 376, "license_type": "no_license", "max_line_length": 34, "num_lines": 18, "path": "/src/cron/parsers/jisuStockParser.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "import json\nfrom ...model import Stock\n\n\n\ndef parse(content):\n data = json.loads(content)\n status = data[\"status\"]\n if (status != 0):\n return None\n stocks = []\n items = data['result']['list']\n for item in items:\n stock = Stock()\n stock.code = item[\"code\"]\n stock.name = item[\"name\"]\n stocks.append(stock)\n return stocks\n" }, { "alpha_fraction": 0.7208480834960938, "alphanum_fraction": 0.7208480834960938, "avg_line_length": 45.16666793823242, "blob_id": "8cfdf427f8ee069e5cc33e6623dd4b9bb8128a07", "content_id": "b5a753099c7af5278746f5cba5390f1d98f1d6c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 283, "license_type": "no_license", "max_line_length": 168, "num_lines": 6, "path": "/cron.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from src.cron.service import add_stock_service as AddStockService, add_stocks_service as AddStocksService, add_history_service as ahs, add_current_daily_service as acds\r\n\r\nif __name__==\"__main__\":\r\n # AddStockService.addStocks()\r\n ahs.addHistoryDaily()\r\n # acds.addDaily()\r\n" }, { "alpha_fraction": 0.38633039593696594, "alphanum_fraction": 0.42105263471603394, "avg_line_length": 32.9487190246582, "blob_id": "a45ad64624f18c98aa4bd8bb7e2968bca71dee8d", "content_id": "2b1f43df722946b68d762c3908f0848d59bb4b3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2746, "license_type": "no_license", "max_line_length": 75, "num_lines": 78, "path": "/src/db/__init__.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ..settings import configs\r\nimport os\r\nimport sqlite3\r\nfrom ..logger import currentLogger\r\n\r\n\r\ndef init_app(app):\r\n DB_NAME = app.config[\"SQLALCHEMY_DATABASE_URI\"]\r\n currentLogger.info(\"DB is {0}\".format(DB_NAME))\r\n if not os.path.exists(DB_NAME):\r\n # 创建数据库\r\n createdb(DB_NAME)\r\n else:\r\n currentLogger.warn(\"{0} has already been existing\".format(DB_NAME))\r\n\r\ndef createdb(dbName):\r\n try:\r\n conn = sqlite3.connect(dbName)\r\n cur = conn.cursor()\r\n cur.execute(\r\n '''\r\n CREATE TABLE stock (\r\n code VARCHAR (10) PRIMARY KEY NOT NULL,\r\n name VARCHAR (10) NOT NULL,\r\n prefix VARCHAR (6) DEFAULT ('sh'),\r\n update_at VARCHAR (20),\r\n type INTEGER DEFAULT(1)\r\n );\r\n ''')\r\n cur.execute(\r\n '''\r\n CREATE TABLE daily (\r\n code VARCHAR (10) NOT NULL,\r\n date VARCHAR (18) NOT NULL,\r\n open VARCHAR (12),\r\n last_close VARCHAR (12),\r\n current VARCHAR (12),\r\n high VARCHAR (12),\r\n low VARCHAR (12),\r\n quantity VARCHAR (20),\r\n amount VARCHAR (30),\r\n bid1 VARCHAR (12),\r\n bid1_amount VARCHAR (20),\r\n bid2 VARCHAR (12),\r\n bid2_amount VARCHAR (20),\r\n bid3 VARCHAR (12),\r\n bid3_amount VARCHAR (20),\r\n bid4 VARCHAR (12),\r\n bid4_amount VARCHAR (20),\r\n bid5 VARCHAR (12),\r\n bid5_amount VARCHAR (20),\r\n ask1 VARCHAR (12),\r\n ask1_amount VARCHAR (20),\r\n ask2 VARCHAR (12),\r\n ask2_amount VARCHAR (20),\r\n ask3 VARCHAR (12),\r\n ask3_amount VARCHAR (20),\r\n ask4 VARCHAR (12),\r\n ask4_amount VARCHAR (20),\r\n ask5 VARCHAR (12),\r\n ask5_amount VARCHAR (20),\r\n update_at VARCHAR (20) NOT NULL,\r\n turnover VARCHAR (10),\r\n CONSTRAINT pk_code_date PRIMARY KEY (\r\n code,\r\n date\r\n )\r\n );\r\n ''')\r\n conn.commit()\r\n currentLogger.info(\"{0} has been created\".format(dbName))\r\n except Exception as e:\r\n currentLogger.error('%s',e)\r\n finally:\r\n if cur!=None:\r\n cur.close()\r\n if conn!=None:\r\n conn.close()\r\n \r\n" }, { "alpha_fraction": 0.5915221571922302, "alphanum_fraction": 0.6281310319900513, "avg_line_length": 23.950000762939453, "blob_id": "2a946405e6c7c85ee4e87060fed4ccdfc3f80450", "content_id": "8572de11e03f8efbdb91688395493490c70c062d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 527, "license_type": "no_license", "max_line_length": 69, "num_lines": 20, "path": "/test.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from src.stat.controller import break_point as bp, stock_filter as sf\r\nfrom src.stat.view import trends, single_atr_view, single_ma_view\r\nfrom src.model import Stock\r\n\r\nif __name__ == \"__main__\":\r\n # Test1\r\n # bp.ShowBreakThroughPoint('300760')\r\n\r\n # Test2\r\n result = sf.selectStock(days=10,breakDays=3)\r\n print(result)\r\n\r\n # Test3\r\n # stock = Stock()\r\n # stock.code = '300760'\r\n # stock.name=\"迈瑞医疗\"\r\n # single_ma_view.ShowSingleMA(stock)\r\n\r\n # Test4\r\n # trends.showCurrentTrends()\r\n" }, { "alpha_fraction": 0.6113360524177551, "alphanum_fraction": 0.6194332242012024, "avg_line_length": 39.16666793823242, "blob_id": "7cd4f7e929ab31e79d19403e2780e09b1fa4ca7a", "content_id": "4b5c1dd97df394ff8c7fdd5d9b839bf8713eeda0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "no_license", "max_line_length": 97, "num_lines": 12, "path": "/src/stat/policies/ma_policy.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "\n\ndef isTarget(traits,totalDays,breakDays=2,maFastDays=5,maSlowDays=10):\n n = len(traits)\n if (totalDays < breakDays):\n return False\n start=n-totalDays\n for i in range(totalDays - breakDays):\n if (traits[start+i].MA[maFastDays] > traits[start+i].MA[maSlowDays]):\n return False\n for i in range(breakDays):\n if (traits[n - breakDays + i].MA[maFastDays] < traits[n - breakDays + i].MA[maSlowDays]):\n return False\n return True\n\n \n" }, { "alpha_fraction": 0.6099518537521362, "alphanum_fraction": 0.6308186054229736, "avg_line_length": 30.789474487304688, "blob_id": "140737906ec82eaeb9793949a2114aa2c633f243", "content_id": "1587f554210e819e87d64e67fd91d7bdf7b42a8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 87, "num_lines": 19, "path": "/src/stat/controller/break_point.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ..service import trait_service as TraitService, break_through_service as btService\r\nfrom .. import stat_bp\r\nfrom flask import jsonify\r\n\r\n\r\n@stat_bp.route(\"/breakpoints/<code>\", methods=['GET','POST'])\r\ndef ShowBreakThroughPoint(code):\r\n traits = TraitService.getTraits(code)\r\n # 估计当天短线突破长线的当前价格\r\n btp = btService.getBreakThroughPoint(traits, 5, 10)\r\n lastTrait = traits[-1]\r\n print(lastTrait)\r\n return jsonify({\r\n \"code\": code,\r\n \"date\": lastTrait.date,\r\n \"ma5\": round(lastTrait.MA[5], 3),\r\n \"ma10\": round(lastTrait.MA[10], 3),\r\n \"target\":round(btp,3)\r\n })\r\n" }, { "alpha_fraction": 0.5681062936782837, "alphanum_fraction": 0.5813953280448914, "avg_line_length": 25.52941131591797, "blob_id": "764e9bfccd1a6f60cd52c4668b6b0676f80cf239", "content_id": "c530d48de99184fee6e878a5d08baaf6ca19c2ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 917, "license_type": "no_license", "max_line_length": 60, "num_lines": 34, "path": "/src/model/errors.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from werkzeug.exceptions import HTTPException\nimport json\n\nclass APIException(HTTPException):\n code = 200\n error_code = 999\n msg = \"unknown error\"\n\n def __init__(self,error_code=None, msg=None, code=None):\n if (code):\n self.code = code\n if (msg):\n self.msg = msg\n if (error_code):\n self.error_code = error_code\n super(APIException, self).__init__(self.msg,None)\n \n def get_body(self, environ=None):\n body = dict(\n msg=self.msg,\n error_code=self.error_code)\n return json.dumps(body)\n \n def get_headers(self, environ=None):\n \"\"\"Get a list of headers.\"\"\"\n return [('Content-Type', 'application/json')]\n \nclass NoFound(APIException):\n error_code = 404\n msg = \"当前地址不存在\"\n\nclass ServerError(APIException):\n msg = 'sorry, we made a mistake!'\n error_code = 999 " }, { "alpha_fraction": 0.472945898771286, "alphanum_fraction": 0.48697394132614136, "avg_line_length": 22.75, "blob_id": "abd23525d3deba536a4024a6b8cc3aa9cb7e8b29", "content_id": "dbb949a5588c61fc2c39d16613f1e09bf954c6fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 537, "license_type": "no_license", "max_line_length": 65, "num_lines": 20, "path": "/src/stat/service/ma_service.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "\r\n\r\ndef calcMA(traits, N=5):\r\n '''\r\n 计算N日均线值\r\n\r\n traits:汇总特征数据集合\r\n N:均值的天数\r\n '''\r\n result=[]\r\n total = 0.0\r\n slowIndex = 0\r\n fastIndex = 0\r\n for fastIndex in range(len(traits)):\r\n trait=traits[fastIndex]\r\n if (fastIndex < N):\r\n total += trait.close\r\n trait.MA[N] = total / (fastIndex + 1)\r\n else:\r\n total = total - traits[slowIndex].close + trait.close\r\n trait.MA[N]=total/N\r\n slowIndex += 1\r\n" }, { "alpha_fraction": 0.5418060421943665, "alphanum_fraction": 0.5501672029495239, "avg_line_length": 30.37837791442871, "blob_id": "0a116dc6631ebecf0cab5d16b210f0ab7b012d44", "content_id": "96a455f8833515398c923e311d97684c3a54b8d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1228, "license_type": "no_license", "max_line_length": 94, "num_lines": 37, "path": "/src/settings.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "import os, sys\r\n\r\n\r\nbaseDir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\r\n\r\nclass BaseConfig(object):\r\n CSRF_ENABLED=True\r\n SECRET_KEY = os.getenv('SECRET_KEY', 'Zench')\r\n CACHE_TYPE='simple'\r\n SQLALCHEMY_TRACK_MODIFICATIONS = False\r\n JOBS = [\r\n {\r\n 'id': 'job1', \r\n 'func': 'src.cron:job1', \r\n 'args': None, \r\n 'trigger': 'cron', # 指定任务触发器 cron\r\n 'day_of_week': 'mon-fri', # 每周1至周5下午16点执行 \r\n 'hour': '15',\r\n 'minute': '10' \r\n }\r\n ]\r\n SCHEDULER_API_ENABLED = True\r\n\r\nclass DevelopmentConfig(BaseConfig):\r\n SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI', os.path.join(baseDir, 'stock_dev.db'))\r\n \r\nclass TestConfig(BaseConfig):\r\n SQLALCHEMY_DATABASE_URI=os.getenv('DATABASE_URI', os.path.join(baseDir,'stock_test.db'))\r\n\r\nclass ProductionConfig(BaseConfig):\r\n SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URI', os.path.join(baseDir, 'stock.db'))\r\n\r\nconfigs={\r\n 'development':DevelopmentConfig,\r\n 'test':TestConfig,\r\n 'production':ProductionConfig\r\n}" }, { "alpha_fraction": 0.5703421831130981, "alphanum_fraction": 0.5703421831130981, "avg_line_length": 25.399999618530273, "blob_id": "ff85ff272cb83a0cfaa1e42c10b159c8c3c0133d", "content_id": "a36218fd083f8de51ba5cb3cf45968793f50ba4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 263, "license_type": "no_license", "max_line_length": 41, "num_lines": 10, "path": "/src/tools/serializer.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from json import JSONDecoder, JSONEncoder\n\nclass DHLEncoder(JSONEncoder):\n def default(self,obj):\n d = {}\n tmp=obj.__dict__\n if ('_sa_instance_state' in tmp):\n tmp.pop('_sa_instance_state')\n d.update(tmp)\n return d" }, { "alpha_fraction": 0.7023809552192688, "alphanum_fraction": 0.7023809552192688, "avg_line_length": 19.5, "blob_id": "a7bd09a6216a14ab6f3479b3fc0e792f47b65f23", "content_id": "21dec516d8912e7683358f81788062fbee1da2df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 84, "license_type": "no_license", "max_line_length": 35, "num_lines": 4, "path": "/src/routers.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from .stat import stat_bp\r\n\r\ndef init_app(app):\r\n app.register_blueprint(stat_bp)" }, { "alpha_fraction": 0.6419098377227783, "alphanum_fraction": 0.6516357064247131, "avg_line_length": 34.45161437988281, "blob_id": "dadfeef2ea568d67f20b7e89adf4cdc64fa919a7", "content_id": "fc83636272434389f06e93a11881bfa3c2ac481c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1171, "license_type": "no_license", "max_line_length": 120, "num_lines": 31, "path": "/src/stat/controller/stock_filter.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...db import dboper\r\nfrom ..util import trait_builder as TraitBuilder\r\nfrom ..service import ma_service as MAService\r\nfrom ..policies import ma_policy as MAPolicy\r\nfrom .. import stat_bp\r\nfrom flask import jsonify\r\n\r\n\r\n@stat_bp.route(\"/stocks/<int:days>/<int:breakDays>\", methods=['GET','POST'])\r\ndef selectStock(days=20,breakDays=1,maFastDays=5,maSlowDays=10):\r\n '''\r\n days:比较的天数\r\n breakDays:快线突破慢线的天数\r\n maFastDays:5日均线\r\n maSlowDays:10日均线\r\n '''\r\n results=[]\r\n stocks = dboper.getStocks()\r\n for stock in stocks:\r\n dailys = dboper.getDailys(stock.code, maSlowDays + days - 1)\r\n traits = []\r\n for daily in dailys:\r\n trait = TraitBuilder.populateTrait(daily)\r\n traits.append(trait)\r\n if (len(traits) < maSlowDays + days - 1):\r\n continue\r\n MAService.calcMA(traits, maFastDays)\r\n MAService.calcMA(traits, maSlowDays)\r\n if (MAPolicy.isTarget(traits,totalDays=days,breakDays=breakDays, maFastDays=maFastDays, maSlowDays=maSlowDays)):\r\n results.append({stock.code: stock.name})\r\n return jsonify(data=results)\r\n " }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6701570749282837, "avg_line_length": 31.823530197143555, "blob_id": "9ab039b35b65ee476faa87febdd6464e317244ab", "content_id": "dfb1c31aa5c580d481bf9e9b7bfc1384471e27bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 573, "license_type": "no_license", "max_line_length": 95, "num_lines": 17, "path": "/src/cron/service/add_stocks_service.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "import requests\r\nfrom ...constant import urls\r\nfrom ...db import dboper\r\nfrom ..parsers import jisuStockParser\r\nfrom ...logger import currentLogger\r\n\r\ndef getStocks(pageNum):\r\n url=urls.JISU_STOCK_URL.format(pageNum)\r\n resp = requests.get(url)\r\n content = resp.text\r\n stocks = jisuStockParser.parse(content)\r\n if (stocks != None):\r\n for stock in stocks:\r\n dboper.insertStock(stock)\r\n currentLogger.info(\"page {0}, total {1} data are inserted\".format(pageNum,len(stocks)))\r\n else:\r\n currentLogger.info(\"No stocks to insert\")" }, { "alpha_fraction": 0.4626006782054901, "alphanum_fraction": 0.5420023202896118, "avg_line_length": 22.828571319580078, "blob_id": "98048836e97f3dfa22174f6327d11282e60faad3", "content_id": "9e6b31097f3ae9236d1fa3449743ce61faa7d8d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 869, "license_type": "no_license", "max_line_length": 29, "num_lines": 35, "path": "/src/cron/parsers/dailyPriceParser.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...model import Daily\r\n\r\n\r\ndef parse(content):\r\n d = content.split(\",\")\r\n daily = Daily()\r\n daily.open = d[1]\r\n daily.last_close = d[2]\r\n daily.current = d[3]\r\n daily.high = d[4]\r\n daily.low = d[5]\r\n daily.quantity = d[8]\r\n daily.amount = d[9]\r\n daily.bid1_amount = d[10]\r\n daily.bid1 = d[11]\r\n daily.bid2_amount = d[12]\r\n daily.bid2 = d[13]\r\n daily.bid3_amount = d[14]\r\n daily.bid3 = d[15]\r\n daily.bid4_amount = d[16]\r\n daily.bid4 = d[17]\r\n daily.bid5_amount = d[18]\r\n daily.bid5 = d[19]\r\n daily.ask1_amount = d[20]\r\n daily.ask1 = d[21]\r\n daily.ask2_amount = d[22]\r\n daily.ask2 = d[23]\r\n daily.ask3_amount = d[24]\r\n daily.ask3 = d[25]\r\n daily.ask4_amount = d[26]\r\n daily.ask4 = d[27]\r\n daily.ask5_amount = d[28]\r\n daily.ask5 = d[29]\r\n daily.date = d[30]\r\n return daily\r\n" }, { "alpha_fraction": 0.62770015001297, "alphanum_fraction": 0.6340533494949341, "avg_line_length": 30.79166603088379, "blob_id": "dc19202e707d2ef713fe31708b0a1f5482b2b0a8", "content_id": "06fa7b8ed4a5a69fbbe0e2a6d8e8cbec51905a7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "no_license", "max_line_length": 78, "num_lines": 24, "path": "/src/cron/service/add_current_daily_service.py", "repo_name": "danghualong/stock", "src_encoding": "UTF-8", "text": "from ...constant import urls\r\nfrom ...db import dboper\r\nfrom ..parsers import dailyPriceParser\r\nfrom ...logger import currentLogger\r\nimport requests\r\n\r\ndef addDaily():\r\n stocks = dboper.getStocks()\r\n if (stocks is None or len(stocks)<=0):\r\n currentLogger.warn(\"no stock fetched\")\r\n return\r\n for stock in stocks:\r\n daily = _getDetail(\"{0}{1}\".format(stock.prefix, stock.code))\r\n daily.code = stock.code\r\n dboper.insertDaily(daily, True)\r\n currentLogger.info(\"----------{0}:{1} insert one daily record\".format(\r\n stock.code, stock.name))\r\n\r\ndef _getDetail(code):\r\n url = urls.DAILY_PRICE_URL.format(code)\r\n resp = requests.get(url)\r\n content = resp.text\r\n daily = dailyPriceParser.parse(content)\r\n return daily\r\n" } ]
38
rlivermorejr/rot13-python
https://github.com/rlivermorejr/rot13-python
6ab2d4c4ee03e8da3eda66d4e4a8fd1d7678e88f
06f5867ae42e009d45de80558b6303a47eb99a6f
a81976d6511017b7b3033dc792ba39f21f9aa774
refs/heads/main
2023-05-15T05:04:26.896067
2021-06-06T19:34:44
2021-06-06T19:34:44
374,441,823
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.5036496520042419, "alphanum_fraction": 0.5224192142486572, "avg_line_length": 21.83333396911621, "blob_id": "2e36595ebeb9bff289a9ff3436757966f985691a", "content_id": "25bac29e99b36eec8292c91d5509b20109851c86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 959, "license_type": "no_license", "max_line_length": 57, "num_lines": 42, "path": "/rot13.py", "repo_name": "rlivermorejr/rot13-python", "src_encoding": "UTF-8", "text": "import sys\nfrom string import ascii_lowercase, ascii_uppercase\n\n\ndef rotate(message):\n \"\"\"\n Returns the encoded or decoded message.\n \"\"\"\n rot_message = ''\n lower = ascii_lowercase\n upper = ascii_uppercase\n for x in message:\n if x in lower:\n if lower.index(x) < 13:\n rot_message += lower[lower.index(x) + 13]\n else:\n rot_message += lower[lower.index(x) - 13]\n elif x in upper:\n if upper.index(x) < 13:\n rot_message += upper[upper.index(x) + 13]\n else:\n rot_message += upper[upper.index(x) - 13]\n else:\n rot_message += x\n\n return rot_message\n\n\ndef main(args):\n \"\"\"Main program code.\"\"\"\n if len(args) != 1:\n print('usage: python rot13.py message')\n sys.exit(1)\n\n message = sys.argv[1]\n\n rot = rotate(message)\n print(rot)\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n" }, { "alpha_fraction": 0.6000000238418579, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 14, "blob_id": "dad3ad2d7ba0ea0a553693cb0ed89bc79b0f068a", "content_id": "bbbbe46ac767fb885cbdebb96166594b12f9076b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15, "license_type": "no_license", "max_line_length": 14, "num_lines": 1, "path": "/README.md", "repo_name": "rlivermorejr/rot13-python", "src_encoding": "UTF-8", "text": "# rot13-python\n" } ]
2
GreyZmeem/habr-proxy
https://github.com/GreyZmeem/habr-proxy
7b57063740b7d13ab93fcb03b1c35441d7d7c5c8
c1c32c6e46603daff83d6bc610e351b504720991
fb1d2bbd4088becdbc396c78a66a5f57b6a2e3ee
refs/heads/master
2021-07-05T07:03:31.117082
2021-04-14T13:53:08
2021-04-14T13:53:08
228,168,456
0
0
null
2019-12-15T10:48:30
2021-04-14T13:48:10
2021-04-14T13:48:08
Python
[ { "alpha_fraction": 0.5346638560295105, "alphanum_fraction": 0.5399159789085388, "avg_line_length": 21.399999618530273, "blob_id": "1ede19792f2fa89561a058e638e6bf65ac7a4eeb", "content_id": "3a08735c47af3d3d4e61025400e53194f52aee34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1904, "license_type": "no_license", "max_line_length": 57, "num_lines": 85, "path": "/main.py", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom argparse import ArgumentParser\nfrom typing import Final\n\nfrom aiohttp import web\nfrom app.application import AppConfig, create_app\nfrom app.proxy import const\n\n_host: Final[str] = \"0.0.0.0\"\n_port: Final[int] = 8080\n\n\ndef get_parser() -> ArgumentParser:\n \"\"\"Build argument parser.\"\"\"\n parser = ArgumentParser(description=\"iVelum proxy\")\n parser.add_argument(\n \"-l\",\n \"--len\",\n nargs=\"?\",\n type=int,\n const=const.word_length,\n default=const.word_length,\n help=\"Word length\",\n dest=\"word_length\",\n )\n parser.add_argument(\n \"-t\",\n \"--text\",\n nargs=\"?\",\n type=str,\n const=const.word_append,\n default=const.word_append,\n help=\"Text appended to words\",\n dest=\"word_append\",\n )\n parser.add_argument(\n \"-u\",\n \"--up\",\n \"--upstream\",\n nargs=\"?\",\n type=str,\n const=const.upstream,\n default=const.upstream,\n help=\"Upstream URL (e.g. 'https://example.com')\",\n dest=\"upstream\",\n )\n parser.add_argument(\n \"--host\",\n nargs=\"?\",\n type=str,\n const=_host,\n default=_host,\n help=\"HTTP server listen address\",\n dest=\"host\",\n )\n parser.add_argument(\n \"--port\",\n nargs=\"?\",\n type=int,\n const=_port,\n default=_port,\n help=\"HTTP server listen port\",\n dest=\"port\",\n )\n return parser\n\n\ndef run():\n \"\"\"Run main application server.\"\"\"\n parser = get_parser()\n args = parser.parse_args()\n\n app_config = AppConfig(\n upstream=args.upstream,\n length=args.word_length,\n append=args.word_append,\n )\n app = create_app(app_config)\n web.run_app(app, host=args.host, port=args.port)\n\n\nif __name__ == \"__main__\":\n run() # type: ignore\n" }, { "alpha_fraction": 0.6508538722991943, "alphanum_fraction": 0.6717267632484436, "avg_line_length": 20.079999923706055, "blob_id": "f32f11c2e5e057c926f5ab310e6c3c54e32804f9", "content_id": "d2330f160bb87a1b8c8a628f6d4fbca1fa8652bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 527, "license_type": "no_license", "max_line_length": 92, "num_lines": 25, "path": "/docker/Dockerfile", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "FROM python:3.8.0-alpine3.10\n\nRUN apk --no-cache add \\\n ca-certificates \\\n curl \\\n build-base \\\n gcc \\\n git \\\n libxml2-dev \\\n libxslt-dev \\\n openssl \\\n musl-dev\nRUN curl https://raw.githubusercontent.com/kennethreitz/pipenv/master/get-pipenv.py | python\n\nWORKDIR /app\nCOPY ./Pipfile ./Pipfile.lock /app/\nRUN pipenv sync\n\nCOPY ./docker/entry.sh /docker-entrypoint.sh\nRUN chmod +x \"/docker-entrypoint.sh\"\nENTRYPOINT [\"/docker-entrypoint.sh\"]\nEXPOSE 8080\nCMD [\"pipenv\", \"run\", \"./main.py\"]\n\nCOPY . /app\n" }, { "alpha_fraction": 0.6807377338409424, "alphanum_fraction": 0.6811475157737732, "avg_line_length": 31.972972869873047, "blob_id": "7491f6ba2462442d173ec18ad60c552fde278b3a", "content_id": "766b5a1360d6f48b1988a3d3e5e134d2b5a80e8e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2440, "license_type": "no_license", "max_line_length": 76, "num_lines": 74, "path": "/app/application.py", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport dataclasses\n\nfrom aiohttp import web\nfrom app.proxy.config import Config, Patcher\nfrom app.proxy.patcher_ivelum import IVelumPatcher, IVelumPatcherConfig\nfrom app.proxy.proxy import Proxy\nfrom app.proxy.req_resp import Request, Response\n\n\[email protected](frozen=True)\nclass AppConfig(object):\n \"\"\"AioHTTP application configuration.\"\"\"\n\n #: Proxied resource (e.g. `https://habr.com`).\n upstream: str\n #: Length of words to patch.\n length: int\n #: String which must be appended to the matched words.\n append: str\n\n\ndef create_app(config: AppConfig) -> web.Application:\n \"\"\"Create AioHTTP application.\"\"\"\n proxy_patcher_config = IVelumPatcherConfig(config.length, config.append)\n proxy_patcher = IVelumPatcher(proxy_patcher_config)\n proxy_config = Config(\"\", config.upstream, proxy_patcher)\n proxy_handler = ProxyHandler(proxy_patcher, proxy_config)\n\n app = web.Application()\n app.add_routes([\n web.get(\"/{tail:.*}\", proxy_handler.dispatch),\n ])\n return app\n\n\nclass ProxyHandler(object):\n \"\"\"Wildcard handler which sends all requests through proxy.\"\"\"\n\n def __init__(self, proxy_patcher: Patcher, proxy_config: Config):\n self.proxy_patcher = proxy_patcher\n self.proxy_config = proxy_config\n\n async def dispatch(self, request: web.Request) -> web.Response:\n \"\"\"Handle HTTP request.\"\"\"\n proxy = self._proxy(request)\n proxy_request = await _aio_to_proxy(request)\n proxy_response = await proxy.dispatch(proxy_request)\n return await _proxy_to_aio(proxy_response)\n\n def _proxy(self, request: web.Request) -> Proxy:\n \"\"\"Create proxy instance for the given request.\"\"\"\n host = f\"{request.scheme}://{request.host}\"\n config = dataclasses.replace(self.proxy_config, host=host)\n return Proxy(config)\n\n\nasync def _aio_to_proxy(request: web.Request) -> Request:\n \"\"\"Build proxy request instance from aiohttp request.\"\"\"\n url = str(request.url)\n body = await request.read()\n headers = tuple(request.headers.items())\n return Request(url, request.method, headers=headers, body=body)\n\n\nasync def _proxy_to_aio(response: Response) -> web.Response:\n \"\"\"Build aiohttp response instance from proxy response.\"\"\"\n headers = dict(response.headers)\n return web.Response(\n body=response.body,\n status=response.status,\n headers=headers,\n )\n" }, { "alpha_fraction": 0.5625, "alphanum_fraction": 0.5711206793785095, "avg_line_length": 22.794872283935547, "blob_id": "a6c228a739acebe38628ce81cfc4c7e1af2fb5cc", "content_id": "1f3f929eb879eb7cee626a4418d92ea9ac969baf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 928, "license_type": "no_license", "max_line_length": 105, "num_lines": 39, "path": "/README.md", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "iVelum Proxy\n=================\n\nCode challenge \nhttps://github.com/ivelum/job/blob/master/code_challenges/python.md\n\n***Build***\n```bash\ndocker build -t habr-proxy -f docker/Dockerfile .\n```\n\n***Available options***\n\n```bash\ndocker run -it --rm habr-proxy -h\n```\n\n```\nusage: main.py [-h] [-l [WORD_LENGTH]] [-t [WORD_APPEND]] [-u [UPSTREAM]] [--host [HOST]] [--port [PORT]]\n\niVelum proxy\n\noptional arguments:\n -h, --help show this help message and exit\n -l [WORD_LENGTH], --len [WORD_LENGTH]\n Word length\n -t [WORD_APPEND], --text [WORD_APPEND]\n Text appended to words\n -u [UPSTREAM], --up [UPSTREAM], --upstream [UPSTREAM]\n Upstream URL (e.g. 'https://example.com')\n --host [HOST] HTTP server listen address\n --port [PORT] HTTP server listen port\n```\n\n***Run proxy***\n\n```bash\ndocker run -it --rm -p 8080:8080 habr-proxy\n```\n" }, { "alpha_fraction": 0.6188119053840637, "alphanum_fraction": 0.6208745837211609, "avg_line_length": 31.31999969482422, "blob_id": "fc6045d3247892f7072c2a84cc56aa36b523e0a1", "content_id": "ba3dcf229bb9043687377d95f23924ad5344fbb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2424, "license_type": "no_license", "max_line_length": 78, "num_lines": 75, "path": "/app/proxy/patcher_ivelum.py", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport dataclasses\nimport itertools\nimport unicodedata\nfrom typing import Iterable, Optional, Set\n\nfrom app.proxy.config import ReqResp, SrcDst\nfrom app.proxy.patcher_default import DefaultPatcher\nfrom bs4 import BeautifulSoup\nfrom bs4.element import NavigableString, Tag\nfrom nltk import wordpunct_tokenize\n\n\[email protected](frozen=True)\nclass IVelumPatcherConfig(object):\n \"\"\"Configuration for the `IVelumPatcher` service.\"\"\"\n\n #: Length of words to patch.\n words_length: int\n #: String which must be appended to the matched words.\n append: str\n\n\nclass IVelumPatcher(DefaultPatcher):\n \"\"\"Patcher implementation for iVelum code challenge.\"\"\"\n\n #: Form of unicode normalization.\n unicode_form: str = \"NFKC\"\n #: Skip patching these tags.\n skip_tags: Set[str] = {\"script\", \"style\"}\n\n def __init__(self, config: IVelumPatcherConfig):\n self.config = config\n\n def patch_body(self, req_resp: ReqResp, hosts: SrcDst) -> Optional[bytes]:\n \"\"\"Iterate over all tags changing its text.\"\"\"\n if not self.must_patch_body(req_resp):\n return req_resp.body\n\n body = super().patch_body(req_resp, hosts)\n text = body.decode(\"utf-8\") # type: ignore\n\n html = BeautifulSoup(text, \"lxml\")\n for tag in html.find_all(name=True):\n if tag.name not in self.skip_tags:\n self.patch_tag(tag)\n\n return html.encode(\"utf-8\")\n\n def patch_tag(self, tag: Tag):\n \"\"\"Patch single tag's text.\"\"\"\n for child_tag in tag.children:\n if not isinstance(child_tag, NavigableString):\n continue\n if child_tag.parent != tag:\n continue\n self.patch_navigable_string(child_tag)\n\n def patch_navigable_string(self, nav_string: NavigableString):\n \"\"\"Replace navigable string tag with a patched text.\"\"\"\n text = unicodedata.normalize(self.unicode_form, nav_string)\n split = ((wordpunct_tokenize(word), \" \") for word in text.split())\n words: Iterable[str] = itertools.chain(*list(\n itertools.chain(*split),\n ))\n words = (\n (\n f\"{word}{self.config.append}\"\n if len(word) == self.config.words_length\n else word\n )\n for word in words\n )\n nav_string.replace_with(NavigableString(\"\".join(words)))\n" }, { "alpha_fraction": 0.594427227973938, "alphanum_fraction": 0.6000562906265259, "avg_line_length": 33.49514389038086, "blob_id": "ee3117cfa7b6f5762bc7254886c309093b5ce96f", "content_id": "b09b50147b1bde9ee87d80785bc7ac32739649c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3553, "license_type": "no_license", "max_line_length": 80, "num_lines": 103, "path": "/app/proxy/patcher_default.py", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport dataclasses\nfrom http import HTTPStatus\nfrom typing import List, Optional, overload\nfrom urllib.parse import ParseResult, urlparse\n\nfrom app.proxy import const\nfrom app.proxy.config import Patcher, ReqResp, SrcDst\nfrom app.proxy.req_resp import Header, Headers, Request, Response\nfrom multidict import CIMultiDict\n\n\n# noinspection PyMethodMayBeStatic\nclass DefaultPatcher(Patcher): # noqa: WPS214\n \"\"\"Default patcher implementation.\"\"\"\n\n remove_headers = const.remove_headers\n\n @overload\n def __call__(\n self,\n req_resp: Request,\n hosts: SrcDst,\n ) -> Request:\n \"\"\"Patch HTTP request.\"\"\"\n\n @overload\n def __call__( # noqa: F811\n self,\n req_resp: Response,\n hosts: SrcDst,\n ) -> Response:\n \"\"\"Patch HTTP response.\"\"\"\n\n def __call__( # noqa: F811\n self,\n req_resp: ReqResp,\n hosts: SrcDst,\n ) -> ReqResp:\n \"\"\"Patch HTTP request / response objects.\"\"\"\n kwargs = {\n \"headers\": self.patch_headers(req_resp, hosts),\n \"body\": self.patch_body(req_resp, hosts),\n }\n if isinstance(req_resp, Request):\n kwargs[\"url\"] = self.patch_url(req_resp, hosts) # type: ignore\n if isinstance(req_resp, Response):\n if req_resp.status == HTTPStatus.PERMANENT_REDIRECT.value:\n kwargs[\"status\"] = HTTPStatus.FOUND.value # type: ignore\n return dataclasses.replace(req_resp, **kwargs)\n\n def patch_headers(self, req_resp: ReqResp, hosts: SrcDst) -> Headers:\n \"\"\"Patch HTTP request / response headers.\"\"\"\n new_headers: List[Header] = []\n for header_name, header_value in req_resp.headers:\n header_name = header_name.lower()\n if header_name in self.remove_headers:\n continue\n new_header = self.patch_header((header_name, header_value), hosts)\n new_headers.append(new_header)\n return tuple(new_headers)\n\n def patch_header(self, header: Header, hosts: SrcDst) -> Header:\n \"\"\"Patch single HTTP header.\"\"\"\n src: ParseResult = urlparse(hosts[0])\n dst: ParseResult = urlparse(hosts[1])\n header_name, header_value = header\n header_value = header_value.replace(\n src.scheme or \"http\",\n dst.scheme or \"http\",\n )\n header_value = header_value.replace(\n src.netloc,\n dst.netloc,\n )\n return header_name, header_value\n\n def patch_url(self, req: Request, hosts: SrcDst) -> str:\n \"\"\"Patch HTTP request url.\"\"\"\n dst: ParseResult = urlparse(hosts[1])\n url: ParseResult = urlparse(req.url)\n url = url._replace(scheme=dst.scheme, netloc=dst.netloc) # noqa: WPS437\n return url.geturl()\n\n def patch_body(self, req_resp: ReqResp, hosts: SrcDst) -> Optional[bytes]:\n \"\"\"Patch HTTP request / response body.\"\"\"\n if not self.must_patch_body(req_resp):\n return req_resp.body\n body = req_resp.body.decode(\"utf-8\") # type: ignore\n body = body.replace(hosts[0], hosts[1])\n return body.encode(\"utf-8\")\n\n def must_patch_body(self, req_resp: ReqResp) -> bool:\n \"\"\"Check if request or response body must be patched.\"\"\"\n if not req_resp.body:\n return False\n\n content_type = CIMultiDict(req_resp.headers).get(\"content-type\")\n if not content_type or not content_type.lower().startswith(\"text/html\"):\n return False\n\n return True\n" }, { "alpha_fraction": 0.6641509532928467, "alphanum_fraction": 0.6654087901115417, "avg_line_length": 21.714284896850586, "blob_id": "8f16a0b04c7063ca8bb40e3e575dc58ede89e15e", "content_id": "95193a8f8e163de72962d7bed5803a9f4ac15fa8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 795, "license_type": "no_license", "max_line_length": 51, "num_lines": 35, "path": "/app/proxy/req_resp.py", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom dataclasses import dataclass, field\nfrom http import HTTPStatus\nfrom typing import Optional, Set, Tuple\n\nHeader = Tuple[str, str]\nHeaders = Tuple[Header, ...]\nHeaderNames = Set[str]\n\n\n@dataclass(frozen=True)\nclass Request(object):\n \"\"\"HTTP request.\"\"\"\n\n #: Requested URL.\n url: str\n #: HTTP request method.\n method: str\n #: HTTP request headers.\n headers: Headers = field(default_factory=tuple)\n #: HTTP request body.\n body: Optional[bytes] = None\n\n\n@dataclass(frozen=True)\nclass Response(object):\n \"\"\"HTTP response.\"\"\"\n\n #: HTTP response headers.\n headers: Headers = field(default_factory=tuple)\n #: HTTP response status code.\n status: int = HTTPStatus.OK.value\n #: HTTP response body.\n body: Optional[bytes] = None\n" }, { "alpha_fraction": 0.41874998807907104, "alphanum_fraction": 0.4437499940395355, "avg_line_length": 15, "blob_id": "804b81af4188726939a2ad95a31eebbb5f90cdbf", "content_id": "c9c30af42332246e05250e1f28f6faa4b368fd33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 160, "license_type": "no_license", "max_line_length": 61, "num_lines": 10, "path": "/docker/entry.sh", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "#!/usr/bin/env sh\n\nset -o errexit\nset -o nounset\n\nif [[ \"${1#-}\" != \"$1\" ]] || [[ \"${1%.conf}\" != \"$1\" ]]; then\n\tset -- pipenv run ./main.py \"$@\"\nfi\n\nexec \"$@\"\n" }, { "alpha_fraction": 0.5975039005279541, "alphanum_fraction": 0.6107644438743591, "avg_line_length": 22.740739822387695, "blob_id": "2f23e946a463905d0aba50940e8a34136c2866a0", "content_id": "cad87f4e4481e525f1cff9222141d57e1e70b4ca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1282, "license_type": "no_license", "max_line_length": 78, "num_lines": 54, "path": "/app/proxy/config.py", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport abc\nfrom dataclasses import dataclass\nfrom typing import Tuple, Union, overload\n\nfrom app.proxy import const\nfrom app.proxy.req_resp import Request, Response\n\nSrcDst = Tuple[str, str]\nReqResp = Union[Request, Response]\n\n\nclass Patcher(abc.ABC):\n \"\"\"Protocol describes methods for patching HTTP requests and responses.\"\"\"\n\n @overload\n def __call__(\n self,\n req_resp: Request,\n hosts: SrcDst,\n ) -> Request:\n \"\"\"Patch HTTP request.\"\"\"\n\n @overload\n def __call__( # noqa: F811\n self,\n req_resp: Response,\n hosts: SrcDst,\n ) -> Response:\n \"\"\"Patch HTTP response.\"\"\"\n\n @abc.abstractmethod\n def __call__( # noqa: F811\n self,\n req_resp: ReqResp,\n hosts: SrcDst,\n ) -> ReqResp:\n \"\"\"Patch either HTTP request or response.\"\"\"\n raise NotImplementedError\n\n\n@dataclass(frozen=True)\nclass Config(object):\n \"\"\"Configuration for `Proxy` service.\"\"\"\n\n #: Local resource (e.g. `http://127.0.0.1:8080`).\n host: str\n #: Proxied resource (e.g. `https://habr.com`).\n upstream: str\n #: Callable for patching HTTP request / response objects.\n patcher: Patcher\n #: Upstream HTTP request timeout.\n timeout: int = const.timeout\n" }, { "alpha_fraction": 0.5894736647605896, "alphanum_fraction": 0.5969924926757812, "avg_line_length": 19.15151596069336, "blob_id": "107e7936417cfee53e3f4662118a54a162dfd831", "content_id": "187f4c756be984519c8f957db1d5bc23846f6c8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 667, "license_type": "no_license", "max_line_length": 60, "num_lines": 33, "path": "/app/proxy/const.py", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nfrom typing import Final, Set\n\n# =======\n# General\n# =======\n\n#: Default upstream.\nupstream: Final[str] = \"https://habr.com\"\n#: List of headers to remove from HTTP requests / responses.\nremove_headers: Final[Set[str]] = {\n \"accept-encoding\",\n \"content-encoding\",\n \"keep-alive\",\n \"p3p\",\n \"public-key-pins\",\n \"strict-transport-security\",\n \"te\",\n \"transfer-encoding\",\n \"upgrade-insecure-requests\",\n}\n#: Upstream request timeout.\ntimeout: Final[int] = 30\n\n# ==============\n# iVelum patcher\n# ==============\n\n#: Default word length.\nword_length: Final[int] = 6\n#: Default text to append.\nword_append: Final[str] = \"™\"\n" }, { "alpha_fraction": 0.6103575825691223, "alphanum_fraction": 0.610974133014679, "avg_line_length": 35.0444450378418, "blob_id": "f182c57770b33d5c9b6f176418219d8ec11f96a5", "content_id": "ef3b61b867a4accc1b99117d307c3e42eff12243", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1622, "license_type": "no_license", "max_line_length": 78, "num_lines": 45, "path": "/app/proxy/proxy.py", "repo_name": "GreyZmeem/habr-proxy", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\nimport aiohttp\nfrom app.proxy.config import Config\nfrom app.proxy.req_resp import Headers, Request, Response\n\n\nclass Proxy(object):\n \"\"\"Asd.\"\"\"\n\n def __init__(self, config: Config):\n self.config: Config = config\n\n async def dispatch(self, request: Request) -> Response:\n \"\"\"Asd.\"\"\"\n request = self.patch_request(request)\n response = await self.make_request(request)\n return self.patch_response(response)\n\n def patch_request(self, request: Request) -> Request:\n \"\"\"Patch HTTP request.\"\"\"\n hosts = self.config.host, self.config.upstream\n return self.config.patcher(request, hosts)\n\n def patch_response(self, response: Response) -> Response:\n \"\"\"Patch HTTP response.\"\"\"\n hosts = self.config.upstream, self.config.host\n return self.config.patcher(response, hosts)\n\n async def make_request(self, request: Request) -> Response:\n \"\"\"Perform HTTP request to the upstream.\"\"\"\n # TODO: Move this code to separate module and defined as a dependency.\n async with aiohttp.ClientSession() as session:\n req_headers = dict(request.headers)\n response = await session.request(\n url=request.url,\n method=request.method,\n headers=req_headers,\n allow_redirects=False,\n raise_for_status=False,\n verify_ssl=False,\n )\n headers: Headers = tuple(response.headers.items())\n body = await response.read()\n return Response(headers, response.status, body)\n" } ]
11
jrthuet/monster_egg_game
https://github.com/jrthuet/monster_egg_game
0f56a62fcf3dc18f59645dcbdc3395dcd4a8a83c
d4cf56a4805d014cabe1178b6634b6c2d3d43f43
001e0c39a618b3b02fb907a6d463cb37d15d3a64
refs/heads/master
2022-10-06T02:16:43.349995
2020-06-10T05:00:36
2020-06-10T05:00:36
271,182,172
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4960620403289795, "alphanum_fraction": 0.5032109618186951, "avg_line_length": 35.866973876953125, "blob_id": "70898559592141c546beef2f3bbfcdce71621c39", "content_id": "55ed00d8acf8a90fdf03c149a709c883983da9a0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8253, "license_type": "no_license", "max_line_length": 174, "num_lines": 218, "path": "/Dungeon GameFINAL.py", "repo_name": "jrthuet/monster_egg_game", "src_encoding": "UTF-8", "text": "from random import choice\r\nfrom random import randint\r\n\r\nclass Board:\r\n def __init___(self, width, length, mcount, ecount, tokens):\r\n Board.width = width\r\n Board.length = length\r\n Board.rooms = rooms\r\n Board.tlist = tlist\r\n Board.mcount = mcount\r\n Board.ecount = ecount\r\n \r\n def create_board(self):\r\n #creates a list of lists containing the coord and \"_|\" to create the room\r\n Board.rooms = []\r\n Board.width = int(input(\"How many rooms wide will your labyrith be? \")) #width of board (y vals for some reason)\r\n Board.length = int(input(\"How many rows long will your labyrith be? \")) #length of board (x vals)\r\n for x in range(0, Board.length):\r\n for y in range(0, Board.width):\r\n r = []\r\n cell=(x, y) \r\n r.append(cell)\r\n r.append(\"_|\")\r\n Board.rooms.append(r) #creates a list of lists containing the coord and \"_|\" to create the room\r\n \r\n def reset_board(self):\r\n Board.rooms = []\r\n for x in range(0, self.length):\r\n for y in range(0, self.width):\r\n r = []\r\n cell=(x, y) \r\n r.append(cell)\r\n r.append(\"_|\")\r\n Board.rooms.append(r) #creates a list of lists containing the coord and \"_|\" to create the room\r\n \r\n tokens = Board.tlist\r\n for t in tokens: #replaces the _ with the token letter\r\n for r in self.rooms:\r\n if t[0] == r[0]:\r\n r[1] = f\"{t[1]}\" #for some reason - needed to drop the | for the board to print correctly.\r\n top = \" _\" * self.width\r\n print(top)\r\n for r in range(self.length):\r\n maps = list(map(lambda x: x[1], self.rooms[(((r+1) * self.width) - self.width):((r+1) *self.width)])) \r\n combo = \"\".join(maps)\r\n print(f\"|{combo}\")\r\n\r\n def print_board(self): \r\n tokens = Board.tlist\r\n for t in tokens: #replaces the _ with the token letter\r\n for r in self.rooms:\r\n if t[0] == r[0]:\r\n r[1] = f\"{t[1]}|\" #pulling the _| or token symbol out of our grid list and putting them into rows\r\n top = \" _\" * self.width\r\n print(top)\r\n for r in range(self.length):\r\n maps = list(map(lambda x: x[1], self.rooms[(((r+1) * self.width) - self.width):((r+1) *self.width)])) \r\n combo = \"\".join(maps)\r\n print(f\"|{combo}\") \r\n\r\nclass Token:\r\n def __init__(self, name, coordinates=[]):\r\n self.name = name\r\n self.coordinates = coordinates\r\n\r\n def __repr__(self):\r\n return f\"<Token: {self.coordinates}>\"\r\n\r\nclass Player(Token): \r\n def __init__(self):\r\n Player.inventory = []\r\n Player.mlist = []\r\n Player.elist = []\r\n Player.end = False\r\n self.name = \"Player\" \r\n\r\n def pmove(self):\r\n roomlist = []\r\n for r in range(len(Board.rooms)):\r\n roomlist.append(Board.rooms[r][0])\r\n\r\n while True:\r\n move = input(\"Which way do you want to move? ('u' for up, 'd' for down, 'r' for right, 'l' for left, 'i' to view inventory, or 'q' to quit) \")\r\n x = Player.coordinates[0][0]\r\n y = Player.coordinates[0][1]\r\n \r\n if move == 'u':\r\n if (x-1, y) in roomlist:\r\n Player.coordinates[0] = (x-1, y)\r\n break\r\n else:\r\n print(\"You are not allowed to move that way. \")\r\n elif move == 'd':\r\n if (x+1, y) in roomlist:\r\n Player.coordinates[0] = (x+1, y)\r\n break\r\n else:\r\n print(\"You are not allowed to move that way. \")\r\n elif move == 'r':\r\n if (x, y+1) in roomlist:\r\n Player.coordinates[0] = (x, y+1)\r\n break\r\n else:\r\n print(\"You are not allowed to move that way. \")\r\n elif move == 'l':\r\n if (x, y-1) in roomlist:\r\n Player.coordinates[0] = (x, y-1)\r\n break\r\n else:\r\n print(\"You are not allowed to move that way. \")\r\n elif move == 'q':\r\n Player.end = True\r\n break\r\n elif move == 'i':\r\n print(\"Current Inventory:\")\r\n for i in Player.inventory:\r\n print(f\"{i.name}\")\r\n else:\r\n print(\"You have pressed an incorrect key. \")\r\n\r\nclass Monsters(Token):\r\n monster_list = []\r\n\r\n def __init__(self):\r\n self.name = \"Monster\"\r\n self.monster_list.append(self)\r\n \r\n def mmove(self, board): #randomly moves monsters around the board\r\n Player.mlist = []\r\n for t in range(len(Board.tlist)): \r\n if Board.tlist[t][1] == \"M|\":\r\n x = randint(0, Board.length-1) \r\n y = randint(0, Board.width-1)\r\n Board.tlist[t][0] = (x, y)\r\n Player.mlist.append((x, y)) #works but only changes the coord in tlist not in M attributes. Also possible that the monsters exist on top of one another.\r\n \r\nclass Eggs(Token): \r\n def __init__(self):\r\n self.name = \"Egg\"\r\nclass Basket(Token):\r\n def __init__(self):\r\n self.name = \"Basket\"\r\n self.inventory = []\r\nclass Door(Token): \r\n def __init__(self):\r\n self.name = \"Door\"\r\ndef main():\r\n board = Board()\r\n player = Player()\r\n\r\n board.create_board()\r\n \r\n roomcopy = []\r\n roomcopy = Board.rooms.copy()\r\n randcoord = []\r\n Board.mcount = int(input(\"How many monsters do you want to face? \"))\r\n Board.ecount = int(input(\"How many eggs do you want to find? \")) \r\n for _ in range(3+Board.mcount+Board.ecount):\r\n token = choice(roomcopy)\r\n randcoord.append(token)\r\n roomcopy.remove(token) \r\n \r\n Board.tlist = [] \r\n door = Door() \r\n door.coordinates = randcoord.pop()\r\n door.coordinates[1] = \"D\"\r\n Board.tlist.append(door.coordinates)\r\n \r\n basket = Basket()\r\n basket.coordinates = randcoord.pop()\r\n basket.coordinates[1] = \"B\"\r\n Board.tlist.append(basket.coordinates)\r\n\r\n for _ in range(Board.ecount): \r\n egg = Eggs()\r\n egg.coordinates = randcoord.pop()\r\n egg.coordinates[1] = \"E\"\r\n Board.tlist.append(egg.coordinates)\r\n Player.elist.append(egg.coordinates[0])\r\n \r\n Player.coordinates = randcoord.pop([0][0])\r\n player.coordinates[1] = \"P\"\r\n Board.tlist.append(Player.coordinates)\r\n \r\n for _ in range(Board.mcount):\r\n monster = Monsters()\r\n monster.coordinates = randcoord.pop()\r\n monster.coordinates[1] = \"M\"\r\n Board.tlist.append(monster.coordinates)\r\n\r\n board.print_board()\r\n \r\n while player.end != True:\r\n player.pmove()\r\n monster.mmove(board)\r\n board.reset_board() \r\n if player.coordinates[0] in player.mlist:\r\n print(\"A monster got you. You lose. Better luck next time.\")\r\n player.end = True\r\n elif basket not in player.inventory:\r\n if player.coordinates[0] == basket.coordinates[0]:\r\n print(\"You found the basket! Now you can look for eggs.\")\r\n player.inventory.append(basket)\r\n Board.tlist.remove(basket.coordinates)\r\n elif basket in player.inventory:\r\n if player.coordinates[0] in player.elist:\r\n print(f\"You found egg number {(board.ecount+1)-len(player.elist)}\")\r\n player.elist.remove(player.coordinates[0])\r\n player.inventory.append(egg)#need a way to ID which egg to remove from tlist\r\n board.tlist.remove([player.coordinates[0], \"E|\"])\r\n if player.elist == []:\r\n print(\"You have all of the eggs. Find the door.\")\r\n elif player.elist == []:\r\n if player.coordinates[0] == door.coordinates[0]:\r\n print(\"You win! Congratulations!\")\r\n break\r\n\r\nmain()" }, { "alpha_fraction": 0.6363636255264282, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 20, "blob_id": "1d7758f8fba4ab8422ab8b66759a3350d2eb74d9", "content_id": "faf1a72ac76e1fbb5ef6eb395e01f5001618a45c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 22, "license_type": "no_license", "max_line_length": 20, "num_lines": 1, "path": "/README.md", "repo_name": "jrthuet/monster_egg_game", "src_encoding": "UTF-8", "text": "\"# monster_egg_game\" \n" } ]
2
Toufyx/troupadour
https://github.com/Toufyx/troupadour
b78b5a36286d49976e546cb3ca63b58e83495458
21b327d5f9603ae2d43a76566e20f6b7b76d55e8
96dedaaa44843636c2b3e2a85b8a5f0bcf242b47
refs/heads/master
2018-01-02T08:12:37.482791
2017-12-04T23:15:14
2017-12-04T23:15:14
71,704,958
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.536384105682373, "alphanum_fraction": 0.536384105682373, "avg_line_length": 23.685184478759766, "blob_id": "bda7f5d2650df65d71c2bffe661386dca60849da", "content_id": "b3a75f990c8566973c5217deec39f5c4696aeee6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1333, "license_type": "no_license", "max_line_length": 70, "num_lines": 54, "path": "/troupadour/views/contact.py", "repo_name": "Toufyx/troupadour", "src_encoding": "UTF-8", "text": "\"\"\"\n[ Toufyx ] contact.py\n\"\"\"\n\nfrom flask.views import MethodView\nfrom flask import json, jsonify\nfrom flask import request\nfrom ..models import Session\nfrom ..models import ContactMessage\n\nclass ContactAPI(MethodView):\n \"\"\"\n ContactAPI class\n ----------------\n\n {\n \"name\": optional string,\n \"email\": optional string - match email,\n \"message\": required string,\n }\n \"\"\"\n\n def clean_data(self, data):\n rData = {}\n\n if \"name\" in data:\n rData[\"contact_name\"] = data[\"name\"]\n\n if \"email\" in data:\n rData[\"contact_mail\"] = data[\"email\"]\n\n if \"message\" not in data:\n return (None, \"message required\")\n rData[\"message\"] = data[\"message\"]\n\n return (rData, None)\n\n def post(self):\n\n # retrieve and validate data\n (data, error) = self.clean_data(request.json)\n if data is None:\n return jsonify({\"status\": \"ko\", \"message\": error})\n\n # save data in database\n try:\n session = Session()\n message = ContactMessage(**data)\n message.save(session)\n except Exception as error:\n return jsonify({\"status\": \"ko\", \"message\": error.message})\n\n # return ok\n return jsonify({\"status\": \"ok\"})\n" }, { "alpha_fraction": 0.5259740352630615, "alphanum_fraction": 0.5275974273681641, "avg_line_length": 26.176469802856445, "blob_id": "82ed96239b0085818e9681721b3e6526e1a8e32e", "content_id": "a78fa3c5d6267b29d3d37e12807cfd82c042c73d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1848, "license_type": "no_license", "max_line_length": 80, "num_lines": 68, "path": "/troupadour/models/base.py", "repo_name": "Toufyx/troupadour", "src_encoding": "UTF-8", "text": "\"\"\"\n================================================================================\n[ Toufyx ] base.py\n base class for the models\n================================================================================\n\"\"\"\n\nimport datetime\n\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, Date\nfrom sqlalchemy.ext.declarative import declared_attr\nfrom sqlalchemy.exc import InvalidRequestError\n\nclass ManagedObject(object):\n\n id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)\n\n @declared_attr\n def __tablename__(cls):\n return cls.__name__.lower()\n\n @classmethod\n def all(cls, session):\n try:\n return session.query(cls).all()\n except Exception as error:\n return []\n\n @classmethod\n def get(cls, session, **kwargs):\n try:\n data = session.query(cls).filter_by(**kwargs).all()\n if len(data) == 0:\n return None\n elif len(data) == 1:\n return data[0]\n else:\n return data\n except Exception as error:\n return None\n\n @classmethod\n def query(cls, session, **kwargs):\n try:\n return session.query(cls).filter_by(**kwargs)\n except Exception as error:\n return None\n\n # to be tested\n def save(self, session):\n try:\n session.add(self)\n session.commit()\n except Exception as error:\n session.rollback()\n raise error\n\n def delete(self, session):\n try:\n session.delete(self)\n session.commit()\n except Exception as error:\n session.rollback()\n raise error\n\n# the bas class for all database objects\nBase = declarative_base(cls=ManagedObject)\n" }, { "alpha_fraction": 0.3852691352367401, "alphanum_fraction": 0.3852691352367401, "avg_line_length": 31.090909957885742, "blob_id": "9b86463072f8d0778da5ccabf9d6b65db14bd416", "content_id": "720b86c07f43af3ca03ab26e910f277d612c55ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 353, "license_type": "no_license", "max_line_length": 80, "num_lines": 11, "path": "/troupadour/models/__init__.py", "repo_name": "Toufyx/troupadour", "src_encoding": "UTF-8", "text": "\"\"\"\n================================================================================\n[ Toufyx ] Core.Models Module\n Group all the models for the core module\n================================================================================\n\"\"\"\n\nfrom .base import Base\nfrom .contact_message import ContactMessage\n\nfrom .database import Session\n" }, { "alpha_fraction": 0.5516223907470703, "alphanum_fraction": 0.5516223907470703, "avg_line_length": 27.25, "blob_id": "eab04d913a40131f80797dd6d6c1b7882669fdee", "content_id": "c65b3142c370c65ac4631b2b2e36b1e63c9fbbb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 678, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/troupadour/models/database.py", "repo_name": "Toufyx/troupadour", "src_encoding": "UTF-8", "text": "\"\"\"\n================================================================================\n[ Toufyx ] database.py\n manage the database access management\n================================================================================\n\"\"\"\n\n# Import SQLAlchemy\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom .base import Base\n\nfrom ..config import SQLALCHEMY_DATABASE_URI\n\n# Manage the database:\n# This will create the database file using SQLAlchemy\n_engine = create_engine(SQLALCHEMY_DATABASE_URI)\nSession = sessionmaker(bind=_engine)\n\ndef setup():\n \"\"\"\n Create all database tables\n \"\"\"\n Base.metadata.create_all(_engine)\n" }, { "alpha_fraction": 0.7465310096740723, "alphanum_fraction": 0.7465310096740723, "avg_line_length": 29.85714340209961, "blob_id": "645f551d8bdd3285551f453ad3145cd1cb249c11", "content_id": "67e31617d9436c4ccf921f29d98c9d487073fefb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1081, "license_type": "no_license", "max_line_length": 91, "num_lines": 35, "path": "/troupadour/app.py", "repo_name": "Toufyx/troupadour", "src_encoding": "UTF-8", "text": "\"\"\"\n[ Toufyx ] App Module\n\n Group all the High level variables\n - the Flask application\n - the database connection\n\n\"\"\"\n\n# Import flask and template operators\nfrom flask import Flask, render_template\n\n# Import a module / component using its blueprint handler variable (mod_auth)\n# from app.auth.controllers import mod_auth as auth_module\n\n# Define the WSGI application object\napplication = Flask(\"troupadour\")\n\n# Configurations\napplication.config.from_object('troupadour.config')\n\n# URLS Mapping\nfrom .views import ContactAPI\napplication.add_url_rule( \"/services/contact/\" , view_func=ContactAPI.as_view( \"contact\" ))\n\n# manage HTTP errors\nfrom .views.errors import handle_http_error\nfrom werkzeug import exceptions\nfrom werkzeug.exceptions import HTTPException\nfrom importlib import import_module\nfor exception_name in exceptions.__all__:\n class_ = exceptions.__dict__[exception_name]\n if class_ in HTTPException.__subclasses__():\n print(\"add exception handler for: \" + class_.__name__)\n application.register_error_handler(class_, handle_http_error)\n\n" }, { "alpha_fraction": 0.5205684304237366, "alphanum_fraction": 0.5280478596687317, "avg_line_length": 30.83333396911621, "blob_id": "8dd617c859cadcd326e5fbd7bdf8b2f9df3887c1", "content_id": "b8765fe1c56b0ce7881a3cfb9ef737c9b825b84f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1337, "license_type": "no_license", "max_line_length": 83, "num_lines": 42, "path": "/troupadour/models/contact_message.py", "repo_name": "Toufyx/troupadour", "src_encoding": "UTF-8", "text": "\"\"\"\n================================================================================\n[ Toufyx ] contact_message.py\n Manage the Contact Message models\n================================================================================\n\"\"\"\n\nfrom . import Base\nfrom sqlalchemy import Column, Integer, String, Date, ForeignKey, Table\nfrom sqlalchemy.orm import relationship\n\nclass ContactMessage(Base):\n \"\"\"\n Contact Message Class\n ---------------------\n \"\"\"\n\n # Contact Message\n message = Column(String(4096), nullable=False)\n\n # Contact Information\n contact_name = Column(String(256), nullable=True)\n contact_mail = Column(String(256), nullable=True)\n\n # New instance instantiation procedure\n def __init__(self, message=None, contact_name=None, contact_mail=None):\n \"\"\" Complete Creator \"\"\"\n self.message = message or \"-\"\n self.contact_name = contact_name\n self.contact_mail = contact_mail\n\n def __repr__(self):\n return '<ContactMessage(message=\"%s\", contact_name=%s, contact_mail=%s)>' \\\n % (self.message, self.contact_name, self.contact_mail)\n\n def serialize(self):\n return {\n 'id': self.id,\n 'message': self.message,\n 'name': self.contact_name,\n 'mail': self.contact_mail,\n }\n" }, { "alpha_fraction": 0.7714285850524902, "alphanum_fraction": 0.7714285850524902, "avg_line_length": 31, "blob_id": "3c768b0b50c8afecec06f12603bbfd6639ef61fa", "content_id": "e9acf7b2154193b4d6fa6cc1c03672b829fd7d57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 35, "license_type": "no_license", "max_line_length": 31, "num_lines": 1, "path": "/troupadour/views/__init__.py", "repo_name": "Toufyx/troupadour", "src_encoding": "UTF-8", "text": "\n\nfrom .contact import ContactAPI\n\n" }, { "alpha_fraction": 0.6796875, "alphanum_fraction": 0.6796875, "avg_line_length": 24.600000381469727, "blob_id": "7995df4a987997e721f25cf18e4e4e9ba4b44969", "content_id": "1bc3553937bd4cc3bb40333d9cc02367b131f51d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 86, "num_lines": 10, "path": "/troupadour/views/errors.py", "repo_name": "Toufyx/troupadour", "src_encoding": "UTF-8", "text": "\"\"\"\n[ Toufyx ] errors.py\n handle HTTP errors response\n\"\"\"\n\nfrom flask.views import MethodView\nfrom flask import json, jsonify\n\ndef handle_http_error(error):\n return jsonify({\"status\": \"ko\", \"code\": error.code, \"message\": error.description})\n" } ]
8
PierreExeter/custom_gym_envs
https://github.com/PierreExeter/custom_gym_envs
5d9be9cb5bf9fb6347f7c55c75de9d7a081eeec2
2b6a1c16a4198c8d9fa64f10fe09a041826ac81a
5653a29dfcdae2054e6bf4e1cff89144bdf63317
refs/heads/master
2023-03-22T06:21:01.589149
2021-03-03T16:28:28
2021-03-03T16:28:28
288,418,334
1
2
null
null
null
null
null
[ { "alpha_fraction": 0.6479556560516357, "alphanum_fraction": 0.6784476637840271, "avg_line_length": 35.04999923706055, "blob_id": "7c0c9ffb96a7b2d90eb7de19608c51de2f78825d", "content_id": "02bc6df0a537198043e5e46a1193448a2cb09d64", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1443, "license_type": "permissive", "max_line_length": 94, "num_lines": 40, "path": "/test_envs/7_test_teleopt_jaco_pybullet.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\nimport pybullet as p\nimport numpy as np\n\nenv = gym.make('ReachingJaco-v1')\nenv.render()\nobservation = env.reset()\nenv.world_creation.print_joint_info(env.robot)\nkeys_actions = {\n p.B3G_LEFT_ARROW: np.array([-0.01, 0, 0]), \n p.B3G_RIGHT_ARROW: np.array([0.01, 0, 0]), \n p.B3G_UP_ARROW: np.array([0, 0, 0.01]), \n p.B3G_DOWN_ARROW: np.array([0, 0, -0.01]),\n p.B3G_ALT: np.array([0, 0.01, 0]), \n p.B3G_SHIFT: np.array([0, -0.01, 0])\n }\n\n# Get the position and orientation of the end effector\nposition, orientation = p.getLinkState(env.robot, 8, computeForwardKinematics=True)[:2]\n\nwhile True:\n env.render()\n\n keys = p.getKeyboardEvents()\n for key, action in keys_actions.items():\n if key in keys and keys[key] & p.KEY_IS_DOWN:\n position += action\n\n # IK to get new joint positions (angles) for the robot\n target_joint_positions = p.calculateInverseKinematics(env.robot, 8, position, orientation)\n target_joint_positions = target_joint_positions[:7]\n\n # Get the joint positions (angles) of the robot arm\n joint_positions, joint_velocities, joint_torques = env.get_motor_joint_states(env.robot)\n joint_positions = np.array(joint_positions)[:7]\n\n # Set joint action to be the error between current and target joint positions\n joint_action = (target_joint_positions - joint_positions) * 10\n observation, reward, done, info = env.step(joint_action)\n\n" }, { "alpha_fraction": 0.6294682025909424, "alphanum_fraction": 0.6739320158958435, "avg_line_length": 22.40816307067871, "blob_id": "b3e17bfda5473daf260b932de10f94a071e2d056", "content_id": "d0c31a0935be727404bcbfe18e217b4a88451f9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1147, "license_type": "permissive", "max_line_length": 73, "num_lines": 49, "path": "/test_envs/8_test_jaco_physicalROS.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\nimport random\nimport rospy\n\n# First of all, launch Jaco in Gazebo in another terminal with:\n# roslaunch kinova_bringup kinova_robot.launch kinova_robotType:=j2n6s300\n\nrospy.init_node(\"kinova_client\", anonymous=True, log_level=rospy.INFO)\nenv = gym.make('JacoReachReal-v0')\n\nprint('Environment:', env)\nprint('Action space:', env.action_space)\nprint(env.action_space.high)\nprint(env.action_space.low)\nprint('State space:', env.observation_space)\nprint(env.observation_space.high)\nprint(env.observation_space.low)\n\n\n\nstate = env.reset()\nprint(\"current state: \", state)\n\naction = [0, 180, 180, 60, 0, 0]\nstate = env.step(action)\nenv.print_tip_pos()\nprint(\"current state: \", state)\n\n\n# for t in range(3):\n\n# # create action\n# ang0 = 0\n# ang1 = 180\n# ang2 = random.randrange(90, 270)\n# ang3 = random.randrange(0, 359)\n# ang4 = random.randrange(0, 359)\n# ang5 = random.randrange(0, 359)\n# action = [ang0, ang1, ang2, ang3, ang4, ang5]\n# print(\"action sent: \", action)\n\n# state = env.step(action)\n# print(\"current state: \", state)\n\n\n# print(\"time step {}\".format(t))\n\nenv.close()\n" }, { "alpha_fraction": 0.6130820512771606, "alphanum_fraction": 0.6197339296340942, "avg_line_length": 21.575000762939453, "blob_id": "03def06766a45a8ef21265904ce56ba5dcc98ca5", "content_id": "6f76fa93f7e4d9294ec5d17a5d0d4e9a7fda2c9c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 902, "license_type": "permissive", "max_line_length": 79, "num_lines": 40, "path": "/test_envs/7_test_jaco_pybullet.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\n\nenv = gym.make('ReachingJaco-v1')\n\n\nprint(\"Action space: \", env.action_space)\nprint(env.action_space.high)\nprint(env.action_space.low)\nprint(\"Observation space: \", env.observation_space)\nprint(env.observation_space.high)\nprint(env.observation_space.low)\n\n\n# env.render()\n# env.render(mode=\"human\") # required by Stable Baselines\n\nfor e in range(3):\n\n obs = env.reset()\n rewards = []\n\n for i in range(1000):\n print(i)\n # env.render()\n action = env.action_space.sample()\n obs, reward, done, info = env.step(action)\n\n print(\"action: \", action)\n print(\"obs: \", obs)\n print(\"reward: \", reward)\n print(\"done: \", done)\n print(\"info: \", info)\n\n rewards.append(reward)\n\n cumulative_reward = sum(rewards)\n print(\"episode {} | cumulative reward : {}\".format(e, cumulative_reward)) \n \nenv.close()" }, { "alpha_fraction": 0.641511857509613, "alphanum_fraction": 0.6714396476745605, "avg_line_length": 27.496322631835938, "blob_id": "43f9ec09ffb82f3010422a9925bcafe44e001907", "content_id": "253d8e18253e7a4106e22c986deba4bbbbf2b583", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7752, "license_type": "permissive", "max_line_length": 98, "num_lines": 272, "path": "/gym_envs/__init__.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "from gym.envs.registration import register\n\n#*********************************************\n\nregister(\n id='foo-v0',\n entry_point='gym_envs.0_minimal_working_example.foo_env:FooEnv',\n)\n\n#*********************************************\n\nregister(\n id='tictac-v0',\n entry_point='gym_envs.1_tictactoe.tictac_env:TicTacEnv',\n)\n\n#*********************************************\n\nregister(\n id='balancebot-v0',\n entry_point='gym_envs.2_balance_bot.balancebot_env:BalancebotEnv',\n kwargs={'render': True}\n)\n\nregister(\n id='balancebot-noise-v0',\n entry_point='gym_envs.2_balance_bot.balancebot_env_noise:BalancebotEnvNoise',\n)\n\n#*********************************************\n\nregister(\n id='particle-v0',\n entry_point='gym_envs.3_particle_goal_oriented.continuous_goal_oriented_particle:ParticleEnv',\n max_episode_steps=250,\n\treward_threshold=1,)\n\n#*********************************************\n\nregister(\n\tid='Reacher1Dof-v0',\n\tentry_point='gym_envs.reacher2D.envs.reacher_env:ReacherBulletEnv1',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher2Dof-v0',\n\tentry_point='gym_envs.reacher2D.envs.reacher_env:ReacherBulletEnv2',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher3Dof-v0',\n\tentry_point='gym_envs.reacher2D.envs.reacher_env:ReacherBulletEnv3',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher4Dof-v0',\n\tentry_point='gym_envs.reacher2D.envs.reacher_env:ReacherBulletEnv4',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher5Dof-v0',\n\tentry_point='gym_envs.reacher2D.envs.reacher_env:ReacherBulletEnv5',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher6Dof-v0',\n\tentry_point='gym_envs.reacher2D.envs.reacher_env:ReacherBulletEnv6',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\n#*********************************************\n\nregister(\n\tid='Reacher1Dof-v1',\n\tentry_point='gym_envs.reacher2D.goal_envs.reacher_env:ReacherBulletEnv1',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher2Dof-v1',\n\tentry_point='gym_envs.reacher2D.goal_envs.reacher_env:ReacherBulletEnv2',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher3Dof-v1',\n\tentry_point='gym_envs.reacher2D.goal_envs.reacher_env:ReacherBulletEnv3',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher4Dof-v1',\n\tentry_point='gym_envs.reacher2D.goal_envs.reacher_env:ReacherBulletEnv4',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher5Dof-v1',\n\tentry_point='gym_envs.reacher2D.goal_envs.reacher_env:ReacherBulletEnv5',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\nregister(\n\tid='Reacher6Dof-v1',\n\tentry_point='gym_envs.reacher2D.goal_envs.reacher_env:ReacherBulletEnv6',\n\tmax_episode_steps=150,\n\treward_threshold=18.0,\n\t)\n\n#*********************************************\n\n# environment for both the physical arm and the Pybullet simulation\nregister(id='widowx_reacher-v0',\n entry_point='gym_envs.5_widowx.v0_widowx_original:WidowxEnv',\n max_episode_steps=100\n )\n\n# environment for the physical arm only \nregister(id='widowx_reacher-v1',\n entry_point='gym_envs.5_widowx.v1_widowx_physical_only:WidowxEnv',\n max_episode_steps=100\n )\n\n# environment for the physical arm only + no start_rospy method \nregister(id='widowx_reacher-v2',\n entry_point='gym_envs.5_widowx.v2_widowx_physical_env_fixedGoal:WidowxEnv',\n max_episode_steps=100\n )\n\n# FOR SOME STRANGE REASON, I CAN'T SPECIFY max_episode_steps for GoalEnv (solved)\n# environment for the physical arm only + no start_rospy method + goal oriented\nregister(id='widowx_reacher-v3',\n entry_point='gym_envs.5_widowx.v3_widowx_physical_goalEnv_fixedGoal:WidowxEnv',\n max_episode_steps=100\n )\n\n# environment for the Pybullet simulation only. ROS install not required\nregister(id='widowx_reacher-v4',\n entry_point='gym_envs.5_widowx.v4_widowx_pybullet_only:WidowxEnv',\n max_episode_steps=100\n )\n\n# environment for the Pybullet simulation + no start_sim required + fixed goal\nregister(id='widowx_reacher-v5',\n entry_point='gym_envs.5_widowx.v5_widowx_pybullet_env_fixedGoal:WidowxEnv',\n max_episode_steps=100\n )\n\n# FOR SOME STRANGE REASON, I CAN'T SPECIFY max_episode_steps for GoalEnv\n# environment for the Pybullet simulation + no start_sim required + goal_oriented + fixed goal\nregister(id='widowx_reacher-v6',\n entry_point='gym_envs.5_widowx.v6_widowx_pybullet_goalEnv_fixedGoal:WidowxEnv',\n max_episode_steps=100\n )\n\n# environment for the Pybullet simulation + no start_sim required + random goal\nregister(id='widowx_reacher-v7',\n entry_point='gym_envs.5_widowx.v7_widowx_pybullet_env_randomGoal:WidowxEnv',\n max_episode_steps=100\n )\n\n# FOR SOME STRANGE REASON, I CAN'T SPECIFY max_episode_steps for GoalEnv (solved)\n# environment for the Pybullet simulation + no start_sim required + goal_oriented + random goal\nregister(id='widowx_reacher-v8',\n entry_point='gym_envs.5_widowx.v8_widowx_pybullet_goalEnv_randomGoal:WidowxEnv',\n max_episode_steps=100\n )\n\n# environment for the physical arm only + no start_rospy method + random goal\nregister(id='widowx_reacher-v12',\n entry_point='gym_envs.5_widowx.v12_widowx_physical_env_randomGoal:WidowxEnv',\n max_episode_steps=100\n )\n \n# environment for the physical arm only + no start_rospy method + goal environment + random goal\nregister(id='widowx_reacher-v13',\n entry_point='gym_envs.5_widowx.v13_widowx_physical_goalEnv_randomGoal:WidowxEnv',\n max_episode_steps=100\n )\n\n#*********************************************\n\n# test gym.GoalEnv\nregister(id='my_goal_env-v0',\n entry_point='gym_envs.6_minimal_goalEnv.my_goal_env:MyGoalEnv'\n )\n\n#*********************************************\n\nregister(\n id='ReachingJaco-v1',\n entry_point='gym_envs.7_reaching_jaco.reaching:ReachingEnv',\n max_episode_steps=100,\n)\n\n#*********************************************\n\n\n# environment using the ROS Topics to move the arm in Gazebo\nregister(\n id='JacoReachGazebo-v0',\n entry_point='gym_envs.reaching_jaco_ROS.jaco_gazebo_topic_env:JacoEnv',\n max_episode_steps=50\n)\n\n# environment using ROS Action client to move the arm in Gazebo\nregister(\n id='JacoReachGazebo-v1',\n entry_point='gym_envs.reaching_jaco_ROS.jaco_gazebo_action_env:JacoEnv',\n max_episode_steps=50\n)\n\n# environment using ROS Action client to move the arm in Gazebo + fixed goal + 1 joint moving only\nregister(\n id='JacoReachGazebo-v2',\n entry_point='gym_envs.reaching_jaco_ROS.jaco_gazebo_actionlib_fixedGoal_1jointOnly:JacoEnv',\n max_episode_steps=50\n)\n\n# environment to move the real arm\nregister(\n id='JacoReachReal-v0',\n entry_point='gym_envs.reaching_jaco_ROS.jaco_real_env:JacoEnv',\n max_episode_steps=50\n)\n\n\n\nregister(\n id='KukaButtonGymEnv-v0',\n entry_point='gym_envs.kuka_gym.kuka_button_gym_env:KukaButtonGymEnv',\n max_episode_steps=None,\n reward_threshold=None\n )\n\n\nregister(\n id='Kuka2ButtonGymEnv-v0',\n entry_point='gym_envs.kuka_gym.kuka_2button_gym_env:Kuka2ButtonGymEnv',\n max_episode_steps=None,\n reward_threshold=None\n )\n\nregister(\n id='KukaMovingButtonGymEnv-v0',\n entry_point='gym_envs.kuka_gym.kuka_moving_button_gym_env:KukaMovingButtonGymEnv',\n max_episode_steps=None,\n reward_threshold=None\n )\n\nregister(\n id='KukaRandButtonGymEnv-v0',\n entry_point='gym_envs.kuka_gym.kuka_rand_button_gym_env:KukaRandButtonGymEnv',\n max_episode_steps=None,\n reward_threshold=None\n )\n\n" }, { "alpha_fraction": 0.6378466486930847, "alphanum_fraction": 0.6827079653739929, "avg_line_length": 23.058822631835938, "blob_id": "b2a865c369a6ce74c1ba033835f30ec8dab2a1a6", "content_id": "ca348224672505d3b29072b0ebd680558e5805b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1226, "license_type": "permissive", "max_line_length": 90, "num_lines": 51, "path": "/test_envs/8_test_jaco_gazebo_topic.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\nimport random\nimport numpy as np \nimport rospy\n\n# First of all, launch Jaco in Gazebo in another terminal with:\n# roslaunch kinova_gazebo robot_launch_noRender_noSphere.launch kinova_robotType:=j2n6s300\n# OR\n# roslaunch kinova_gazebo robot_launch_render.launch kinova_robotType:=j2n6s300\n\nrospy.init_node(\"kinova_client\", anonymous=True, log_level=rospy.INFO)\nenv = gym.make('JacoReachGazebo-v0')\n\nprint('Environment:', env)\nprint('Action space:', env.action_space)\n# print(env.action_space.high)\n# print(env.action_space.low)\nprint('State space:', env.observation_space)\n# print(env.observation_space.high)\n# print(env.observation_space.low)\n\n\n\nstate = env.reset()\nprint(\"current state: \", state)\n\naction = [0, 90, 180, 60, 0, 0]\nstate = env.step(action)\n\n\n\n# for t in range(3):\n\n# # create action\n# ang0 = 0\n# ang1 = 180\n# ang2 = random.randrange(90, 270)\n# ang3 = random.randrange(0, 359)\n# ang4 = random.randrange(0, 359)\n# ang5 = random.randrange(0, 359)\n# action = [ang0, ang1, ang2, ang3, ang4, ang5]\n# print(\"action sent: \", action)\n\n# state = env.step(action)\n# print(\"current state: \", state)\n\n\n# print(\"time step {}\".format(t))\n\nenv.close()" }, { "alpha_fraction": 0.6009359359741211, "alphanum_fraction": 0.6200441718101501, "avg_line_length": 30.789257049560547, "blob_id": "982109e6ba3cdb569bf843377610c54d9af28981", "content_id": "3229ff60eeee924af01ffbce078cde923c0bd8ac", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7693, "license_type": "permissive", "max_line_length": 141, "num_lines": 242, "path": "/gym_envs/reaching_jaco_ROS/ros_scripts/jaco_gazebo_action_client.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n\nimport actionlib\nimport rospy\nimport numpy as np\n\nfrom control_msgs.msg import FollowJointTrajectoryAction, FollowJointTrajectoryGoal, JointTrajectoryControllerState\nfrom trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint\nfrom gazebo_msgs.msg import LinkStates, ModelState\nfrom std_srvs.srv import Empty\nfrom sensor_msgs.msg import JointState\nfrom geometry_msgs.msg import Pose, Point\n\n\nclass JacoGazeboActionClient:\n\n def __init__(self):\n \n action_address = \"/j2n6s300/effort_joint_trajectory_controller/follow_joint_trajectory\"\n self.client = actionlib.SimpleActionClient(action_address, FollowJointTrajectoryAction)\n\n self.pub_topic = '/gazebo/set_model_state'\n self.pub = rospy.Publisher(self.pub_topic, ModelState, queue_size=1)\n\n # Unpause the physics\n rospy.wait_for_service('/gazebo/unpause_physics')\n unpause_gazebo = rospy.ServiceProxy('/gazebo/unpause_physics', Empty)\n unpause_gazebo()\n\n\n def move_arm(self, points_list):\n # # Unpause the physics\n # rospy.wait_for_service('/gazebo/unpause_physics')\n # unpause_gazebo = rospy.ServiceProxy('/gazebo/unpause_physics', Empty)\n # unpause_gazebo()\n\n self.client.wait_for_server()\n\n goal = FollowJointTrajectoryGoal() \n\n # We need to fill the goal message with its components\n # \n # check msg structure with: rosmsg info FollowJointTrajectoryGoal\n # It is composed of 4 sub-messages:\n # \"trajectory\" of type trajectory_msgs/JointTrajectory \n # \"path_tolerance\" of type control_msgs/JointTolerance\n # \"goal_tolerance\" of type control_msgs/JointTolerance\n # \"goal_time_tolerance\" of type duration\n\n trajectory_msg = JointTrajectory()\n # check msg structure with: rosmsg info JointTrajectory\n # It is composed of 3 sub-messages:\n # \"header\" of type std_msgs/Header \n # \"joint_names\" of type string\n # \"points\" of type trajectory_msgs/JointTrajectoryPoint\n\n trajectory_msg.joint_names = [\n \"j2n6s300_joint_1\", \n \"j2n6s300_joint_2\", \n \"j2n6s300_joint_3\", \n \"j2n6s300_joint_4\", \n \"j2n6s300_joint_5\", \n \"j2n6s300_joint_6\"\n ]\n\n points_msg = JointTrajectoryPoint()\n # check msg structure with: rosmsg info JointTrajectoryPoint\n # It is composed of 5 sub-messages:\n # \"positions\" of type float64\n # \"velocities\" of type float64\n # \"accelerations\" of type float64\n # \"efforts\" of type float64\n # \"time_from_start\" of type duration\n \n points_msg.positions = points_list\n points_msg.velocities = [0, 0, 0, 0, 0, 0]\n points_msg.accelerations = [0, 0, 0, 0, 0, 0]\n points_msg.effort = [0, 0, 0, 0, 0, 0]\n points_msg.time_from_start = rospy.Duration(0.01)\n\n # fill in points message of the trajectory message\n trajectory_msg.points = [points_msg]\n\n # fill in trajectory message of the goal\n goal.trajectory = trajectory_msg\n\n # self.client.send_goal_and_wait(goal)\n self.client.send_goal(goal)\n self.client.wait_for_result()\n\n # wait for the robot to finish moving\n # rospy.sleep(2) # wait for 2s\n while not self.robot_has_stopped():\n pass\n\n # return self.client.get_state()\n\n\n def move_sphere(self, coords_list):\n\n model_state_msg = ModelState()\n # check msg structure with: rosmsg info gazebo_msgs/ModelState\n # It is composed of 4 sub-messages:\n # model_name of type string\n # pose of type geometry_msgs/Pose\n # twist of type geometry_msgs/Twist \n # reference_frame of type string\n\n pose_msg = Pose()\n # rosmsg info geometry_msgs/Pose\n # It is composed of 2 sub-messages\n # position of type geometry_msgs/Point\n # orientation of type geometry_msgs/Quaternion \n\n point_msg = Point()\n # rosmsg info geometry_msgs/Point\n # It is composed of 3 sub-messages\n # x of type float64\n # y of type float64\n # z of type float64\n point_msg.x = coords_list[0]\n point_msg.y = coords_list[1]\n point_msg.z = coords_list[2]\n\n pose_msg.position = point_msg\n\n model_state_msg.model_name = \"my_sphere3\"\n model_state_msg.pose = pose_msg\n model_state_msg.reference_frame = \"world\"\n\n # print(model_state_msg)\n \n self.pub.publish(model_state_msg)\n\n\n\n def cancel_move(self):\n self.client.cancel_all_goals()\n\n\n def read_state_old(self):\n self.status = rospy.wait_for_message(\"/j2n6s300/effort_joint_trajectory_controller/state\", JointTrajectoryControllerState)\n \n # convert tuple to list and concatenate\n self.state = list(self.status.actual.positions) + list(self.status.actual.velocities)\n # also self.status.actual.accelerations, self.status.actual.effort\n\n return self.state\n\n\n def read_state(self):\n self.status = rospy.wait_for_message(\"/j2n6s300/joint_states\", JointState)\n \n self.joint_names = self.status.name\n # print(self.joint_names)\n\n self.pos = self.status.position\n self.vel = self.status.velocity\n self.eff = self.status.effort\n\n # return self.status\n return np.asarray(self.pos + self.vel + self.eff)\n\n\n def read_state_simple(self):\n \"\"\"\n read state of the joints only (not the fingers) + removed the efforts\n \"\"\"\n\n self.status = rospy.wait_for_message(\"/j2n6s300/joint_states\", JointState)\n \n self.joint_names = self.status.name[:6]\n # print(self.joint_names)\n\n self.pos = self.status.position[:6]\n self.vel = self.status.velocity[:6]\n\n # return self.status\n return np.asarray(self.pos + self.vel)\n\n\n def robot_has_stopped(self):\n \"\"\"\n Check if the robot joints are moving\n \"\"\"\n self.status = rospy.wait_for_message(\"/j2n6s300/joint_states\", JointState)\n self.vel = self.status.velocity[:6]\n\n self.is_stopped = False\n if (abs(self.vel[0]) < 0.01):\n self.is_stopped = True\n\n return self.is_stopped\n\n def read_angle_joint1(self):\n \"\"\"\n read joint angle 1\n \"\"\"\n\n self.status = rospy.wait_for_message(\"/j2n6s300/joint_states\", JointState)\n self.pos = self.status.position[:1]\n \n return np.asarray(self.pos)\n\n\n def get_tip_coord(self):\n self.status = rospy.wait_for_message(\"/gazebo/link_states\", LinkStates)\n # see also topic /tf\n\n self.joint_names = self.status.name\n self.pos = self.status.pose\n\n # BE CAREFUL: joint number changes if I add a sphere!\n # print(self.joint_names[8])\n # print(self.status.pose[8].position)\n\n\n # for i in range(14):\n # print(i)\n # print(\"joint:\")\n # print(self.joint_names[i])\n # print(\"pose:\")\n # print(self.status.pose[i])\n\n return [self.status.pose[8].position.x, self.status.pose[8].position.y, self.status.pose[8].position.z]\n \n\n\n\n# rospy.init_node(\"kinova_client_yo\")\n\n# client = JacoGazeboActionClient()\n# client.cancel_move()\n# client.move_arm([3, 1.57, 3.14, 0, 0, 0])\n\n# # client.move_sphere([1, 1, 1])\n\n# print(client.read_state_simple())\n# # print(client.read_state2())\n# print(client.get_tip_coord()) # PB: reading coordinate doesn't wait until the arm has finished moving. SOLUTION: wait for 2s. To improve.\n\n# print(client.read_state())\n" }, { "alpha_fraction": 0.7153846025466919, "alphanum_fraction": 0.7230769395828247, "avg_line_length": 17.714284896850586, "blob_id": "68b9a2cb59c95b6c08cc17f650f65f4021ddfc97", "content_id": "a39b7d312bb02c1ed344f047aa679fc3a26dffc8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 130, "license_type": "permissive", "max_line_length": 67, "num_lines": 7, "path": "/test_envs/6_test_minimal_goaEnv.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\n\n\nenv = gym.make('my_goal_env-v0')\n\nprint(\"isinstance(env, gym.GoalEnv)\", isinstance(env, gym.GoalEnv))" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6851851940155029, "avg_line_length": 9.800000190734863, "blob_id": "93c70e535bc41e015dd7739ed64b4da2b95c0cde", "content_id": "827a329880a3ec5c67c1da6b5bb97fed60e0cdf4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 54, "license_type": "permissive", "max_line_length": 24, "num_lines": 5, "path": "/test_envs/0_test_minimal_working_example.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\n\n\nenv = gym.make('foo-v0')\n" }, { "alpha_fraction": 0.6044568419456482, "alphanum_fraction": 0.6274373531341553, "avg_line_length": 25.55555534362793, "blob_id": "c827cc21576d60e8dcbe010ba05dcf565f52e4f2", "content_id": "958360c68ee957cb12d63bb16e0406e19f947b25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1436, "license_type": "permissive", "max_line_length": 85, "num_lines": 54, "path": "/test_envs/4_test_reacher2D.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport time\nimport pybullet_envs\nimport gym_envs\n\n# env = gym.make('ReacherBulletEnv-v0')\n# env = gym.make('Reacher1Dof-v0')\n# env = gym.make('Reacher2Dof-v0')\n# env = gym.make('Reacher3Dof-v0')\n# env = gym.make('Reacher4Dof-v0')\n# env = gym.make('Reacher5Dof-v0')\nenv = gym.make('Reacher6Dof-v0')\n\n# with goal env\n# env = gym.make('Reacher1Dof-v1')\n# env = gym.make('Reacher2Dof-v1')\n# env = gym.make('Reacher3Dof-v1')\n# env = gym.make('Reacher4Dof-v1')\n# env = gym.make('Reacher5Dof-v1')\n# env = gym.make('Reacher6Dof-v1')\n\n\nenv.render(mode=\"human\") \n\nprint(\"Action space: \", env.action_space)\nprint(env.action_space.high)\nprint(env.action_space.low)\nprint(\"Observation space: \", env.observation_space)\n# print(env.observation_space.high) # comment for goalEnv\n# print(env.observation_space.low) # comment for goalEnv\n\n\nfor episode in range(50):\n obs = env.reset() \n rewards = []\n \n for t in range(200):\n action = env.action_space.sample() \n obs, reward, done, info = env.step(action) \n\n print(\"action: \", action)\n print(\"obs: \", obs)\n print(\"reward: \", reward)\n print(\"done: \", done)\n print(\"info: \", info)\n print(\"timestep: \", t)\n\n rewards.append(reward)\n time.sleep(1./30.) \n\n cumulative_reward = sum(rewards)\n print(\"episode {} | cumulative reward : {}\".format(episode, cumulative_reward)) \n \nenv.close()\n\n\n" }, { "alpha_fraction": 0.6529209613800049, "alphanum_fraction": 0.6597937941551208, "avg_line_length": 26.714284896850586, "blob_id": "aceb3c55f0347db7326233ca7979e50f9684543c", "content_id": "2f9e62831ddb33f94f17f6b8f820fe8c5e2f6151", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1164, "license_type": "permissive", "max_line_length": 96, "num_lines": 42, "path": "/ROS_packages/custom_ROS_envs/turtlebot2_wall_env/src/turtlebot2_wall_random.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport gym\nimport rospy\nfrom openai_ros.openai_ros_common import StartOpenAI_ROS_Environment\n\n# initialise environment\nrospy.init_node('turtlebot2_wall_random', anonymous=True, log_level=rospy.WARN)\ntask_and_robot_environment_name = rospy.get_param('/turtlebot2/task_and_robot_environment_name')\nenv = StartOpenAI_ROS_Environment(task_and_robot_environment_name)\n\nprint(\"Environment: \", env)\nprint(\"Action space: \", env.action_space)\n# print(env.action_space.high)\n# print(env.action_space.low)\nprint(\"Observation space: \", env.observation_space)\nprint(env.observation_space.high)\nprint(env.observation_space.low)\n\n\nfor episode in range(20):\n\n env.reset()\n\n for t in range(100):\n\n action = env.action_space.sample()\n obs, reward, done, info = env.step(action)\n\n print(\"episode: \", episode)\n print(\"timestep: \", t)\n print(\"obs: \", obs)\n print(\"action:\", action)\n print(\"reward: \", reward)\n print(\"done: \", done)\n print(\"info: \", info)\n \n if done:\n print(\"Episode {} finished after {} timesteps\".format(episode, t+1))\n break\n\nenv.close()\n" }, { "alpha_fraction": 0.5960590839385986, "alphanum_fraction": 0.6059113144874573, "avg_line_length": 23.707317352294922, "blob_id": "711867c7cec86e75b27d7abdae974d0045e0fe22", "content_id": "8e3f47e8a0c0ed33c94960cee1f18ca6168a37ec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1015, "license_type": "permissive", "max_line_length": 85, "num_lines": 41, "path": "/test_envs/3_test_particle_env.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\nimport time\n\n\nenv = gym.make('particle-v0')\n# env.render(mode=\"human\") \n\nprint(\"Action space: \", env.action_space)\nprint(env.action_space.high)\nprint(env.action_space.low)\nprint(\"Observation space: \", env.observation_space)\n# print(env.observation_space.high)\n# print(env.observation_space.low)\n\n\nprint(\"isinstance(env, gym.GoalEnv)\", isinstance(env, gym.GoalEnv))\n\nfor episode in range(200):\n obs = env.reset() \n rewards = []\n \n for t in range(100):\n env.render() \n action = env.action_space.sample() \n obs, reward, done, info = env.step(action) \n rewards.append(reward)\n time.sleep(1./30.) \n\n print(\"action: \", action)\n print(\"obs: \", obs)\n print(\"reward: \", reward)\n print(\"done: \", done)\n print(\"info: \", info)\n print(\"timestep: \", t)\n\n\n cumulative_reward = sum(rewards)\n print(\"episode {} | cumulative reward : {}\".format(episode, cumulative_reward)) \n \nenv.close()\n\n\n" }, { "alpha_fraction": 0.598512589931488, "alphanum_fraction": 0.6273167133331299, "avg_line_length": 44.29411697387695, "blob_id": "35a8bdc226c6dc33f2010c479773c1a8829d4ae8", "content_id": "73a2e6a495f4fd8044f26e4bd676f557904614fb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8471, "license_type": "permissive", "max_line_length": 259, "num_lines": 187, "path": "/gym_envs/7_reaching_jaco/env.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import os, time, datetime\nimport gym\nfrom gym import spaces\nfrom gym.utils import seeding\nimport numpy as np\nimport pybullet as p\nimport cv2\n# from keras.models import load_model\nfrom screeninfo import get_monitors\nfrom .world_creation import WorldCreation\n\n\nclass RobotEnv(gym.Env):\n def __init__(self, robot_type='jaco', frame_skip=5, time_step=0.02, action_robot_len=7, obs_robot_len=30):\n # Start the bullet physics server\n self.id = p.connect(p.DIRECT)\n # print('Physics server ID:', self.id)\n self.gui = False\n\n self.robot_type = robot_type\n self.action_robot_len = action_robot_len\n self.obs_robot_len = obs_robot_len\n self.action_space = spaces.Box(low=np.array([-1.0]*(self.action_robot_len)), high=np.array([1.0]*(self.action_robot_len)), dtype=np.float32)\n self.observation_space = spaces.Box(low=np.array([-1.0]*(self.obs_robot_len)), high=np.array([1.0]*(self.obs_robot_len)), dtype=np.float32)\n\n # Execute actions at 10 Hz by default. A new action every 0.1 seconds\n self.frame_skip = frame_skip\n self.time_step = time_step\n\n self.setup_timing()\n self.seed(1001)\n\n self.world_creation = WorldCreation(self.id, robot_type=robot_type, time_step=self.time_step, np_random=self.np_random)\n # self.util = Util(self.id, self.np_random)\n\n # p.startStateLogging(p.STATE_LOGGING_VIDEO_MP4, \"racecar.mp4\") # added by Pierre\n\n self.record_video = False #True\n self.video_writer = None #cv2.VideoWriter('Hola.avi', cv2.VideoWriter_fourcc(*'MJPG'), 10, (10, 10)) # (don' work)\n try:\n self.width = get_monitors()[0].width\n self.height = get_monitors()[0].height\n except Exception as e:\n self.width = 1920\n self.height = 1080\n # self.width = 3840\n # self.height = 2160\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def step(self, action):\n raise NotImplementedError('Implement observations')\n\n def _get_obs(self, forces):\n raise NotImplementedError('Implement observations')\n\n def reset(self):\n raise NotImplementedError('Implement reset')\n\n def take_step(self, action, robot_arm='left', gains=0.05, forces=1, step_sim=True):\n action = np.clip(action, a_min=self.action_space.low, a_max=self.action_space.high)\n # print('cameraYaw=%.2f, cameraPitch=%.2f, distance=%.2f' % p.getDebugVisualizerCamera(physicsClientId=self.id)[-4:-1])\n\n # print('Total time:', self.total_time)\n # self.total_time += 0.1\n self.iteration += 1\n if self.last_sim_time is None:\n self.last_sim_time = time.time()\n\n action *= 0.05\n action_robot = action\n indices = self.robot_left_arm_joint_indices if robot_arm == 'left' else self.robot_right_arm_joint_indices if robot_arm == 'right' else self.robot_both_arm_joint_indices\n\n robot_joint_states = p.getJointStates(self.robot, jointIndices=indices, physicsClientId=self.id)\n robot_joint_positions = np.array([x[0] for x in robot_joint_states])\n\n for _ in range(self.frame_skip):\n action_robot[robot_joint_positions + action_robot < self.robot_lower_limits] = 0\n action_robot[robot_joint_positions + action_robot > self.robot_upper_limits] = 0\n robot_joint_positions += action_robot\n\n p.setJointMotorControlArray(self.robot, jointIndices=indices, controlMode=p.POSITION_CONTROL, targetPositions=robot_joint_positions, positionGains=np.array([gains]*self.action_robot_len), forces=[forces]*self.action_robot_len, physicsClientId=self.id)\n\n self.setup_record_video() # pierre\n\n if step_sim:\n # Update robot position\n for _ in range(self.frame_skip):\n p.stepSimulation(physicsClientId=self.id)\n self.update_targets()\n if self.gui:\n # Slow down time so that the simulation matches real time\n self.slow_time()\n self.record_video_frame()\n\n def reset_robot_joints(self):\n # Reset all robot joints\n for rj in range(p.getNumJoints(self.robot, physicsClientId=self.id)):\n p.resetJointState(self.robot, jointIndex=rj, targetValue=0, targetVelocity=0, physicsClientId=self.id)\n\n def joint_limited_weighting(self, q, lower_limits, upper_limits):\n phi = 0.5\n lam = 0.05\n weights = []\n for qi, l, u in zip(q, lower_limits, upper_limits):\n qr = 0.5*(u - l)\n weights.append(1.0 - np.power(phi, (qr - np.abs(qr - qi + l)) / (lam*qr) + 1))\n if weights[-1] < 0.001:\n weights[-1] = 0.001\n # Joint-limited-weighting\n joint_limit_weight = np.diag(weights)\n return joint_limit_weight\n\n def get_motor_joint_states(self, robot):\n num_joints = p.getNumJoints(robot, physicsClientId=self.id)\n joint_states = p.getJointStates(robot, range(num_joints), physicsClientId=self.id)\n joint_infos = [p.getJointInfo(robot, i, physicsClientId=self.id) for i in range(num_joints)]\n joint_states = [j for j, i in zip(joint_states, joint_infos) if i[2] != p.JOINT_FIXED]\n joint_positions = [state[0] for state in joint_states]\n joint_velocities = [state[1] for state in joint_states]\n joint_torques = [state[3] for state in joint_states]\n return joint_positions, joint_velocities, joint_torques\n\n def position_robot_toc(self, robot, joints, joint_indices, lower_limits, upper_limits, pos_offset=np.zeros(3)):\n\n if type(joints) == int:\n joints = [joints]\n joint_indices = [joint_indices]\n lower_limits = [lower_limits]\n upper_limits = [upper_limits]\n\n # Reset all robot joints\n self.reset_robot_joints()\n\n # best_position = np.array([-0.03778406, -0.07913912, 0. ])\n best_position = np.array([0, 0, 0])\n best_orientation = np.array([0.0, 0.0, -0.029410315999288762, 0.9995674230950217])\n best_start_joint_poses = [[ 0.79499653, 1.66096791, -1.29904527, 2.52316092, -0.14608365, 1.67627263, -1.80315766]]\n\n # spawn robot\n p.resetBasePositionAndOrientation(robot, pos_offset + best_position, best_orientation, physicsClientId=self.id)\n\n for i, joint in enumerate(joints):\n self.world_creation.setup_robot_joints(robot, joint_indices[i], lower_limits[i], upper_limits[i], randomize_joint_positions=False, default_positions=np.array(best_start_joint_poses[i]), tool=None)\n \n return best_position, best_orientation, best_start_joint_poses\n\n def slow_time(self):\n # Slow down time so that the simulation matches real time\n t = time.time() - self.last_sim_time\n if t < self.time_step:\n time.sleep(self.time_step - t)\n self.last_sim_time = time.time()\n\n def setup_timing(self):\n self.total_time = 0\n self.last_sim_time = None\n self.iteration = 0\n\n def setup_record_video(self):\n if self.record_video and self.gui:\n if self.video_writer is not None:\n self.video_writer.release()\n now = datetime.datetime.now()\n date = now.strftime('%Y-%m-%d_%H-%M-%S')\n self.video_writer = cv2.VideoWriter('%s.avi' % (date), cv2.VideoWriter_fourcc(*'MJPG'), 10, (self.width, self.height))\n\n def record_video_frame(self):\n if self.record_video and self.gui:\n frame = np.reshape(p.getCameraImage(width=self.width, height=self.height, renderer=p.ER_BULLET_HARDWARE_OPENGL, physicsClientId=self.id)[2], (self.height, self.width, 4))[:, :, :3]\n # frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n self.video_writer.write(frame)\n\n def update_targets(self):\n pass\n\n def render(self, mode='human'):\n if not self.gui:\n self.gui = True\n p.disconnect(self.id)\n self.id = p.connect(p.GUI, options='--background_color_red=0.8 --background_color_green=0.9 --background_color_blue=1.0 --width=%d --height=%d' % (self.width, self.height))\n\n self.world_creation = WorldCreation(self.id, robot_type=self.robot_type, time_step=self.time_step, np_random=self.np_random)\n # self.util = Util(self.id, self.np_random)\n # print('Physics server ID:', self.id)\n\n" }, { "alpha_fraction": 0.6985566020011902, "alphanum_fraction": 0.7229830026626587, "avg_line_length": 38.30181884765625, "blob_id": "5678183e12cd367b08eb3b94ffe5d09742995f96", "content_id": "45fb37f58a9348883e3cce8bbc19e0972ee1b3b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 10808, "license_type": "permissive", "max_line_length": 571, "num_lines": 275, "path": "/README.md", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "# Custom Gym Environments\nSome custom Gym environments for reinforcement learning.\n\n## Installation and environment registration (Pybullet-based environments)\n\n```bash\ngit clone https://github.com/PierreExeter/custom_gym_envs.git\ncd custom_gym_envs/\nconda env create -f environment.yml\nconda activate gym_envs\npip install -e . # to register the Gym environmnents locally\n```\n## Installation of the ROS-based environments\n\n1. Install ROS Melodic\n\n2. Create and initialise your [Catkin workspace](http://wiki.ros.org/ROS/Tutorials/InstallingandConfiguringROSEnvironment).\n\n3. Install the dependencies for the Kinova-ros package, as indicated [here](https://github.com/Kinovarobotics/kinova-ros/wiki/Gazebo).\n\n```bash\nsudo apt-get install ros-<distro>-gazebo-ros-control\nsudo apt-get install ros-<distro>-ros-controllers*\nsudo apt-get install ros-<distro>-trac-ik-kinematics-plugin\nsudo apt-get install ros-<distro>-effort-controllers \nsudo apt-get install ros-<distro>-joint-state-controller \nsudo apt-get install ros-<distro>-joint-trajectory-controller \nsudo apt-get install ros-<distro>-controller-*\n```\n\n(replace `<distro>` by your ROS distribution, for example `kinetic` or `melodic`)\n\n4. Install ROS packages and create simulation workspace\n\n```bash\nmkdir -p ~/simulation_ws/src\ncp -r custom_gym_envs/ROS_packages/openai_ros ~/simulation_ws/src\n\n# Alternatively, clone original repository and checkout version2\n# git clone https://bitbucket.org/theconstructcore/openai_ros.git\n# cd openai_ros\n# git checkout version2\n\ncd ~/simulation_ws/\ncatkin_make\nsource devel/setup.bash\necho $ROS_PACKAGE_PATH\n```\n\nCheck that you see something like:\n\n```bash\n/home/user/simulation_ws/src:/home/user/catkin_ws/src:/opt/ros/melodic/share\n```\n\n```bash\ncp -r custom_gym_envs/ROS_packages/custom_ROS_envs/ ~/catkin_ws/src\ncd ~/catkin_ws\ncatkin_make\n```\n\n5. Edit ros_ws_abspath \n\nIn each config folder, edit the yaml file and change the ros_ws_abspath to match your path: \"/home/user/simulation_ws\".\nFor example:\n\n```bash\nvim ~/catkin_ws/src/custom_ROS_envs/cartpole3d_env/config/cartpole3d_random_params.yaml\n```\n\n6. Source and load rospack profile\n\nIn a new shell, execute:\n\n```bash\ncd ~/simulation_ws\ncatkin_make\nsource devel/setup.bash\nrospack profile\n```\n\nIn your main shell, execute:\n\n```bash\ncd ~/catkin_ws\nsource devel/setup.bash\nrospack profile\n```\n\n\n## Test the ROS-based environments\n\n```bash\nroslaunch cartpole3d_env start_training_cartpole3d_random.launch\nroslaunch turtlebot2_maze_env start_turtlebot2_maze_random.launch\nroslaunch turtlebot2_wall_env start_turtlebot2_wall_random.launch\n```\n\n\n## Test the Pybullet environments\n\nExecute scripts in the test_envs folder. For example:\n\n```bash\npython test_envs/4_test_reacher2D.py\n```\n\n## Test the Jaco Reach environments in Gazebo\n\nFirst, execute the ROS launch in a separate terminal:\n\n```bash\nroslaunch kinova_gazebo robot_launch_render.launch kinova_robotType:=j2n6s300 # Gazebo simulation\n# OR\nroslaunch kinova_bringup kinova_robot.launch kinova_robotType:=j2n6s300 # Physical arm\n```\n\nThen execute the test script in the test_envs folder. For example:\n\n```bash\npython test_envs/8_test_jaco_gazebo_actionlib.py\n```\n\nNote, the kinova-ros package was adapted from the [official package](https://github.com/Kinovarobotics/kinova-ros).\n\n\n## Environments description\n\n| Name | Action space | Observation space | Rewards |\n| ---------| -------------------| -----------------------| ------------- |\n| balancebot-v0 | Discrete(9): used to define wheel target velocity | Box(3,): [cube orientation , cube angular velocity , wheel velocity] | 0.1 - abs(self.vt - self.vd) * 0.005 |\n| particle-v0 | Box(2,): [force_x, force_y] | Dict(\"achieved_goal\": [coord_x, coord_y], \"desired_goal\": [coord_x, coord_y], \"observation\": [pos_x, pos_y, vel_x, vel_y]) | - dist (dense) or bool(dist <= distance_threshold) (sparse) |\n| Reacher2Dof-v0 | Box(2,): [0.05 * torque_1, 0.05 * torque_2] | Box(8,): [target_x, target_y, dist_to_target_x, dist_to_target_y, joint0_angle, joint0_vel, joint1_angle, joint1_vel | [change in dist to target, electricity_cost, stuck_joint_cost] |\n| Reacher2Dof-v1 | Box(2,): [0.05 * torque_1, 0.05 * torque_2] | Dict(\"achieved_goal\": [tip_x, tip_y], \"desired_goal\": [target_x, target_y], \"observation\": *same as above* ) | - dist |\n| widowx_reacher-v5 | Box(6,): [angle_change_joint1, angle_change_joint2, angle_change_joint3, angle_change_joint4, angle_change_joint5, angle_change_joint6] | Box(9,): [target_x, target_y, target_z, joint_angle1, joint_angle2, joint_angle3, joint_angle4, joint_angle5, joint_angle6] | - dist ^ 2 |\n| widowx_reacher-v7 | Box(6,): [angle_change_joint1, angle_change_joint2, angle_change_joint3, angle_change_joint4, angle_change_joint5, angle_change_joint6] | Dict(\"achieved_goal\": [tip_x, tip_y, tip_z], \"desired_goal\": [target_x, target_y, target_z], \"observation\": *same as above* ) | - dist ^ 2 |\n| ReachingJaco-v1 | Box(7,): [joint1_angle + 0.05 * action1, joint2_angle + 0.05 * action2, joint3_angle + 0.05 * action3, joint4_angle + 0.05 * action4, joint5_angle + 0.05 * action5, joint6_angle + 0.05 * action6, joint7_angle + 0.05 * action7] | Box(17,): [gripper_x - torso_x, gripper_y - torso_y, gripper_z - torso_z, gripper_x - target_x, gripper_y - target_y, gripper_z - target_z, joint_angle1, joint_angle2, joint_angle3, joint_angle4, joint_angle5, joint_angle6, joint_angle7, gripper_orient_x, gripper_orient_y, gripper_orient_z, gripper_orient_w] | - dist |\n| CartPoleStayUp-v0 | Discrete(2): 0 = \"move cart to position - pos_step (move left)\" or 1 = \"move cart to position + pos_step (move right)\" | Box(4,): [base_position, base_velocity, pole_angle, pole_velocity] | if not done: reward = reward_pole_angle + reward_for_effective_movement else reward = -2000000 |\n| MyTurtleBot2Maze-v0 | Discrete(3): 0 = \"move forward\", 1 = \"turn left\", 2 = \"turn right\" | Box(6,): [laser_scan array] | if not done: reward = +5 (forward) or +1 (turn) else reward = -200 |\n| MyTurtleBot2Wall-v0 | Discrete(3): 0 = \"move forward\", 1 = \"turn left\", 2 = \"turn right\" | Box(7,): [discretized_laser_scan, odometry_array] | if not done: reward = +5 (forward) or +1 (turn) ; if distance_difference < 0: reward = +5 ; if done and in desired_position: reward = +200 else reward = -200 |\n| JacoReachGazebo-v1 | Box(6,): [joint_angle_array] | Box(12,): [joint_angle_array, joint_angular_velocity_array] | - dist |\n| JacoReachGazebo-v2 | Box(1,): [angle1_increment] | Box(4,): [joint1_angle, target_x, target_y, target_z] | - dist |\n\n### Balance Bot (Pybullet)\n\nA simple Pybullet robot. The goal is to maintain the cube upwards as long as possible. Adapted from [this repo](https://github.com/yconst/balance-bot/).\n\nEnvironment name: \n- balancebot-v0\n- balancebot-noise-v0\n\n<img src=\"imgs/balancebot.gif\"/>\n\n\n### Particle\n\nA Goal Env (for testing Hindsight Experience Replay) where a red particle must reach the green target in a 2D plane. The particle is controlled by force. Adapted from [here](https://github.com/openai/baselines/issues/428)\n\nEnvironment name: \n- particle-v0\n\n<img src=\"imgs/particle.gif\"/>\n\n### Reacher2D (Pybullet)\n\nAn articulated arm in a 2D plane composed of 1 to 6 joints. The goal is to bring the tip as close as possible to the target sphere. Adapted from [this repo](https://github.com/benelot/pybullet-gym).\n\nEnvironment name: \n- Reacher1Dof-v0\n- Reacher2Dof-v0\n- Reacher3Dof-v0\n- Reacher4Dof-v0\n- Reacher5Dof-v0\n- Reacher6Dof-v0\n- Reacher1Dof-v1 (goalEnv)\n- Reacher2Dof-v1 (goalEnv)\n- Reacher3Dof-v1 (goalEnv)\n- Reacher4Dof-v1 (goalEnv)\n- Reacher5Dof-v1 (goalEnv)\n- Reacher6Dof-v1 (goalEnv)\n\n\n<img src=\"imgs/reacher2D.gif\"/>\n\n### WidowX arm (Pybullet)\n\nThe WidowX robotic arm in Pybullet. The goal is to bring the tip as close as possible to the target sphere. Adapted from [this repo](https://github.com/bhyang/replab).\n\nEnvironment name:\n- widowx_reacher-v0 (env for both the physical arm and the Pybullet simulation)\n- widowx_reacher-v1 (env for the physical arm only) \n- widowx_reacher-v2 (env for the physical arm only + no start_rospy method)\n- widowx_reacher-v3 (env for the physical arm only + no start_rospy method + goal oriented)\n- widowx_reacher-v4 (env for the Pybullet simulation only. ROS install not required)\n- widowx_reacher-v5 (env for the Pybullet simulation + no start_sim required + fixed goal)\n- widowx_reacher-v6 (env for the Pybullet simulation + no start_sim required + goal_oriented + fixed goal)\n- widowx_reacher-v7 (env for the Pybullet simulation + no start_sim required + random goal)\n- widowx_reacher-v8 (env for the Pybullet simulation + no start_sim required + goal_oriented + random goal)\n- widowx_reacher-v12 (env for the physical arm only + no start_rospy method + random goal)\n- widowx_reacher-v13 (env for the physical arm only + no start_rospy method + goal environment + random goal)\n\n\n<img src=\"imgs/widowx.gif\"/>\n\n### Jaco arm (Pybullet)\n\nThe Jaco arm in Pybullet. The goal is to bring the tip as close as possible to the target sphere. Adapted from [this repo](https://github.com/Healthcare-Robotics/assistive-gym).\n\nEnvironment name: \n- ReachingJaco-v1\n\n<img src=\"imgs/jaco.gif\"/>\n\n\n### Cartpole3D (ROS / Gazebo)\n\nThe Cartpole in ROS / Gazebo. The goal is to balance the pole upwards as long as possible. Adapted from [this repo](https://bitbucket.org/theconstructcore/openai_examples_projects/src/master/). \n\nEnvironment name: \n- CartPoleStayUp-v0\n\n<img src=\"imgs/cartpole3d.gif\"/>\n\n\n### Turtlebot2 Maze (ROS / Gazebo)\n\nThe Turtlebot2 robot in ROS / Gazebo. The goal is to avoid touching the walls. Adapted from [this repo](https://bitbucket.org/theconstructcore/openai_examples_projects/src/master/). \n\nEnvironment name: \n- MyTurtleBot2Maze-v0\n\n<img src=\"imgs/turtlebot2_maze.gif\"/>\n\n\n### Turtlebot2 Wall (ROS / Gazebo)\n\nThe Turtlebot2 robot in ROS / Gazebo. The goal is to avoid touching the wall. Adapted from [this repo](https://bitbucket.org/theconstructcore/openai_examples_projects/src/master/). \n\nEnvironment name: \n- MyTurtleBot2Wall-v0\n\n<img src=\"imgs/turtlebot2_wall.gif\"/>\n\n\n### Jaco arm (ROS / Gazebo)\n\nThe Jaco arm in ROS / Gazebo. The goal is to bring the tip as close as possible to the target sphere.\n\nEnvironment name: \n- JacoReachGazebo-v0 (Jaco arm in Gazebo with Topics)\n- JacoReachGazebo-v1 (Jaco arm in Gazebo with actionlib)\n- JacoReachGazebo-v2 (Jaco arm in Gazebo with actionlib + fixed target + only 1 joint moving + angle change)\n- JacoReachReal-v0 (Physical Jaco arm env)\n\n<img src=\"imgs/jaco_ros.gif\"/>\n\n<img src=\"imgs/jaco_ros_simple.gif\"/>\n\n\n### Minimal Working Example: GymEnv and GoalEnv\n\nEnvironment name: \n- foo-v0 (GymEnv)\n- my_goal_env-v0 (goalEnv)\n\n### Tic-Tac-Toe environment\n\nEnvironment name: \n- tictac-v0\n\n\n## Tested on\n\n- conda 4.8.3\n- Python 3.7\n" }, { "alpha_fraction": 0.5808550119400024, "alphanum_fraction": 0.5966542959213257, "avg_line_length": 23.930233001708984, "blob_id": "3a7cb94914d9eab4abfad62ca98e52e83bbe8640", "content_id": "fc2df5b340538dba5bb203bd14b49f2849eb869c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1076, "license_type": "permissive", "max_line_length": 85, "num_lines": 43, "path": "/test_envs/2_test_balance_bot.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\nimport time\n\n\nenv = gym.make(\"balancebot-v0\")\n# env = gym.make('ReacherPyBulletEnv-v0')\n\nenv.render(mode=\"human\") # this needs to be placed BEFORE env.reset() \n# env.reset() \n\nprint(\"Action space: \", env.action_space)\n# print(env.action_space.high)\n# print(env.action_space.low)\nprint(\"Observation space: \", env.observation_space)\nprint(env.observation_space.high)\nprint(env.observation_space.low)\n\n\nfor episode in range(20):\n obs = env.reset() \n rewards = []\n \n for t in range(200): \n action = env.action_space.sample() \n # action = [0.00001, 0]\n\n state, reward, done, info = env.step(action) \n rewards.append(reward)\n\n print(\"action: \", action)\n print(\"obs: \", obs)\n print(\"reward: \", reward)\n print(\"done: \", done)\n print(\"info: \", info)\n print(\"timestep: \", t)\n\n time.sleep(1./30.) \n\n cumulative_reward = sum(rewards)\n print(\"episode {} | cumulative reward : {}\".format(episode, cumulative_reward)) \n \nenv.close()\n\n\n\n\n" }, { "alpha_fraction": 0.5211591720581055, "alphanum_fraction": 0.560257613658905, "avg_line_length": 23.704545974731445, "blob_id": "5238883c92cc51097a46716eedc1388e111fd551", "content_id": "da95098ecd4c3cb00a0b1aa93494232c6e92400a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2174, "license_type": "permissive", "max_line_length": 113, "num_lines": 88, "path": "/gym_envs/1_tictactoe/tictac_env.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\n\nclass TicTacEnv(gym.Env):\n\tmetadata = {'render.modes': ['human']}\n\n\n\tdef __init__(self):\n\t\tself.state = []\n\t\tfor i in range(3):\n\t\t\tself.state += [[]]\n\t\t\tfor j in range(3):\n\t\t\t\tself.state[i] += [\"-\"]\n\t\tself.counter = 0\n\t\tself.done = 0\n\t\tself.add = [0, 0]\n\t\tself.reward = 0\n\n\tdef check(self):\n\n\t\tif(self.counter<5):\n\t\t\treturn 0\n\t\tfor i in range(3):\n\t\t\tif(self.state[i][0] != \"-\" and self.state[i][1] == self.state[i][0] and self.state[i][1] == self.state[i][2]):\n\t\t\t\tif(self.state[i][0] == \"o\"):\n\t\t\t\t\treturn 1\n\t\t\t\telse:\n\t\t\t\t\treturn 2\n\t\t\tif(self.state[0][i] != \"-\" and self.state[1][i] == self.state[0][i] and self.state[1][i] == self.state[2][i]):\n\t\t\t\tif(self.state[0][i] == \"o\"):\n\t\t\t\t\treturn 1\n\t\t\t\telse:\n\t\t\t\t\treturn 2\n\t\tif(self.state[0][0] != \"-\" and self.state[1][1] == self.state[0][0] and self.state[1][1] == self.state[2][2]):\n\t\t\tif(self.state[0][0] == \"o\"):\n\t\t\t\treturn 1\n\t\t\telse:\n\t\t\t\treturn 2\n\t\tif(self.state[0][2] != \"-\" and self.state[0][2] == self.state[1][1] and self.state[1][1] == self.state[2][0]):\n\t\t\tif(self.state[1][1] == \"o\"):\n\t\t\t\treturn 1\n\t\t\telse:\n\t\t\t\treturn 2\n\n\tdef step(self, target):\n\t\tif self.done == 1:\n\t\t\tprint(\"Game Over\")\n\t\t\treturn [self.state, self.reward, self.done, self.add]\n\t\telif self.state[int(target/3)][target%3] != \"-\":\n\t\t\tprint(\"Invalid Step\")\n\t\t\treturn [self.state, self.reward, self.done, self.add]\n\t\telse:\n\t\t\tif(self.counter%2 == 0):\n\t\t\t\tself.state[int(target/3)][target%3] = \"o\"\n\t\t\telse:\n\t\t\t\tself.state[int(target/3)][target%3] = \"x\"\n\t\t\tself.counter += 1\n\t\t\tif(self.counter == 9):\n\t\t\t\tself.done = 1;\n\n\t\twin = self.check()\n\t\tif(win):\n\t\t\tself.done = 1;\n\t\t\tprint(\"Player \", win, \" wins.\", sep = \"\", end = \"\\n\")\n\t\t\tself.add[win-1] = 1;\n\t\t\tif win == 1:\n\t\t\t\tself.reward = 100\n\t\t\telse:\n\t\t\t\tself.reward = -100\n\n\t\treturn [self.state, self.reward, self.done, self.add]\n\n\tdef reset(self):\n\t\tfor i in range(3):\n\t\t\tfor j in range(3):\n\t\t\t\tself.state[i][j] = \"-\"\n\t\tself.counter = 0\n\t\tself.done = 0\n\t\tself.add = [0, 0]\n\t\tself.reward = 0\n\t\treturn self.state\n\n\tdef render(self):\n\t\tfor i in range(3):\n\t\t\tfor j in range(3):\n\t\t\t\tprint(self.state[i][j], end = \" \")\n\t\t\tprint(\"\")\n" }, { "alpha_fraction": 0.5586097836494446, "alphanum_fraction": 0.569510281085968, "avg_line_length": 37.59756088256836, "blob_id": "edbc3137d01bbc2c299cb11339c1802af6bb38b1", "content_id": "0395ada24e0af90695f0688a89ccfad5ec127d37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6330, "license_type": "permissive", "max_line_length": 94, "num_lines": 164, "path": "/gym_envs/3_particle_goal_oriented/continuous_goal_oriented_particle.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import os\nimport copy\nimport numpy as np\n\nimport gym\nfrom gym import error, spaces\nfrom gym.utils import seeding\nfrom collections import OrderedDict\n\n\ndef goal_distance(goal_a, goal_b):\n assert goal_a.shape == goal_b.shape\n return np.linalg.norm(goal_a - goal_b, axis=-1)\n\n\nclass ParticleEnv(gym.GoalEnv):\n def __init__(self):\n self.metadata = {\n #TODO understand what to do with render modes\n 'render.modes': ['human', 'rgb_array'],\n 'video.frames_per_second': 50\n }\n\n # Env variables\n self.min_action = -1.0\n self.max_action = 1.0\n self.min_position = -1.0\n self.max_position = 1.0\n self.distance_threshold = 0.05 # Default 0.05\n self.max_speed = 0.05\n self.power = self.max_speed/20\n self.state = None\n self.reward_type = \"sparse\"\n\n # Env Spaces\n self.min_positions = np.array([self.min_position, self.min_position])\n self.max_positions = np.array([self.max_position, self.max_position])\n min_state = np.array([self.min_position, self.min_position,\n -self.max_speed, -self.max_speed])\n max_state = np.array([self.max_position, self.max_position,\n self.max_speed, self.max_speed])\n min_action = np.array([-1, -1])\n max_action = np.array([1, 1])\n self.action_space = spaces.Box(min_action, max_action, dtype='float32')\n self.start_state_space = spaces.Box(low=min_state, high=max_state)\n self.observation_space = spaces.Dict(dict(\n desired_goal=spaces.Box(self.min_positions, self.max_positions, dtype='float32'),\n achieved_goal=spaces.Box(self.min_positions, self.max_positions, dtype='float32'),\n observation=spaces.Box(min_state, max_state, dtype='float32'),\n ))\n\n # Setup\n self.viewer = None\n self.seed()\n self.goal = self._sample_goal()\n self.reset()\n\n # Env methods\n # ----------------------------\n\n def seed(self, seed=None):\n self.np_random, seed = seeding.np_random(seed)\n return [seed]\n\n def step(self, action):\n position = self.state[0:2].copy()\n velocity = self.state[2:4].copy()\n force = np.clip(action, self.action_space.low, self.action_space.high)\n velocity += force*self.power\n velocity = np.clip(velocity, np.array([-self.max_speed, -self.max_speed]),\n np.array([self.max_speed, self.max_speed]))\n position += velocity\n clip_position = np.clip(position, self.min_positions, self.max_positions)\n # Invert appropriate velocity component after collision and bounce off\n # of a wall.\n collision = (position == clip_position).astype(int)\n collision[collision == 0] = -1\n velocity = np.multiply(velocity, collision)\n # Set state\n self.state[0:2] = clip_position\n self.state[2:4] = velocity\n obs = self._get_obs()\n info = {\n 'is_success': self._is_success(obs['achieved_goal'], self.goal),\n }\n done = info['is_success']\n reward = self.compute_reward(obs['achieved_goal'], self.goal, info)\n return obs, reward, done, info\n\n def reset(self):\n self.state = self.start_state_space.sample().copy()\n self.goal = self._sample_goal().copy()\n obs = self._get_obs()\n return obs\n\n def close(self):\n if self.viewer is not None:\n self.viewer.finish()\n self.viewer = None\n\n def render(self, mode='human'):\n screen_width = 400\n screen_height = 400\n\n world_width = self.max_position - self.min_position\n scale_w = screen_width / world_width\n scale_h = screen_height / world_width\n point_radius = np.ceil(scale_w * self.distance_threshold / 2)\n\n if self.viewer is None:\n from gym.envs.classic_control import rendering\n self.viewer = rendering.Viewer(screen_width, screen_height)\n self.agent_trans = rendering.Transform()\n agent_circle = rendering.make_circle(point_radius)\n agent_circle.set_color(.8, .2, .2)\n agent_circle.add_attr(self.agent_trans)\n self.viewer.add_geom(agent_circle)\n self.goal_trans = rendering.Transform()\n goal_circle = rendering.make_circle(point_radius)\n goal_circle.set_color(.2, .8, .2)\n goal_circle.add_attr(self.goal_trans)\n self.viewer.add_geom(goal_circle)\n\n pos = self.state[0:2]\n self.agent_trans.set_translation((pos[0] - self.min_position) * scale_w,\n (pos[1] - self.min_position) * scale_h)\n self.goal_trans.set_translation((self.goal[0] - self.min_position) * scale_w,\n (self.goal[1] - self.min_position) * scale_h)\n\n return self.viewer.render(return_rgb_array=mode == 'rgb_array')\n\n # Extension methods\n # ----------------------------\n def _get_obs(self):\n return OrderedDict([(\"desired_goal\", self.goal.copy()),\n (\"achieved_goal\", self.state[0:2].copy()),\n (\"observation\", self.state.copy())])\n\n def _is_success(self, achieved_goal, desired_goal):\n \"\"\"Indicates whether or not the achieved goal successfully achieved the desired goal.\n \"\"\"\n success = ((goal_distance(desired_goal, achieved_goal) <\n self.distance_threshold)).astype(np.float32)\n if success:\n print(\"Success!!! With distance of {} between a_g:{}, and d_g {}\"\n \"!\".format(goal_distance(achieved_goal, desired_goal),\n achieved_goal, desired_goal))\n return success\n\n def _sample_goal(self):\n \"\"\"Samples a new goal and returns it.\n \"\"\"\n goal = self.observation_space.sample()[\"desired_goal\"].copy()\n return goal\n\n # GoalEnv methods\n # ----------------------------\n\n def compute_reward(self, achieved_goal, goal, info):\n dist = goal_distance(achieved_goal, goal)\n if self.reward_type == 'sparse':\n return (dist <= self.distance_threshold).astype(np.float32)\n else:\n return -dist\n" }, { "alpha_fraction": 0.48691391944885254, "alphanum_fraction": 0.5124038457870483, "avg_line_length": 31.97341537475586, "blob_id": "fb03fade76877ef10e5939276aa412585e57cc22", "content_id": "7e7b16911352ab2b68602293f51ac34ca45cea07", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16124, "license_type": "permissive", "max_line_length": 112, "num_lines": 489, "path": "/gym_envs/reacher2D/envs/reacher_env.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "from gym_envs.reacher2D.envs.env_bases import BaseBulletEnv\nfrom gym_envs.reacher2D.envs.scene_bases import SingleRobotEmptyScene\nimport numpy as np\nfrom gym_envs.reacher2D.envs.reacher import Reacher1\nfrom gym_envs.reacher2D.envs.reacher import Reacher2\nfrom gym_envs.reacher2D.envs.reacher import Reacher3\nfrom gym_envs.reacher2D.envs.reacher import Reacher4\nfrom gym_envs.reacher2D.envs.reacher import Reacher5\nfrom gym_envs.reacher2D.envs.reacher import Reacher6\n\n\nclass ReacherBulletEnv1(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher1()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n\n self.robot.apply_action(a)\n self.scene.global_step()\n\n state = self.robot.calc_state() # sets self.to_target_vec\n\n potential_old = self.potential\n self.potential = self.robot.calc_potential()\n\n electricity_cost = (\n -0.10 * ( \n np.abs(a[0] * self.robot.angle0_dot) \n ) # work torque*angular_velocity\n - 0.01 * (\n np.abs(a[0]) \n ) # stall torque require some energy\n )\n\n stuck_joint_cost = 0 # stuck joint don't apply when the robot only has 1 joint\n\n \n self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n self.HUD(state, a, False)\n tot_reward = sum(self.rewards)\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n info = self.extra_info()\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return state, tot_reward, done, info\n\n def extra_info(self):\n dist_ft_origin, dist_t_origin, dist_ft_t, max_reach = self.robot.robot_info()\n\n is_success = False\n if dist_ft_t <= 0.01:\n is_success = True\n\n info = {\n \"dist_ft_origin\": dist_ft_origin,\n \"dist_t_origin\": dist_t_origin,\n \"dist_ft_t\": dist_ft_t,\n \"max_reach\": max_reach,\n \"is_success\": is_success\n }\n \n return info\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\nclass ReacherBulletEnv2(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher2()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n self.robot.apply_action(a)\n self.scene.global_step()\n\n state = self.robot.calc_state() # sets self.to_target_vec\n\n potential_old = self.potential\n self.potential = self.robot.calc_potential()\n\n electricity_cost = (\n -0.10 * ( \n np.abs(a[0] * self.robot.angle0_dot) + \n np.abs(a[1] * self.robot.angle1_dot)\n ) # work torque*angular_velocity\n - 0.01 * (\n np.abs(a[0]) + \n np.abs(a[1])\n ) # stall torque require some energy\n )\n\n stuck_joint_cost = 0\n if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n \n self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n self.HUD(state, a, False)\n tot_reward = sum(self.rewards)\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n info = self.extra_info()\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return state, tot_reward, done, info\n\n def extra_info(self):\n dist_ft_origin, dist_t_origin, dist_ft_t, max_reach = self.robot.robot_info()\n\n self.is_success = False\n if dist_ft_t <= 0.01:\n self.is_success = True\n\n info = {\n \"dist_ft_origin\": dist_ft_origin,\n \"dist_t_origin\": dist_t_origin,\n \"dist_ft_t\": dist_ft_t,\n \"max_reach\": max_reach,\n \"is_success\": self.is_success\n }\n \n return info\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\n\nclass ReacherBulletEnv3(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher3()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n\n self.robot.apply_action(a)\n self.scene.global_step()\n\n state = self.robot.calc_state() # sets self.to_target_vec\n\n potential_old = self.potential\n self.potential = self.robot.calc_potential()\n\n electricity_cost = (\n -0.10 * ( \n np.abs(a[0] * self.robot.angle0_dot) + \n np.abs(a[1] * self.robot.angle0_dot) + \n np.abs(a[2] * self.robot.angle1_dot)\n ) # work torque*angular_velocity\n - 0.01 * (\n np.abs(a[0]) + \n np.abs(a[1]) + \n np.abs(a[2])\n ) # stall torque require some energy\n )\n\n stuck_joint_cost = 0\n if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle2) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n \n self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n self.HUD(state, a, False)\n tot_reward = sum(self.rewards)\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n info = self.extra_info()\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return state, tot_reward, done, info\n\n def extra_info(self):\n dist_ft_origin, dist_t_origin, dist_ft_t, max_reach = self.robot.robot_info()\n\n is_success = False\n if dist_ft_t <= 0.01:\n is_success = True\n\n info = {\n \"dist_ft_origin\": dist_ft_origin,\n \"dist_t_origin\": dist_t_origin,\n \"dist_ft_t\": dist_ft_t,\n \"max_reach\": max_reach,\n \"is_success\": is_success\n }\n \n return info\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\n\n\nclass ReacherBulletEnv4(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher4()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n self.robot.apply_action(a)\n self.scene.global_step()\n\n state = self.robot.calc_state() # sets self.to_target_vec\n\n potential_old = self.potential\n self.potential = self.robot.calc_potential()\n\n electricity_cost = (\n -0.10 * ( \n np.abs(a[0] * self.robot.angle0_dot) + \n np.abs(a[1] * self.robot.angle0_dot) + \n np.abs(a[2] * self.robot.angle0_dot) + \n np.abs(a[3] * self.robot.angle1_dot)\n ) # work torque*angular_velocity\n - 0.01 * (\n np.abs(a[0]) + \n np.abs(a[1]) + \n np.abs(a[2]) + \n np.abs(a[3])\n ) # stall torque require some energy\n )\n\n stuck_joint_cost = 0\n if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle2) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle3) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n \n self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n self.HUD(state, a, False)\n tot_reward = sum(self.rewards)\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n info = self.extra_info()\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return state, tot_reward, done, info\n\n def extra_info(self):\n dist_ft_origin, dist_t_origin, dist_ft_t, max_reach = self.robot.robot_info()\n\n is_success = False\n if dist_ft_t <= 0.01:\n is_success = True\n\n info = {\n \"dist_ft_origin\": dist_ft_origin,\n \"dist_t_origin\": dist_t_origin,\n \"dist_ft_t\": dist_ft_t,\n \"max_reach\": max_reach,\n \"is_success\": is_success\n }\n \n return info\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\n\nclass ReacherBulletEnv5(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher5()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n self.robot.apply_action(a)\n self.scene.global_step()\n\n state = self.robot.calc_state() # sets self.to_target_vec\n\n potential_old = self.potential\n self.potential = self.robot.calc_potential()\n\n electricity_cost = (\n -0.10 * ( \n np.abs(a[0] * self.robot.angle0_dot) + \n np.abs(a[1] * self.robot.angle0_dot) + \n np.abs(a[2] * self.robot.angle0_dot) + \n np.abs(a[3] * self.robot.angle0_dot) + \n np.abs(a[4] * self.robot.angle1_dot)\n ) # work torque*angular_velocity\n - 0.01 * (\n np.abs(a[0]) + \n np.abs(a[1]) + \n np.abs(a[2]) + \n np.abs(a[3]) + \n np.abs(a[4])\n ) # stall torque require some energy\n )\n\n stuck_joint_cost = 0\n if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle2) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle3) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle4) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n \n self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n self.HUD(state, a, False)\n tot_reward = sum(self.rewards)\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n info = self.extra_info()\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return state, tot_reward, done, info\n\n def extra_info(self):\n dist_ft_origin, dist_t_origin, dist_ft_t, max_reach = self.robot.robot_info()\n\n is_success = False\n if dist_ft_t <= 0.01:\n is_success = True\n\n info = {\n \"dist_ft_origin\": dist_ft_origin,\n \"dist_t_origin\": dist_t_origin,\n \"dist_ft_t\": dist_ft_t,\n \"max_reach\": max_reach,\n \"is_success\": is_success\n }\n \n return info\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\nclass ReacherBulletEnv6(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher6()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n self.robot.apply_action(a)\n self.scene.global_step()\n\n state = self.robot.calc_state() # sets self.to_target_vec\n\n potential_old = self.potential\n self.potential = self.robot.calc_potential()\n\n electricity_cost = (\n -0.10 * ( \n np.abs(a[0] * self.robot.angle0_dot) + \n np.abs(a[1] * self.robot.angle0_dot) + \n np.abs(a[2] * self.robot.angle0_dot) + \n np.abs(a[3] * self.robot.angle0_dot) + \n np.abs(a[4] * self.robot.angle0_dot) + \n np.abs(a[5] * self.robot.angle1_dot)\n ) # work torque*angular_velocity\n - 0.01 * (\n np.abs(a[0]) + \n np.abs(a[1]) + \n np.abs(a[2]) + \n np.abs(a[3]) + \n np.abs(a[4]) + \n np.abs(a[5])\n ) # stall torque require some energy\n )\n\n stuck_joint_cost = 0\n if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle2) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle3) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle4) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n if np.abs(np.abs(self.robot.angle5) - 1) < 0.01:\n stuck_joint_cost -= 0.1\n \n self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n self.HUD(state, a, False)\n tot_reward = sum(self.rewards)\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n info = self.extra_info()\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return state, tot_reward, done, info\n\n def extra_info(self):\n dist_ft_origin, dist_t_origin, dist_ft_t, max_reach = self.robot.robot_info()\n\n is_success = False\n if dist_ft_t <= 0.01:\n is_success = True\n\n info = {\n \"dist_ft_origin\": dist_ft_origin,\n \"dist_t_origin\": dist_t_origin,\n \"dist_ft_t\": dist_ft_t,\n \"max_reach\": max_reach,\n \"is_success\": is_success\n }\n \n return info\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n" }, { "alpha_fraction": 0.5809959769248962, "alphanum_fraction": 0.6038923859596252, "avg_line_length": 29.92035484313965, "blob_id": "cbae6d67e5a8065d91e2d84ab4131d890e1eaf6f", "content_id": "99ec5b791bae6f13cf0f28cf278ecdea8d67ed30", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3494, "license_type": "permissive", "max_line_length": 117, "num_lines": 113, "path": "/gym_envs/8_reaching_jaco_ROS/jaco_gazebo_actionlib_fixedGoal_1jointOnly.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\nimport random\n\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\nfrom gym_envs.reaching_jaco_ROS.ros_scripts.jaco_gazebo_action_client import JacoGazeboActionClient\n\n\n\nclass JacoEnv(gym.Env):\n\n def __init__(self):\n\n self.robot = JacoGazeboActionClient()\n\n self.action_dim = 6\n # self.obs_dim = 36\n self.obs_dim = 12 # when using read_state_simple\n\n high = np.ones([self.action_dim])\n self.action_space = gym.spaces.Box(-high, high)\n \n high = np.inf * np.ones([self.obs_dim])\n self.observation_space = gym.spaces.Box(-high, high)\n \n\n def convert_action_to_deg(self, a, OldMin, OldMax, NewMin, NewMax):\n \n OldRange = (OldMax - OldMin) \n NewRange = (NewMax - NewMin) \n\n return (((a - OldMin) * NewRange) / OldRange) + NewMin\n \n \n def action2deg(self, action):\n action[0] = self.convert_action_to_deg(action[0], OldMin=-1, OldMax=1, NewMin=0, NewMax=360)\n action[1] = 180\n action[2] = self.convert_action_to_deg(action[2], OldMin=-1, OldMax=1, NewMin=90, NewMax=270)\n action[3] = self.convert_action_to_deg(action[3], OldMin=-1, OldMax=1, NewMin=0, NewMax=360)\n action[4] = self.convert_action_to_deg(action[4], OldMin=-1, OldMax=1, NewMin=0, NewMax=360)\n action[5] = self.convert_action_to_deg(action[5], OldMin=-1, OldMax=1, NewMin=0, NewMax=360)\n\n return action\n\n\n def step(self, action):\n\n # convert action from range [-1, 1] to [0, 360] \n self.action = self.action2deg(action)\n\n # convert to radians \n self.action = np.radians(self.action)\n\n # move arm \n self.robot.move_arm(self.action)\n \n # get state\n # self.observation = self.robot.read_state()\n self.observation = self.robot.read_state_simple() # only return 12 values instead of 36\n\n # calculate reward\n self.tip_coord = self.robot.get_tip_coord()\n self.dist_to_target = np.linalg.norm(self.tip_coord - self.target_vect)\n self.reward = - self.dist_to_target \n\n # create info\n self.info = {\"tip coordinates\": self.tip_coord, \"target coordinates\": self.target_vect}\n\n # create done\n self.done = False\n\n # IF DEFINING DONE AS FOLLOWS, THE EPISODE ENDS EARLY AND A GOOD AGENT WILL RECEIVED A PENALTY FOR BEING GOOD\n # COOMENT THIS\n # if self.dist_to_target < 0.01:\n # self.done = True\n \n # print(\"tip position: \", self.tip_coord)\n # print(\"target vect: \", self.target_vect)\n # print(\"dist_to_target: \", self.dist_to_target)\n\n return self.observation, self.reward, self.done, self.info\n\n\n def reset(self): \n\n self.robot.cancel_move()\n\n pos = [10, 180, 90, 0, 0, 0]\n pos = np.radians(pos)\n\n self.robot.move_arm(pos)\n print(\"Jaco reset to initial position\")\n\n # get observation\n self.obs = self.robot.read_state_simple_bla()\n\n # Fixed target coordinates\n x_target = 0.7\n y_target = 0\n z_target = 0.7\n\n self.target_vect = np.array([x_target, y_target, z_target])\n print(\"Fixed target coordinates initialised\")\n\n # if testing: graphically move the sphere target, if training, comment this line\n self.robot.move_sphere(self.target_vect)\n\n return self.obs\n\n\n def render(self, mode='human', close=False):\n pass\n" }, { "alpha_fraction": 0.644410252571106, "alphanum_fraction": 0.6599961519241333, "avg_line_length": 60.869049072265625, "blob_id": "0522a3b0283d492e94223b91b8df4e273e23edcd", "content_id": "abf4981d6831189cd5ee2f32cf127b5ecb2497a8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10394, "license_type": "permissive", "max_line_length": 243, "num_lines": 168, "path": "/gym_envs/7_reaching_jaco/world_creation.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\nimport pybullet as p\nfrom screeninfo import get_monitors\n\nclass WorldCreation:\n\n\n def __init__(self, pid, robot_type='jaco', time_step=0.02, np_random=None):\n self.id = pid\n self.robot_type = robot_type\n self.time_step = time_step\n self.np_random = np_random\n self.directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'assets')\n\n\n def create_new_world(self, print_joints=False):\n\n p.resetSimulation(physicsClientId=self.id)\n\n # Configure camera position\n p.resetDebugVisualizerCamera(cameraDistance=1.75, cameraYaw=-25, cameraPitch=-45, cameraTargetPosition=[-0.2, 0, 0.4], physicsClientId=self.id)\n\n p.configureDebugVisualizer(p.COV_ENABLE_MOUSE_PICKING, 0, physicsClientId=self.id)\n p.configureDebugVisualizer(p.COV_ENABLE_GUI, 0, physicsClientId=self.id)\n\n # Load all models off screen and then move them into place\n p.loadURDF(os.path.join(self.directory, 'plane', 'plane.urdf'), physicsClientId=self.id)\n\n # Disable rendering during creation\n p.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 0, physicsClientId=self.id)\n\n p.setTimeStep(self.time_step, physicsClientId=self.id)\n # Disable real time simulation so that the simulation only advances when we call stepSimulation\n p.setRealTimeSimulation(0, physicsClientId=self.id)\n\n # Jaco\n robot, robot_lower_limits, robot_upper_limits, robot_right_arm_joint_indices, robot_left_arm_joint_indices = self.init_jaco(print_joints)\n\n return robot, robot_lower_limits, robot_upper_limits, robot_right_arm_joint_indices, robot_left_arm_joint_indices\n\n\n def enforce_joint_limits(self, body):\n # Enforce joint limits\n joint_states = p.getJointStates(body, jointIndices=list(range(p.getNumJoints(body, physicsClientId=self.id))), physicsClientId=self.id)\n joint_positions = np.array([x[0] for x in joint_states])\n lower_limits = []\n upper_limits = []\n for j in range(p.getNumJoints(body, physicsClientId=self.id)):\n joint_info = p.getJointInfo(body, j, physicsClientId=self.id)\n joint_name = joint_info[1]\n joint_pos = joint_positions[j]\n lower_limit = joint_info[8]\n upper_limit = joint_info[9]\n if lower_limit == 0 and upper_limit == -1:\n lower_limit = -1e10\n upper_limit = 1e10\n lower_limits.append(lower_limit)\n upper_limits.append(upper_limit)\n # print(joint_name, joint_pos, lower_limit, upper_limit)\n if joint_pos < lower_limit:\n p.resetJointState(body, jointIndex=j, targetValue=lower_limit, targetVelocity=0, physicsClientId=self.id)\n elif joint_pos > upper_limit:\n p.resetJointState(body, jointIndex=j, targetValue=upper_limit, targetVelocity=0, physicsClientId=self.id)\n lower_limits = np.array(lower_limits)\n upper_limits = np.array(upper_limits)\n return lower_limits, upper_limits\n\n\n def init_jaco(self, print_joints=False):\n robot = p.loadURDF(os.path.join(self.directory, 'jaco', 'j2s7s300_gym.urdf'), useFixedBase=True, basePosition=[0, 0, 0], flags=p.URDF_USE_SELF_COLLISION, physicsClientId=self.id)\n robot_arm_joint_indices = [1, 2, 3, 4, 5, 6, 7]\n if print_joints:\n self.print_joint_info(robot, show_fixed=True)\n\n # Initialize and position\n p.resetBasePositionAndOrientation(robot, [-2, -2, 0.975], [0, 0, 0, 1], physicsClientId=self.id)\n\n # Grab and enforce robot arm joint limits\n lower_limits, upper_limits = self.enforce_joint_limits(robot)\n\n return robot, lower_limits, upper_limits, robot_arm_joint_indices, robot_arm_joint_indices\n\n\n def set_gripper_open_position(self, robot, position=0, left=True, set_instantly=False, indices=None):\n indices_new = [9, 11, 13]\n positions = [position, position, position]\n if indices is None:\n indices = indices_new\n\n if set_instantly:\n for i, j in enumerate(indices):\n p.resetJointState(robot, jointIndex=j, targetValue=positions[i], targetVelocity=0, physicsClientId=self.id)\n p.setJointMotorControlArray(robot, jointIndices=indices, controlMode=p.POSITION_CONTROL, targetPositions=positions, positionGains=np.array([0.05]*len(indices)), forces=[500]*len(indices), physicsClientId=self.id)\n\n\n def init_tool(self, robot, mesh_scale=[1]*3, pos_offset=[0]*3, orient_offset=[0, 0, 0, 1], left=True, maximal=False, alpha=1.0):\n if left:\n gripper_pos, gripper_orient = p.getLinkState(robot, 8, computeForwardKinematics=True, physicsClientId=self.id)[:2]\n else:\n gripper_pos, gripper_orient = p.getLinkState(robot, 8, computeForwardKinematics=True, physicsClientId=self.id)[:2]\n transform_pos, transform_orient = p.multiplyTransforms(positionA=gripper_pos, orientationA=gripper_orient, positionB=pos_offset, orientationB=orient_offset, physicsClientId=self.id)\n \n self.task = 'scratch_itch' # added by Pierre to choose the tool\n\n if self.task == 'scratch_itch':\n tool = p.loadURDF(os.path.join(self.directory, 'tools', 'tool_scratch.urdf'), basePosition=transform_pos, baseOrientation=transform_orient, physicsClientId=self.id)\n elif self.task == 'bed_bathing':\n tool = p.loadURDF(os.path.join(self.directory, 'tools', 'wiper.urdf'), basePosition=transform_pos, baseOrientation=transform_orient, physicsClientId=self.id)\n elif self.task in ['drinking', 'scooping', 'feeding', 'arm_manipulation']:\n if self.task == 'drinking':\n visual_filename = os.path.join(self.directory, 'tools', 'plastic_coffee_cup.obj')\n collision_filename = os.path.join(self.directory, 'tools', 'plastic_coffee_cup_vhacd.obj')\n elif self.task in ['scooping', 'feeding']:\n visual_filename = os.path.join(self.directory, 'tools', 'spoon_reduced_compressed.obj')\n collision_filename = os.path.join(self.directory, 'tools', 'spoon_vhacd.obj')\n elif self.task == 'arm_manipulation':\n visual_filename = os.path.join(self.directory, 'tools', 'arm_manipulation_scooper.obj')\n collision_filename = os.path.join(self.directory, 'tools', 'arm_manipulation_scooper_vhacd.obj')\n tool_visual = p.createVisualShape(shapeType=p.GEOM_MESH, fileName=visual_filename, meshScale=mesh_scale, rgbaColor=[1, 1, 1, alpha], physicsClientId=self.id)\n tool_collision = p.createCollisionShape(shapeType=p.GEOM_MESH, fileName=collision_filename, meshScale=mesh_scale, physicsClientId=self.id)\n tool = p.createMultiBody(baseMass=0.01, baseCollisionShapeIndex=tool_collision, baseVisualShapeIndex=tool_visual, basePosition=transform_pos, baseOrientation=transform_orient, useMaximalCoordinates=maximal, physicsClientId=self.id)\n if left:\n # Disable collisions between the tool and robot\n for j in [7, 8, 9, 10, 11, 12, 13, 14]:\n for tj in list(range(p.getNumJoints(tool, physicsClientId=self.id))) + [-1]:\n p.setCollisionFilterPair(robot, tool, j, tj, False, physicsClientId=self.id)\n # Create constraint that keeps the tool in the gripper\n constraint = p.createConstraint(robot, 8, tool, -1, p.JOINT_FIXED, [0, 0, 0], parentFramePosition=pos_offset, childFramePosition=[0, 0, 0], parentFrameOrientation=orient_offset, physicsClientId=self.id)\n else:\n # Disable collisions between the tool and robot\n for j in [7, 8, 9, 10, 11, 12, 13, 14]:\n for tj in list(range(p.getNumJoints(tool, physicsClientId=self.id))) + [-1]:\n p.setCollisionFilterPair(robot, tool, j, tj, False, physicsClientId=self.id)\n # Create constraint that keeps the tool in the gripper\n constraint = p.createConstraint(robot, 8, tool, -1, p.JOINT_FIXED, [0, 0, 0], parentFramePosition=pos_offset, childFramePosition=[0, 0, 0], parentFrameOrientation=orient_offset, physicsClientId=self.id)\n p.changeConstraint(constraint, maxForce=500, physicsClientId=self.id)\n return tool\n\n def setup_robot_joints(self, robot, robot_joint_indices, lower_limits, upper_limits, randomize_joint_positions=False, default_positions=[1, 1, 0, -1.75, 0, -1.1, -0.5], tool=None):\n if randomize_joint_positions:\n # Randomize arm joint positions\n # Keep trying random joint positions until the end effector is not colliding with anything\n retry = True\n while retry:\n for j, lower_limit, upper_limit in zip(robot_joint_indices, lower_limits, upper_limits):\n if lower_limit == -1e10:\n lower_limit = -np.pi\n upper_limit = np.pi\n joint_range = upper_limit - lower_limit\n p.resetJointState(robot, jointIndex=j, targetValue=self.np_random.uniform(lower_limit + joint_range/6.0, upper_limit - joint_range/6.0), targetVelocity=0, physicsClientId=self.id)\n p.stepSimulation(physicsClientId=self.id)\n retry = len(p.getContactPoints(bodyA=robot, physicsClientId=self.id)) > 0\n if tool is not None:\n retry = retry or (len(p.getContactPoints(bodyA=tool, physicsClientId=self.id)) > 0)\n else:\n default_positions[default_positions < lower_limits] = lower_limits[default_positions < lower_limits]\n default_positions[default_positions > upper_limits] = upper_limits[default_positions > upper_limits]\n for i, j in enumerate(robot_joint_indices):\n p.resetJointState(robot, jointIndex=j, targetValue=default_positions[i], targetVelocity=0, physicsClientId=self.id)\n\n def print_joint_info(self, body, show_fixed=True):\n joint_names = []\n for j in range(p.getNumJoints(body, physicsClientId=self.id)):\n if show_fixed or p.getJointInfo(body, j, physicsClientId=self.id)[2] != p.JOINT_FIXED:\n print(p.getJointInfo(body, j, physicsClientId=self.id))\n joint_names.append((j, p.getJointInfo(body, j, physicsClientId=self.id)[1]))\n print(joint_names)\n" }, { "alpha_fraction": 0.5263692140579224, "alphanum_fraction": 0.5437862873077393, "avg_line_length": 35.65327453613281, "blob_id": "476ab6a68f918cc147caed26ecfa7ecc9e7f742b", "content_id": "4f69df3687386e74807c89da1f9ed56cd9077f35", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 24631, "license_type": "permissive", "max_line_length": 124, "num_lines": 672, "path": "/gym_envs/reacher2D/goal_envs/reacher_env.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "from gym_envs.reacher2D.goal_envs.env_bases import BaseBulletEnv\nfrom gym_envs.reacher2D.goal_envs.scene_bases import SingleRobotEmptyScene\nfrom gym import GoalEnv, spaces\nimport numpy as np\nfrom gym_envs.reacher2D.goal_envs.reacher import Reacher1\nfrom gym_envs.reacher2D.goal_envs.reacher import Reacher2\nfrom gym_envs.reacher2D.goal_envs.reacher import Reacher3\nfrom gym_envs.reacher2D.goal_envs.reacher import Reacher4\nfrom gym_envs.reacher2D.goal_envs.reacher import Reacher5\nfrom gym_envs.reacher2D.goal_envs.reacher import Reacher6\n\n\nclass ReacherBulletEnv1(BaseBulletEnv, GoalEnv):\n def __init__(self):\n self.robot = Reacher1()\n BaseBulletEnv.__init__(self, self.robot)\n\n self.REWARD_WEIGHTS = np.array([1, 0.3])\n self.SUCCESS_GOAL_REWARD = 0.12\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n\n self.robot.apply_action(a)\n self.scene.global_step()\n\n current_state = self.robot.calc_state() # sets self.to_target_vec\n\n # potential_old = self.potential\n # self.potential = self.robot.calc_potential()\n\n # electricity_cost = (\n # -0.10 * ( \n # np.abs(a[0] * self.robot.angle0_dot) \n # ) # work torque*angular_velocity\n # - 0.01 * (\n # np.abs(a[0]) \n # ) # stall torque require some energy\n # )\n\n # stuck_joint_cost = 0 # stuck joint don't apply when the robot only has 1 joint\n\n \n # self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n # self.HUD(current_state, a, False)\n # tot_reward = sum(self.rewards)\n\n # define info\n info = self.robot.extra_info()\n\n obs = {'observation': current_state, 'achieved_goal': info['fingertip_coord'], 'desired_goal': info['target_coord']}\n\n tot_reward = self.compute_reward(obs['achieved_goal'], obs['desired_goal'], info) # new HER goal\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n\n # update info\n # info['is_success'] = self._is_success(obs['achieved_goal'], obs['desired_goal'])\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return obs, tot_reward, done, info\n\n # this should be equivalent ?\n def compute_reward(self, achieved_goal, desired_goal, info):\n self.dist_vec = np.array(achieved_goal - np.array(desired_goal)) \n return - np.linalg.norm(self.dist_vec)\n \n \n # def compute_reward(self, achieved_goal, desired_goal, p=0.5):\n # \"\"\"\n # Proximity to the goal is rewarded\n\n # We use a weighted p-norm\n # :param achieved_goal: the goal that was achieved\n # :param desired_goal: the goal that was desired\n # :param p: the Lp^p norm used in the reward. Use p<1 to have high kurtosis for rewards in [0, 1]\n # :return: the corresponding reward\n # \"\"\"\n # return - np.power(np.dot(np.abs(achieved_goal - desired_goal), self.REWARD_WEIGHTS), p)\n\n\n # def _is_success(self, achieved_goal, desired_goal):\n # return self.compute_reward(achieved_goal, desired_goal) > -self.SUCCESS_GOAL_REWARD\n\n\n # def extra_info(self):\n # dist_ft_origin, dist_t_origin, dist_ft_t, max_reach, target_vect, fingertip_vect = self.robot.robot_info()\n\n # info = {\n # \"dist_ft_origin\": dist_ft_origin,\n # \"dist_t_origin\": dist_t_origin,\n # \"dist_ft_t\": dist_ft_t,\n # \"max_reach\": max_reach,\n # \"target_coord\": target_vect,\n # \"fingertip_coord\": fingertip_vect\n # }\n \n # return info\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\nclass ReacherBulletEnv2(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher2()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n self.robot.apply_action(a)\n self.scene.global_step()\n\n current_state = self.robot.calc_state() # sets self.to_target_vec\n\n # potential_old = self.potential\n # self.potential = self.robot.calc_potential()\n\n # electricity_cost = (\n # -0.10 * ( \n # np.abs(a[0] * self.robot.angle0_dot) + \n # np.abs(a[1] * self.robot.angle1_dot)\n # ) # work torque*angular_velocity\n # - 0.01 * (\n # np.abs(a[0]) + \n # np.abs(a[1])\n # ) # stall torque require some energy\n # )\n\n # stuck_joint_cost = 0\n # if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n \n # self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n # self.HUD(current_state, a, False)\n # tot_reward = sum(self.rewards)\n\n # define info\n info = self.robot.extra_info()\n\n obs = {'observation': current_state, 'achieved_goal': info['fingertip_coord'], 'desired_goal': info['target_coord']}\n\n tot_reward = self.compute_reward(obs['achieved_goal'], obs['desired_goal'], info) # new HER goal\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n\n # update info\n # info['is_success'] = self._is_success(obs['achieved_goal'], obs['desired_goal'])\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return obs, tot_reward, done, info\n\n # this should be equivalent ?\n def compute_reward(self, achieved_goal, desired_goal, info):\n self.dist_vec = np.array(achieved_goal - np.array(desired_goal)) \n return - np.linalg.norm(self.dist_vec)\n \n \n # def compute_reward(self, achieved_goal, desired_goal, p=0.5):\n # \"\"\"\n # Proximity to the goal is rewarded\n\n # We use a weighted p-norm\n # :param achieved_goal: the goal that was achieved\n # :param desired_goal: the goal that was desired\n # :param p: the Lp^p norm used in the reward. Use p<1 to have high kurtosis for rewards in [0, 1]\n # :return: the corresponding reward\n # \"\"\"\n # return - np.power(np.dot(np.abs(achieved_goal - desired_goal), self.REWARD_WEIGHTS), p)\n\n\n # def _is_success(self, achieved_goal, desired_goal):\n # return self.compute_reward(achieved_goal, desired_goal) > -self.SUCCESS_GOAL_REWARD\n\n\n # def extra_info(self):\n # dist_ft_origin, dist_t_origin, dist_ft_t, max_reach, target_vect, fingertip_vect = self.robot.robot_info()\n\n # info = {\n # \"dist_ft_origin\": dist_ft_origin,\n # \"dist_t_origin\": dist_t_origin,\n # \"dist_ft_t\": dist_ft_t,\n # \"max_reach\": max_reach,\n # \"target_coord\": target_vect,\n # \"fingertip_coord\": fingertip_vect\n # }\n \n # return info\n\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\n\nclass ReacherBulletEnv3(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher3()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n\n self.robot.apply_action(a)\n self.scene.global_step()\n\n current_state = self.robot.calc_state() # sets self.to_target_vec\n\n # potential_old = self.potential\n # self.potential = self.robot.calc_potential()\n\n # electricity_cost = (\n # -0.10 * ( \n # np.abs(a[0] * self.robot.angle0_dot) + \n # np.abs(a[1] * self.robot.angle0_dot) + \n # np.abs(a[2] * self.robot.angle1_dot)\n # ) # work torque*angular_velocity\n # - 0.01 * (\n # np.abs(a[0]) + \n # np.abs(a[1]) + \n # np.abs(a[2])\n # ) # stall torque require some energy\n # )\n\n # stuck_joint_cost = 0\n # if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle2) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n \n # self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n # self.HUD(current_state, a, False)\n # tot_reward = sum(self.rewards)\n\n # define info\n info = self.robot.extra_info()\n\n obs = {'observation': current_state, 'achieved_goal': info['fingertip_coord'], 'desired_goal': info['target_coord']}\n\n tot_reward = self.compute_reward(obs['achieved_goal'], obs['desired_goal'], info) # new HER goal\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n\n # update info\n # info['is_success'] = self._is_success(obs['achieved_goal'], obs['desired_goal'])\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return obs, tot_reward, done, info\n\n # this should be equivalent ?\n def compute_reward(self, achieved_goal, desired_goal, info):\n self.dist_vec = np.array(achieved_goal - np.array(desired_goal)) \n return - np.linalg.norm(self.dist_vec)\n \n \n # def compute_reward(self, achieved_goal, desired_goal, p=0.5):\n # \"\"\"\n # Proximity to the goal is rewarded\n\n # We use a weighted p-norm\n # :param achieved_goal: the goal that was achieved\n # :param desired_goal: the goal that was desired\n # :param p: the Lp^p norm used in the reward. Use p<1 to have high kurtosis for rewards in [0, 1]\n # :return: the corresponding reward\n # \"\"\"\n # return - np.power(np.dot(np.abs(achieved_goal - desired_goal), self.REWARD_WEIGHTS), p)\n\n\n # def _is_success(self, achieved_goal, desired_goal):\n # return self.compute_reward(achieved_goal, desired_goal) > -self.SUCCESS_GOAL_REWARD\n\n\n # def extra_info(self):\n # dist_ft_origin, dist_t_origin, dist_ft_t, max_reach, target_vect, fingertip_vect = self.robot.robot_info()\n\n # info = {\n # \"dist_ft_origin\": dist_ft_origin,\n # \"dist_t_origin\": dist_t_origin,\n # \"dist_ft_t\": dist_ft_t,\n # \"max_reach\": max_reach,\n # \"target_coord\": target_vect,\n # \"fingertip_coord\": fingertip_vect\n # }\n \n # return info\n\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\n\n\nclass ReacherBulletEnv4(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher4()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n self.robot.apply_action(a)\n self.scene.global_step()\n\n current_state = self.robot.calc_state() # sets self.to_target_vec\n\n # potential_old = self.potential\n # self.potential = self.robot.calc_potential()\n\n # electricity_cost = (\n # -0.10 * ( \n # np.abs(a[0] * self.robot.angle0_dot) + \n # np.abs(a[1] * self.robot.angle0_dot) + \n # np.abs(a[2] * self.robot.angle0_dot) + \n # np.abs(a[3] * self.robot.angle1_dot)\n # ) # work torque*angular_velocity\n # - 0.01 * (\n # np.abs(a[0]) + \n # np.abs(a[1]) + \n # np.abs(a[2]) + \n # np.abs(a[3])\n # ) # stall torque require some energy\n # )\n\n # stuck_joint_cost = 0\n # if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle2) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle3) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n \n # self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n # self.HUD(current_state, a, False)\n # tot_reward = sum(self.rewards)\n\n # define info\n info = self.robot.extra_info()\n\n obs = {'observation': current_state, 'achieved_goal': info['fingertip_coord'], 'desired_goal': info['target_coord']}\n\n tot_reward = self.compute_reward(obs['achieved_goal'], obs['desired_goal'], info) # new HER goal\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n\n # update info\n # info['is_success'] = self._is_success(obs['achieved_goal'], obs['desired_goal'])\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return obs, tot_reward, done, info\n\n # this should be equivalent ?\n def compute_reward(self, achieved_goal, desired_goal, info):\n self.dist_vec = np.array(achieved_goal - np.array(desired_goal)) \n return - np.linalg.norm(self.dist_vec)\n \n \n # def compute_reward(self, achieved_goal, desired_goal, p=0.5):\n # \"\"\"\n # Proximity to the goal is rewarded\n\n # We use a weighted p-norm\n # :param achieved_goal: the goal that was achieved\n # :param desired_goal: the goal that was desired\n # :param p: the Lp^p norm used in the reward. Use p<1 to have high kurtosis for rewards in [0, 1]\n # :return: the corresponding reward\n # \"\"\"\n # return - np.power(np.dot(np.abs(achieved_goal - desired_goal), self.REWARD_WEIGHTS), p)\n\n\n # def _is_success(self, achieved_goal, desired_goal):\n # return self.compute_reward(achieved_goal, desired_goal) > -self.SUCCESS_GOAL_REWARD\n\n\n # def extra_info(self):\n # dist_ft_origin, dist_t_origin, dist_ft_t, max_reach, target_vect, fingertip_vect = self.robot.robot_info()\n\n # info = {\n # \"dist_ft_origin\": dist_ft_origin,\n # \"dist_t_origin\": dist_t_origin,\n # \"dist_ft_t\": dist_ft_t,\n # \"max_reach\": max_reach,\n # \"target_coord\": target_vect,\n # \"fingertip_coord\": fingertip_vect\n # }\n \n # return info\n\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\n\nclass ReacherBulletEnv5(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher5()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n self.robot.apply_action(a)\n self.scene.global_step()\n\n current_state = self.robot.calc_state() # sets self.to_target_vec\n\n # potential_old = self.potential\n # self.potential = self.robot.calc_potential()\n\n # electricity_cost = (\n # -0.10 * ( \n # np.abs(a[0] * self.robot.angle0_dot) + \n # np.abs(a[1] * self.robot.angle0_dot) + \n # np.abs(a[2] * self.robot.angle0_dot) + \n # np.abs(a[3] * self.robot.angle0_dot) + \n # np.abs(a[4] * self.robot.angle1_dot)\n # ) # work torque*angular_velocity\n # - 0.01 * (\n # np.abs(a[0]) + \n # np.abs(a[1]) + \n # np.abs(a[2]) + \n # np.abs(a[3]) + \n # np.abs(a[4])\n # ) # stall torque require some energy\n # )\n\n # stuck_joint_cost = 0\n # if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle2) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle3) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle4) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n \n # self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n # self.HUD(current_state, a, False)\n # tot_reward = sum(self.rewards)\n\n # define info\n info = self.robot.extra_info()\n\n obs = {'observation': current_state, 'achieved_goal': info['fingertip_coord'], 'desired_goal': info['target_coord']}\n\n tot_reward = self.compute_reward(obs['achieved_goal'], obs['desired_goal'], info) # new HER goal\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n\n # update info\n # info['is_success'] = self._is_success(obs['achieved_goal'], obs['desired_goal'])\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return obs, tot_reward, done, info\n\n # this should be equivalent ?\n def compute_reward(self, achieved_goal, desired_goal, info):\n self.dist_vec = np.array(achieved_goal - np.array(desired_goal)) \n return - np.linalg.norm(self.dist_vec)\n \n \n # def compute_reward(self, achieved_goal, desired_goal, p=0.5):\n # \"\"\"\n # Proximity to the goal is rewarded\n\n # We use a weighted p-norm\n # :param achieved_goal: the goal that was achieved\n # :param desired_goal: the goal that was desired\n # :param p: the Lp^p norm used in the reward. Use p<1 to have high kurtosis for rewards in [0, 1]\n # :return: the corresponding reward\n # \"\"\"\n # return - np.power(np.dot(np.abs(achieved_goal - desired_goal), self.REWARD_WEIGHTS), p)\n\n\n # def _is_success(self, achieved_goal, desired_goal):\n # return self.compute_reward(achieved_goal, desired_goal) > -self.SUCCESS_GOAL_REWARD\n\n\n # def extra_info(self):\n # dist_ft_origin, dist_t_origin, dist_ft_t, max_reach, target_vect, fingertip_vect = self.robot.robot_info()\n\n # info = {\n # \"dist_ft_origin\": dist_ft_origin,\n # \"dist_t_origin\": dist_t_origin,\n # \"dist_ft_t\": dist_ft_t,\n # \"max_reach\": max_reach,\n # \"target_coord\": target_vect,\n # \"fingertip_coord\": fingertip_vect\n # }\n \n # return info\n\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n\n\nclass ReacherBulletEnv6(BaseBulletEnv):\n def __init__(self):\n self.robot = Reacher6()\n BaseBulletEnv.__init__(self, self.robot)\n\n def create_single_player_scene(self, bullet_client):\n return SingleRobotEmptyScene(bullet_client, gravity=0.0, timestep=0.0165, frame_skip=1)\n\n def step(self, a):\n assert (not self.scene.multiplayer)\n self.robot.apply_action(a)\n self.scene.global_step()\n\n current_state = self.robot.calc_state() # sets self.to_target_vec\n\n # potential_old = self.potential\n # self.potential = self.robot.calc_potential()\n\n # electricity_cost = (\n # -0.10 * ( \n # np.abs(a[0] * self.robot.angle0_dot) + \n # np.abs(a[1] * self.robot.angle0_dot) + \n # np.abs(a[2] * self.robot.angle0_dot) + \n # np.abs(a[3] * self.robot.angle0_dot) + \n # np.abs(a[4] * self.robot.angle0_dot) + \n # np.abs(a[5] * self.robot.angle1_dot)\n # ) # work torque*angular_velocity\n # - 0.01 * (\n # np.abs(a[0]) + \n # np.abs(a[1]) + \n # np.abs(a[2]) + \n # np.abs(a[3]) + \n # np.abs(a[4]) + \n # np.abs(a[5])\n # ) # stall torque require some energy\n # )\n\n # stuck_joint_cost = 0\n # if np.abs(np.abs(self.robot.angle1) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle2) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle3) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle4) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n # if np.abs(np.abs(self.robot.angle5) - 1) < 0.01:\n # stuck_joint_cost -= 0.1\n \n # self.rewards = [float(self.potential - potential_old), float(electricity_cost), float(stuck_joint_cost)]\n # self.HUD(current_state, a, False)\n # tot_reward = sum(self.rewards)\n\n # define info\n info = self.robot.extra_info()\n\n obs = {'observation': current_state, 'achieved_goal': info['fingertip_coord'], 'desired_goal': info['target_coord']}\n\n tot_reward = self.compute_reward(obs['achieved_goal'], obs['desired_goal'], info) # new HER goal\n\n # Define done: an episode is successful if the distance fingertip - target <= 0.01\n done = False\n\n # update info\n # info['is_success'] = self._is_success(obs['achieved_goal'], obs['desired_goal'])\n\n # if info[\"dist_ft_t\"] <= 0.01: \n # print(\"target reached!\")\n # tot_reward += 10\n # done=True\n\n return obs, tot_reward, done, info\n\n # this should be equivalent ?\n def compute_reward(self, achieved_goal, desired_goal, info):\n self.dist_vec = np.array(achieved_goal - np.array(desired_goal)) \n return - np.linalg.norm(self.dist_vec)\n \n \n # def compute_reward(self, achieved_goal, desired_goal, p=0.5):\n # \"\"\"\n # Proximity to the goal is rewarded\n\n # We use a weighted p-norm\n # :param achieved_goal: the goal that was achieved\n # :param desired_goal: the goal that was desired\n # :param p: the Lp^p norm used in the reward. Use p<1 to have high kurtosis for rewards in [0, 1]\n # :return: the corresponding reward\n # \"\"\"\n # return - np.power(np.dot(np.abs(achieved_goal - desired_goal), self.REWARD_WEIGHTS), p)\n\n\n # def _is_success(self, achieved_goal, desired_goal):\n # return self.compute_reward(achieved_goal, desired_goal) > -self.SUCCESS_GOAL_REWARD\n\n\n # def extra_info(self):\n # dist_ft_origin, dist_t_origin, dist_ft_t, max_reach, target_vect, fingertip_vect = self.robot.robot_info()\n\n # info = {\n # \"dist_ft_origin\": dist_ft_origin,\n # \"dist_t_origin\": dist_t_origin,\n # \"dist_ft_t\": dist_ft_t,\n # \"max_reach\": max_reach,\n # \"target_coord\": target_vect,\n # \"fingertip_coord\": fingertip_vect\n # }\n \n # return info\n\n\n\n def camera_adjust(self):\n x, y, z = self.robot.fingertip.pose().xyz()\n x *= 0.5\n y *= 0.5\n self.camera.move_and_look_at(0.3, 0.3, 0.3, x, y, z)\n" }, { "alpha_fraction": 0.6022228598594666, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 29.526784896850586, "blob_id": "2a2f8b6194e57981f0b68aa24fa740cf70887eb4", "content_id": "2441f9120ba027d123a4f9af0610951826060cef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3419, "license_type": "permissive", "max_line_length": 183, "num_lines": 112, "path": "/gym_envs/reaching_jaco_ROS/jaco_gazebo_actionlib_fixedGoal_1jointOnly.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport numpy as np\nimport random\nimport time\n\nfrom gym import error, spaces, utils\nfrom gym.utils import seeding\nfrom gym_envs.reaching_jaco_ROS.ros_scripts.jaco_gazebo_action_client import JacoGazeboActionClient\n\n\n\nclass JacoEnv(gym.Env):\n\n def __init__(self):\n\n self.robot = JacoGazeboActionClient()\n\n self.action_dim = 1\n self.obs_dim = 4\n\n high = np.ones([self.action_dim])\n self.action_space = gym.spaces.Box(-high, high)\n \n high = np.ones([self.obs_dim])\n self.observation_space = gym.spaces.Box(-high, high)\n \n\n def convert_action_to_new_range(self, a, OldMin, OldMax, NewMin, NewMax):\n \n OldRange = (OldMax - OldMin) \n NewRange = (NewMax - NewMin) \n\n return (((a - OldMin) * NewRange) / OldRange) + NewMin\n \n \n def action2increment(self, action):\n self.max_increment_step = 10 # in degree. Decrease to increase accuracy but reduce amplitude motion.\n\n self.angle_increment = self.convert_action_to_new_range(action, OldMin=-1, OldMax=1, NewMin=-(2*np.pi/360*self.max_increment_step), NewMax=2*np.pi/360*self.max_increment_step)\n return self.angle_increment\n\n\n def step(self, action):\n\n # read old angle\n self.old_angle1 = self.robot.read_angle_joint1()\n\n # calculate new angle\n self.angle_change1 = self.action2increment(action) \n self.new_angle1 = self.old_angle1 + self.angle_change1\n\n # create array of joint angles and move arm \n self.joint_angles = np.concatenate((self.new_angle1, [np.pi, np.pi/2, 0, 0, 0]), axis=None)\n self.robot.move_arm(self.joint_angles)\n \n # get state\n self.angle1 = self.robot.read_angle_joint1()\n\n self.obs = np.concatenate((self.angle1, self.target_vect), axis=None)\n\n # calculate reward\n self.tip_coord = self.robot.get_tip_coord()\n self.dist_to_target = np.linalg.norm(self.tip_coord - self.target_vect)\n self.reward = - self.dist_to_target \n\n # create info\n self.info = {\"tip position\": self.tip_coord, \"goal position\": self.target_vect, \"total_distance\": self.dist_to_target}\n\n # create done\n self.done = False\n\n # IF DEFINING DONE AS FOLLOWS, THE EPISODE ENDS EARLY AND A GOOD AGENT WILL RECEIVED A PENALTY FOR BEING GOOD\n # COOMENT THIS\n # if self.dist_to_target < 0.01:\n # self.done = True\n \n # print(\"tip position: \", self.tip_coord)\n # print(\"target vect: \", self.target_vect)\n # print(\"dist_to_target: \", self.dist_to_target)\n\n return self.obs, self.reward, self.done, self.info\n\n\n def reset(self): \n\n self.robot.cancel_move()\n\n pos = [0, np.pi, np.pi/2, 0, 0, 0]\n\n self.robot.move_arm(pos)\n # time.sleep(2)\n print(\"Jaco reset to initial position\")\n\n # get observation\n self.obs = self.robot.read_angle_joint1()\n\n # Fixed target coordinates\n x_target = 0.7\n y_target = 0\n z_target = 0.7\n\n self.target_vect = np.array([x_target, y_target, z_target])\n print(\"Fixed target coordinates initialised\")\n\n # if testing: graphically move the sphere target, if training, comment this line\n # self.robot.move_sphere(self.target_vect)\n\n return self.obs\n\n\n def render(self, mode='human', close=False):\n pass\n" }, { "alpha_fraction": 0.5873544216156006, "alphanum_fraction": 0.599833607673645, "avg_line_length": 23.53061294555664, "blob_id": "be5becc615ffc9785140f833d66220583e3fe6bf", "content_id": "80c887a12b118dfd24133cf8467e63e8081880ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1202, "license_type": "permissive", "max_line_length": 60, "num_lines": 49, "path": "/test_envs/14_test_kuka_button_env_registration.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "\"\"\" Test env with random actions \"\"\"\n\nimport time\nimport gym\nimport gym_envs\n# from stable_baselines3.common.env_checker import check_env\n\nenv = gym.make('KukaButtonGymEnv-v0')\n# print(\"any warnings?\", check_env(env))\n\n# Comment this out for goal environments\nprint(\"Action space: \", env.action_space)\n# print(\"low: \", env.action_space.low)\n# print(\"high: \", env.action_space.high)\nprint(\"Observation space: \", env.observation_space)\n# print(\"low: \", env.observation_space.low)\n# print(\"high: \", env.observation_space.high)\n\nenv.render()\n\n\nfor episode in range(5):\n obs = env.reset()\n rewards = []\n\n for t in range(100):\n action = env.action_space.sample()\n # action = [0, 0, 0, 0, 0, 4]\n\n obs, reward, done, info = env.step(action)\n env.render()\n\n print(\"action: \", action)\n print(\"obs: \", obs)\n print(\"reward: \", reward)\n print(\"done: \", done)\n print(\"info: \", info)\n print(\"timestep: \", t)\n\n rewards.append(reward)\n time.sleep(1. / 30.)\n\n cumulative_reward = sum(rewards)\n print(\n \"episode {} | cumulative reward : {}\".format(\n episode,\n cumulative_reward))\n\nenv.close()\n" }, { "alpha_fraction": 0.6705107092857361, "alphanum_fraction": 0.6820428371429443, "avg_line_length": 25.369565963745117, "blob_id": "a2d664a69f2a7a44a87a4a8c3dc983338fd53bcc", "content_id": "0864951fa2cb8baca0ad334da31d75e2cdb01abb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1214, "license_type": "permissive", "max_line_length": 90, "num_lines": 46, "path": "/test_envs/8_test_jaco_gazebo_actionlib_fixedGoal_1jointOnly.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\nimport random\nimport numpy as np \nimport rospy\n\n# First of all, launch Jaco in Gazebo in another terminal with:\n# roslaunch kinova_gazebo robot_launch_noRender_noSphere.launch kinova_robotType:=j2n6s300\n# OR\n# roslaunch kinova_gazebo robot_launch_render.launch kinova_robotType:=j2n6s300\n\nrospy.init_node(\"kinova_client\", anonymous=True, log_level=rospy.INFO)\nenv = gym.make('JacoReachGazebo-v2')\n\nprint('Environment:', env)\nprint('Action space:', env.action_space)\nprint(env.action_space.high)\nprint(env.action_space.low)\nprint('State space:', env.observation_space)\nprint(env.observation_space.high)\nprint(env.observation_space.low)\n\n\nfor episode in range(3):\n\n obs = env.reset()\n rewards = []\n\n for t in range(20):\n\n action = env.action_space.sample()\n obs, reward, done, info = env.step(action)\n\n print(\"timestep:\", t)\n print(\"action: \", action)\n print(\"observation: \", obs)\n print(\"reward: \", reward)\n print(\"done: \", done)\n print(\"info: \", info)\n\n rewards.append(reward)\n\n cumulative_reward = sum(rewards)\n print(\"episode {} | cumulative reward : {}\".format(episode, cumulative_reward)) \n\nenv.close()\n\n" }, { "alpha_fraction": 0.4885057508945465, "alphanum_fraction": 0.49712643027305603, "avg_line_length": 16.399999618530273, "blob_id": "882d997263cf92719005f29954449400675b096d", "content_id": "17f8ba27f8bfb9c42f14447361aedaf89933156b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 348, "license_type": "permissive", "max_line_length": 53, "num_lines": 20, "path": "/test_envs/1_test_tictactoe.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import gym\nimport gym_envs\n\n\nenv = gym.make('tictac-v0')\n\nfor e in range(3):\n env.reset()\n print(\"######\")\n print(\"EPISODE: \", e)\n print(\"######\")\n\n for t in range(9):\n env.render()\n action = t\n state, reward, done, info = env.step(action) \n print(\"reward: \", reward)\n print(\"******\")\n\nenv.close()\n" }, { "alpha_fraction": 0.6677566766738892, "alphanum_fraction": 0.6875408887863159, "avg_line_length": 59.5544548034668, "blob_id": "268bac978b5b4d1d51a40a5dcb6ef432313ff802", "content_id": "5fda3f4ab9461afc6c145a93020fb80e31844fa0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6116, "license_type": "permissive", "max_line_length": 296, "num_lines": 101, "path": "/gym_envs/7_reaching_jaco/reaching.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "import os\nfrom gym import spaces\nimport numpy as np\nimport pybullet as p\nfrom .env import RobotEnv\n\n\nclass ReachingEnv(RobotEnv):\n\n def __init__(self, robot_type='jaco'):\n super(ReachingEnv, self).__init__(robot_type=robot_type, frame_skip=5, time_step=0.02, action_robot_len=7, obs_robot_len=17)\n\n def step(self, action):\n\n # from config file (deleted) (task = [reaching])\n self.robot_forces = 1.0\n self.robot_gains = 0.05\n self.distance_weight = 1.0\n self.task_success_threshold = 0.03\n\n # Execute action\n self.take_step(action, robot_arm='right', gains=self.robot_gains, forces=self.robot_forces)\n\n # Get the Euclidean distance between the robot's end effector and the target\n gripper_pos = np.array(p.getLinkState(self.robot, 8, computeForwardKinematics=True, physicsClientId=self.id)[0])\n reward_distance_target = -np.linalg.norm(gripper_pos - self.target_pos)\n \n # Get end effector velocity\n # end_effector_velocity = np.linalg.norm(p.getLinkState(self.robot, 8, computeForwardKinematics=True, computeLinkVelocity=True, physicsClientId=self.id)[6])\n\n # Get observations and reward\n obs = self._get_obs()\n reward = self.distance_weight * reward_distance_target\n\n info = {'task_success': int(-reward_distance_target <= self.task_success_threshold), 'action_robot_len': self.action_robot_len, 'obs_robot_len': self.obs_robot_len}\n done = False\n\n return obs, reward, done, info\n\n def _get_obs(self):\n torso_pos = np.array(p.getLinkState(self.robot, 0, computeForwardKinematics=True, physicsClientId=self.id)[0])\n robot_right_joint_positions = np.array([x[0] for x in p.getJointStates(self.robot, jointIndices=self.robot_right_arm_joint_indices, physicsClientId=self.id)])\n gripper_pos, gripper_orient = p.getLinkState(self.robot, 8, computeForwardKinematics=True, physicsClientId=self.id)[:2]\n\n # print(\"torso_pos: \", torso_pos)\n # print(\"robot_right_joint_positions: \", robot_right_joint_positions)\n # print(\"gripper_pos: \", gripper_pos)\n # print(\"gripper_orient: \", gripper_orient)\n # print(\"self.target_pos: \", self.target_pos)\n # print(\"forces: \", forces)\n\n # why did they define the robot obs this way and not by joint angle position and velocity (sounds more intuitive)?\n # why do they include the target in the definition of the target position?\n robot_obs = np.concatenate([gripper_pos-torso_pos, gripper_pos-self.target_pos, robot_right_joint_positions, gripper_orient]).ravel()\n\n return robot_obs\n\n def reset(self):\n self.setup_timing()\n self.task_success = 0\n self.contact_points_on_arm = {}\n self.robot, self.robot_lower_limits, self.robot_upper_limits, self.robot_right_arm_joint_indices, self.robot_left_arm_joint_indices = self.world_creation.create_new_world(print_joints=False)\n \n self.robot_lower_limits = self.robot_lower_limits[self.robot_left_arm_joint_indices]\n self.robot_upper_limits = self.robot_upper_limits[self.robot_left_arm_joint_indices]\n self.reset_robot_joints()\n\n # Disable gravity\n # p.setGravity(0, 0, -9.81, physicsClientId=self.id)\n p.setGravity(0, 0, 0, physicsClientId=self.id)\n # p.setGravity(0, 0, 0, body=self.robot, physicsClientId=self.id)\n\n # assuming that the max reach of the Jaco is 0.7, the target is generated randomly inside the inscribed cube of the reaching sphere\n self.target_pos = np.array([0, 0, 0.95]) + np.array([self.np_random.uniform(-0.7*np.cos(np.pi/4), 0.7*np.cos(np.pi/4)), self.np_random.uniform(-0.7*np.cos(np.pi/4), 0.7*np.cos(np.pi/4)), self.np_random.uniform(0, 0.7*np.cos(np.pi/4))])\n self.target_orient = p.getQuaternionFromEuler(np.array([0, np.pi/2.0, 0]), physicsClientId=self.id)\n sphere_collision = -1\n sphere_visual = p.createVisualShape(shapeType=p.GEOM_SPHERE, radius=0.03, rgbaColor=[0, 1, 0, 1], physicsClientId=self.id)\n self.target = p.createMultiBody(baseMass=0.0, baseCollisionShapeIndex=sphere_collision, baseVisualShapeIndex=sphere_visual, basePosition=self.target_pos, useMaximalCoordinates=False, physicsClientId=self.id)\n\n # Jaco\n _, _ , _ = self.position_robot_toc(self.robot, 8, self.robot_left_arm_joint_indices, self.robot_lower_limits, self.robot_upper_limits, pos_offset=np.array([0, 0, 0.6]))\n \n self.world_creation.set_gripper_open_position(self.robot, position=1.1, left=True, set_instantly=True)\n \n # load tool\n self.tool = self.world_creation.init_tool(self.robot, mesh_scale=[1]*3, pos_offset=[-0.01, 0, 0.03], orient_offset=p.getQuaternionFromEuler([0, -np.pi/2.0, 0], physicsClientId=self.id), maximal=False)\n \n # Load a nightstand in the environment for the jaco arm\n self.nightstand_scale = 0.275\n visual_filename = os.path.join(self.world_creation.directory, 'nightstand', 'nightstand.obj')\n collision_filename = os.path.join(self.world_creation.directory, 'nightstand', 'nightstand.obj')\n nightstand_visual = p.createVisualShape(shapeType=p.GEOM_MESH, fileName=visual_filename, meshScale=[self.nightstand_scale]*3, rgbaColor=[0.5, 0.5, 0.5, 1.0], physicsClientId=self.id)\n nightstand_collision = p.createCollisionShape(shapeType=p.GEOM_MESH, fileName=collision_filename, meshScale=[self.nightstand_scale]*3, physicsClientId=self.id)\n nightstand_pos = np.array([0, 0, 0])\n nightstand_orient = p.getQuaternionFromEuler(np.array([np.pi/2.0, 0, 0]), physicsClientId=self.id)\n self.nightstand = p.createMultiBody(baseMass=0, baseCollisionShapeIndex=nightstand_collision, baseVisualShapeIndex=nightstand_visual, basePosition=nightstand_pos, baseOrientation=nightstand_orient, baseInertialFramePosition=[0, 0, 0], useMaximalCoordinates=False, physicsClientId=self.id)\n \n # Enable rendering\n p.configureDebugVisualizer(p.COV_ENABLE_RENDERING, 1, physicsClientId=self.id)\n\n return self._get_obs()\n" }, { "alpha_fraction": 0.566486656665802, "alphanum_fraction": 0.6000641584396362, "avg_line_length": 38.04384231567383, "blob_id": "85cf4aa1275cdea2121f1b18473a177b2cac5d18", "content_id": "ee057eed495e1af062e20ee08f3cb58895795283", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 18703, "license_type": "permissive", "max_line_length": 106, "num_lines": 479, "path": "/gym_envs/reacher2D/envs/reacher.py", "repo_name": "PierreExeter/custom_gym_envs", "src_encoding": "UTF-8", "text": "from gym_envs.reacher2D.envs.robot_bases import MJCFBasedRobot\nimport numpy as np\n\n\nclass Reacher1(MJCFBasedRobot):\n TARG_LIMIT = 0.11 #0.27 #0.01 #0.27\n\n def __init__(self):\n MJCFBasedRobot.__init__(self, 'reacher_1dof.xml', 'body0', action_dim=1, obs_dim=6)\n\n def robot_specific_reset(self, bullet_client):\n\n self.fingertip = self.parts[\"fingertip\"]\n self.target = self.parts[\"target\"]\n self.joint0 = self.jdict[\"joint0\"]\n\n self.joint0.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n\n # make sure that the target is reachable\n self.dist_target_origin = 1\n self.max_reach = 0\n\n while self.dist_target_origin > self.max_reach:\n\n self.jdict[\"target_x\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n self.jdict[\"target_y\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n\n _, self.dist_target_origin, _, self.max_reach = self.robot_info()\n\n def apply_action(self, a):\n assert (np.isfinite(a).all())\n self.joint0.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))\n\n def calc_state(self):\n self.angle0, self.angle0_dot = self.joint0.current_relative_position()\n\n target_x, _ = self.jdict[\"target_x\"].current_position()\n target_y, _ = self.jdict[\"target_y\"].current_position()\n\n self.to_target_vec = np.array(self.fingertip.pose().xyz()) - np.array(self.target.pose().xyz()) \n\n return np.array([\n target_x,\n target_y,\n self.to_target_vec[0],\n self.to_target_vec[1],\n self.angle0,\n self.angle0_dot\n ])\n\n def calc_potential(self):\n return -100 * np.linalg.norm(self.to_target_vec)\n\n def robot_info(self):\n\n self.target_vect = np.array(self.target.pose().xyz())[:-1]\n self.fingertip_vect = np.array(self.fingertip.pose().xyz())[:-1]\n\n dist_ft_origin = np.linalg.norm(self.fingertip_vect) \n dist_t_origin = np.linalg.norm(self.target_vect)\n dist_ft_t = np.linalg.norm(self.fingertip_vect - self.target_vect)\n max_reach = 0.11\n\n return dist_ft_origin, dist_t_origin, dist_ft_t, max_reach\n\n\nclass Reacher2(MJCFBasedRobot):\n TARG_LIMIT = 0.22 #0.27\n\n def __init__(self):\n MJCFBasedRobot.__init__(self, 'reacher_2dof.xml', 'body0', action_dim=2, obs_dim=8)\n\n def robot_specific_reset(self, bullet_client):\n\n self.fingertip = self.parts[\"fingertip\"]\n self.target = self.parts[\"target\"]\n\n self.joint0 = self.jdict[\"joint0\"]\n self.joint1 = self.jdict[\"joint1\"]\n\n self.joint0.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint1.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n\n # make sure that the target is reachable\n self.dist_target_origin = 1\n self.max_reach = 0\n\n while self.dist_target_origin > self.max_reach:\n\n self.jdict[\"target_x\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n self.jdict[\"target_y\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n\n _, self.dist_target_origin, _, self.max_reach = self.robot_info()\n\n def apply_action(self, a):\n assert (np.isfinite(a).all())\n self.joint0.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))\n self.joint1.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))\n\n def calc_state(self):\n self.angle0, self.angle0_dot = self.joint0.current_relative_position()\n self.angle1, self.angle1_dot = self.joint1.current_relative_position()\n\n target_x, _ = self.jdict[\"target_x\"].current_position()\n target_y, _ = self.jdict[\"target_y\"].current_position()\n\n self.to_target_vec = np.array(self.fingertip.pose().xyz()) - np.array(self.target.pose().xyz())\n\n return np.array([\n target_x,\n target_y,\n self.to_target_vec[0],\n self.to_target_vec[1],\n self.angle0,\n self.angle0_dot,\n self.angle1,\n self.angle1_dot\n ])\n\n def calc_potential(self):\n return -100 * np.linalg.norm(self.to_target_vec)\n\n def robot_info(self):\n\n self.target_vect = np.array(self.target.pose().xyz())[:-1]\n self.fingertip_vect = np.array(self.fingertip.pose().xyz())[:-1]\n\n dist_ft_origin = np.linalg.norm(self.fingertip_vect) \n dist_t_origin = np.linalg.norm(self.target_vect)\n dist_ft_t = np.linalg.norm(self.fingertip_vect - self.target_vect)\n max_reach = 0.11*2\n\n return dist_ft_origin, dist_t_origin, dist_ft_t, max_reach\n\nclass Reacher3(MJCFBasedRobot):\n TARG_LIMIT = 0.33 #0.27\n\n def __init__(self):\n MJCFBasedRobot.__init__(self, 'reacher_3dof.xml', 'body0', action_dim=3, obs_dim=10)\n\n def robot_specific_reset(self, bullet_client):\n\n self.fingertip = self.parts[\"fingertip\"]\n self.target = self.parts[\"target\"]\n\n self.joint0 = self.jdict[\"joint0\"]\n self.joint1 = self.jdict[\"joint1\"]\n self.joint2 = self.jdict[\"joint2\"]\n\n self.joint0.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint1.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint2.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n\n # make sure that the target is reachable\n self.dist_target_origin = 1\n self.max_reach = 0\n\n while self.dist_target_origin > self.max_reach:\n\n self.jdict[\"target_x\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n self.jdict[\"target_y\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n\n _, self.dist_target_origin, _, self.max_reach = self.robot_info()\n\n def apply_action(self, a): \n assert (np.isfinite(a).all())\n self.joint0.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))\n self.joint1.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))\n self.joint2.set_motor_torque(0.05 * float(np.clip(a[2], -1, +1)))\n\n def calc_state(self):\n self.angle0, self.angle0_dot = self.joint0.current_relative_position()\n self.angle1, self.angle1_dot = self.joint1.current_relative_position()\n self.angle2, self.angle2_dot = self.joint2.current_relative_position()\n\n target_x, _ = self.jdict[\"target_x\"].current_position()\n target_y, _ = self.jdict[\"target_y\"].current_position()\n\n self.to_target_vec = np.array(self.fingertip.pose().xyz()) - np.array(self.target.pose().xyz())\n\n return np.array([\n target_x,\n target_y,\n self.to_target_vec[0],\n self.to_target_vec[1],\n self.angle0,\n self.angle0_dot,\n self.angle1,\n self.angle1_dot,\n self.angle2,\n self.angle2_dot\n ])\n\n def calc_potential(self):\n return -100 * np.linalg.norm(self.to_target_vec)\n\n def robot_info(self):\n\n self.target_vect = np.array(self.target.pose().xyz())[:-1]\n self.fingertip_vect = np.array(self.fingertip.pose().xyz())[:-1]\n\n dist_ft_origin = np.linalg.norm(self.fingertip_vect) \n dist_t_origin = np.linalg.norm(self.target_vect)\n dist_ft_t = np.linalg.norm(self.fingertip_vect - self.target_vect)\n max_reach = 0.11*3\n\n return dist_ft_origin, dist_t_origin, dist_ft_t, max_reach\n\n\nclass Reacher4(MJCFBasedRobot):\n TARG_LIMIT = 0.44 #0.27\n\n def __init__(self):\n MJCFBasedRobot.__init__(self, 'reacher_4dof.xml', 'body0', action_dim=4, obs_dim=12)\n\n def robot_specific_reset(self, bullet_client):\n\n self.fingertip = self.parts[\"fingertip\"]\n self.target = self.parts[\"target\"]\n\n self.joint0 = self.jdict[\"joint0\"]\n self.joint1 = self.jdict[\"joint1\"]\n self.joint2 = self.jdict[\"joint2\"]\n self.joint3 = self.jdict[\"joint3\"]\n\n self.joint0.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint1.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint2.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint3.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n\n # make sure that the target is reachable\n self.dist_target_origin = 1\n self.max_reach = 0\n\n while self.dist_target_origin > self.max_reach:\n\n self.jdict[\"target_x\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n self.jdict[\"target_y\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n\n _, self.dist_target_origin, _, self.max_reach = self.robot_info()\n \n def apply_action(self, a):\n assert (np.isfinite(a).all())\n self.joint0.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))\n self.joint1.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))\n self.joint2.set_motor_torque(0.05 * float(np.clip(a[2], -1, +1)))\n self.joint3.set_motor_torque(0.05 * float(np.clip(a[3], -1, +1)))\n\n def calc_state(self):\n self.angle0, self.angle0_dot = self.joint0.current_relative_position()\n self.angle1, self.angle1_dot = self.joint1.current_relative_position()\n self.angle2, self.angle2_dot = self.joint2.current_relative_position()\n self.angle3, self.angle3_dot = self.joint3.current_relative_position()\n\n target_x, _ = self.jdict[\"target_x\"].current_position()\n target_y, _ = self.jdict[\"target_y\"].current_position()\n\n self.to_target_vec = np.array(self.fingertip.pose().xyz()) - np.array(self.target.pose().xyz())\n\n return np.array([\n target_x,\n target_y,\n self.to_target_vec[0],\n self.to_target_vec[1],\n self.angle0,\n self.angle0_dot,\n self.angle1,\n self.angle1_dot,\n self.angle2,\n self.angle2_dot,\n self.angle3,\n self.angle3_dot\n ])\n\n def calc_potential(self):\n return -100 * np.linalg.norm(self.to_target_vec)\n\n def robot_info(self):\n\n self.target_vect = np.array(self.target.pose().xyz())[:-1]\n self.fingertip_vect = np.array(self.fingertip.pose().xyz())[:-1]\n\n dist_ft_origin = np.linalg.norm(self.fingertip_vect) \n dist_t_origin = np.linalg.norm(self.target_vect)\n dist_ft_t = np.linalg.norm(self.fingertip_vect - self.target_vect)\n max_reach = 0.11*4\n\n return dist_ft_origin, dist_t_origin, dist_ft_t, max_reach\n\nclass Reacher5(MJCFBasedRobot):\n TARG_LIMIT = 0.55 #0.27\n\n def __init__(self):\n MJCFBasedRobot.__init__(self, 'reacher_5dof.xml', 'body0', action_dim=5, obs_dim=14)\n\n def robot_specific_reset(self, bullet_client):\n\n self.fingertip = self.parts[\"fingertip\"]\n self.target = self.parts[\"target\"]\n\n self.joint0 = self.jdict[\"joint0\"]\n self.joint1 = self.jdict[\"joint1\"]\n self.joint2 = self.jdict[\"joint2\"]\n self.joint3 = self.jdict[\"joint3\"]\n self.joint4 = self.jdict[\"joint4\"]\n\n self.joint0.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint1.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint2.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint3.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint4.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n\n # make sure that the target is reachable\n self.dist_target_origin = 1\n self.max_reach = 0\n\n while self.dist_target_origin > self.max_reach:\n\n self.jdict[\"target_x\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n self.jdict[\"target_y\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n\n _, self.dist_target_origin, _, self.max_reach = self.robot_info()\n \n def apply_action(self, a):\n assert (np.isfinite(a).all())\n self.joint0.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))\n self.joint1.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))\n self.joint2.set_motor_torque(0.05 * float(np.clip(a[2], -1, +1)))\n self.joint3.set_motor_torque(0.05 * float(np.clip(a[3], -1, +1)))\n self.joint4.set_motor_torque(0.05 * float(np.clip(a[4], -1, +1)))\n\n def calc_state(self):\n self.angle0, self.angle0_dot = self.joint0.current_relative_position()\n self.angle1, self.angle1_dot = self.joint1.current_relative_position()\n self.angle2, self.angle2_dot = self.joint2.current_relative_position()\n self.angle3, self.angle3_dot = self.joint3.current_relative_position()\n self.angle4, self.angle4_dot = self.joint4.current_relative_position()\n\n target_x, _ = self.jdict[\"target_x\"].current_position()\n target_y, _ = self.jdict[\"target_y\"].current_position()\n\n self.to_target_vec = np.array(self.fingertip.pose().xyz()) - np.array(self.target.pose().xyz())\n\n return np.array([\n target_x,\n target_y,\n self.to_target_vec[0],\n self.to_target_vec[1],\n self.angle0,\n self.angle0_dot,\n self.angle1,\n self.angle1_dot,\n self.angle2,\n self.angle2_dot,\n self.angle3,\n self.angle3_dot,\n self.angle4,\n self.angle4_dot\n ])\n\n def calc_potential(self):\n return -100 * np.linalg.norm(self.to_target_vec)\n\n def robot_info(self):\n\n self.target_vect = np.array(self.target.pose().xyz())[:-1]\n self.fingertip_vect = np.array(self.fingertip.pose().xyz())[:-1]\n\n dist_ft_origin = np.linalg.norm(self.fingertip_vect) \n dist_t_origin = np.linalg.norm(self.target_vect)\n dist_ft_t = np.linalg.norm(self.fingertip_vect - self.target_vect)\n max_reach = 0.11*5\n\n return dist_ft_origin, dist_t_origin, dist_ft_t, max_reach\n\nclass Reacher6(MJCFBasedRobot):\n TARG_LIMIT = 0.66 #0.27\n\n def __init__(self):\n MJCFBasedRobot.__init__(self, 'reacher_6dof.xml', 'body0', action_dim=6, obs_dim=16)\n\n def robot_specific_reset(self, bullet_client):\n\n self.fingertip = self.parts[\"fingertip\"]\n self.target = self.parts[\"target\"]\n\n self.joint0 = self.jdict[\"joint0\"]\n self.joint1 = self.jdict[\"joint1\"]\n self.joint2 = self.jdict[\"joint2\"]\n self.joint3 = self.jdict[\"joint3\"]\n self.joint4 = self.jdict[\"joint4\"]\n self.joint5 = self.jdict[\"joint5\"]\n\n self.joint0.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint1.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint2.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint3.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint4.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n self.joint5.reset_current_position(self.np_random.uniform(low=-3.14, high=3.14), 0)\n\n # make sure that the target is reachable\n self.dist_target_origin = 1\n self.max_reach = 0\n\n while self.dist_target_origin > self.max_reach:\n\n self.jdict[\"target_x\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n self.jdict[\"target_y\"].reset_current_position(\n self.np_random.uniform(low=-self.TARG_LIMIT, high=self.TARG_LIMIT), 0)\n\n _, self.dist_target_origin, _, self.max_reach = self.robot_info()\n \n \n def apply_action(self, a):\n assert (np.isfinite(a).all())\n self.joint0.set_motor_torque(0.05 * float(np.clip(a[0], -1, +1)))\n self.joint1.set_motor_torque(0.05 * float(np.clip(a[1], -1, +1)))\n self.joint2.set_motor_torque(0.05 * float(np.clip(a[2], -1, +1)))\n self.joint3.set_motor_torque(0.05 * float(np.clip(a[3], -1, +1)))\n self.joint4.set_motor_torque(0.05 * float(np.clip(a[4], -1, +1)))\n self.joint5.set_motor_torque(0.05 * float(np.clip(a[5], -1, +1)))\n\n def calc_state(self):\n self.angle0, self.angle0_dot = self.joint0.current_relative_position()\n self.angle1, self.angle1_dot = self.joint1.current_relative_position()\n self.angle2, self.angle2_dot = self.joint2.current_relative_position()\n self.angle3, self.angle3_dot = self.joint3.current_relative_position()\n self.angle4, self.angle4_dot = self.joint4.current_relative_position()\n self.angle5, self.angle5_dot = self.joint5.current_relative_position()\n\n target_x, _ = self.jdict[\"target_x\"].current_position()\n target_y, _ = self.jdict[\"target_y\"].current_position()\n\n self.to_target_vec = np.array(self.fingertip.pose().xyz()) - np.array(self.target.pose().xyz())\n\n return np.array([\n target_x,\n target_y,\n self.to_target_vec[0],\n self.to_target_vec[1],\n self.angle0,\n self.angle0_dot,\n self.angle1,\n self.angle1_dot,\n self.angle2,\n self.angle2_dot,\n self.angle3,\n self.angle3_dot,\n self.angle4,\n self.angle4_dot,\n self.angle5,\n self.angle5_dot\n ])\n\n def calc_potential(self):\n return -100 * np.linalg.norm(self.to_target_vec)\n\n def robot_info(self):\n\n self.target_vect = np.array(self.target.pose().xyz())[:-1]\n self.fingertip_vect = np.array(self.fingertip.pose().xyz())[:-1]\n\n dist_ft_origin = np.linalg.norm(self.fingertip_vect) \n dist_t_origin = np.linalg.norm(self.target_vect)\n dist_ft_t = np.linalg.norm(self.fingertip_vect - self.target_vect)\n max_reach = 0.11*6\n\n return dist_ft_origin, dist_t_origin, dist_ft_t, max_reach\n\n" } ]
26
evefangy/wikicat
https://github.com/evefangy/wikicat
f01580ee34d2e9af62b52d8098d1147789c06a6d
7b34bfccfd7b8c23253c4acdcc330f05e245c8df
e8f0b99cacdbeeb08a7ff91e4b772552027b1dab
refs/heads/master
2018-12-25T01:21:00.106404
2018-12-22T06:25:13
2018-12-22T06:25:13
103,317,106
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4972953498363495, "alphanum_fraction": 0.5088351964950562, "avg_line_length": 26.729999542236328, "blob_id": "5f9098ef999b64c4dbab700843c1c1898e7ee785", "content_id": "e8dcc94c4ce7cbd4e904e46cca139d2ef5b4b1d7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2773, "license_type": "no_license", "max_line_length": 98, "num_lines": 100, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Completely_random_tree/1_randomly_generate_edge_list.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\nusing namespace std;\n#include <time.h> /* time */\n#include <algorithm> // std::random_shuffle\n#include <ctime> // std::time\n#include <cstdlib> // std::rand, std::srand\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 3){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Number_of_articles | Output_Address\"<<endl;\n cout<<\"(e.g 33749 ./Output)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string num_art_str = argv[1];\n int num_art = stoi(num_art_str);\n string output_addr = argv[2];\n output_addr+=\"/sorted_completely_random_tree_weight.txt\";\n \n srand ( unsigned ( std::time(0) ) );\n \n \n \n // randomly permute the index\n vector<int> index_to_insert;\n for (int i=0; i<num_art; i++) {\n index_to_insert.push_back(i);\n }\n random_shuffle ( index_to_insert.begin(), index_to_insert.end() );\n\n map<int, vector<vector<int> >, greater<int> > sorted_weight;\n \n \n\n // grab every 2 artciles and randomly assign a weight to them \n for (int i=0;i<index_to_insert.size();i++){\n if (i+1==index_to_insert.size()) continue;\n int a1 = index_to_insert[i];\n int a2 = index_to_insert[i+1];\n\n // randomly assign a weight between 1 and 30\n int weight = rand()%100+1;\n vector<int> article_index_pairs;\n article_index_pairs.push_back(a1);\n article_index_pairs.push_back(a2);\n\n sorted_weight[weight].push_back(article_index_pairs);\n }\n \n\n ofstream outfile;\n outfile.open(output_addr);\n for (auto it=sorted_weight.begin(); it!=sorted_weight.end();it++){\n // for every pair\n for (auto i=0;i<it->second.size();i++){\n outfile<<it->first;\n for (auto j=0;j<it->second[i].size();j++){\n outfile<<\", \"<<it->second[i][j];\n }\n outfile<<endl;\n }\n }\n\n outfile.close();\n \n \n \n return 0;\n}\n" }, { "alpha_fraction": 0.5811023712158203, "alphanum_fraction": 0.5853018164634705, "avg_line_length": 19.45161247253418, "blob_id": "86a9221f4a31a9244ba00c259cd9a23716cb0df6", "content_id": "58ab118ebd51b95a1537e6729985acca45791d02", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1905, "license_type": "no_license", "max_line_length": 102, "num_lines": 93, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/Archieve/create_bow.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import collections, re\nfrom collections import Counter\n\noutput_addr = \"/Users/eve/Desktop\"\ninput_addr = \"/Users/eve/Desktop/test.txt\"\n\nbow_mat_addr = output_addr+\"/bow_matrix.txt\"\nbow_art_addr = output_addr+\"/bow_words.txt\"\nbow_whole_addr = output_addr+\"/bow_entire_freq.txt\"\n\nbow_mat = open(bow_mat_addr, 'w')\nbow_words = open(bow_art_addr, 'w')\nbow_whole = open(bow_whole_addr, 'w')\n\n\nline = \"\"\nc = 0\nbagsofwords = Counter()\nsumbags = Counter()\n# sumbags_tmp = Counter()\ntext = []\n\nbow = Counter()\n\n# get all words in the bow vector\nwith open(input_addr,'r') as f:\n\tfor line in f:\n\t\tline = line.strip()\n\t\tif(len(line)!=0):\n\t\t\tif line == \"************************** New Article *************************\":\n\t\t\t\tc+=1\n\t\t\t\tprint(c)\n\t\t\t\tbagsofwords = [ collections.Counter(re.findall(r'\\w+', txt)) for txt in text]\n\n\t\t\t\tsumbags = sum(bagsofwords, collections.Counter())\n\t\t\t\t\n\t\t\t\tbow = sumbags+bow\n\n\t\t\t\tbagsofwords = []\n\t\t\t\ttext = []\n\n\t\t\telse:\n\t\t\t\ttext.append(line)\n\t\t\t\n\nf.close()\n\n# reset all counter in bow to \"0\" : used in adding the set to produce the bag of words on all articles\nfor i in bow:\n\tbow_whole.write(i)\n\tbow_whole.write(\": \")\n\tbow_whole.write(str(bow[i]))\n\tbow_whole.write(\"\\n\")\n\tbow[i] = 0\n\tbow_words.write(i)\n\tbow_words.write(\"\\n\")\n\nbow_whole.close()\nbow_words.close()\n\nc = 0\nwith open(input_addr,'r') as f:\n\tfor line in f:\n\t\tline = line.strip()\n\t\tif(len(line)!=0):\n\t\t\tif line == \"************************** New Article *************************\":\n\t\t\t\tc+=1\n\t\t\t\tprint(c)\n\t\t\t\tbagsofwords = [ collections.Counter(re.findall(r'\\w+', txt)) for txt in text]\n\n\t\t\t\tsumbags = sum(bagsofwords, collections.Counter())\n\n\t\t\t\tfor i in bow:\n\t\t\t\t\tbow_mat.write(str(sumbags[i]))\n\t\t\t\t\tbow_mat.write(\" \")\n\t\t\t\tbow_mat.write(\"\\n\")\n\n\t\t\t\tbow_mat.write(\"\\n\\n\")\n\t\t\t\tbow_mat.write(line)\n\t\t\t\tbow_mat.write(\"\\n\\n\")\n\n\t\t\t\tbagsofwords = []\n\t\t\t\ttext = []\n\n\t\t\telse:\n\t\t\t\ttext.append(line)\n\t\t\t\n\nf.close()\n\n\n\nbow_mat.close()\n\n\n\n" }, { "alpha_fraction": 0.46097561717033386, "alphanum_fraction": 0.4754355251789093, "avg_line_length": 21.7738094329834, "blob_id": "a212a551d01911573afc01d6fe35623e43e44aa5", "content_id": "d1f46471f362343c4b52e6c122da19c63b523509", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5740, "license_type": "no_license", "max_line_length": 103, "num_lines": 252, "path": "/Desktop/Wiki/Code/1_Generate_Tree/get_new_edge_list/1_common_editor.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n\n\nusing namespace std;\n\n\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if(tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n \n }\n tmp = \"\";\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n if(tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n \n }\n}\n\n\nvector<int> calculate_intersection(unordered_set<string>& s1, unordered_set<string>& s2){\n // cout<<\"here3\"<<endl;\n int intersection = 0;\n\n int total = s1.size()+s2.size();\n\n int union_ = 0;\n\n for (auto i=s2.begin(); i!=s2.end();i++){\n if (s1.count(*i)==1){\n intersection++;\n }\n }\n\n union_ = total-intersection;\n\n vector<int> ans;\n ans.push_back(intersection);\n ans.push_back(union_);\n\n return ans;\n}\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 7){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_article_editor | Output_address | q | artname | edge_list | used_art\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string infile = argv[1];\n string output_address = argv[2];\n string q_str = argv[3];\n double q = stod(q_str);\n\n string artname_addr = argv[4];\n string edge_list_addr = argv[5];\n\n string used_art_addr = argv[6];\n\n output_address += \"/edge_list_with_q_\";\n output_address = output_address + q_str +\".txt\";\n\n // cout<<\"here0.0\"<<endl;\n\n bool isLog = false;\n if (q==-1){\n isLog = true;\n }\n\n ifstream used_art_file;\n used_art_file.open(used_art_addr);\n if (!used_art_file){\n cout<<\"can't open artname\"<<endl;\n exit(0);\n }\n\n\n\n ifstream artname;\n artname.open(artname_addr);\n if (!artname){\n cout<<\"can't open artname\"<<endl;\n exit(0);\n }\n\n ifstream art_ed;\n art_ed.open(infile);\n if (!art_ed){\n cout<<\"can't open arted\"<<endl;\n exit(0);\n }\n \n\n// cout<<\"here1.0\"<<endl;\n\n unordered_set<string> used_art;\n vector<string> parsed;\n string line;\n\n \n while(!used_art_file.eof()){ // store used article ids\n getline(used_art_file, line);\n if (line.size()!=0){\n\n parsed.clear();\n parse(line, parsed);\n if (parsed.size()==1){\n used_art.insert(parsed[0]);\n }\n else{\n used_art.insert(parsed[1]);\n }\n }\n }\n\n cout<<\"collected \"<<used_art.size()<<\" used articles\"<<endl;\n used_art_file.close();\n\n\n unordered_map<string,string> artname_map;\n\n int line_ctr = 0;\n while(!artname.eof()){\n getline(artname, line);\n if (line.size()!=0){\n\n parsed.clear();\n parse(line, parsed);\n if (parsed.size()==1){\n if (used_art.count(parsed[0])==1){\n artname_map[parsed[0]] = line_ctr; // store key: article id, value: encoded\n }\n \n }\n else{\n if (used_art.count(parsed[1])==1){\n artname_map[parsed[1]] = parsed[0];\n }\n }\n line_ctr++;\n }\n }\n\n cout<<\"collected \"<<artname_map.size()<<\" artnames\"<<endl;\n artname.close();\n\n\n ofstream outfile;\n outfile.open(output_address);\n if (!outfile){\n cout<<\"can't open outfile\"<<endl;\n exit(0);\n }\n\n// cout<<\"here0\"<<endl;\n\n unordered_set<string> ed;\n unordered_map<string, unordered_set<string> > article_editor_map;\n\n\n // store all article along with its editors\n while(!art_ed.eof()){\n getline(art_ed, line);\n if (line.size()!=0){\n parsed.clear();\n parse(line, parsed);\n string a = parsed[0];\n ed.clear();\n for (int i=1;i<parsed.size();i++){\n ed.insert(parsed[i]);\n }\n\n article_editor_map[artname_map[a]] = ed;\n }\n }\n\n cout<<\"collected \"<<article_editor_map.size()<<\" article_editor sets\"<<endl;\n \n // cout<<\"here1\"<<endl;\n\n art_ed.close();\n\n ifstream edge_list;\n edge_list.open(edge_list_addr);\n if(!edge_list){\n cout<<\"Can't open egde list\"<<endl;\n exit(0);\n }\n\n string a1;\n string a2;\n\n// cout<<\"here2\"<<endl;\n vector<int> inter_union;\n while(!edge_list.eof()){\n getline(edge_list, line);\n if(line.size()!=0){\n parsed.clear();\n parse(line, parsed);\n a1 = parsed[0];\n a2 = parsed[1];\n\n if (article_editor_map.count(a1)==0 || article_editor_map.count(a2)==0) continue;\n\n\n inter_union.clear();\n inter_union = calculate_intersection(article_editor_map[a1], article_editor_map[a2]);\n\n // cout<<inter_union[0]<<\"---\"<<inter_union[1]<<endl;\n double new_weight = 0.0;\n if (isLog){\n new_weight = inter_union[0]*1.0/log10(inter_union[1]);\n }\n\n else{\n new_weight = inter_union[0]*1.0/pow(inter_union[1], q);\n }\n\n if (!isinf(new_weight)){\n outfile<<a1<<\", \"<<a2<<\", \"<<new_weight<<endl;\n }\n \n \n }\n }\n\n// cout<<\"here4\"<<endl;\n\n\n\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5197044610977173, "alphanum_fraction": 0.5320196747779846, "avg_line_length": 25.19354820251465, "blob_id": "8e6d522a7352069178a73ed2c3fdf0d74eafc956", "content_id": "6aae753c90b605809d26d1496288d181be7eb1a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1624, "license_type": "no_license", "max_line_length": 81, "num_lines": 62, "path": "/Desktop/Wiki/Code/Helper/remove_duplicates.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "\n# check against check duplicates again!!!!!!!!!!!!!!!! there're still some error \n\n\nif __name__ == \"__main__\":\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\tseen = set()\n\n\tart_file = open(\"/Users/eve/Desktop/unique_combined.txt\", \"w\")\n\n\tline = \"\"\n\ttmp = []\n\t#load already processed article\n\twith open(\"/Users/eve/Desktop/combined.txt\") as f:\n\t \n\t\tfor line in f:\n\t\t\tif len(line.strip()) != 0 :\n\t\t\t\tnum+=1\n\t\t\t\tline = line.strip('\\n')\n\t\t\t\ttmp = line.split(\", \")\n\t\t\t\tif tmp[0] in seen:\n\t\t\t\t\tcounter += 1\n\t\t\t\telse:\n\t\t\t\t\tseen.add(tmp[0])\n\t\t\t\t\tart_file.write(line)\n\t\t\t\t\tart_file.write('\\n')\n\t\n\tprint \"There are \"+str(num)+\" articles with \"+str(counter)+\" repetitions\"\t\n\n\tprint(str(num-counter))\n\t# num = 0\n\t# counter = 0\n\t# with open(\"/Users/eve/Desktop/art_w_major_editor_cate_1.txt\") as f:\n\t \n\t# \tfor line in f:\n\t# \t\tif len(line.strip()) != 0 :\n\t# \t\t\tnum+=1\n\t# \t\t\tline = line.strip('\\n')\n\t# \t\t\tif line in seen:\n\t# \t\t\t\tcounter += 1\n\t# \t\t\telse:\n\t# \t\t\t\tseen.add(line)\n\t# \t\t\t\t# art_file.write(line.replace(\"&#039;\",\"'\"))\n\t# \t\t\t\tart_file.write(line)\n\t# \t\t\t\tart_file.write('\\n')\n\t# print \"There are \"+str(num)+\" articles with \"+str(counter)+\" repetitions\"\t\n\t# with open(\"/Users/eve/Desktop/Wiki/Life/\"+name+\"_2.txt\") as f:\n\t# for line in f:\n\t# \tif len(line.strip()) != 0 :\n\t# \t\tnum+=1\n\t# \t line = line.lower()\n\t# \t line = line.strip('\\n')\n\t# \t if line in seen:\n\t# \t print(line)\n\t# \t counter += 1\n\t# \t else:\n\t# \t seen.add(line)\n\t# \t art_file.write(line)\n\t# \t art_file.write('\\n')\n\n\tprint counter\n\tprint num" }, { "alpha_fraction": 0.4594453275203705, "alphanum_fraction": 0.47095760703086853, "avg_line_length": 22.157575607299805, "blob_id": "7c4c605a22b0af017207e63466331b1184c97de2", "content_id": "a38985ba01d5ba5d76354d61d46057a6afab0852", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3824, "license_type": "no_license", "max_line_length": 104, "num_lines": 165, "path": "/2_Compare_Tree/Generate_BOW_tree/7_add_remaining_arts.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 7_get_article_weight_pair_new\n//\n// Created by Eve on 10/24/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n//\n// main.cpp\n// 7_get_article_weight_pair\n//\n// Created by Eve on 10/17/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n\n/*********************************************************************************/\n// The code goes through artname created and get articles that don't share any\n// edges -> create an edge to link all those articles with a weight that is smaller\n// than current minimum weight\n/*********************************************************************************/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n\nusing namespace std;\n\n\n\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if(s[i+1]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\n\n\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 5){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_artname | Address_for_edge_list | Output_address | Number_of_articles\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string artname_add = argv[1];\n string edge_addr = argv[2];\n string output_address = argv[3];\n output_address+=\"/new_edge_list.txt\";\n string tmp = argv[4];\n int num_art = stoi(tmp);\n\n \n ofstream outfile;\n outfile.open(output_address);\n \n //initiate map for storing article_name and its index (for look up)\n unordered_set<string> stored_article;\n \n //local variables\n vector<string> parsed;\n string line = \"\";\n\n ifstream infile;\n infile.open(artname_add);\n\n if(!infile){\n cerr<<\"Can't open infile\"<<endl;\n exit(1);\n }\n\n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n \n parsed.clear();\n parse(line, parsed);\n if(stored_article.count(parsed[0])!=0){\n cerr<<\"existed\"<<endl;\n exit(0);\n }\n stored_article.insert(parsed[0]);\n \n }\n }\n infile.close();\n\n cout<<\"Finish storing artname\"<<endl;\n cout<<\"There are \"<<stored_article.size()<<\" articles with at least one edge\"<<endl;\n \n vector<string> unstored;\n string curr_art=\"\";\n for(int i=0;i<num_art;i++){\n curr_art = to_string(i);\n if(stored_article.count(curr_art)==0){\n unstored.push_back(curr_art);\n }\n }\n \n cout<<\"There are \"<<unstored.size()<<\" articles with no edge\"<<endl;\n \n infile.open(edge_addr);\n \n if(!infile){\n cerr<<\"Can't open infile\"<<endl;\n exit(1);\n }\n \n \n int counter = 0;\n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n outfile<<line<<endl;\n counter++;\n }\n }\n \n for(int i=0; i<unstored.size();i++){\n if(i==0){\n continue;\n }\n outfile<<unstored[0]<<\", \"<<unstored[i]<<\", -1\"<<endl;\n counter++;\n }\n \n \n infile.close();\n \n \n \n cout<<\"Completed\"<<endl;\n \n cout<<\"-------------------------------\"<<endl;\n\n cout<<\"There are \"<<counter<<\" weight pairs in total\"<<endl;\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.44701987504959106, "alphanum_fraction": 0.45695364475250244, "avg_line_length": 27.850000381469727, "blob_id": "6f1b4b1d7cc8ada7e8483af2ed40fdfc3fd27a6a", "content_id": "54cbb5ced8fca48b4ce2ee172404adb6199f3949", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "no_license", "max_line_length": 77, "num_lines": 20, "path": "/Desktop/Wiki/Code/Helper/get article index.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "\nimport urllib2\nimport re\nif __name__ == \"__main__\":\n # text_file = open(\"/Users/eve/Desktop/Wiki/revision_history_2.txt\", \"w\")\n myline = \"$20_bill_U.S.\"\n with open(\"/Users/eve/Desktop/Wiki/article_title.txt\",'r') as f:\n \tcounter = 0; \n\n # print \"here\"\n for line in f:\n counter = counter+1 \n line = line.strip('\\n')\n line = line.strip('\\t')\n title = line\n # print(title)\n\n if(myline == title.strip()):\n print(counter)\t\n print(title)\n break\n \n\n \t\t \t\n\n" }, { "alpha_fraction": 0.7249240279197693, "alphanum_fraction": 0.7416413426399231, "avg_line_length": 49.61538314819336, "blob_id": "d5e2c2df5585b96d0186ec89a028f572dd3ac02d", "content_id": "a49c6f5c278e74b974091ad0002c55a4b10d63c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 658, "license_type": "no_license", "max_line_length": 89, "num_lines": 13, "path": "/Desktop/Wiki/Code/5_Get_Random_Tree_Error_Bar/run.sh", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "ALL_TREE_FOLDER=\"/Users/eve/Desktop/Wiki/Code/5_Get_Random_Tree_Error_Bar/Test/All_Trees\"\nSAMPLED_FOLDER=\"/Users/eve/Desktop/Wiki/Code/5_Get_Random_Tree_Error_Bar/Test/Sampled\" \nNUMBER_OF_SAMPLES=\"5\"\nNUMBER_OF_ARTICLES_TO_SAMPLE=\"10\"\nEND_FOLDER_NUMBER=\"4\"\ng++ 1_create_random_tree.cpp -o a.out\n./a.out $ALL_TREE_FOLDER $SAMPLED_FOLDER $NUMBER_OF_SAMPLES\ng++ 2_pick_n_locate_art.cpp -o b.out\n./b.out $NUMBER_OF_ARTICLES_TO_SAMPLE $SAMPLED_FOLDER $ALL_TREE_FOLDER\ng++ 3_find_similarity.cpp -o c.out\n./c.out 0 $END_FOLDER_NUMBER $SAMPLED_FOLDER $ALL_TREE_FOLDER\ng++ 4_get_tree_similarity.cpp -o d.out\n./d.out $NUMBER_OF_SAMPLES $SAMPLED_FOLDER $ALL_TREE_FOLDER\n" }, { "alpha_fraction": 0.4512573182582855, "alphanum_fraction": 0.46503618359565735, "avg_line_length": 23.369747161865234, "blob_id": "2bd5055049f52387070c64fed1520274c284d0ad", "content_id": "c93708a7a42429c73df325464e842e379d8189cd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2905, "license_type": "no_license", "max_line_length": 98, "num_lines": 119, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/3(helper)_get_word_freq.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 7_get_article_weight_pair_new\n//\n// Created by Eve on 10/24/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n//\n// main.cpp\n// 7_get_article_weight_pair\n//\n// Created by Eve on 10/17/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n\n/*********************************************************************************/\n/* The code takes in editors and the articles they did major revisions for. The */\n/* code outputs the edge list for article pairs in the following format: */\n/* [art_weight_pair]: article_decode 1, article_decode 2, weight */\n/* [art_index_name]: article_decode, article_name */\n/*********************************************************************************/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n\nusing namespace std;\n\nunordered_map<string, string> real_article_id;\n\nint curr_in = -1; //current index of the new inserted article [used in addEdge]\nint num_noEdge = 0;\n\nbool new_art;\nbool store_art1;\nbool store_art2;\nstring art_index1;\nstring art_index2;\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if(s[i+1]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 2){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Word_w_Arts_file_addr\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string infile_addr = argv[1];\n \n \n \n \n \n// //initiate map for storing weight pair\n// unordered_map<int, map<int, int> >weight;\n// //initiate map for storing article_name and its index (for look up)\n// unordered_map<string, int> article_index;\n \n //local variables\n vector<string> parsed;\n string line = \"\";\n\n //////////////////////////\n // Create edge list //\n //////////////////////////\n ifstream infile;\n infile.open (infile_addr);\n \n int i = 0;\n \n if(!infile){\n cerr<<\"Can't open infile\"<<endl;\n exit(1);\n }\n int l = 0;\n while(!infile.eof()){\n getline(infile,line);\n l+=1;\n if (!line.empty()){\n i++;\n parsed.clear();\n parse(line, parsed);\n cout<<parsed.size()<<endl;\n }\n }\n infile.close();\n//\n return 0;\n}\n\n\n\n" }, { "alpha_fraction": 0.4794599115848541, "alphanum_fraction": 0.48865267634391785, "avg_line_length": 29.412281036376953, "blob_id": "371e0cd9d6d4381615c87cabc1abeac54ebf1462", "content_id": "a81759bc42cd502e511c102f58e9fe64031ba1ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3481, "license_type": "no_license", "max_line_length": 139, "num_lines": 114, "path": "/1_Generate_Tree/1_get_cate_continue.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetSubcate(cate):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&list=categorymembers&cmtype=subcat&cmlimit=500&cmpageid=\" + str(cate)\n subcat = [] \n next = '' \n while True:\n req = urllib2.Request(url+next)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n subcat += re.findall('<cm [^>]*>', response) \n cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n if not cont: #break the loop if 'continue' element missing\n break\n next = \"&cmcontinue=\" + cont.group(1) \n return subcat\n\ndef GetCateId(cate_name):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&titles=Category:\" + cate_name\n subcat = [] \n found = ''\n # while True:\n req = urllib2.Request(url)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n subcat += re.findall('<page [^>]*>', response) \n # cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n # if not cont: #break the loop if 'continue' element missing\n # break \n if len(subcat)>1:\n printf(\"\\n\\rGet multiple ids for the category\")\n return\n try:\n found = re.search('pageid=\"(.+?)\"',subcat[0]).group(1)\n except AttributeError:\n found = ''\n printf(\"No pageid is found for the category\")\n return found \n \n\n\nif __name__ == \"__main__\":\n\n start = 44949\n \n add = \"/Users/eve/Desktop/Wiki/Life/All_Cate/cate_ids_\"\n add += str(start)\n add += \".txt\"\n\n add2 = \"/Users/eve/Desktop/Wiki/Life/All_Cate/cate_name_\"\n add2 += str(start)\n add2 += \".txt\"\n\n\n id_file = open(add, \"w\")\n cate_file = open(add2, \"w\")\n\n tmp = []\n seen = set()\n cate_name = []\n found = ''\n c_id = 0\n c = 0\n counter = 0\n\n\n counter = start\n with open(\"/Users/eve/Desktop/Wiki/Life/All_Cate/cate_ids.txt\",'r') as f:\n c = 0\n for line in f:\n line = line.strip('\\n')\n seen.add(int(line))\n if c >= start:\n cate_name.append(int(line))\n seen.add(int(line))\n # print c\n c += 1\n\n # main_cate = \"Life\"\n # #category id for main category\n # found = GetCateId(main_cate)\n # c_id = int(found)\n # seen.add(c_id)\n # cate_name.append(c_id)\n # id_file.write(found)\n # cate_file.write(main_cate)\n\n\n\n while cate_name:\n tmp = GetSubcate(cate_name[0])\n for i in tmp[0:len(tmp)]:\n found = re.search('pageid=\"(.+?)\"', i).group(1)\n c_id=int(found)\n if c_id not in seen:\n seen.add(c_id)\n cate_name.append(c_id)\n id_file.write('\\n')\n id_file.write(found)\n # id_file.write('why')\n found = re.search('title=\"Category:(.+?)\"', i).group(1)\n found = found.replace(\" \",\"_\")\n# found = found.lower()\n cate_file.write('\\n')\n cate_file.write(found) \n tmp = []\n cate_name.pop(0)\n counter += 1\n print counter\n\n cate_file.close()\n id_file.close()\n print \"Finished!!!!!Finallyyyyyyyyy\"\n\n\n\n \n\n\n\n\n\n\n" }, { "alpha_fraction": 0.41378912329673767, "alphanum_fraction": 0.4240674376487732, "avg_line_length": 24.089855194091797, "blob_id": "81b8ff4e48945bc5d8ef2da914518457c78bed74", "content_id": "69046b52bc3eb543c15e6bf3dab268793c09bbd8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8659, "license_type": "no_license", "max_line_length": 126, "num_lines": 345, "path": "/Desktop/Wiki/Code/3_Create_Bar_Graph/cal_topical_measurement.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n#include <math.h>\n\nusing namespace std;\n\n\nint curr_in = -1; //current index of the new inserted article [used in addEdge]\nint num_noEdge = 0;\n\nbool new_art;\nbool store_art1;\nbool store_art2;\nstring art_index1;\nstring art_index2;\n\n\nvoid parsed_by_space(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n if(tmp.size()!=0){\n parsed.push_back(tmp);\n }\n \n}\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if(s[i+1]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\n\n\n\n\nstring most_freq(vector<string>& g){\n sort(g.begin(), g.end());\n \n //Finding the mode of the entered words\n int _count = 0;\n int _max = 0;\n string mode;\n for (unsigned int test = 0, j = 1; test<g.size(); test++, j++) {\n if (g[test] == g[j]) {\n _count++;\n }\n else if (g[test] != g[j]) {\n if (_count>_max) {\n _max = _count;\n mode = g[test];\n }\n _count = 0;\n }\n }\n return mode;\n}\n\n\ndouble cal_top(vector<string>& g, vector<double>& ed_size){\n if(ed_size.size()==1){\n return 1.0;\n }\n \n double max_v = 0.0;\n double min_v = 1.0;\n// //normalize the ed_size\n// for(int i=0;i<ed_size.size();i++){\n// cout<<ed_size[i]<<\" \";\n// if (ed_size[i]<min_v) {\n// min_v = ed_size[i];\n// }\n// if(ed_size[i]>max_v){\n// max_v = ed_size[i];\n// }\n// }\n// cout<<endl;\n \n double sum_v = 0.0;\n //calculate edit percentage\n for(int i=0;i<ed_size.size();i++){\n sum_v += ed_size[i];\n \n }\n\n\n\n \n double entro = 0.0;\n for(int i=0;i<ed_size.size();i++){\n// ed_size[i] = (ed_size[i]-min_v)*1.0/(max_v-min_v);\n ed_size[i] = ed_size[i]/sum_v;\n entro = entro+(ed_size[i]*log(ed_size[i]));\n cout<<ed_size[i]<<\" \";\n }\n cout<<endl;\n cout<<\"-------\"<<endl;\n \n //calculate the entrope\n double top_m = 0.0;\n top_m = (log(ed_size.size())+entro)/log(ed_size.size());\n cout<<\"top_m = \"<<top_m<<endl;\n return top_m;\n \n \n// //count number of topics\n// double top_m = 0.0;\n//\n// sort(g.begin(), g.end());\n// vector<int> counter;\n//\n// int curr = 0;\n// int num = 0;\n// for(int i=1;i<g.size();i++){\n// if(g[curr]==g[i]){\n// num++;\n// }\n// else{\n// curr = i;\n// counter.push_back(num);\n// num = 0;\n// }\n// }\n// return counter.size();\n \n// //Finding the mode of the entered words\n// int _count = 0;\n// int _max = 0;\n//// string mode;\n// for (unsigned int test = 0, j = 1; test<g.size(); test++, j++) {\n// if (g[test] == g[j]) {\n// _count++;\n// }\n// else if (g[test] != g[j]) {\n// if (_count>_max) {\n// _max = _count;\n//// mode = g[test];\n// }\n// _count = 0;\n// }\n// }\n//\n// top_m = _max*1.0/g.size();\n// return top_m;\n \n}\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 5){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_major_editor_w_article_file | Output_address | category_group_file | article_category_file \"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string output_address = argv[2];\n output_address+=\"/topical_measure.txt\";\n string err_address = argv[2];\n err_address+=\"/unstored_cate.txt\";\n string top_address = argv[2];\n top_address+=\"/top_bar.txt\";\n \n \n string cate_addr = argv[3];\n string art_cate_addr = argv[4];\n \n //store each category's corresponding group\n unordered_map<string, string> cate_map;\n \n //local variables\n vector<string> parsed;\n string line = \"\";\n \n //store counter\n ofstream outfile, errfile, top_bar;\n outfile.open (output_address);\n errfile.open(err_address);\n top_bar.open(top_address);\n\n \n ifstream infile, cate_group, art_cate;\n \n //store categories to their corresponding group\n cate_group.open(cate_addr);\n while(!cate_group.eof()){\n getline(cate_group,line);\n if (!line.empty()){\n parsed.clear();\n parse(line, parsed);\n for(int i=0;i<parsed.size();i++){\n if(i==0) continue;\n cate_map[parsed[i]] = parsed[0];\n// cout<<parsed[i]<<\" \"<<parsed[0]<<endl;\n }\n }\n }\n cate_group.close();\n \n cout<<\"Stored \"<<cate_map.size()<<\" categories\"<<endl;\n \n \n // Go through each article and its categories. Find the groups those categories belong to.\n // Assign the article to a group that appeared the most frequently\n unordered_map<string, string> art_cate_group;\n vector<string> tmp;\n art_cate.open(art_cate_addr);\n while(!art_cate.eof()){\n getline(art_cate,line);\n if (!line.empty()){\n parsed.clear();\n parsed_by_space(line, parsed);\n tmp.clear();\n if(art_cate_group.count(parsed[0])!=0){\n cerr<<parsed[0]<< \"has existed in the map\"<<endl;\n continue;\n }\n\n for(int i=0;i<parsed.size();i++){\n if(i==0) continue;\n //if the category doesn't exist\n if(cate_map.count(parsed[i])==0){\n errfile<<parsed[i]<<endl;\n continue;\n }\n tmp.push_back(cate_map[parsed[i]]);\n }\n \n //use the most frequent group\n art_cate_group[parsed[0]] = most_freq(tmp);\n }\n }\n art_cate.close();\n \n \n infile.open (argv[1]);\n\n double top_m = 0.0;\n \n if(!infile){\n cerr<<\"Can't open infile\"<<endl;\n exit(1);\n }\n \n vector<double> ed_size;\n int index = 0;\n string art_group = \"\";\n \n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n parsed.clear();\n parse(line, parsed);\n \n tmp.clear();\n ed_size.clear();\n if(parsed.size()<2){\n cerr<<\"parsed.size()<2\"<<endl;\n exit(0);\n }\n for(int i=1;i<parsed.size();i+=2){\n \n \n //locate index\n art_group = art_cate_group[parsed[i]];\n// cout<<art_group<<\" \";\n// cout<<art_group<<\"----\"<<endl;\n if(tmp.size()<1){\n tmp.push_back(art_group);\n ed_size.push_back(stod(parsed[i+1]));\n continue;\n }\n \n \n index=0;\n while(index<tmp.size() && tmp[index] != art_group){\n index++;\n }\n \n //can't locate\n if(index==tmp.size()){\n tmp.push_back(art_group);\n ed_size.push_back(stod(parsed[i+1]));\n }\n else {\n ed_size[index]+=stod(parsed[i+1]);\n }\n }\n// cout<<\"+++++\"<<endl;\n \n top_m = cal_top(tmp, ed_size);\n // <------------------------------------------------------\n if(top_m!=0.0){\n outfile<<parsed[0]<<\" \"<<parsed.size()/2<<\" \"<<top_m;\n if(top_m>=0.3){\n top_bar<<parsed.size()/2<<endl;\n outfile<<\" \"<<parsed.size()/2;\n }\n else{\n outfile<<\" -1\";\n }\n \n \n outfile<<endl;\n }\n \n \n }\n }\n infile.close();\n\n \n cout<<\"Completed\"<<endl;\n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.39208707213401794, "alphanum_fraction": 0.4012978971004486, "avg_line_length": 24.81621551513672, "blob_id": "1172d6f2f9645ebaa4bb0817725d51388890a81c", "content_id": "f90fec7298981473059df1ba51bb0b833668e066", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4778, "license_type": "no_license", "max_line_length": 110, "num_lines": 185, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Generate_tree_based_on_edit_size/1_get_major_editor_and_size.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// convert_name_to_id\n//\n// Created by Eve on 2/6/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\n\nusing namespace std;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==','){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else{\n if(line[i]!=' '){\n tmp+=line[i];\n \n }\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 5){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"used_art_file | parsed_rev_history_addr | Output_Address | version\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string used_art_file = argv[1];\n string parsed_rev_history_addr = argv[2];\n string output_addr = argv[3];\n string v = argv[4];\n output_addr+=\"/1_article_editor_edit_size_\"+v+\".txt\";\n \n \n ifstream used_art, rev_history;\n used_art.open(used_art_file);\n rev_history.open(parsed_rev_history_addr);\n \n ofstream outfile;\n outfile.open(output_addr);\n\n if(!outfile){\n cerr<<\"can't open output file\"<<endl;\n exit(0);\n }\n\n\n \n //read in id file\n unordered_set<string> used_art_set;\n\n string line;\n vector<string> parsed;\n int c=0;\n while(!used_art.eof()){\n line = \"\";\n getline(used_art, line);\n if(line.size()>0){\n parsed.clear();\n parse(parsed, line);\n if(parsed.size()!=1){\n cerr<<\"parsed.size()!=1\"<<endl;\n exit(0);\n }\n used_art_set.insert(parsed[0]);\n c++;\n }\n }\n cout<<\"Stored \"<<c<<\" articles\"<<endl;\n \n \n used_art.close();\n\n unordered_map<string, double> editor_edit_size;\n\n c = 0;\n \n bool isNewArt = true;\n bool isUsedArt = false;\n\n int total_num_art = 0;\n int num_processed_art = 0;\n\n while(!rev_history.eof()){\n line = \"\";\n getline(rev_history, line);\n\n // if it's an empty line (new article)\n if (line.size()==0 || line==\" \"){\n if (!isNewArt){\n for(auto it=editor_edit_size.begin(); it!=editor_edit_size.end();it++){\n if (it->second>=0.10){\n outfile<<\", \"<<it->first<<\", \"<<it->second;\n }\n }\n \n isNewArt = true;\n isUsedArt = false;\n editor_edit_size.clear();\n total_num_art++;\n }\n \n }\n else if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n\n // article id\n if (isNewArt){\n if (parsed.size()!=1){\n cerr<<\"Article ID format is wrong\"<<endl;\n cout<<line<<endl;\n exit(0);\n }\n\n if (used_art_set.count(parsed[0])==1){\n isUsedArt = true;\n outfile<<endl;\n outfile<<parsed[0];\n num_processed_art++;\n }\n\n }\n else{\n if (isUsedArt){\n // article size\n if (parsed.size()==1){\n \n }\n\n // ed history\n else{\n int n = parsed.size();\n\n if(parsed[1]!=\"0\"){\n try{\n editor_edit_size[parsed[n-3]] += stod(parsed[n-1]);\n }\n \n catch(std::exception& e){\n cout << \"Could not convert string to double\" << endl;\n cout<<\"[\"<<line<<\"]\"<<endl;\n }\n }\n }\n }\n \n }\n \n \n isNewArt = false;\n }\n \n }\n \n rev_history.close();\n outfile.close();\n\n cout<<\"There are \"<<num_processed_art<<\"/\"<<total_num_art<<\" articles processed in the rev history\"<<endl;\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5017530918121338, "alphanum_fraction": 0.5150396823883057, "avg_line_length": 33.2088623046875, "blob_id": "a498ece04cd27f50ad01acf20c4a6a72197d11d7", "content_id": "1533930ea1c4203c4c5aca8fd1d3ce95899aa1b7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5419, "license_type": "no_license", "max_line_length": 159, "num_lines": 158, "path": "/Helper/get_article_of_category.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetTitles(cate):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&list=categorymembers&cmnamespace=0&cmprop=ids|title&cmlimit=500&cmtitle=Category:\" + cate\n art = [] #list of all accumulated articles\n next = '' \n #information for the next request\n while True:\n req = urllib2.Request(url+next)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n\n art += re.findall('<cm [^>]*>', response) #adds all article info from the current request to the list\n\n cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n if not cont: #break the loop if 'continue' element missing\n break\n\n next = \"&cmcontinue=\" + cont.group(1) #gets the revision Id from which to start the next request\n # print \"article length: \"\n # print len(art)\n return art\n\ndef GetSubcate(cate):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&list=categorymembers&cmtype=subcat&cmlimit=500&cmtitle=Category:\" + cate\n subcat = [] \n next = '' \n \n while True:\n req = urllib2.Request(url+next)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n\n subcat += re.findall('<cm [^>]*>', response) \n\n cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n if not cont: #break the loop if 'continue' element missing\n break\n\n next = \"&cmcontinue=\" + cont.group(1) \n # print \"subcat length: \"\n # print len(subcat)\n return subcat\n\n\n\nif __name__ == \"__main__\":\n \n level = 0\n art_num = 0\n curr_cat_num = 0 #number of node we are looking at for current level\n curr_level_max = 1 #number of subcategories of current level \n next_level_max = 0 #number of subcategories of next level\n\n id_file = open(\"/Users/eve/Desktop/Wiki/Life/New/article_id_104624.txt\", \"w\")\n art_file = open(\"/Users/eve/Desktop/Wiki/Life/New/article_104624.txt\", \"w\")\n cate_file = open(\"/Users/eve/Desktop/Wiki/Life/New/category_104624.txt\", \"w\")\n # data_file = open(\"/Users/eve/Desktop/Wiki/Life/data.txt\", \"w\")\n cate_name = []\n subcat = 0\n seen = set()\n\n \n start = 104624 #haven't run this category yet\n counter = start\n with open(\"/Users/eve/Desktop/Wiki/Life/Article_And_Category/category.txt\",'r') as f:\n c = 0\n for line in f:\n line = line.strip('\\n')\n seen.add(line)\n if c >= start:\n # print line\n cate_name.append(line)\n seen.add(line)\n c += 1\n\n\n\n\n\n while cate_name:\n # data_file.write(cate_name[0])\n\n article = GetTitles(cate_name[0])\n \n for i in article[0:len(article)]:\n # extract article title for current category (cate_name[0])\n try:\n artname = re.search('title=\"(.+?)\"', i).group(1)\n artid = re.search('pageid=\"(.+?)\"', i).group(1)\n # print artid\n except AttributeError:\n artname = ''\n artid = ''\n artname = artname.replace(\" \",\"_\")\n art_file.write(artname)\n art_file.write('\\n')\n id_file.write(artid)\n id_file.write('\\n')\n\n art_file.write('\\n\\n') #seperation for each (sub)category\n id_file.write('\\n\\n')\n art_num += len(article) #increment article number for current level\n\n # data_file.write(\" \")\n # data_file.write(str(len(article)))\n # data_file.write(\"\\n\")\n\n\n subcat = 0\n print cate_name[0]\n tmp = GetSubcate(cate_name[0])\n for i in tmp[0:len(tmp)]:\n try:\n found = re.search('title=\"Category:(.+?)\"', i).group(1)\n except AttributeError:\n found = ''\n found = found.replace(\" \",\"_\")\n found = found.lower()\n # subcat += 1\n if found not in seen:\n seen.add(found)\n cate_name.append(found)\n cate_file.write(found)\n cate_file.write('\\n')\n # cate_file.write('\\n\\n') #seperation for children in each category\n\n next_level_max += subcat\n curr_cat_num += 1\n \n # if curr_cat_num==curr_level_max/2:\n # print \"-----------------------------50 percent completet-----------------------------\"\n\n # we are currently at the last category of current level\n if curr_cat_num==curr_level_max:\n # print \"level, number of subcategories, number of articles of the level\"\n # print level\n # print next_level_max #category num of each level\n # print art_num #article num of each level\n art_num = 0\n level += 1\n curr_cat_num = 0\n curr_level_max = next_level_max\n next_level_max = 0\n\n cate_name.pop(0)\n counter += 1\n if counter%10 == 0:\n print counter\n\n\n # for i in cate_name[0:len(cate_name)]: \n # print i\n\n art_file.close()\n cate_file.close()\n id_file.close()\n\n\n\n \n\n\n\n\n\n\n" }, { "alpha_fraction": 0.558465301990509, "alphanum_fraction": 0.5816078186035156, "avg_line_length": 30.82524299621582, "blob_id": "b577cd49c98b4b4a93bf3dbadb66fcb0a2f84632", "content_id": "f4be5bdb8fcaa75905023ee6f2940837b76f82ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3284, "license_type": "no_license", "max_line_length": 124, "num_lines": 103, "path": "/Desktop/Wiki/Code/1_Generate_Tree/5_get_art_with_major_editors.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "# The code parse and reformat the revision history to the following form\n\n# article title, major editor 1, major editor 2...\n\n# Note 1. The major author is defined as authors with more than 10% edition history compare to the whole article\n# 2. Unregistered editor is not recorded in the output\n# 3. Users with a comma in the name is considered and the comma portion of the name is replaced by \"_,\"\n#\t 4. Articles with size smaller than 100B doesn't have their major editors recorded\n\nimport sys\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 5:\n\t\tprint \"--------------------------------------------------------------------------------\"\n\t\tprint \"Too few arguments. Please provide the information in the following format. \"\n\t\tprint \"Address_for_parsed_rev_file Output_address category_range_and_output_version starting_line_number(starting from 1)\"\n\t\tprint \"(e.g ./parsed_rev_cate_0_to_100000.txt ./output 0_to_100000_2 1\"\n\t\tprint \"--------------------------------------------------------------------------------\"\n\t\tsys.exit()\n\n\toutput_address = sys.argv[2]+\"/art_w_major_editor_cate_\"+sys.argv[3]+\".txt\"\n\tinput_address = sys.argv[1]\n\tstart_line = int(sys.argv[4])\n\tinsufficient_art_addr = sys.argv[2]+\"/art_smaller_than_100B_cate_\"+sys.argv[3]+\".txt\"\n\n\tart_file = open(output_address, \"w\")\n\tsmall_art_file = open(insufficient_art_addr, \"w\")\n\tnew_art = False\n\tistitle = 0 #flag indicates the current line is a article title \n\tif start_line == 1:\n\t\tnew_art = True\n\t\tistitle = 1\n\t\n\tart_title = \"\"\n\tc = 0 #current line number (starting at 1)\n\tis_small_article = False\n\n\tart_size = 0\n\n\twith open(input_address,'r') as f:\n\t\tfor line in f:\n\t\t\tc+=1\n\t\t\tif c >= start_line: \n\t\t\t\t# print c\n\t\t\t\tif c%100000==0:\n\t\t\t\t\tprint c\n\n\t\t\t\tline = line.strip()\n\t\t\t\t# print line\n\t\t\t\t\n\t\t\t\t# empty line indicates the end of an article\n\t\t\t\tif not line:\n\t\t\t\t\t# print \"detetct empty line\"\n\t\t\t\t\tistitle = 1\n\t\t\t\t\tnew_art = True\n\t\n\t\t\t\telse:\n\t\t\t\t\t# title or page size\n\t\t\t\t\tif new_art == True:\n\t\t\t\t\t\t# if it's a page size\n\t\t\t\t\t\tif istitle == 0:\n\t\t\t\t\t\t\tistitle = 1\n\t\t\t\t\t\t\tnew_art = False\n\t\t\t\t\t\t\td = unicode(line)\n\t\t\t\t\t\t\tif d.isnumeric():\n\t\t\t\t\t\t\t\tif int(line)<100:\n\t\t\t\t\t\t\t\t\tis_small_article = True\n\t\t\t\t\t\t\t\t\tsmall_art_file.write(art_title)\n\t\t\t\t\t\t\t\t\tsmall_art_file.write(\"\\n\")\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tis_small_article = True\n\t\t\t\t\t\t# if it's an article title\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tart_file.write('\\n') \n\t\t\t\t\t\t\tart_title = line\n\t\t\t\t\t\t\tart_file.write(art_title)\n\t\t\t\t\t\t\tistitle = 0\n\t\t\t\t\t\t\tis_small_article = False\n\t\t\t\t\t\n\t\t\t\t\t# rev history\n\t\t\t\t\telse:\n\t\t\t\t\t\t# if the article size is bigger than 100B, get its revision history\n\t\t\t\t\t\tif is_small_article == False:\n\t\t\t\t\t\t\ttmp = line.split(\", \")\n\n\t\t\t\t\t\t\t# take care of the case when there's comma in editor's names\n\t\t\t\t\t\t\tif(len(tmp)>4):\n\t\t\t\t\t\t\t\t# if it's a major edit\n\t\t\t\t\t\t\t\tif float(tmp[len(tmp)-1]) >= 0.1:\n\t\t\t\t\t\t\t\t\t# if it's a registered user\n\t\t\t\t\t\t\t\t\tif tmp[len(tmp)-3] != \"0\":\n\t\t\t\t\t\t\t\t\t\tart_file.write(\", \")\n\t\t\t\t\t\t\t\t\t\tart_file.write(tmp[len(tmp)-3])\n\n\t\t\t\t\t\t\t#filter out minor edits\n\t\t\t\t\t\t\telif float(tmp[3]) >= 0.05:\n\t\t\t\t\t\t\t\t#filter out unregistered users\n\t\t\t\t\t\t\t\tif tmp[1] != \"0\":\n\t\t\t\t\t\t\t\t\tart_file.write(\", \")\n\t\t\t\t\t\t\t\t\tart_file.write(tmp[1])\n\t\t\t\n\tart_file.close()\n\tprint \"Remember to remove the duplicates in the end if multiple versions of outputs are created\"\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4221821427345276, "alphanum_fraction": 0.43234261870384216, "avg_line_length": 26.85978889465332, "blob_id": "ee0d3b5a25be5f4353c4dab04f8abc63fcdfe7b9", "content_id": "2b8784653e10b675f177e553d16fcfeb538b931d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 10531, "license_type": "no_license", "max_line_length": 140, "num_lines": 378, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/6_2_create_tree.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//////////////////////////////////////////////////////////////////////\n// The code takes in group assignments calculated for each article //\n// every iteration and construct a tree structure based on the //\n// result. //\n// //\n// Input: Group Assignment File //\n// Example: {[-1, -1, 2, 2], [2, 2, 2, 2]} //\n// //\n// Output: Tree Encoding //\n// Example: {[0: ], [0_0: 0, 1], [0_0_0: 2,3]} //\n// --------------------------------------------------------------- //\n// Note: //\n// 1. For input file, each row indicates the result after an //\n// iteration of union-find. Each index corresponds to the //\n// article //\n//////////////////////////////////////////////////////////////////////\n\n\n\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <stdlib.h>\n#include <vector>\n#include <fstream>\n#include <set>\n#include <map>\n\nint processed = 0;\nint num_art = 0;\nbool all_art = false;\n\nusing namespace std;\n\n\nbool comp_map(const string& l, const string& r)\n{\n int left_lv = 0;\n int right_lv = 0;\n \n vector<string> left_node;\n vector<string> right_node;\n \n string l_node = \"\";\n string r_node = \"\";\n \n for(int i=0;i<l.size();i++){\n if(l[i] == '_'){\n left_node.push_back(l_node);\n left_lv++;\n l_node = \"\";\n }\n else{\n l_node+=l[i];\n }\n }\n \n for(int i=0;i<r.size();i++){\n if(r[i] == '_'){\n right_node.push_back(r_node);\n right_lv++;\n r_node = \"\";\n }\n else{\n r_node+=r[i];\n }\n }\n if(left_lv<right_lv){\n return true;\n }\n else if(left_lv>right_lv){\n return false;\n }\n else{\n for(int i=0;i<left_node.size();i++){\n if(left_node[i]<right_node[i]){\n return true;\n }\n else if (left_node[i]>right_node[i]){\n return false;\n }\n }\n }\n return true;\n}\n\n\n\n//map<string, vector<int>, comp_map>::iterator search_map(map<string, vector<int>, comp_map>& enc, string s){\n// map<string, vector<int>, comp_map>::iterator it;\n// for(it = enc.begin();it!=enc.end();it++){\n// if(it->first == s){\n// return it;\n// }\n// }\n// return it;\n//}\n//\n//void insert_map(map<string, vector<int>, comp_map>& enc, string s, int num){\n// map<string, vector<int>, comp_map>::iterator it = search_map(enc, s);\n// if(it==enc.end()){\n// vector<int> tmp;\n// tmp.push_back(num);\n// enc[s] = tmp;\n// }\n// else{\n// it->second.push_back(num);\n// }\n//}\n\n\n\n\nvoid parse(string& s, vector<int>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(stoi(tmp));\n }\n \n tmp = \"\";\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(stoi(tmp));\n }\n}\n\n\n\n\n\n\nvoid get_tree_enco(const vector<vector<int> >& group, int ite, int child_counter, string prev_enco, \n vector<int>& indices, map<string, vector<int> >& tree_enco){\n map<int, int> visited; //id, child number\n int c = 0;\n int ite_index = group[0].size()-1-ite;\n \n int next_ite = ite+1;\n string curr_enco = prev_enco+\"_\"+to_string(child_counter);\n vector<vector<int> > new_indices;\n new_indices.clear();\n vector<int> tmp;\n int index = 0;\n \n vector<int> arts;\n arts.clear();\n tree_enco[curr_enco] = arts;\n \n \n map<string, vector<int> >::iterator it = tree_enco.find(curr_enco);\n if(it==tree_enco.end()){\n cerr<<\"cannot locate \"<<curr_enco<<\" from the map\"<<endl;\n exit(0);\n }\n \n for(int i=0;i<indices.size();i++){\n index = indices[i];\n //base case\n if(group[index][ite_index] == -1){\n if(it==tree_enco.end()){\n cerr<<\"cannot locate \"<<curr_enco<<\" from the map\"<<endl;\n exit(0);\n }\n it->second.push_back(index);\n \n processed++;\n }\n else{\n //last level\n if(ite == group[0].size()){\n it->second.push_back(index);\n \n processed++;\n }\n else{\n //if it's a new child\n if(visited.count(group[index][ite_index])==0){\n visited[group[index][ite_index]] = c;\n tmp.clear();\n tmp.push_back(index);\n new_indices.push_back(tmp);\n c++;\n }\n //get old children's counter\n else{\n int child_num = visited[group[index][ite_index]];\n new_indices[child_num].push_back(index);\n }\n }\n \n }\n \n }\n \n for(int i=0;i<new_indices.size();i++){\n get_tree_enco(group, next_ite, i, curr_enco, new_indices[i], tree_enco);\n \n }\n \n}\n\nvoid get_tree_enco_start(const vector<vector<int> >& group, map<string, vector<int> >& tree_enco){\n // initiate root\n string curr_enco = \"_0\";\n vector<int> arts;\n tree_enco[curr_enco] = arts;\n\n int last_ite_index = group[0].size()-1;\n int next_ite = 1;\n \n\n map<int, int> visited; //id, child number\n int child_counter = 0;\n\n vector<vector<int> > new_indices;\n vector<int> tmp;\n\n //store and locate the group in the map\n map<string, vector<int> >::iterator it = tree_enco.find(curr_enco);\n if(it==tree_enco.end()){\n cerr<<\"cannot locate \"<<curr_enco<<\" from the map\"<<endl;\n exit(0);\n }\n \n for(int i=0;i<group.size();i++){\n\n //if the current article didn't get merged into the tree [NEED TO BE IMPLEMENTED: updated 10/28/2018]\n if(group[i][last_ite_index] == -1){\n }\n else{\n //if it's a new child\n if(visited.count(group[i][last_ite_index])==0){\n visited[group[i][last_ite_index]] = child_counter;\n tmp.clear();\n tmp.push_back(i);\n new_indices.push_back(tmp);\n child_counter++;\n }\n //get old children's counter\n else{\n int child_num = visited[group[i][last_ite_index]];\n new_indices[child_num].push_back(i);\n }\n }\n \n }\n \n for(int i=0;i<new_indices.size();i++){\n get_tree_enco(group, next_ite, i, curr_enco, new_indices[i], tree_enco);\n \n }\n \n}\n\n\n\n\nint main(int argc, const char * argv[]){\n /*------------------------Get all inputs---------------------------*/\n if(argc < 3){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n\n cout<<\"Group_Iteration_File | Output_address | [Optional: output used articles (0/1)]\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string group_add = argv[1];\n string output_add = argv[2];\n output_add+=\"/tree_enco.txt\";\n string used_article_addr = argv[2];\n used_article_addr = used_article_addr+\"/used_article(encoded).txt\";\n\n\n ofstream used_article;\n\n if (argc == 4){\n used_article.open(used_article_addr);\n }\n \n \n /*------------------------ Create I/O File -------------------------*/\n ifstream group_file;\n group_file.open(group_add); //read in group assignment for each iteration\n ofstream outfile;\n outfile.open(output_add); //output file\n \n if(!group_file){\n cerr<<\"Can't open \"<<group_add<<endl;\n exit(0);\n }\n \n if(!outfile){\n cerr<<\"Can't create \"<<output_add<<endl;\n exit(0);\n }\n \n \n /*------------------------- Read in Group Assigments ---------------------------*/\n // group_ite file: \n // [{a1_group_ite1, a2_group_ite1, a3_group_ite1...}\n // {a1_group_ite2, a2_group_ite2, a3_group_ite2...}]\n\n // group array:\n // [{a1_ite1, a1_ite2, a1_ite3...}\n // {a2_ite1, a2_ite2, a2_ite3...}]\n\n string line = \"\";\n vector<int> parsed;\n\n vector<vector<int> > group;\n vector<int> tmp;\n\n int c=0;\n while(!group_file.eof()){\n getline(group_file, line);\n if(line.size()!=0){\n parsed.clear();\n parse(line, parsed);\n if(parsed.size()==0){\n cerr<<\"parsed.size()==0\"<<endl;\n exit(0);\n }\n\n if(c==0){\n num_art = parsed.size();\n for(int i=0;i<parsed.size();i++){\n tmp.clear();\n tmp.push_back(parsed[i]);\n group.push_back(tmp);\n }\n }\n else{\n for(int i=0;i<parsed.size();i++){\n group[i].push_back(parsed[i]);\n }\n }\n c++;\n }\n }\n\n group_file.close();\n \n /*---------------------------- Extract Groups and Articles in Each Group --------------------------------*/\n map<string, vector<int> > enc;\n\n get_tree_enco_start(group, enc);\n //output result\n for(map<string, vector<int> >::iterator it = enc.begin();it!=enc.end();it++){\n outfile<<it->first<<\", \";\n for(int i=0;i<it->second.size();i++){\n outfile<<it->second[i];\n if (argc==4){\n used_article<<it->second[i]<<endl;\n }\n if(i!=it->second.size()-1){\n outfile<<\", \";\n }\n }\n outfile<<endl;\n }\n\n cout<<endl<<\"There are \"<<processed<<\" out of \"<<num_art<<\" articles got merged into the tree (with an edge weight >= threshold)\"<<endl;\n //c+1 to include the root\n cout<<\"There are \"<<c+1<<\" levels in the tree\"<<endl;\n \n \n return 0;\n}\n" }, { "alpha_fraction": 0.47394222021102905, "alphanum_fraction": 0.48968008160591125, "avg_line_length": 28.24150848388672, "blob_id": "97f2ba33f564948ee0df628a053485600e89c983", "content_id": "edf812497146e11ca2a09cb22d7806e0be291803", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7754, "license_type": "no_license", "max_line_length": 142, "num_lines": 265, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/Archieve/6_create_art_weight_pair.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 7_get_article_weight_pair_new\n//\n// Created by Eve on 10/24/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n//\n// main.cpp\n// 7_get_article_weight_pair\n//\n// Created by Eve on 10/17/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n\n/*********************************************************************************/\n/* The code takes in editors and the articles they did major revisions for. The */\n/* code outputs the edge list for article pairs in the following format: */\n/* [art_weight_pair]: article_decode 1, article_decode 2, weight */\n/* [art_index_name]: article_decode, article_name */\n/*********************************************************************************/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n\nusing namespace std;\n\nunordered_map<string, string> real_article_id;\n\nint curr_in = -1; //current index of the new inserted article [used in addEdge]\nint num_noEdge = 0;\n\nbool new_art;\nbool store_art1;\nbool store_art2;\nstring art_index1;\nstring art_index2;\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if(s[i+1]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\nint getArtIndex(string& a, unordered_map<string, int>& article_index, ofstream&artname){\n int c = 0; //count the number of appearance of an article in the map\n unordered_map<string, int>::iterator it;\n int in_a = 0; //article index\n c = article_index.count(a);\n //if new article\n if(c == 0){\n curr_in+=1;\n article_index[a] = curr_in;\n in_a = curr_in;\n artname<<curr_in<<\", \"<<a<<endl;\n }\n //otherwise, directly get the index of the article\n else if (c == 1){\n it = article_index.find(a);\n in_a = it->second;\n }\n \n return in_a;\n}\n\n\nvoid addEdge(vector<string>& parsed, unordered_map<int, map<int,int> >& weight, unordered_map<string, int>& article_index, ofstream& artname){\n int in_a1 = 0;\n int in_a2 = 0;\n int tmp = 0;\n int c = 0; //counter for article appearances in weight\n \n string real_a1 = \"\";\n string real_a2 = \"\";\n unordered_map<int, map<int,int> >::iterator it;\n map<int,int>::iterator it2;\n \n \n \n //skip the first element (author name), take each pair\n for(int i=1;i<parsed.size();i++){\n for(int j = i+1;j<parsed.size();j++){\n real_a1 = real_article_id[parsed[i]];\n real_a2 = real_article_id[parsed[j]];\n \n in_a1 = getArtIndex(real_a1, article_index, artname);\n \n in_a2 = getArtIndex(real_a2, article_index, artname);\n \n //swap a1 a2 index to ensure a1 has smaller index (avoid repetition)\n if(in_a1>in_a2){\n tmp = in_a1;\n in_a1 = in_a2;\n in_a2 = tmp;\n }\n c = weight.count(in_a1);\n //if new article\n if(c == 0){\n map<int, int> edge;\n edge[in_a2] = 1;\n weight[in_a1] = edge;\n }\n //if the article is not in weight\n else{\n it = weight.find(in_a1); //locate article 1\n it2 = (it->second).find(in_a2); //locate article 2 from article 1'a edges\n // if article 2 doesnt have an edge with article 1\n if(it2 == (it->second).end()){\n (it->second)[in_a2] = 1;\n }\n else{\n it2->second+=1;\n }\n }\n }\n \n }\n}\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_word_articles_file Address_for_real_article_id Output_address\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string output_address = argv[3];\n string real_id_addr = argv[2];\n string edge_list_addr = output_address+\"/art_weight_pair_2.txt\";\n string art_index_addr = output_address+\"/art_name_2.txt\";\n string freq_w_addr = output_address+\"/freq_w_2.txt\";\n \n \n \n \n //initiate map for storing weight pair\n unordered_map<int, map<int, int> >weight;\n //initiate map for storing article_name and its index (for look up)\n unordered_map<string, int> article_index;\n \n //local variables\n vector<string> parsed;\n string line = \"\";\n \n new_art = false;\n store_art1 = false;\n store_art2 = false;\n //********** articles, weight pair *******//\n ofstream art_weight_pair;\n art_weight_pair.open (edge_list_addr);\n \n //********** article index, names *******//\n ofstream art_index_name;\n art_index_name.open (art_index_addr);\n \n \n \n //load and store article ids (since article ids in word_articles are only article index\n ifstream real_id;\n real_id.open(real_id_addr);\n int num_art = 0;\n if(!real_id) {\n cerr<<\"Can't open file\"<<endl;\n exit(1);\n }\n while (!real_id.eof()){\n getline(real_id, line);\n if(line.size()!=0){\n parsed.clear();\n parse(line, parsed);\n if(parsed.size()==2){\n real_article_id[to_string(parsed[1])] = parsed[1];\n num_art++;\n }\n else{\n cerr<<\"parsed.size()!=2\"<<endl;\n exit(0);\n }\n \n }\n }\n cout<<\"There are in total \"<<num_art<<\" articles\"<<endl;\n \n //////////////////////////\n // Create edge list //\n //////////////////////////\n ifstream infile;\n infile.open (argv[1]);\n \n ofstream freq;\n freq.open(freq_w_addr);\n freq<<\"The file stores the most appeared words (freq>number of articles/4) and the number of articles it appears\"<<endl;\n int i = 0;\n \n if(!infile){\n cerr<<\"Can't open infile\"<<endl;\n exit(1);\n }\n int l = 0;\n while(!infile.eof()){\n getline(infile,line);\n l+=1;\n cout<<l<<endl;\n if (!line.empty()){\n i++;\n parsed.clear();\n parse(line, parsed);\n cout<<\"parsed.size() = \"<<parsed.size()<<endl;\n if(parsed.size()>2000) {\n freq<<parsed[0]<<\": \"<<parsed.size()<<endl;\n continue;\n }\n addEdge(parsed, weight, article_index, art_index_name);\n \n }\n }\n infile.close();\n freq.close();\n \n if(curr_in+1!=num_art){\n cerr<<\"Found \"<<curr_in+1<<\" articles when creating indices compared to a total of\"<< num_art<<\" articles\"<<endl;\n // exit(0);\n }\n \n //*********** print out art_weight pair ************//\n unordered_map<int, map<int,int> >::iterator it;\n map<int,int>::iterator it2;\n for (it = weight.begin();it!=weight.end();it++){\n for(it2 = (it->second).begin();it2!=(it->second).end();it2++){\n if(it2->second==1) continue; //filter out weight=1 pairs\n art_weight_pair<<it->first<<\", \"<<it2->first<<\", \"<<it2->second<<endl;\n }\n }\n art_weight_pair.close();\n \n \n cout<<\"Completed\"<<endl;\n \n return 0;\n}\n\n\n\n" }, { "alpha_fraction": 0.5384852290153503, "alphanum_fraction": 0.5548029541969299, "avg_line_length": 22.84558868408203, "blob_id": "d04bd54be3b21aa9abb1522d411bd33538fd38ee", "content_id": "700226bb80041a70319fa2d307f715619c490443", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3248, "license_type": "no_license", "max_line_length": 138, "num_lines": 136, "path": "/3_Create_Bar_Graph/get_edit_size/1_convert_name_to_id_parsed_rev.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "# The code parse and reformat the revision history to the following form\n\n# article title, major editor 1, major editor 2...\n\n# Note 1. The major author is defined as authors with more than 10% edition history compare to the whole article\n# 2. Unregistered editor is not recorded in the output\n# 3. Users with a comma in the name is considered and the comma portion of the name is replaced by \"_,\"\n#\t 4. Articles with size smaller than 100B doesn't have their major editors recorded\n\nimport sys\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 6:\n\t\tprint \"--------------------------------------------------------------------------------\"\n\t\tprint \"Too few arguments. Please provide the information in the following format. \"\n\t\tprint \"Parsed_rev_file | Output_address | category_range_and_output_version | starting_line_number(starting from 1) | used_article_addr\"\n\t\tprint \"(e.g ./parsed_rev_cate_0_to_100000.txt ./output 0_to_100000_2 1 artname.txt)\" \n\t\tprint \"--------------------------------------------------------------------------------\"\n\t\tsys.exit()\n\n\toutput_address = sys.argv[2]+\"/parsed_\"+sys.argv[3]+\".txt\"\n\tinput_address = sys.argv[1]\n\tstart_line = int(sys.argv[4])\n\tart_name = sys.argv[5]\n\n\tart_file = open(output_address, \"w\")\n\n\t#local variables\n\tnew_art = False\n\tistitle = 0 #flag indicates the current line is a article title \n\tif start_line <= 1:\n\t\tnew_art = True\n\t\tistitle = 1\n\t\n\tart_title = \"\"\n\n\n\tc = 0 #current line number (starting at 1)\n\n\n\tid_name = {}\n\tparsed = []\n\tname = \"\"\n\n\tnum = 0\n\n\twith open(art_name,'r') as a_f:\t\t\n\t\tfor line in a_f:\n\t\t\tline = line.strip()\n\t\t\tif not line:\n\t\t\t\tprint \"detect empty line\"\n\t\t\telse:\n\t\t\t\tparsed = line.split(', ')\n\t\t\t\tfor i in range(len(parsed)):\n\t\t\t\t\tif i==0:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tname += parsed[i]\n\n\t\t\t\t# name = name.lower()\n\t\t\t\tid_name[name] = parsed[0]\n\t\t\t\t\n\t\t\t\tname = name.lower()\n\t\t\t\tif name not in id_name:\n\t\t\t\t\tid_name[name] = parsed[0]\n\t\t\t\tname = \"\"\n\t\t\t\t\n\ta_f.close()\n\tprint(len(id_name))\n\tprint(\"\\n\")\n\n\t\n\n\n\tarticle_id = \"\"\n\tnot_save = False\n\tno_id = 0\n\tnum_art_w_id = 0\n\tnum_art = 0\n\twith open(input_address,'r') as f:\n\t\tfor line in f:\n\t\t\tc+=1\n\t\t\tif c >= start_line:\n\t\t\t\tline = line.strip()\n\t\t\t\t\n\t\t\t\t# empty line indicates the end of an article\n\t\t\t\tif not line:\n# print \"detetct empty line\"\n\t\t\t\t\tistitle = 1\n\t\t\t\t\tnew_art = True\n\t\n\t\t\t\telse:\n\t\t\t\t\t# title or page size\n\t\t\t\t\tif new_art == True:\n\t\t\t\t\t\t# if it's a page size\n\t\t\t\t\t\tif istitle == 0:\n\t\t\t\t\t\t\tistitle = 1\n\t\t\t\t\t\t\tnew_art = False\n\t\t\t\t\t\t\tif not_save == False:\n\t\t\t\t\t\t\t\tart_file.write(line)\n\t\t\t\t\t\t\t\tart_file.write('\\n')\n\n\n\t\t\t\t\t\t# if it's an article title\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tistitle = 0\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tart_title = line\n\n\t\t\t\t\t\t\tnum_art += 1\n\t\t\t\t\t\t\t# art_title = art_title.lower()\n\n\t\t\t\t\t\t\tif art_title not in id_name:\n\t\t\t\t\t\t\t\tnot_save = True\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tnot_save = False\n\n\t\t\t\t\t\t\tif not_save == False: \n\t\t\t\t\t\t\t\tarticle_id = id_name[art_title]\n\t\t\t\t\t\t\t\tart_file.write('\\n') \n\t\t\t\t\t\t\t\tart_file.write(article_id)\t\n\t\t\t\t\t\t\t\tart_file.write('\\n') \n\t\t\t\t\t\t\t\t# not_save = False\n\t\t\t\t\t\t\t\tnum_art_w_id += 1\n\t\t\t\t\t\n\t\t\t\t\t# rev history\n\t\t\t\t\telse:\n\t\t\t\t\t\tif not_save == False:\n\t\t\t\t\t\t\tart_file.write(line)\n\t\t\t\t\t\t\tart_file.write('\\n') \n\t\t\t\t\t\t\n\n\t\t\t\n\tart_file.close()\n\tprint(num_art)\n\tprint(num_art_w_id)\n\n\n\n\n\n" }, { "alpha_fraction": 0.5641592741012573, "alphanum_fraction": 0.5674778819084167, "avg_line_length": 18.65217399597168, "blob_id": "34d9d19f3b155a8a1d2edaaff74716c10472f0b7", "content_id": "75096c27198f6e140dc9ac637263017305b06bc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 904, "license_type": "no_license", "max_line_length": 81, "num_lines": 46, "path": "/2_Compare_Tree/Generate_BOW_tree/Archieve/bag_of_words.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import collections, re\n\noutput_addr = \"/Users/eve/Desktop/bow.txt\"\noutfile = open(output_addr, 'w')\n\nline = \"\"\nc = 0\nbagsofwords = []\nsumbags = []\ntext = []\nwith open(\"/Users/eve/Desktop/w_o_stop_words.txt\",'r') as f:\n\tfor line in f:\n\t\tline = line.strip()\n\t\tif(len(line)!=0):\n\t\t\tif line == \"************************** New Article *************************\":\n\t\t\t\tc+=1\n\t\t\t\tprint(c)\n\t\t\t\tbagsofwords = [ collections.Counter(re.findall(r'\\w+', txt)) for txt in text]\n\n\t\t\t\tsumbags = sum(bagsofwords, collections.Counter())\n\t\t\t\tfor i in sumbags:\n\t\t\t\t\toutfile.write(i)\n\t\t\t\t\toutfile.write(\": \")\n\t\t\t\t\toutfile.write(str(sumbags[i]))\n\t\t\t\t\toutfile.write(\"\\n\")\n\t\t\t\toutfile.write(\"\\n\")\n\n\t\t\t\toutfile.write(\"\\n\\n\")\n\t\t\t\toutfile.write(line)\n\t\t\t\toutfile.write(\"\\n\\n\")\n\n\t\t\t\tbagsofwords = []\n\t\t\t\ttext = []\n\n\t\t\telse:\n\t\t\t\ttext.append(line)\n\t\t\t\n\nf.close()\noutfile.close()\n\n\n\n\n\n# sumbags = sum(bagsofwords, collections.Counter())\n" }, { "alpha_fraction": 0.6282894611358643, "alphanum_fraction": 0.6348684430122375, "avg_line_length": 25.34782600402832, "blob_id": "b338b00774671d9ecc2cee0b1fe90f18735691bf", "content_id": "d62a2cf0865779c2dc596609072c9f5cc570075f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 608, "license_type": "no_license", "max_line_length": 67, "num_lines": 23, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Generate_LDA_trees/2_decode_LDA.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "art_topic_addr = '/Users/eve/Desktop/DLA/art_topic_pass_2.txt'\nart_id_addr = '/Users/eve/Desktop/DLA/art_id.txt'\ndecoded_art_topic_addr = '/Users/eve/Desktop/DLA/art_topic_new.txt'\n\ndecoded = open(decoded_art_topic_addr, 'w')\n\nart_id = []\n\nfor line in open(art_id_addr):\n\tline = line.lower().strip().replace(',', ' ')\n\tart_id.append(line)\n\ntmp = []\nfor line in open(art_topic_addr):\n\tline = line.lower().strip().replace(',', ' ')\n\ttmp = line.split()\n\tfor i in range(0, len(tmp)):\n\t\tif i==0:\n\t\t\tdecoded.write(art_id[int(tmp[0])])\n\t\telse:\n\t\t\tdecoded.write(\", \")\n\t\t\tdecoded.write(tmp[i])\n\tdecoded.write(\"\\n\")\n\n\n" }, { "alpha_fraction": 0.6513761281967163, "alphanum_fraction": 0.6788991093635559, "avg_line_length": 35.33333206176758, "blob_id": "681be394c265a63f15976d6059036564cad18fb3", "content_id": "c1d2846cb83a91860fec64307d119c1d15f0ce8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 109, "license_type": "no_license", "max_line_length": 38, "num_lines": 3, "path": "/Desktop/Wiki/Code/6_Compare_Any_Two_Trees/compile.sh", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "g++ 1_pick_n_location.cpp -o a.out\ng++ 2_find_similarity.cpp -o b.out\ng++ 3_get_tree_similarity.cpp -o c.out\n" }, { "alpha_fraction": 0.616115391254425, "alphanum_fraction": 0.6365236043930054, "avg_line_length": 21.1796875, "blob_id": "8ea68f9ee35884b85a26e598192f28ab2a2f7539", "content_id": "bca7d6dd28609ba0f3b6771ae533e948814ca00f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2842, "license_type": "no_license", "max_line_length": 99, "num_lines": 128, "path": "/2_Compare_Tree/Generate_BOW_tree/Archieve/tf-idf.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nimport numpy as np\n\n# vectorizer = CountVectorizer(strip_accents='unicode', stop_words = 'english', analyzer == 'word')\nvectorizer = CountVectorizer()\ncorpus = []\n# input_addr = \"/Users/eve/Desktop/w_o_stop_words_enhanced.txt\"\ninput_addr = \"/Users/eve/Desktop/test.txt\"\noutput_addr = \"/Users/eve/Desktop\"\ntop_k = 10\n\nbow_words_addr = output_addr+\"/bow_words.txt\"\ncount_mat_addr = output_addr+\"/count_mat.txt\"\ntf_addr = output_addr+\"/tf-idf_result.txt\"\nart_word_addr = output_addr+\"/art_word.txt\"\nbow_words=open(bow_words_addr, 'w')\ncount_mat=open(count_mat_addr, 'w')\ntf= open(tf_addr,'w')\nart_word = open(art_word_addr, 'w')\n\nline = \"\"\ntext = []\na = 0\nc = 0\nwith open(input_addr,'r') as f:\n\tfor line in f:\n\t\tline = line.strip()\n\t\tif(len(line)!=0):\n\t\t\tif line == \"************************** New Article *************************\":\n\t\t\t\t# c+=1\n\t\t\t\t# print(c)\n\n\t\t\t\tline = \"\"\n\t\t\t\ta = 0\n\t\t\t\tfor i in text:\n\t\t\t\t\ta+=1\n\t\t\t\t\tline+=i\n\t\t\t\t\tif len(text)!=a:\n\t\t\t\t\t\tline+=\", \"\n\n\t\t\t\tcorpus.append(line)\n\n\t\t\t\ttext = []\n\n\t\t\telse:\n\t\t\t\ttext.append(line)\nf.close()\nprint(\"Loaded all articles\")\n\ncounts_tmp = vectorizer.fit_transform(corpus) #transform all articles\nprint(\"Finish creating bag of words\")\n\n#get all bow words in order\nwords = vectorizer.get_feature_names()\nfor i in words:\n\tbow_words.write(i.decode('UTF-8'))\n\tbow_words.write('\\n')\nbow_words.close()\nprint \"Total number of words in bow: \"\n\n\n#print out bow matrix\ncounts = counts_tmp.toarray() \n\nprint(str(len(counts[0])))\n# c=0\nfor i in counts:\n\t# print c\n\tcount_mat.write(str(i))\n\tcount_mat.write(\"\\n\")\ncount_mat.close()\nprint(\"Finished storing all bag of words\\n\")\n\n\n####### the API already normalized each row in the transform function\n# counts = counts.astype(float)\n\n# c = 0\n# for i in counts:\n# \tminrow = min(i)\n# \tmaxrow = max(i)\n# \tcounts[c] = (i-minrow)/(maxrow-minrow)\n# \tc+=1\n\n\ntransformer = TfidfTransformer()\ntfidf = transformer.fit_transform(counts).toarray()\nprint(\"Finished calculating tf-idf score\\n\")\n# print counts\nfor i in tfidf:\n\ttf.write(str(i))\n\ttf.write(\"\\n\")\ntf.close()\nprint(\"Finished storing tf-idf score\\n\")\n\n# get the index of top 100 biggest tf-idf value words of each row \n# x = np.array([3, 4, 2, 1, 5, 6, 7, 8, 100, 200, 300, 400, 500, 600, 20, -11])\n# ind = np.argpartition(x, -7)[-7:]\n# print ind\n# print x[ind]\n# print tfidf\n\nc=0\nfor i in tfidf:\n\t#get index of top 100 words\n\tind = np.argpartition(i, -top_k)[-top_k:]\n\t# ind.sort()\n\tart_word.write(str(c))\n\tfor j in ind:\n\t\tart_word.write(\", \")\n\t\tart_word.write(str(j))\n\tc+=1\n\tprint(c)\n\tart_word.write(\"\\n\")\n\n\t# c=0\n\t# for j in range(0, len(i)):\n\t# \tif c<len(ind) and j==ind[c]:\n\t# \t\tc+=1\n\t# \telse:\n\t# \t\ti[j] = 0.0\n\n# print tfidf\n\nprint \"Processed \", str(c), \" articles\"\n\nart_word.close()\n\n\n\n" }, { "alpha_fraction": 0.6283934116363525, "alphanum_fraction": 0.6399644017219543, "avg_line_length": 24.247190475463867, "blob_id": "a93cb71f72b0bc1f1c0297ad79235905dc1e8d4f", "content_id": "386a101c65ac42d7751bebdb49479719d82a4504", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2247, "license_type": "no_license", "max_line_length": 102, "num_lines": 89, "path": "/2_Compare_Tree/Generate_BOW_tree/2_tf_updated.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport numpy as np\n\n# vectorizer = CountVectorizer(strip_accents='unicode', stop_words = 'english', analyzer == 'word')\nvectorizer = TfidfVectorizer()\ncorpus = []\ninput_addr = \"/Users/eve/Desktop/w_o_stop_words.txt\"\n# input_addr = \"/Users/eve/Desktop/test.txt\"\noutput_addr = \"/Users/eve/Desktop\"\ntop_k = 100 #get top 100 words with highest idf score each row\n\nbow_words_addr = output_addr+\"/bow_words.txt\"\n# count_mat_addr = output_addr+\"/count_mat_2.txt\"\ntf_addr = output_addr+\"/tf-idf_result.txt\"\nart_word_addr = output_addr+\"/art_word.txt\"\nbow_words=open(bow_words_addr, 'w')\n# count_mat=open(count_mat_addr, 'w')\ntf= open(tf_addr,'w')\nart_word = open(art_word_addr, 'w')\n\n#store all articles in a corpus\nline = \"\"\ntext = []\na = 0\nc = 0\nwith open(input_addr,'r') as f:\n\tfor line in f:\n\t\tline = line.strip()\n\t\tif(len(line)!=0):\n\t\t\tif line == \"************************** New Article *************************\":\n\t\t\t\tc+=1\n\t\t\t\t# print(c)\n\n\t\t\t\tline = \"\"\n\t\t\t\ta = 0\n\t\t\t\tfor i in text:\n\t\t\t\t\ta+=1\n\t\t\t\t\tline+=i\n\t\t\t\t\tif len(text)!=a:\n\t\t\t\t\t\tline+=\", \"\n\n\t\t\t\tcorpus.append(line)\n\n\t\t\t\ttext = []\n\n\t\t\telse:\n\t\t\t\ttext.append(line)\nf.close()\nprint \"Loaded all\", str(c), \" articles\"\n\n# caluclate the idf score for the corpus [note that a row-wise normalization is done in the transform]\ntf_tmp = vectorizer.fit_transform(corpus) \nprint(\"Finish calculating tf-ifd\")\n\n\n# get the top 100 words with biggest idf score \n# store the article, w1, w2, ... in the art_word\nnum_art = c\nc = 0\nfor r in range (0, num_art):\n\ttf_idf = tf_tmp[r,:].toarray()\n\ttf.write(str(tf_idf[0]))\n\ttf.write(\"\\n\")\n\tind = np.argpartition(tf_idf[0], -top_k)[-top_k:]\n\tart_word.write(str(r))\n\tfor j in ind:\n\t\tart_word.write(\", \")\n\t\tart_word.write(str(j))\n\tc+=1\n\tprint(c)\n\tart_word.write(\"\\n\")\n\nprint \"Processed \", str(c), \" articles\"\n\n# tf_idf = tf_tmp[0,:].toarray()\n# print \"Total number of words in bow: \", str(len(tf_idf[0]))\n\nart_word.close()\ntf.close()\n\n\n#get all bow words in order\nwords = vectorizer.get_feature_names()\nfor i in words:\n\tbow_words.write(i.decode('UTF-8'))\n\tbow_words.write('\\n')\nbow_words.close()\nprint \"Total number of words in bow: \", str(len(words))\n" }, { "alpha_fraction": 0.43373116850852966, "alphanum_fraction": 0.44943466782569885, "avg_line_length": 22.932331085205078, "blob_id": "e6bd1d8d518a33ae69734df8065c92b76c5a6c3b", "content_id": "e8ff7bf2d1e7c58266484d453723cff3b69c1e1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3185, "license_type": "no_license", "max_line_length": 111, "num_lines": 133, "path": "/3_Create_Bar_Graph/get_edit_size/3_filter_out_less_than_100B.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// get_editor_with_art\n//\n// Created by Eve on 9/19/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n/////////////////////////////////////////////////////////////////////////\n// Code rearrage the parsed revision history //\n// (following article, major editor 1, major editor 2,... format) //\n// to the following format //\n// editor 1, majorly edited article 1, majorly edited article 2, ... //\n/////////////////////////////////////////////////////////////////////////\n\n\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <unordered_set>\nusing namespace std;\n\nint num_art = 0;\nint num_none_ed = 0;\nint min_ed = 0;\n\nvoid parse(string& line, vector<string>& parsed){\n string tmp = \"\";\n bool name = true;\n for(int i=0;i<line.size();i++){\n if((line[i] == ',') && (name == true)){\n name = false;\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp += line[i];\n }\n }\n parsed.push_back(tmp);\n \n}\n\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_art_w_major_editor_file | Output_address | category_range_and_output_version\"<<endl;\n// cout<<\"(e.g ./art_w_major_editor_cate_0_to_100000.txt ./Parsed 0_to_100000_2)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n\n \n string output_address = argv[2];\n string cate_range = argv[3];\n string output_file_address = output_address+\"/filtered_ed_size.txt\";\n \n \n ofstream outfile;\n outfile.open (output_file_address);\n \n \n string input_address = argv[1];\n fstream infile;\n infile.open(input_address);\n \n \n\n unordered_map <string, string> info;\n \n \n int counter = 0; //current line number\n \n \n string line = \"\";\n \n \n if(!infile){\n cerr<<\"Can't open the file\"<<endl;\n exit(1);\n }\n \n vector<string> parsed;\n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n parsed.clear();\n parse(line, parsed);\n if(parsed.size()<2){\n continue;\n \n }\n if(info.count(parsed[0])==0){\n info[parsed[0]] = parsed[1];\n }\n else{\n if(info[parsed[0]].size()<parsed[1].size()){\n info[parsed[0]] = parsed[1];\n }\n }\n \n }\n \n }\n infile.close();\n \n cout<<\"There are \"<<info.size()<<\" articles\"<<endl;\n \n //print to a text file\n\n for (auto it = info.begin();it!=info.end();it++){\n \n \n outfile<<it->first<<\",\";\n \n outfile<<it->second<<endl;\n \n }\n \n outfile.close();\n\n cout<<\"Completed\"<<endl;\n \n \n return 1;\n}\n\n" }, { "alpha_fraction": 0.741134762763977, "alphanum_fraction": 0.783687949180603, "avg_line_length": 39.42856979370117, "blob_id": "3b3dbf4c598b1ea15b23ff4068ff49cbaff69ee8", "content_id": "e98af1e239905fd8adddacf55fa7699aca19df26", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 282, "license_type": "no_license", "max_line_length": 50, "num_lines": 7, "path": "/2_Compare_Tree/find_similarity/Tests/readme.txt", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "Test Cases Explained\n0: Test for completely Same Trees\n1: Test for path with different size 1 and 4\n2: Test for path with different size 2 and 4\n3: Test for path with different size 3 and 4\n4: Test for ancestor node with more than one child\n5: Test for tree with duplicated articles" }, { "alpha_fraction": 0.4517495036125183, "alphanum_fraction": 0.46712726354599, "avg_line_length": 26.521472930908203, "blob_id": "4f00f16f3f7955f95c9947978d25c371c785b2d1", "content_id": "aabcf10377e6be74788648c08dc353ed499dac48", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4488, "license_type": "no_license", "max_line_length": 100, "num_lines": 163, "path": "/2_Compare_Tree/Generate_BOW_tree/8_sort_edgelist.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 8_sort_art_weight\n//\n// Created by Eve on 10/17/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <map>\n#include <unordered_map>\nusing namespace std;\n\nint c;\nbool change_a1 = false;\nbool change_a2 = false;\nunordered_map<string, int> a_index;\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if(s[i+1]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n \n}\n\nvoid addToMap(string& s, map<int, vector<pair<int,int> >,greater<int> >& m, vector<string>& parsed){\n parsed.clear();\n parse(s,parsed);\n if(parsed.size()<3) {\n cerr<<\"incomplete edge list: \"<<s<<endl;\n return;\n }\n vector<pair<int,int> > tmp;\n int w = stoi(parsed[2]);\n // map<int, vector<pair<string,string> > >::iterator it;\n map<int, vector<pair<int,int> > >::iterator it;\n it = m.find(w);\n if(it == m.end()){\n tmp.clear();\n \n if(a_index.count(parsed[0]) == 0){\n c+=1;\n a_index[parsed[0]] = c;\n change_a1 = true;\n// cout<<parsed[0]<<endl;\n \n }\n if(a_index.count(parsed[1]) == 0){\n c+=1;\n a_index[parsed[1]] = c;\n change_a2 = true;\n// cout<<parsed[1]<<endl;\n }\n \n tmp.push_back(make_pair(a_index[parsed[0]], a_index[parsed[1]]));\n// cout<<\"here\"<<endl;\n m[w] = tmp;\n }\n else{\n if(a_index.count(parsed[0]) == 0){\n c+=1;\n a_index[parsed[0]] = c;\n change_a1 = true;\n// cout<<parsed[0]<<endl;\n \n }\n if(a_index.count(parsed[1]) == 0){\n c+=1;\n a_index[parsed[1]] = c;\n change_a2 = true;\n// cout<<parsed[1]<<endl;\n }\n it->second.push_back(make_pair(a_index[parsed[0]], a_index[parsed[1]]));\n// cout<<\"here2\"<<endl;\n }\n}\nint main(int argc, const char * argv[]) {\n if(argc < 3){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_art_weight_pair_file Output_address\"<<endl;\n cout<<\"(e.g ./art_weight_pair_cate_0_to_100000.txt ./)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string output_address = argv[2];\n string sorted_addr = output_address+\"/sorted_weight.txt\";\n string num_edge_addr = output_address+\"/num_edge.txt\";\n \n map<int, vector<pair<int,int> >, greater<int> > sorted;\n\n// cout<<a_index.size()<<endl;\n map<int, vector<pair<int,int> > >::iterator it;\n // input article_weight pair\n ifstream infile;\n infile.open(argv[1]);\n\n // sorted graph\n ofstream weight_graph;\n weight_graph.open(sorted_addr);\n \n // number of edges with certain weight\n ofstream num_edge;\n num_edge.open (num_edge_addr);\n \n // ************ parse art_weight_pair.txt ************* //\n string line = \"\";\n vector<string> parsed;\n c = -1;\n \n if(!infile){\n cerr<<\"Can't open the file\"<<endl;\n exit(1);\n }\n while(!infile.eof()){\n getline(infile,line);\n \n if (!line.empty()){\n addToMap(line, sorted, parsed);\n// if(change_a1){\n// change_a1 = false;\n// artname<<a_index[parsed[0]]<<\", \"<<parsed[0]<<endl;\n// }\n// if(change_a2){\n// change_a2 = false;\n// artname<<a_index[parsed[1]]<<\", \"<<parsed[1]<<endl;\n// }\n }\n }\n infile.close();\n \n num_edge<<\"Weight | Number of Article Pairs \"<<endl;\n for(it=sorted.begin();it!=sorted.end();it++){\n for(int i=0;i<it->second.size();i++){\n weight_graph<<it->first<<\", \"<<it->second[i].first<<\", \"<<it->second[i].second<<endl;\n }\n num_edge<<it->first<<\" \"<<it->second.size()<<endl;\n }\n num_edge.close();\n weight_graph.close();\n \n cout<<\"Completed\"<<endl;\n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.5043103694915771, "alphanum_fraction": 0.517241358757019, "avg_line_length": 28.564102172851562, "blob_id": "96d91383a812aaae0bd4126b71c5c2bd67d09ddd", "content_id": "c2f22059b9521d9ea0a44964bc52299cb0353390", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2320, "license_type": "no_license", "max_line_length": 151, "num_lines": 78, "path": "/Desktop/Wiki/Code/1_Generate_Tree/2_get_art.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetTitles(cate):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&list=categorymembers&cmnamespace=0&cmprop=ids|title&cmlimit=500&cmpageid=\" + cate\n art = [] #list of all accumulated articles\n next = '' \n #information for the next request\n while True:\n req = urllib2.Request(url+next)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n\n art += re.findall('<cm [^>]*>', response) #adds all article info from the current request to the list\n\n cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n if not cont: #break the loop if 'continue' element missing\n break\n\n next = \"&cmcontinue=\" + cont.group(1) #gets the revision Id from which to start the next request\n\n return art\n\n\n\nif __name__ == \"__main__\":\n\n id_file = open(\"/Users/eve/Desktop/article_ids.txt\", \"w\")\n art_file = open(\"/Users/eve/Desktop/article_name.txt\", \"w\")\n \n start = 104624 #haven't run this category yet\n # start = 0\n counter = start\n\n cate_ids = []\n\n\n with open(\"/Users/eve/Desktop/cate_ids_0_44949.txt\",'r') as f:\n c = 0\n for line in f:\n line = line.strip('\\n')\n if c >= start:\n cate_ids.append(line)\n c += 1\n f.close()\n\n\n\n article = []\n artname = \"\"\n artid = \"\"\n \n while cate_ids:\n article = GetTitles(cate_ids[0])\n for i in article[0:len(article)]:\n # extract article title for current category (cate_name[0])\n artname = re.search('title=\"(.+?)\"', i).group(1)\n artname = artname.replace(\" \",\"_\")\n art_file.write(artname)\n art_file.write('\\n')\n \n artid = re.search('pageid=\"(.+?)\"', i).group(1)\n # print artid\n id_file.write(artid)\n id_file.write('\\n')\n\n art_file.write('\\n\\n') #seperation for each (sub)category\n id_file.write('\\n\\n')\n\n cate_ids.pop(0)\n print counter\n counter += 1\n \n\n\n art_file.close()\n id_file.close()\n print \"Finished!!!!!Finallyyyyyyyyy\"\n\n\n\n \n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5498132109642029, "alphanum_fraction": 0.5622665286064148, "avg_line_length": 21.928571701049805, "blob_id": "250e72210df61d4365a8e3a5fad11e7a072e0919", "content_id": "8e9c9d1cd2ed12a2099be9a2f46459af2b04ecd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1606, "license_type": "no_license", "max_line_length": 85, "num_lines": 70, "path": "/Desktop/Wiki/Code/Helper/match_name_file_with_id_file.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "if __name__ == \"__main__\":\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\tseen = set()\n\tindex_to_remove = [] #note that since we use num as a counter, the index starts at 0\n\n\tid_file = open(\"/Users/eve/Desktop/past_ids\", \"w\")\n\tname_file = open(\"/Users/eve/Desktop/past_name\", \"w\")\n\n\tline = \"\"\n\n\t# load all processed article names\n\twith open(\"/Users/eve/Desktop/combined.txt\") as f:\n\n\t for line in f:\n\t \tif len(line.strip()) != 0:\n\t \t\tnum+=1\n\t\t line = line.strip('\\n')\n\t\t if line in seen:\n\t\t \tcounter += 1\n\t\t else:\n\t\t\t\t\tseen.add(line)\n\t\t\t\t\t# print line\n\n\tprint \"finish scanning original file\"\n \tprint counter\n \tprint num\n\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\n\twith open(\"/Users/eve/Desktop/unique_name.txt\") as f:\n\n\t for line in f:\n\t \tif len(line.strip()) != 0:\n\t \t\tnum+=1\n\t\t line = line.strip('\\n')\n\t\t # print line\n\t\t if line in seen:\n\t\t \tname_file.write(line)\n\t\t \tname_file.write('\\n')\n\t\t else:\n\t\t\t\t\tindex_to_remove.append(num)\n\t\t\t\t\tcounter+=1;\n\n\n\tprint \"file 2\"\n \tprint counter\n \tprint num\n\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\n\tc = 0\n\twith open(\"/Users/eve/Desktop/unique_id.txt\") as f:\n\t for line in f:\n\t \tif len(line.strip()) != 0:\n\t \t\tnum+=1\n\t\t line = line.strip('\\n')\n\t\t if c<len(index_to_remove) and num == index_to_remove[c]:\n\t\t \tc +=1\n\t\t \tcounter +=1\n\t\t else:\n\t\t\t\t\tid_file.write(line)\n\t\t\t\t\tid_file.write('\\n')\n\n\n\tprint \"file 3\"\n \tprint counter\n \tprint num\n\n" }, { "alpha_fraction": 0.6446610689163208, "alphanum_fraction": 0.6555161476135254, "avg_line_length": 28.503267288208008, "blob_id": "8eef726a525b32d658e6fef7e10231cf87d47707", "content_id": "a4e5e566af2c698fe3b0d0b5889465b4fb500da1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4514, "license_type": "no_license", "max_line_length": 105, "num_lines": 153, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/2_tf_and_freq_updated.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "from sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport numpy as np\nimport os\n\noutput_folder = \"/Users/eve/Desktop/Major_Editor_5/Create_BoW_Tree\"\n# ------- input address -------\ninput_addr = output_folder+\"/1_w_o_stop_words.txt\"\n\npath = output_folder+\"/TF_IDF_Freq\"\ntry: \n os.mkdir(path)\nexcept OSError: \n print (\"Creation of the directory %s failed\" % path)\nelse: \n print (\"Successfully created the directory %s \" % path)\n\noutput_addr = output_folder+\"/TF_IDF_Freq\"\ntop_k = 100 #get top 100 words with highest idf score each row\n\n# ------- output address -------\nbow_words_addr = output_addr+\"/2_bow_words_tf_and_freq.txt\"\ncount_mat_addr = output_addr+\"/2_count_mat_tf_and_freq.txt\"\ntf_addr = output_addr+\"/2_tf-idf_result_tf_and_freq.txt\"\nart_word_addr = output_addr+\"/2_art_word_tf_and_freq.txt\"\n\nbow_words = open(bow_words_addr, 'w')\n# count_file = open(count_mat_addr, 'w')\n# tf_file = open(tf_addr,'w')\nart_word = open(art_word_addr, 'w')\n\n# --------- initiate corpus and verctors -------\n# vectorizer_count = CountVectorizer(strip_accents='unicode', stop_words = 'english', analyzer = 'word')\nvectorizer_count = CountVectorizer(strip_accents='unicode', analyzer = 'word')\n\nvectorizer_tfidf = TfidfVectorizer()\ncorpus = []\n\n# store contents for all articles in a corpus\n# corpus: [contents for article 1, contents for article 2...]\nline = \"\"\ncontent = []\ncontent_line_ctr = 0\nnum_art = 0 # article counter\nwith open(input_addr,'r') as f:\n\tfor line in f:\n\t\tline = line.strip()\n\t\tif(len(line)!=0):\n\t\t\t# finish reading in content for one article\n\t\t\tif line == \"************************** New Article *************************\":\n\t\t\t\tnum_art += 1\n\t\t\t\tline = \"\"\n\t\t\t\tcontent_line_ctr = 0\n\t\t\t\t# concat every section in an artcle to one line\n\t\t\t\tfor text in content:\n\t\t\t\t\tcontent_line_ctr += 1\n\t\t\t\t\tline += text\n\t\t\t\t\tif content_line_ctr!=len(content):\n\t\t\t\t\t\tline += \", \"\n\n\t\t\t\tcorpus.append(line)\n\n\t\t\t\tcontent = []\n\n\t\t\telse:\n\t\t\t\tcontent.append(line)\nf.close()\nprint \"Loaded all\", str(num_art), \" articles\"\n\n\ncount_matrix = []\ntf_matrix = []\n\n# caluclate the counts for the corpus \ncount_matrix = (vectorizer_count.fit_transform(corpus))\n# caluclate the tf-idf score for the corpus [note that a row-wise normalization is done in the transform]\ntf_matrix = (vectorizer_tfidf.fit_transform(corpus))\n\t\nprint(\"Finish calculating word counts\")\nprint(\"Finish calculating tf-idf\")\n\n# error check (if two matrices are different sized)\nfor r in range (0, num_art):\n\tcount_score = count_matrix[r,:].toarray()\n\ttf_idf_score = tf_matrix[r,:].toarray()\n\tif (len(tf_idf_score[0])!=len(count_score[0])):\n\t\tprint(\"count_matrix and tf-idf_marix are different in size\")\n\t\tprint(\"count_matrix [\"+str(r)+\"] length=\"+str(len(count_score[0])))\n\t\tprint(\"tf_matrix [\"+str(r)+\"] length=\"+str(len(tf_idf_score[0])))\n\t\texit()\n\n\n# get the top 100 words with biggest idf*frequency score \n# store the article, w1, w2, ... in the art_word\nc = 0\nfor r in range (0, num_art):\n\ttf_idf_score = tf_matrix[r,:].toarray()\n\tcount_score = count_matrix[r,:].toarray()\n\t# tf_file.write(str(tf_idf_score[0]))\n\t# tf_file.write(\"\\n\")\n\t# count_file.write(str(count_score[0]))\n\t# count_file.write(\"\\n\")\n\n\tmultiplied_score = []\n\n\tfor i in range(0, len(tf_idf_score[0])):\n\t\tmultiplied_score.append(tf_idf_score[0][i]*count_score[0][i])\n\t\n\tmultiplied_score = np.array(multiplied_score)\n\n\t# print(\"tfidf\")\n\t# print(tf_idf_score[0])\n\t# print(\"count\")\n\t# print(count_score[0])\n\t# print(\"multiplied_score\")\n\t# print(multiplied_score)\n\n\t# if (top_k>len(tf_idf_score[0])):\n\t# \ttop_k = len(tf_idf_score[0])\n\t# \tprint(\"Top_k is bigger than the size of bag of words (\"+str(len(tf_idf_score[0]))+\")\")\n\t# \tprint(\"We are using k = \"+str(len(tf_idf_score[0]))+'\\n')\n\n\tind = np.argpartition(multiplied_score, -top_k)[-top_k:]\n\t# print(\"ind\")\n\t# print(ind)\n\t\n\tart_word.write(str(r))\n\t# if there are fewer than k words in the article, get maximum\n\tfor j in ind:\n\t\tif multiplied_score[j]>0:\n\t\t\tart_word.write(\", \")\n\t\t\tart_word.write(str(j))\n\tc += 1\n\tprint(c)\n\tart_word.write(\"\\n\")\n\nprint \"Processed \", str(c), \" articles\"\n\n# tf_idf = tf_tmp[0,:].toarray()\n# print \"Total number of words in bow: \", str(len(tf_idf[0]))\n\n# art_word.close()\n# tf_file.close()\n# count_file.close()\n\n\n#get all bow words in order\nwords = vectorizer_tfidf.get_feature_names()\nfor i in words:\n\tbow_words.write(i.decode('UTF-8'))\n\tbow_words.write('\\n')\nbow_words.close()\nprint \"Total number of words in bow: \", str(len(words))\n" }, { "alpha_fraction": 0.5641025900840759, "alphanum_fraction": 0.5961538553237915, "avg_line_length": 11, "blob_id": "f83e8fb9889cc78c79c1fb9a2887fb942de049a6", "content_id": "807f2eedb474df7b9e307b0d7801832ec7537f98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 156, "license_type": "no_license", "max_line_length": 30, "num_lines": 13, "path": "/Desktop/Wiki/Code/Helper/get_words.hpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// get_words.hpp\n// \n//\n// Created by Eve on 2/13/18.\n//\n\n#ifndef get_words_hpp\n#define get_words_hpp\n\n#include <stdio.h>\n\n#endif /* get_words_hpp */\n" }, { "alpha_fraction": 0.4743667244911194, "alphanum_fraction": 0.48283275961875916, "avg_line_length": 29.431493759155273, "blob_id": "d871b9c4b98e6822f9183a626b88877f16ab6a22", "content_id": "44529a08ed34170cc4066e2953272f733525e436", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 14883, "license_type": "no_license", "max_line_length": 148, "num_lines": 489, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/6_1_get_enco.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "/////////////////////////////////////////////////////////////////////////////////////\n// The code calculates the new group assignment after merging all //\n// pairs for each level. //\n// //\n// Boost library (a sample code prepared by Alejandro was used as a reference): //\n// At first, we created a node for every article. Each article was //\n// originally assigned to itself as a group. Union-find was run to //\n// merge two articles. Once the number of pairs we grabbed was as //\n// desired, we check the new group assignments for every article: //\n// 1) If an article has a new group or has some other articles joined in //\n// (become the parent), record the group number in output file //\n// 2) If an article hasn't been merged, record the group number as -1 //\n// //\n// Output: Group Assignment File //\n// Example: {[-1, -1, 2, 2], [2, 2, 2, 2]} //\n// ------------------------------------------------------------------ //\n// Note: //\n// 1. Each row of the output file shows the group assignment of each iteration, //\n// each index of of row corresponds to the article_index. -1 means the article //\n// stays in its own group (has never merged with any group). Once an article //\n// is merged into a group, the group number is recorded. //\n// //\n// 2. All article index in the input file must be consecutive and start from 0 //\n// for the boost library to work //\n/////////////////////////////////////////////////////////////////////////////////////\n\n\n/*!\n * \\brief Uses boost disjoint_sets with a custom class.\n *\n * \\author Alejandro Mallea <[email protected]>\n *\n * \\copyright The MIT License\n */\n\n#include <algorithm>\n#include <iomanip>\n#include <iostream>\n#include <stdlib.h>\n#include <vector>\n#include <fstream>\n#include <set>\n#include <map>\n#include <unordered_set>\n#include <string>\n\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/pending/property.hpp>\nusing namespace std;\n\nint current_counter = 0;\n\n//////////////////////////////////////////////////\n// Disjoint Set Class & Helpers //\n//////////////////////////////////////////////////\n\nclass Element\n{\npublic:\n explicit\n Element(int n) {art_index = n;}\n \n int get_art_index() const { return art_index; }\n \n size_t dsID; //in this implementation dsID=art_index\n size_t dsRank;\n size_t dsParent;\n \nprivate:\n int art_index;\n};\n\ninline bool\noperator==(Element const& lhs, Element const& rhs)\n{\n return lhs.get_art_index() == rhs.get_art_index();\n}\n\ninline bool\noperator!=(Element const& lhs, Element const& rhs)\n{\n return ! operator==(lhs, rhs);\n}\n\nclass Parent\n{\npublic:\n Parent(std::vector<Element>& e) : mElements(e) { }\n std::vector<Element>& mElements;\n};\n\nclass Rank\n{\npublic:\n Rank(std::vector<Element>& e) : mElements(e) { }\n std::vector<Element>& mElements;\n};\n\ntemplate <>\nstruct boost::property_traits<Rank*>\n{\n typedef size_t value_type;\n};\n\ninline Element const&\nget(Parent* pa, Element const& k)\n{\n return pa->mElements.at(k.dsParent);\n}\n\ninline void\nput(Parent* pa, Element k, Element const& val)\n{\n pa->mElements.at(k.dsID).dsParent = val.dsID;\n}\n\ninline size_t const&\nget(Rank*, Element const& k)\n{\n return k.dsRank;\n}\n\ninline void\nput(Rank* pa, Element k, size_t const& val)\n{\n pa->mElements.at(k.dsID).dsRank = val;\n}\n\n\nvoid printElements(std::vector<Element>& elements)\n{\n cout<<\"---------------- ID [Group] ---------------------\"<<endl;\n for (size_t i = 0; i < elements.size(); ++i)\n {\n std::cout << std::setw(4) << elements[i].get_art_index()<<\"[\"<<elements[i].dsParent<<\"]\"<<endl;;\n }\n \n cout<<\"---------------------------------------------------\"<<endl;\n}\n\ninline bool\ncompareByParent(Element const& lhs, Element const& rhs)\n{\n return lhs.dsParent < rhs.dsParent;\n}\n\ninline bool\ncompareByArtIndex(Element const& lhs, Element const& rhs)\n{\n return lhs.get_art_index() < rhs.get_art_index();\n}\n\nvoid display_groups(vector<Element> elements, boost::disjoint_sets<Rank*, Parent*> sets){\n \n //^^^ do not pass elements by reference since the function sorts it!!!!! ^^^\n \n cout << \"Found \" << sets.count_sets(elements.begin(), elements.end()) << \" groups\" << endl;\n \n sets.compress_sets(elements.begin(), elements.end());\n std::sort(elements.begin(), elements.end(), compareByParent);\n \n size_t first = 0;\n while (first < elements.size())\n {\n size_t currentParent = elements.at(first).dsParent;\n size_t last = first;\n while (last < elements.size() && elements.at(last).dsParent == currentParent)\n {\n ++last;\n }\n std::cout << \"\\tRange: [\" << first << \",\" << last << \"). <dsParent = \"<<currentParent<<\">. Sorted elements: \";\n for (size_t i = first; i < last; ++i)\n {\n std::cout << elements.at(i).get_art_index() << \" \";\n }\n std::cout << std::endl;\n first = last;\n }\n \n}\n\nvoid display_certain_groups(vector<Element>& elements_original, size_t& g1, size_t& g2, size_t& g3, size_t& g4){\n// map<size_t, vector<size_t> > g; //group_id, list of article_ids\n //create \"map\"\n vector<vector<size_t> > g;\n vector<size_t> emp;\n for(int i=0;i<elements_original.size();i++){\n g.push_back(emp);\n }\n \n size_t group = 0; //group id\n size_t artid = 0; //article id\n //store all articles in a group to a map\n for(int i=0;i<elements_original.size();i++){\n group = elements_original[i].dsParent;\n artid = elements_original[i].dsID;\n \n //store\n g[group].push_back(artid);\n }\n \n cout<<\"Group \"<<g1<<\": \";\n for(int i=0;i<g[g1].size();i++){\n cout<<g[g1][i]<<\" \";\n }\n cout<<endl;\n \n cout<<\"Group \"<<g2<<\": \";\n for(int i=0;i<g[g2].size();i++){\n cout<<g[g2][i]<<\" \";\n }\n cout<<endl;\n \n cout<<\"Group \"<<g3<<\": \";\n for(int i=0;i<g[g3].size();i++){\n cout<<g[g3][i]<<\" \";\n }\n cout<<endl;\n \n cout<<\"Group \"<<g4<<\": \";\n for(int i=0;i<g[g4].size();i++){\n cout<<g[g4][i]<<\" \";\n }\n cout<<endl;\n \n \n}\n\n\n////////////////////////////////////\n// Parse Function //\n////////////////////////////////////\nvoid parse(string& s, vector<double>& parsed){\n parsed.clear();\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(stod(tmp));\n }\n \n tmp = \"\";\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(stod(tmp));\n }\n}\n\n////////////////////////////////////\n// Create First Level //\n////////////////////////////////////\nvoid create_first_level(std::vector<Element>& elements, vector<int>& prev_g, ofstream& outfile)\n{\n // for (int i = 0; i < elements.size(); ++i){\n // cout<<elements[i].dsParent<<\" \";\n // }\n // cout<<endl;\n\n //initiate every group to -1\n vector<int> new_group(prev_g.size(), -1);\n \n for (int i = 0; i < elements.size(); ++i)\n {\n int new_group_id = elements[i].dsParent;\n int old_group_id = prev_g[i]; //group assignment from previous iteration\n \n //if the article has been merged\n if(new_group_id!=i){\n prev_g[i] = new_group_id; //update for next iteration\n new_group[i] = new_group_id;\n \n new_group[new_group_id] = new_group_id; //also update the assignment for the group this article is merged into\n }\n \n }\n \n //output\n for(int i=0;i<new_group.size()-1;i++){\n outfile<<new_group[i]<<\", \";\n }\n outfile<<new_group[new_group.size()-1]<<endl;\n \n \n}\n\n\nvoid create_level(std::vector<Element>& elements, vector<int>& prev_g, ofstream& outfile)\n{\n // for (int i = 0; i < elements.size(); ++i){\n // cout<<elements[i].dsParent<<\" \";\n // }\n // cout<<endl;\n\n vector<int> new_group(prev_g.size(), -1);\n for (int i = 0; i < elements.size(); ++i)\n {\n int new_group_id = elements[i].dsParent;\n int old_group_id = prev_g[i];\n if(new_group_id!=i){\n prev_g[i] = new_group_id;\n new_group[i] = new_group_id;\n \n prev_g[new_group_id] = new_group_id;\n new_group[new_group_id] = new_group_id;\n }\n //if the article has been merged before, update the group number\n else if(new_group[i]==-1 && old_group_id!=-1){\n new_group[i] = old_group_id;\n \n }\n }\n \n //output\n for(int i=0;i<new_group.size()-1;i++){\n outfile<<new_group[i]<<\", \";\n }\n outfile<<new_group[new_group.size()-1]<<endl;\n \n}\n\n\n\nint main(int argc, const char * argv[])\n{\n \n //==================== load inputs =====================\n if(argc < 6){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_sorted_edge_list_file | Output_address | Minimum_Weight_to_Consider | Number_Articles | min_num_articles_to_merge\"<<endl;\n cout<<\"(e.g ./sorted_weight.txt ./ 3 33000 168)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string output_add = argv[2];\n string enc_address = output_add+\"/group_ite.txt\";\n double common_ed_limit = stod(argv[3]);\n int num_art = atoi(argv[4]);\n \n ofstream group_ite;\n group_ite.open(enc_address);\n\n string min_merge = argv[5];\n double min_num_articles_to_merge = stod(min_merge);\n // int min_num_articles_to_merge = 1;\n cout<<\"We will merge at least \"<<min_num_articles_to_merge<<\" articles per level\"<<endl;\n \n \n //-------------------------- Create Node for Each Article -----------------------------\n vector<Element> elements;\n vector<int> initial_group;\n \n elements.reserve(num_art);\n for (int i=0;i<num_art;i++){\n elements.push_back(Element(i));\n elements[i].dsID = i;\n initial_group.push_back(-1);\n }\n \n Rank rank(elements);\n Parent parent(elements);\n \n boost::disjoint_sets<Rank*, Parent*> sets(&rank, &parent);\n \n for (size_t i = 0; i < elements.size(); ++i)\n {\n sets.make_set(elements.at(i));\n }\n \n \n /*------------------------- Read In Edge List ---------------------------*/\n //local variables\n vector<double> parsed;\n double current_weight = -10.0;\n std::unordered_set<int> merged_articles;\n int num_article_merged = 0; // count number of articles merged for the current level\n \n //get edge list for weight, article_pair (in descending order)\n ifstream edge_list;\n edge_list.open (argv[1]);\n \n string line = \"\";\n int c = 0; //line counter\n bool first_lv = true;\n \n \n size_t g1 = 0;\n size_t g2 = 0;\n size_t new_g1 = 0;\n size_t new_g2 = 0;\n int num_lvs = 0;\n \n while(!edge_list.eof()){\n line = \"\";\n parsed.clear();\n getline(edge_list,line);\n if (!line.empty()){\n parse(line, parsed);\n if(c==0){\n current_weight = parsed[0];\n }\n \n //if the current weight is smaller than desired, stop grabbing edges <--------------\n if(parsed[0]<common_ed_limit) break;\n \n //grabbed enough edges, start creating the level (update group status in output file)\n if(parsed[0]!=current_weight && num_article_merged >= min_num_articles_to_merge){\n\n num_lvs++;\n num_article_merged = 0;\n sets.compress_sets(elements.begin(), elements.end());\n \n \n cout<<num_lvs<<\" Creating level for weight \"<<current_weight<<\"...\"<<endl;\n current_weight = parsed[0];\n \n if(first_lv == true){\n first_lv = false;\n create_first_level(elements, initial_group, group_ite);\n }\n else{\n create_level(elements, initial_group, group_ite);\n }\n \n }\n\n // error check: index for the current article is out of range\n if (parsed[1]>=num_art){\n cerr<<\"Detected article index [\"<<parsed[1]<<\"] out of range (number of article initialized = \"<<num_art<<\")\"<<endl;\n exit(0);\n }\n if (parsed[2]>=num_art){\n cerr<<\"Detected article index [\"<<parsed[2]<<\"] out of range (number of article initialized = \"<<num_art<<\")\"<<endl;\n exit(0);\n }\n\n g1 = elements[parsed[1]].dsParent;\n g2 = elements[parsed[2]].dsParent;\n\n // count the number of newly merged articles of the level\n if (merged_articles.count(parsed[1])==0){\n merged_articles.insert(parsed[1]);\n num_article_merged++;\n }\n\n if (merged_articles.count(parsed[2])==0){\n merged_articles.insert(parsed[2]);\n num_article_merged++;\n }\n\n if(g1==g2){\n continue;\n }\n sets.union_set(elements[parsed[1]], elements[parsed[2]]);\n\n // cout<<\"merging \"<<parsed[1]<<\" and \"<<parsed[2]<<endl;\n // cout<<\"[\";\n // for (int i = 0; i < elements.size(); ++i){\n // cout<<i<<\" \";\n // }\n // cout<<\"]\"<<endl;\n // for (int i = 0; i < elements.size(); ++i){\n // cout<<elements[i].dsParent<<\" \";\n // }\n // cout<<endl;\n\n }\n c++;\n }\n edge_list.close();\n \n \n //Store last level\n sets.compress_sets(elements.begin(), elements.end());\n num_lvs++;\n\n cout<<\"Creating level for weight \"<<current_weight<<\"...\"<<endl;\n create_level(elements, initial_group, group_ite);\n\n cout<<\"There are in total \"<<num_lvs<<\" levels in the tree\"<<endl;\n \n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.4333333373069763, "alphanum_fraction": 0.4441666603088379, "avg_line_length": 24.167831420898438, "blob_id": "4639ad779d932196acc3b0816772146f427b408d", "content_id": "b5c4dedd58e07e279ef8334408fbb95990557872", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3601, "license_type": "no_license", "max_line_length": 106, "num_lines": 143, "path": "/Desktop/Wiki/Code/1_Generate_Tree/10_decode_tree.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// convert_name_to_id\n//\n// Created by Eve on 2/6/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\n\nusing namespace std;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==',' || line[i]==':' ){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else{\n if(line[i]!=' '){\n tmp+=line[i];\n \n }\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"artname_file | revision_tree_file | Output_Address | [optional: used article (0/1)]\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string artname_file_addr = argv[1];\n string tree_addr = argv[2];\n string output_addr = argv[3];\n output_addr+=\"/7_decoded_tree.txt\";\n \n string used_art_addr = argv[3];\n used_art_addr += \"/used_article.txt\";\n \n ifstream artname_file, tree;\n artname_file.open(artname_file_addr);\n tree.open(tree_addr);\n \n ofstream outfile;\n outfile.open(output_addr);\n\n ofstream used_art;\n if (argc == 5){\n used_art.open(used_art_addr);\n }\n \n if(!outfile){\n cerr<<\"can't open output file\"<<endl;\n exit(0);\n }\n\n\n \n //read in id file\n map<string, string> id_name;\n string line;\n string id, name;\n vector<string> parsed;\n int c=0;\n while(!artname_file.eof()){\n line = \"\";\n getline(artname_file, line);\n if(line.size()>0){\n parsed.clear();\n parse(parsed, line);\n if(parsed.size()!=2){\n cerr<<\"parsed.size()!=2\"<<endl;\n exit(0);\n }\n id_name[parsed[0]] = parsed[1];\n c++;\n }\n }\n cout<<\"Stored \"<<c<<\" articles\"<<endl;\n \n \n artname_file.close();\n\n c = 0;\n int num_used_art = 0;\n while(!tree.eof()){\n line = \"\";\n getline(tree, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n \n outfile<<parsed[0];\n for(int i=1;i<parsed.size();i++){\n if(parsed[i]!=\" \" && parsed[i].size()!=0){\n if (id_name.count(parsed[i])==0){\n cerr<<\"Encoded article \"<<parsed[i]<<\" can't be decoded\"<<endl;\n exit(0);\n }\n outfile<<\", \"<<id_name[parsed[i]];\n\n if (argc == 5){\n used_art<<id_name[parsed[i]]<<endl;\n num_used_art++;\n }\n\n c++;\n }\n \n }\n outfile<<endl;\n }\n \n }\n \n tree.close();\n outfile.close();\n\n cout<<\"Decoded \"<<c<<\" articles\"<<endl;\n cout<<\"Number of decoded articles indicate the number of articles in the tree\"<<endl;\n cout<<\"There are \"<<num_used_art<<\" articles used in the tree\"<<endl;\n return 0;\n}\n\n" }, { "alpha_fraction": 0.6121647953987122, "alphanum_fraction": 0.6402877569198608, "avg_line_length": 22.18181800842285, "blob_id": "9916200cbe36560a94865fb195039e7f8ac6027c", "content_id": "1aa4beaf893e305f1c7efd1b3bf129f933be5fd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1529, "license_type": "no_license", "max_line_length": 138, "num_lines": 66, "path": "/Desktop/Wiki/Code/Helper/combine two files.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "if __name__ == \"__main__\":\n\t\n\tprint (\"Make sure duplicates in the end of the file is removed (overlaps)\")\n\tprint(\"Adjust the spaces between the transition of files\")\n\tprint(\"\")\n\tprint (\"Start...\")\n\t#output file\n\ttext_file = open(\"/Users/eve/Desktop/combined.txt\",'w')\n\t\n\t#open file 1\n\t# c = 1\n\t# p = False\n\twith open(\"/Users/eve/Desktop/Major_Editor_5/Create_Edit_Size_Tree/1_article_editor_edit_size_0.txt\",'r') as f:\n\t\tfor line in f:\n\t\t\ttext_file.write(line)\t\n\tf.close()\n\n\tprint(\"Finished one file\")\n\n\n\ttext_file.write(\"\\n\")\n\n\t# #open file 2\n\twith open(\"/Users/eve/Desktop/Major_Editor_5/Create_Edit_Size_Tree/1_article_editor_edit_size.txt\",'r') as f:\n\t\t\n\t\tfor line in f:\n\t\t\ttext_file.write(line)\n\n\tf.close()\n\tprint(\"Finished two files\")\n\n\ttext_file.write(\"\\n\")\n\n\t# # # #open file 3\n\t# with open(\"/Volumes/Eve/Wiki/All_Materials_for_Paper/Experiment/Art_w_Major_Editors/art_w_major_editor_cate_104624_1.4M.txt\",'r') as f:\n\t\t\n\t# \tfor line in f:\n\t# \t\ttext_file.write(line)\n\t# f.close()\n\t\n\t# # text_file.write(\"\\n\")\n\n\t# print(\"Finished three files\")\n\n\t# # # \t# #open file 3\n\t# with open(\"/Volumes/Eve/Wiki/Life/Rev/revision_history_cate_31790_to_104624_2.txt\",'r') as f:\n\t\t\n\t# \tfor line in f:\n\t# \t\ttext_file.write(line)\n\n\t# f.close()\n\n\t# print(\"Finished four files\")\n\t# text_file.write(\"\\n\")\n\n\t# # # \t# #open file 3\n\t# with open(\"/Volumes/Eve/Wiki/Life/Rev/revision_history_cate_31790_to_104624_2.txt\",'r') as f:\n\t\t\n\t# \tfor line in f:\n\t# \t\ttext_file.write(line)\n\n\t# f.close()\n\t\n\t# print(\"Finished five files\")\n\n\ttext_file.close()" }, { "alpha_fraction": 0.48507827520370483, "alphanum_fraction": 0.49461838603019714, "avg_line_length": 26.066225051879883, "blob_id": "32c791567d0bf9ee9d000d7c6a0e1c59638a0f5d", "content_id": "7bcc5a6e80f9339a7ce8ce3776b388d89ce05032", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4089, "license_type": "no_license", "max_line_length": 116, "num_lines": 151, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Archieve/generate_random_tree(same_structure).cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// generate_random\n//\n// Created by Eve on 3/9/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n\n/****************************************************************/\n// The code is written for randomly choose an article of a given\n// structure, where the structure (tree enco) and number of\n// articles in each node is the same.\n//\n// [Input format]\n// <Tree.txt>\n// tree_enc_, art_id1, art_id2, ...\n//\n// <Artname.txt>\n// index, article id\n//\n//\n// [Output format]\n// (random tree has articles in their real article ids)\n// Tree encoding, random article 1, random article 2 ...\n//\n/***************************************************************/\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\nusing namespace std;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 5){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Tree_Address(merged group_art and tree_enco) | Used_Article_addr | Output_Address | Num_Nodes\"<<endl;\n cout<<\"(e.g ./tree.txt ./used_art.txt ./Output 27)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string tree_enco_addr = argv[1];\n string artname_addr = argv[2];\n string output_addr = argv[3];\n output_addr+=\"/random_tree_structure_new.txt\";\n \n string t_n = argv[4];\n int tot_nodes = stoi(t_n);\n \n // get all articles in the tree\n vector<string> all_articles;\n set<int> visited;\n \n string line = \"\";\n vector<string> parsed;\n ifstream artname;\n artname.open(artname_addr);\n while(!artname.eof()){\n getline(artname, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n if(parsed.size()!=1){\n cerr<<\"parsed.size()!=1\"<<endl;\n exit (0);\n }\n all_articles.push_back(parsed[0]); //store real article ids\n }\n }\n \n artname.close();\n \n //get revision tree structure\n ifstream tree_enco;\n tree_enco.open(tree_enco_addr);\n \n int num_art_per_node = 0;\n int total_art_num = all_articles.size();\n int num_art_rem = total_art_num;\n int avg_num_per_node = total_art_num/tot_nodes*2;\n if(avg_num_per_node==0) avg_num_per_node = 1;\n int index = 0;\n \n ofstream outfile;\n outfile.open(output_addr);\n int c=0;\n while(!tree_enco.eof()){\n getline(tree_enco, line);\n c++;\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n //calculate number of articles in each node\n num_art_per_node = rand()%(avg_num_per_node);\n num_art_rem -= num_art_per_node;\n outfile<<parsed[0];\n \n if(c == tot_nodes){\n num_art_per_node = num_art_rem;\n num_art_rem = 0;\n }\n \n //randomly pick and store n articles in the node\n for(int i=0;i<num_art_per_node;i++){\n index = rand()%total_art_num;\n while(visited.find(index)!=visited.end()){\n index = rand()%total_art_num;\n }\n visited.insert(index);\n outfile<<\", \"<<all_articles[index];\n }\n outfile<<endl;\n \n }\n }\n \n if(num_art_rem!=0){\n cerr<<\"Didn't store all articles\"<<endl;\n exit(0);\n }\n \n tree_enco.close();\n outfile.close();\n \n \n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.5102599263191223, "alphanum_fraction": 0.5184678435325623, "avg_line_length": 24.64912223815918, "blob_id": "95f385eb92057e4fbd7bb5d0949b9204b2166cac", "content_id": "0265d963997de2d319bfe5413ba1a465aa939c4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1462, "license_type": "no_license", "max_line_length": 159, "num_lines": 57, "path": "/2_Compare_Tree/Generate_BOW_tree/0_get_art_content.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetContent(title, outfile):\n\turl = \"https://en.wikipedia.org/w/api.php?format=xml&action=query&prop=extracts&explaintext=1&exlimit=1&pageids=\" + title \n\tnext = '' \n\twhile True:\n\t\treq = urllib2.Request(url+next)\n\t\tresponse = urllib2.urlopen(req)\n\t\tresponse = response.read() #web request \n\t\tcont = re.search('<continue excontinue=\"([^\"]+)\"', response)\n\t\tif not cont: \n\t\t\t# content += response \n\t\t\toutfile.write(response) \n\t\t\tbreak\n\t\tnext = \"&excontinue=\" + cont.group(1) \n\t#return content\n\n\n\nif __name__ == \"__main__\":\n\n\tart = []\n\ttmp = []\n\tcounter = 0\n\n\toutput_addr = \"/Users/eve/Desktop/art_content.txt\"\n\toutfile = open(output_addr, 'w')\n\n\n\n\twith open(\"/Users/eve/Desktop/used_articles.txt\",'r') as f:\n\n\t\tfor line in f:\n\t\t\t\n\t\t\t# art = []\n\t\t\tcounter = counter+1\n\t\t\tif counter>=1:\n\t\t\t\tline = line.strip('\\n')\n\t\t\t\tGetContent(line, outfile)\n\t\t\t\tprint line\n\t\t\t\toutfile.write(\"\\r\\n\\r\\n************************** New Article *************************\\r\\n\\r\\n\") #seperate each article\n\n\t\t\t\t# art = line.split(', ')\n\t\t\t\t# if len(art)==2:\n\t\t\t\t# \tGetContent(art[1], outfile)\n\t\t\t\t# \tprint art[1]\n\t\t\t\t# \toutfile.write(\"\\r\\n\\r\\n************************** New Article *************************\\r\\n\\r\\n\") #seperate each article\n\t\t\t\t# else:\n\t\t\t\t# \tbreak\n\t\t\t\t\n\t\t\tprint(counter)\n\n\toutfile.close()\n\n\n\tprint \"Finished!!!!!\"\n" }, { "alpha_fraction": 0.4544527530670166, "alphanum_fraction": 0.4656696021556854, "avg_line_length": 25.030973434448242, "blob_id": "244b7c8859704db2b12d593666d2932ceab3ebf3", "content_id": "f929692d9ae2d3af6c1e13ce14efa60b750a2b7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5886, "license_type": "no_license", "max_line_length": 106, "num_lines": 226, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/9_add_remaining_arts.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 7_get_article_weight_pair_new\n//\n// Created by Eve on 10/24/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n//\n// main.cpp\n// 7_get_article_weight_pair\n//\n// Created by Eve on 10/17/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n\n/*********************************************************************************/\n// The code goes through the list of all articles we used to create BoW tree\n// and create a root node to hold all articles that did not get saved in the generated\n// tree (article content cannot be found/article content is now <100B/article shares\n// too few (we used 3 for cutoff) high tf-idf word with any other articles)\n/*********************************************************************************/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n\nusing namespace std;\n\n\n\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if (tmp!=\" \" && tmp.size()!=0){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n if (tmp!=\" \" && tmp.size()!=0){\n parsed.push_back(tmp);\n }\n}\n\nint count_levels(string& s){\n int lv = 0;\n for(int i=0; i<s.length();i++){\n if(s[i]=='_'){\n lv++;\n }\n }\n return lv;\n}\n\n\n\n\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_used_article | Address_for_decoded_tree | Output_address\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string used_art_addr = argv[1];\n string decoded_tree_addr = argv[2];\n string output_address = argv[3];\n output_address+=\"/9_BoW_tree.txt\";\n\n \n ofstream outfile;\n outfile.open(output_address);\n \n //initiate set for storing encountered articles\n unordered_set<string> stored_article;\n vector<string> unstored;\n \n //local variables\n vector<string> parsed;\n string line = \"\";\n\n ifstream infile;\n infile.open(decoded_tree_addr);\n\n\n //get all articles in the generated tree\n if(!infile){\n cerr<<\"Can't open \"<<decoded_tree_addr<<endl;\n exit(1);\n }\n\n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n \n parsed.clear();\n parse(line, parsed);\n\n for (int i=1;i<parsed.size();i++){\n if(stored_article.count(parsed[i])!=0){\n cerr<<\"generated tree contains duplicates [article \"<<parsed[i]<<\"]\"<<endl;\n exit(0);\n }\n stored_article.insert(parsed[i]);\n }\n }\n }\n infile.close();\n\n cout<<\"There are \"<<stored_article.size()<<\" articles in the generated tree\"<<endl;\n \n \n\n\n //get articles that did not get stored in the tree\n infile.open(used_art_addr);\n //get all articles in the generated tree\n if(!infile){\n cerr<<\"Can't open \"<<used_art_addr<<endl;\n exit(1);\n }\n\n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n \n parsed.clear();\n parse(line, parsed);\n\n if(parsed.size()!=1){\n // cerr<<\"parsed.size()!=1\"<<endl;\n // exit(0);\n //check if it's an article that didn't get stored\n if (stored_article.count(parsed[1])==0){\n unstored.push_back(parsed[1]);\n }\n }\n else{\n //check if it's an article that didn't get stored\n if (stored_article.count(parsed[0])==0){\n unstored.push_back(parsed[0]);\n }\n }\n\n \n }\n }\n infile.close();\n\n cout<<\"There are \"<<unstored.size()<<\" articles that did not get stored in the tree\"<<endl;\n\n //create a node to hold all unstored articles\n outfile<<\"_0\"<<endl;\n\n infile.open(decoded_tree_addr);\n \n if(!infile){\n cerr<<\"Can't open \"<<decoded_tree_addr<<endl;\n exit(1);\n }\n \n int line_ctr = 0;\n int num_lv = INT_MIN;\n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n parsed.clear();\n parse(line, parsed);\n string new_node_code = \"\";\n if (line_ctr == 0){\n if (parsed[0]!=\"_0\" || parsed.size()!=1){\n cerr<<\"The first node in the generated tree is not empty\"<<endl;\n cout<<line<<endl;\n exit(0);\n }\n line_ctr++;\n new_node_code = \"_0_0\";\n outfile<<new_node_code;\n for (int i=0; i<unstored.size();i++){\n outfile<<\", \"<<unstored[i];\n }\n outfile<<endl;\n }\n else{\n new_node_code = \"_0\"+parsed[0];\n outfile<<new_node_code;\n for (int i=1;i<parsed.size();i++){\n outfile<<\", \"<<parsed[i];\n }\n outfile<<endl;\n }\n num_lv = max(num_lv, count_levels(new_node_code));\n }\n }\n \n \n infile.close();\n \n \n cout<<\"There are in total \"<<unstored.size()+stored_article.size()<<\" articles now in the tree\"<<endl;\n\n cout<<\"There are \"<<num_lv<<\" levels in the tree\"<<endl;\n \n cout<<\"Completed\"<<endl;\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.487089067697525, "alphanum_fraction": 0.4986000061035156, "avg_line_length": 28.67076873779297, "blob_id": "03202ab6a1708394c7c879f78501889fd21954ad", "content_id": "518bc738a6d3ec53aa84b1703a1535a5f4ccb59e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 9644, "license_type": "no_license", "max_line_length": 125, "num_lines": 325, "path": "/Desktop/Wiki/Code/4_Get_Error_Bar/4_get_tree_similarity.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// get_tree_similarity\n//\n// Created by Eve on 2/6/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <algorithm>\n#include <unordered_set>\n\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <errno.h>\n\nfloat max_score = -1.0;\nfloat avg_score = 0.0;\nint path_count = 0;\n\nfloat avg_path_using_max = 0.0;\ndouble avg_path_using_avg = 0.0;\nfloat max_path = -1.0;\nfloat min_path = 1.0;\nint tot_path = 0;\n\n\nusing namespace std;\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n //corner case: if the input is an article name\n if(line[1] == '-'){ //use line[1] b/c first char maybe a negative sign\n parsed.push_back(\"-\");\n// cout<<\"here\"<<endl;\n return;\n }\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else {\n tmp+=line[i];\n }\n }\n if(tmp != \"\"){\n parsed.push_back(tmp);\n }\n \n// for(int i=0;i<parsed.size();i++){\n// cout<<parsed[i]<<\" \";\n// }\n// cout<<endl;\n}\n\nvoid output_score(vector<vector<float> >& sim_matrix, ofstream& outfile){\n vector<vector<float> > opt_score;\n for(int i=0;i<sim_matrix.size();i++){\n vector<float> tmp;\n for(int j=0;j<sim_matrix[0].size();j++){\n tmp.push_back(0.0);\n }\n opt_score.push_back(tmp);\n }\n //initiate the first row with max running score\n opt_score[0][0] = sim_matrix[0][0];\n for (int i=1;i<sim_matrix[0].size();i++){\n if(opt_score[0][i-1]>sim_matrix[0][i]){\n opt_score[0][i] = opt_score[0][i-1];\n }\n else{\n opt_score[0][i] = sim_matrix[0][i];\n }\n }\n for(int i=1;i<sim_matrix.size();i++){\n for(int j=i;j<sim_matrix[0].size();j++){\n opt_score[i][j] = max(opt_score[i-1][j-1]+sim_matrix[i][j], opt_score[i][j-1]);\n }\n }\n\n // calculate the optimal similarity score for the path \n float opt = 0.0;\n if (sim_matrix[0].size()!=2){\n // subtract the root and the leaf node\n opt = (opt_score[sim_matrix.size()-1][sim_matrix[0].size()-1]-2)/(sim_matrix[0].size()-2);\n }\n\n \n outfile<<opt<<\" \";\n avg_score += opt;\n path_count += 1;\n if(opt>max_score){max_score = opt;}\n \n \n if(opt>max_path){max_path = opt;}\n if(opt<min_path){min_path = opt;}\n}\n\nvoid main_function(string& output_addr, string& avg_score_addr, string& best_score_addr, string& sim_addr){\n \n max_score = -1.0;\n avg_score = 0.0;\n path_count = 0;\n \n avg_path_using_max = 0.0;\n avg_path_using_avg = 0.0;\n max_path = -1.0;\n min_path = 1.0;\n tot_path = 0;\n //create output file\n ofstream outfile;\n outfile.open(output_addr);\n \n ofstream avg_file;\n avg_file.open(avg_score_addr);\n ofstream best_file;\n best_file.open(best_score_addr);\n \n //get similarity matrix\n ifstream sim_matrix_file;\n sim_matrix_file.open(sim_addr);\n string line = \"\";\n vector<string> parsed;\n vector<vector<float> > sim_matrix;\n vector<float> row;\n sim_matrix.clear();\n bool first_art = true;\n bool reached_limit = false;\n int c=0;\n while(!sim_matrix_file.eof()){\n line = \"\";\n getline(sim_matrix_file, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n // cout<<\"line: \"<<line<<endl;\n \n //start to analyze the similarity score on a new article\n if(parsed[0]==\"-\"){\n if(!first_art){\n outfile<<endl;\n // cout<<\"avg_score: \"<<avg_score<<endl;\n float avg_score_tmp = avg_score/path_count;\n \n outfile<<\"Average Score: \"<<avg_score_tmp<<endl;\n outfile<<\"Best Score: \"<<max_score<<endl<<endl;\n \n avg_file<<avg_score_tmp<<endl;\n best_file<<max_score<<endl;\n \n avg_path_using_avg = avg_path_using_avg+ avg_score_tmp;\n // cout<<avg_path_using_avg<<\" \"<<avg_score_tmp<<endl;\n avg_path_using_max += max_score;\n \n max_score = -1.0;\n avg_score = 0.0;\n path_count = 0;\n }\n c++;\n if(c==100000){\n reached_limit = true;\n }\n first_art = false;\n tot_path+=1;\n // cout<<line<<endl;\n outfile<<\"Sampled article\"<<line<<endl;\n outfile<<\"Optimal Score(s): \";\n }\n else{\n row.clear();\n // cout<<\"parsed size : \"<<parsed.size()<<endl;\n for(int i=0;i<parsed.size();i++){\n if(parsed[i] == \"nan\"){\n cerr<<\"<------- NAN appeared in the similarity score ------>\"<<endl;\n exit(0);\n }\n row.push_back(stof(parsed[i]));\n }\n sim_matrix.push_back(row);\n }\n }\n //if reach the end of one matrix\n else{\n if(sim_matrix.size()!=0){\n output_score(sim_matrix, outfile);\n sim_matrix.clear();\n if(reached_limit==true){\n break;\n }\n \n }\n \n }\n }\n sim_matrix_file.close();\n \n //output last pair\n outfile<<endl;\n float avg_score_tmp = avg_score/path_count;\n \n outfile<<\"Average Score: \"<<avg_score_tmp<<endl;\n outfile<<\"Best Score: \"<<max_score<<endl<<endl;\n avg_file<<avg_score_tmp<<endl;\n best_file<<max_score<<endl;\n \n avg_path_using_avg = avg_path_using_avg+avg_score_tmp;\n avg_path_using_max += max_score;\n \n \n // cout<<avg_path_using_avg<<endl;\n // cout<<tot_path<<endl;\n \n outfile<<\"-------------------------------------------\"<<endl;\n outfile<<\"Average Score of All Sampled Path (using max_score): \"<<avg_path_using_max/tot_path<<endl;\n outfile<<\"Average Score of All Sampled Path (using avg_score): \"<<avg_path_using_avg/tot_path<<endl;\n outfile<<\"Maximum Score of All Sampled Path: \"<<max_path<<endl;\n outfile<<\"Minimum Score of All Sampled Path: \"<<min_path<<endl;\n outfile<<\"Analyzed \"<<tot_path<<\" article paths in total\"<<endl;\n \n // cout<<avg_path_using_max/tot_path<<\" \"<<avg_path_using_avg/tot_path<<\" \"<<max_path<<\" \"<<min_path<<\" \"<<tot_path<<\" \";\n cout<<avg_path_using_max/tot_path<<\" \"<<avg_path_using_avg/tot_path<<\" \";\n\n outfile.close();\n best_file.close();\n avg_file.close();\n}\n\n\nint getTreeNames (string dir, vector<string> &files)\n{\n DIR *dp;\n struct dirent *dirp;\n if((dp = opendir(dir.c_str())) == NULL ) {\n cout << \"Error(\" << errno << \") opening \" << dir << endl;\n return errno;\n }\n \n while ((dirp = readdir(dp)) != NULL) {\n if (string(dirp->d_name)!= \".\" && string(dirp->d_name) != \"..\" && string(dirp->d_name) != \".DS_Store\"){\n string tree_name = string(dirp->d_name);\n string tree = \"\";\n int found = tree_name.find(\".txt\");\n if (found==std::string::npos){\n cerr<<\"cannot locate the name of the tree\"<<endl;\n exit(0);\n }\n else{\n tree = tree_name.substr(0, found);\n }\n\n if (tree!=\"wiki_tree\") {\n files.push_back(tree);\n }\n }\n }\n closedir(dp);\n return 0;\n}\n\nint main(int argc, const char * argv[]) {\n\tif (argc<4){\n\t\tcerr<<\"Please enter the number of folders | sampled_groups folder | All_Tree_Folder\"<<endl;\n\t\treturn 0;\n\t}\n\n\n\tint numFolder = stoi(argv[1]);\n\n \n string tree_folder_addr = argv[3];\n vector<string> tree_names;\n getTreeNames(tree_folder_addr, tree_names);\n\n cout<<\"here\"<<endl;\n for (int i =0;i<tree_names.size();i++){\n cout<<tree_names[i]<<endl;\n }\n // tree_names.push_back(\"rand_tree\");\n // tree_names.push_back(\"rev_tree\");\n string folder_path = argv[2];\n vector<string> subFolder;\n // getdir(folder_path, subFolder);\n \n// subFolder.push_back(\"0\");\n \n for (int i=0;i<numFolder;i++){\n if (i%10 >= 7) continue;\n\t\tsubFolder.push_back(to_string(i));\n cout<<i<<endl;\n\t}\n \n for (int j=0;j<tree_names.size();j++){\n cout<<tree_names[j]<<\" _\";\n }\n cout<<endl;\n\n for (int i=0;i<subFolder.size();i++){\n cout<<subFolder[i]<<\" \";\n string curr_folder_path = folder_path+\"/\"+subFolder[i];\n for (int j=0;j<tree_names.size();j++){\n //create a folder to hold each comparison result\n string comp_folder_path = curr_folder_path+\"/\"+tree_names[j]+\" vs wiki\";\n \n string sim_addr = comp_folder_path+\"/reported_similartity.txt\";\n string output_addr = comp_folder_path+\"/similarity_score.txt\";\n string best_score_addr = comp_folder_path+\"/best_score.txt\";\n string avg_score_addr = comp_folder_path+\"/avg_score.txt\";\n \n main_function(output_addr, avg_score_addr, best_score_addr, sim_addr);\n }\n cout<<endl;\n \n }\n \n return 0;\n}\n" }, { "alpha_fraction": 0.6371803879737854, "alphanum_fraction": 0.6586040258407593, "avg_line_length": 21.88888931274414, "blob_id": "098cd8e0587144e106addccd5035509fc72dd60c", "content_id": "ec92dc68d4695cd9107c12dad282baae0fb9e4ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1447, "license_type": "no_license", "max_line_length": 132, "num_lines": 63, "path": "/Desktop/Wiki/Code/3_Create_Bar_Graph/get_edit_size/test.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "# The code parse and reformat the revision history to the following form\n\n# article title, major editor 1, major editor 2...\n\n# Note 1. The major author is defined as authors with more than 10% edition history compare to the whole article\n# 2. Unregistered editor is not recorded in the output\n# 3. Users with a comma in the name is considered and the comma portion of the name is replaced by \"_,\"\n#\t 4. Articles with size smaller than 100B doesn't have their major editors recorded\n\nimport sys\n\nif __name__ == \"__main__\":\n\t\n\n\toutput_address = \"/Users/eve/Desktop/not_exits.txt\"\n\toutfile = open(output_address, \"w\")\n\n\tused_address = \"/Users/eve/Dropbox/Wiki/two_trees/used_articles.txt\"\n\n\tparsed_artname_addr = \"/Volumes/easystore/Wiki/COLING/All_Materials_for_Paper/Experiment/2_Parsed_Rev_History/artname_0_104624.txt\"\n\n\n\tc = 0\n\n\n\tpart1 = set()\n\t\n\tname = \"\"\n\n\tnum = 0\n\n\n\twith open(parsed_artname_addr,'r') as a_f:\t\t\n\t\tfor line in a_f:\n\t\t\tline = line.strip()\n\t\t\tif not line:\n\t\t\t\tprint \"detect empty line\"\n\t\t\telse:\n\t\t\t\tparsed = line.split(', ')\n\t\t\t\tpart1.add(parsed[0])\n\t\t\t\t\n\ta_f.close()\n\tprint \"Parsed 1 has .. articles: \"\n\tprint(len(part1))\n\n\t\n\texited_counter = 0\n\twith open(used_address,'r') as f:\n\t\tfor line in f:\n\t\t\t\n\t\t\tline = line.strip()\n\t\t\tif len(line)>0:\n\t\t\t\tc+=1\n\t\t\t\tif line in part1:\n\t\t\t\t\texited_counter += 1\n\t\t\t\telse:\n\t\t\t\t\toutfile.write(line)\n\t\t\t\t\toutfile.write('\\n')\n\tf.close()\n\t\t\t\n\t\n\tprint(c)\n\tprint(exited_counter) \n\n\n\n\n" }, { "alpha_fraction": 0.5404462814331055, "alphanum_fraction": 0.5453277826309204, "avg_line_length": 19.19718360900879, "blob_id": "6171af3ed8c66541a2664ff6be380473469cdfed", "content_id": "e40c62b695b2389b8cf7b61e66432512aa1a59e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1436, "license_type": "no_license", "max_line_length": 69, "num_lines": 71, "path": "/Desktop/Wiki/parse_string.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\nusing namespace std;\n\nvoid parse(vector<string>& parsed, string& s){\n\tstring tmp = \"\";\n\n\tstring curr_char = \"\";\n\tfor (int i=0;i<s.size();i++){\n\t\tcurr_char = s[i];\n\t\tif (curr_char==\":\" || curr_char == \"•\"){\n\t\t\tif (tmp.size()!=0 && tmp!= \" \"){\n\t\t\t\tparsed.push_back(tmp);\n\t\t\t}\n\t\t\ttmp = \"\";\n\t\t}\n\t\telse if (s[i]!=' '){\n\t\t\ttmp+=s[i];\n\t\t}\n\t}\n\n\tif (tmp.size()!=0 && tmp!= \" \"){\n\t\tparsed.push_back(tmp);\n\t}\n\n}\n\n\nint main(int argc, const char * argv[]){\n\tstring infile_addr=\"/Users/eve/Desktop/input_string.txt\";\n\t\n\tifstream infile;\n\tvector<string> parsed;\n\tinfile.open(infile_addr);\n\tstring line=\"\";\n\twhile(!infile.eof()){\n\t\tgetline(infile, line);\n\t\tif (line!=\"\"){\n\t\t\tparsed.clear();\n\t\t\tparse(parsed, line);\n\t\t\tfor (int i=0;i<parsed.size();i++){\n\t\t\t\tcout<<parsed[i]<<endl;\n\t\t\t}\n\n\t\t\t// line.erase(remove(line.begin(), line.end(), '\\n'), line.end());\n\t\t\t// line.erase(remove(line.begin(), line.end(), '\\t'), line.end());\n\t\t\t// line = \"Lunch \"+line;\n\t\t\t// dish_name = dish_name+\"\\\"\"+line+\"\\\", \";\n\t\t\t// // cout<<endl;\n\t\t\t// cout<<\"\\\"\"<<line<<\"\\\":{\"<<endl;\n\t\t\t// cout<<\"\\tprice:{\"<<endl;\n\t\t\t// cout<<\"\\t\\tsm: 6.10,\"<<endl;\n\t\t\t// cout<<\"\\t},\"<<endl;\n\t\t\t// cout<<\"\\tsides: lunch_sides\"<<endl;;\n\t\t\t// cout<<\"},\"<<endl;\n\n\t\t}\n\t}\n\n\t// cout<<dish_name<<endl;\n\n\n}" }, { "alpha_fraction": 0.5558035969734192, "alphanum_fraction": 0.5629464387893677, "avg_line_length": 25.66666603088379, "blob_id": "102e54adb3b511ede1f0354fd5cf626ec1456ea7", "content_id": "cbf7015012cacd7d2b51678289da2f31ed52c264", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2240, "license_type": "no_license", "max_line_length": 138, "num_lines": 84, "path": "/Helper/filter_out_nonrecorded_arts.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "// The code is for filtering out articles in <arts_w_major_editors> that do not exist in the wiki tree\n//\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\nusing namespace std;\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n \n \n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\n//index art\nvoid store_id(unordered_set<string>& artname, string& line){\n vector<string> parsed;\n parse(line, parsed);\n\n if(artname.count(parsed[0])!=0){\n cerr<<\"existed\"<<endl;\n exit(0);\n }\n artname.insert(parsed[0]);\n// cout<<parsed[0]<<endl;\n \n}\n\nint main(int argc, const char * argv[]) {\n ifstream artname_txt;\n artname_txt.open(\"/Users/eve/Desktop/Wiki/Life/WikiTree/unique_art_id.txt\");\n unordered_set<string> artname;\n string line = \"\";\n \n while(!artname_txt.eof()){\n getline(artname_txt, line);\n if(line.size()!=0){\n store_id(artname, line);\n }\n }\n \n ifstream input;\n input.open(\"/Volumes/easystore/Wiki/All_Materials_for_Paper/Experiment/3_Art_w_Major_Editors/unique_combined.txt\");\n line = \"\";\n int counter = 0;\n ofstream nonexisted_arts, art_w_major_ed;\n art_w_major_ed.open(\"/Volumes/easystore/Wiki/All_Materials_for_Paper/Experiment/3_Art_w_Major_Editors/unique_combined(filtered).txt\");\n nonexisted_arts.open(\"/Volumes/easystore/Wiki/All_Materials_for_Paper/Experiment/3_Art_w_Major_Editors/nonexisted.txt\");\n \n vector<string> par;\n while(!input.eof()){\n getline(input, line);\n if(line.size()!=0){\n par.clear();\n parse(line,par);\n if(artname.count(par[0])==0){\n counter++;\n nonexisted_arts<<par[0]<<endl;\n continue;\n }\n art_w_major_ed<<line<<endl;\n }\n }\n \n cout<<\"There are \"<<counter<<\" parsed articles that do not exists in wikitree\"<<endl;\n \n return 0;\n}\n" }, { "alpha_fraction": 0.49795711040496826, "alphanum_fraction": 0.5112359523773193, "avg_line_length": 32.63793182373047, "blob_id": "8c1122bcb177781999b5a715a8b6d7f8ad850f32", "content_id": "9b135be250d2812a15e81dfe4edf4a2ae7868979", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3916, "license_type": "no_license", "max_line_length": 159, "num_lines": 116, "path": "/Desktop/Wiki/Code/Helper/get_article_and_subcat.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetTitles(cate):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&list=categorymembers&cmnamespace=0&cmprop=ids|title&cmlimit=500&cmtitle=Category:\" + cate\n art = [] #list of all accumulated articles\n next = '' \n #information for the next request\n while True:\n req = urllib2.Request(url+next)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n\n art += re.findall('<cm [^>]*>', response) #adds all article info from the current request to the list\n\n cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n if not cont: #break the loop if 'continue' element missing\n break\n\n next = \"&cmcontinue=\" + cont.group(1) #gets the revision Id from which to start the next request\n\n return art\n\ndef GetSubcate(cate):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&list=categorymembers&cmtype=subcat&cmlimit=500&cmtitle=Category:\" + cate\n subcat = [] \n next = '' \n \n while True:\n req = urllib2.Request(url+next)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n\n subcat += re.findall('<cm [^>]*>', response) \n\n cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n if not cont: #break the loop if 'continue' element missing\n break\n\n next = \"&cmcontinue=\" + cont.group(1) \n return subcat\n\n\n\nif __name__ == \"__main__\":\n\n id_file = open(\"/Users/eve/Desktop/Wiki/Life/Article_And_Category/article_id_104624.txt\", \"w\")\n art_file = open(\"/Users/eve/Desktop/Wiki/Life/Article_And_Category/article_104624.txt\", \"w\")\n cate_file = open(\"/Users/eve/Desktop/Wiki/Life/Article_And_Category/category_104624.txt\", \"w\")\n cate_name = []\n # subcat = 0\n seen = set()\n\n \n start = 104624 #haven't run this category yet\n counter = start\n with open(\"/Users/eve/Desktop/Wiki/Life/Article_And_Category/category.txt\",'r') as f:\n c = 0\n for line in f:\n line = line.strip('\\n')\n seen.add(line)\n if c >= start:\n cate_name.append(line)\n seen.add(line)\n print c\n c += 1\n\n\n\n\n\n while cate_name:\n article = GetTitles(cate_name[0])\n \n for i in article[0:len(article)]:\n # extract article title for current category (cate_name[0])\n try:\n artname = re.search('title=\"(.+?)\"', i).group(1)\n artid = re.search('pageid=\"(.+?)\"', i).group(1)\n except AttributeError:\n artname = ''\n artid = ''\n artname = artname.replace(\" \",\"_\")\n art_file.write(artname)\n id_file.write(artid)\n art_file.write('\\n')\n id_file.write('\\n')\n\n art_file.write('\\n\\n') #seperation for each (sub)category\n id_file.write('\\n\\n')\n\n tmp = GetSubcate(cate_name[0])\n for i in tmp[0:len(tmp)]:\n try:\n found = re.search('title=\"Category:(.+?)\"', i).group(1)\n except AttributeError:\n found = ''\n found = found.replace(\" \",\"_\")\n found = found.lower()\n # subcat += 1\n if found not in seen:\n seen.add(found)\n cate_name.append(found)\n cate_file.write(found)\n cate_file.write('\\n')\n\n\n cate_name.pop(0)\n counter += 1\n print counter\n\n\n art_file.close()\n cate_file.close()\n id_file.close()\n print \"Finished!!!!!Finallyyyyyyyyy\"\n\n\n\n \n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5449258685112, "alphanum_fraction": 0.5632451176643372, "avg_line_length": 25.8203125, "blob_id": "43189f0eab82f16ea1a26619c92479f24ed446f1", "content_id": "8fa931c6f649f779168aa66a1a0c39ea507fea9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3439, "license_type": "no_license", "max_line_length": 138, "num_lines": 128, "path": "/Desktop/Wiki/Code/3_Create_Bar_Graph/get_edit_size/2_get_art_with_major_editors.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "# The code parse and reformat the revision history to the following form\n\n# article title, major editor 1, major editor 2...\n\n# Note 1. The major author is defined as authors with more than 10% edition history compare to the whole article\n# 2. Unregistered editor is not recorded in the output\n# 3. Users with a comma in the name is considered and the comma portion of the name is replaced by \"_,\"\n#\t 4. Articles with size smaller than 100B doesn't have their major editors recorded\n\nimport sys\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 6:\n\t\tprint \"--------------------------------------------------------------------------------\"\n\t\tprint \"Too few arguments. Please provide the information in the following format. \"\n\t\tprint \"Parsed_rev_file | Output_address | category_range_and_output_version | starting_line_number(starting from 1) | used_article_addr\"\n\t\tprint \"(e.g ./parsed_rev_cate_0_to_100000.txt ./output 0_to_100000_2 1 used_art.txt\" \n\t\tprint \"--------------------------------------------------------------------------------\"\n\t\tsys.exit()\n\n\toutput_address = sys.argv[2]+\"/art_w_major_editor_cate_\"+sys.argv[3]+\".txt\"\n\tinput_address = sys.argv[1]\n\tstart_line = int(sys.argv[4])\n\tart_name = sys.argv[5]\n\n\tart_file = open(output_address, \"w\")\n\n\t#local variables\n\tnew_art = False\n\tistitle = 0 #flag indicates the current line is a article title \n\tif start_line == 1:\n\t\tnew_art = True\n\t\tistitle = 1\n\t\n\tart_title = \"\"\n\ttargetArt = False\n\n\tc = 0 #current line number (starting at 1)\n\n\n\tused_art = set()\n\twith open(art_name,'r') as a_f:\n\t\tfor line in a_f:\n\t\t\tline = line.strip()\n\t\t\tif not line:\n\t\t\t\tprint \"detect empty line\"\n\t\t\telse:\n\t\t\t\tused_art.add(line)\n\n\n\tprint(len(used_art))\n\n\n\tart_size = 0\n\tpage_size = 0\n\tis_small_article = False\n\n\twith open(input_address,'r') as f:\n\t\tfor line in f:\n\t\t\tc+=1\n\t\t\tif c >= start_line:\n\t\t\t\t# if c%1000 == 0:\n\t\t\t\t# \tprint c\n\t\t\t\tline = line.strip()\n\t\t\t\t# print line\n\t\t\t\t\n\t\t\t\t# empty line indicates the end of an article\n\t\t\t\tif not line:\n# print \"detetct empty line\"\n\t\t\t\t\tistitle = 1\n\t\t\t\t\tnew_art = True\n\t\n\t\t\t\telse:\n\t\t\t\t\t# title or page size\n\t\t\t\t\tif new_art == True:\n\t\t\t\t\t\t# if it's a page size\n\t\t\t\t\t\tif istitle == 0:\n\t\t\t\t\t\t\tistitle = 1\n\t\t\t\t\t\t\tnew_art = False\n\t\t\t\t\t\t\tpage_size = int(line)\n\t\t\t\t\t\t\tif page_size>=100:\n\t\t\t\t\t\t\t\tis_small_article = False\n\n\n\t\t\t\t\t\t# if it's an article title\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tistitle = 0\n\t\t\t\t\t\t\tis_small_article = True\n\t\t\t\t\t\t\tif line in used_art:\n\t\t\t\t\t\t\t\tart_file.write('\\n') \n\t\t\t\t\t\t\t\tart_title = line\n\t\t\t\t\t\t\t\tart_file.write(art_title)\n\t\t\t\t\t\t\t\ttargetArt = True\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\ttargetArt = False\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t# rev history\n\t\t\t\t\telse:\n\t\t\t\t\t\t# if the article is the target article, get its revision history\n\t\t\t\t\t\tif targetArt == True and is_small_article == False:\n\t\t\t\t\t\t\ttmp = line.split(\", \")\n\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tif(len(tmp)>4):\n\t\t\t\t\t\t\t\t# if it's a registered user\n\t\t\t\t\t\t\t\tif tmp[len(tmp)-3] != \"0\":\n\t\t\t\t\t\t\t\t\t#editor name\n\t\t\t\t\t\t\t\t\tart_file.write(\", \")\n\n\t\t\t\t\t\t\t\t\tart_file.write(tmp[len(tmp)-3])\n\t\t\t\t\t\t\t\t\t#edit size\n\t\t\t\t\t\t\t\t\tart_file.write(\", \")\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tart_file.write(tmp[len(tmp)-1])\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tif tmp[1] != \"0\":\n\t\t\t\t\t\t\t\t\t#editor name\n\t\t\t\t\t\t\t\t\tart_file.write(\", \")\n\t\t\t\t\t\t\t\t\tart_file.write(tmp[1])\n\t\t\t\t\t\t\t\t\t#edit size\n\t\t\t\t\t\t\t\t\tart_file.write(\", \")\n\t\t\t\t\t\t\t\t\tart_file.write(tmp[3])\n\n\t\t\t\n\tart_file.close()\n\tprint \"Remember to remove the duplicates in the end if multiple versions of outputs are created\"\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.477554053068161, "alphanum_fraction": 0.49381059408187866, "avg_line_length": 30.037036895751953, "blob_id": "bb212428de5303ad6873a0ef9ba5a9d1d035ac8c", "content_id": "347ead89af522697ba1e8b9542d24e3940590449", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6707, "license_type": "no_license", "max_line_length": 143, "num_lines": 216, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/4_edge_list.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 7_get_article_weight_pair_new\n//\n// Created by Eve on 10/24/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n//\n// main.cpp\n// 7_get_article_weight_pair\n//\n// Created by Eve on 10/17/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n\n/*********************************************************************************/\n/* The code takes in editors and the articles they did major revisions for. The */\n/* code outputs the edge list for article pairs in the following format: */\n/* [art_weight_pair]: article_decode 1, <article_decode 2, weight> */\n/* [art_index_name]: article_decode, article_name */\n/*********************************************************************************/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n\nusing namespace std;\n\n\nunordered_set<int> all_articles;\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\n\nvoid addEdge(vector<string>& parsed, unordered_map<int, unordered_map<int,int> >& weight){\n // article ids (or indices)\n int in_a1 = 0;\n int in_a2 = 0;\n int article_exits = 0;\n\n // map for storing weight pairs: article 1, <article 2, counter>\n unordered_map<int, unordered_map<int,int> >::iterator it;\n unordered_map<int,int>::iterator it2;\n \n //skip the first element (tf-idf word), take each pair\n for(int i=1;i<parsed.size();i++){\n for(int j = i+1;j<parsed.size();j++){\n in_a1 = stoi(parsed[i]);\n in_a2 = stoi(parsed[j]);\n\n all_articles.insert(in_a1);\n all_articles.insert(in_a2);\n\n //swap a1 a2 index to ensure a1 has smaller index (avoid repetition)\n if(in_a1>in_a2){\n swap(in_a1, in_a2);\n }\n article_exits = weight.count(in_a1);\n \n //if new article\n if(article_exits == 0){\n unordered_map<int, int> edge;\n edge[in_a2] = 1;\n weight[in_a1] = edge;\n }\n \n //if the article exists\n else{\n it = weight.find(in_a1); //locate article 1\n it2 = (it->second).find(in_a2); //locate article 2 from article 1'a edges\n // if article 2 doesnt have an edge with article 1\n if(it2 == (it->second).end()){\n (it->second)[in_a2] = 1;\n }\n else{\n it2->second += 1;\n }\n }\n }\n \n }\n}\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 5){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_tf-idf_word_w_article_file | Output_address | upper-bound_on_num_art_uses_the_same_word | number_of_articles\"<<endl;\n cout<<\"(e.g ./3_word_w_art.txt ./ 1000 33749)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string output_address = argv[2];\n string edge_list_addr = output_address+\"/4_art_weight_pair.txt\";\n string num_in = argv[3];\n int art_num_upper_bound = stoi(num_in);\n num_in = argv[4];\n int number_of_articles = stoi(num_in);\n \n //initiate map for storing weight pair: article 1, <article 2, counter>\n unordered_map<int, unordered_map<int, int> >weight;\n \n //local variables\n vector<string> parsed;\n string line = \"\";\n \n //********** articles, weight pair *******//\n ofstream art_weight_pair;\n art_weight_pair.open (edge_list_addr);\n\n\n //////////////////////////\n // Create edge list //\n //////////////////////////\n ifstream infile;\n infile.open (argv[1]);\n\n if(!infile){\n cerr<<\"Can't open infile\"<<endl;\n exit(1);\n }\n int line_ctr = 0;\n while(!infile.eof()){\n getline(infile,line);\n line_ctr += 1;\n if (!line.empty()){\n // track progress\n if(line_ctr %1000 == 0){\n cout<<line_ctr<<endl;\n }\n \n parsed.clear();\n parse(line, parsed);\n \n //if the number of artilces uses the tf-idf word is bigger than upper-bound, skip\n if((parsed.size()-1) > art_num_upper_bound){\n continue;\n }\n \n addEdge(parsed, weight);\n \n }\n }\n infile.close();\n\n\n cout<<\"Finish creating weight pairs\"<<endl;\n \n int art_pair_counter = 0;\n //*********** print out art_weight pair ************//\n int c = 0;\n unordered_map<int, unordered_map<int,int> >::iterator it;\n unordered_map<int,int>::iterator it2;\n for (it = weight.begin();it!=weight.end();it++){\n art_pair_counter+= (it->second).size();\n for(it2 = (it->second).begin();it2!=(it->second).end();it2++){\n art_weight_pair<<it->first<<\", \"<<it2->first<<\", \"<<it2->second<<endl;\n }\n c++;\n if(c%100==0){\n cout<<\"stored \"<<c<<\"/\"<<weight.size()<<endl;\n }\n }\n art_weight_pair.close();\n\n int num_wo_edges = 0;\n if (all_articles.size()<number_of_articles){\n string articles_wo_edges = output_address+\"/4_articles_wo_edges.txt\";\n ofstream wo_edges;\n wo_edges.open(articles_wo_edges);\n \n\n for (int i=0;i<number_of_articles;i++){\n if (all_articles.count(i)==0){\n wo_edges<<i<<endl;\n num_wo_edges++;\n }\n }\n\n wo_edges.close();\n }\n cout<<\"Completed\"<<endl;\n \n cout<<\"-------------------------------\"<<endl;\n cout<<\"The code did not encode the indices for articles. However, when getting TF-IDF words, articles are encoded. \"; \n cout<<\"Please follow the standard of TF-IDF word encoding to decode the tree\"<<endl;\n cout<<\"There are \"<<all_articles.size()<<\" articles with at least one edge\"<<endl;\n cout<<\"There are \"<<num_wo_edges<<\" articles without edges\"<<endl;\n cout<<\"There are \"<<num_wo_edges+all_articles.size()<<\" articles in total [compare to \"\n <<number_of_articles<<\" as reported]\"<<endl; \n cout<<\"There are \"<<art_pair_counter<<\" weight pairs in total\"<<endl;\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.4775816798210144, "alphanum_fraction": 0.48688289523124695, "avg_line_length": 28.321678161621094, "blob_id": "f664b80bd94d9c4d0936f0f0c7af86dd833e5345", "content_id": "f9662cb9a6ca8605da322db326a08d57c0463787", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8387, "license_type": "no_license", "max_line_length": 193, "num_lines": 286, "path": "/Desktop/Wiki/Code/5_Get_Random_Tree_Error_Bar/2_pick_n_locate_art.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// pick_n_locate_art\n//\n// Created by Eve on 2/3/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n/****************************************************************/\n// The code is written for randomly choose an article and\n// locate the article in both trees (e.g. wiki and rev tree).\n//\n// [Input format]\n// tree_enc_, art_id1, art_id2, ...\n//\n//\n//\n// [Output format]\n//\n// Chosen article_id 1\n// <tree encoding for the node(s) that contains the article\n// in tree 1>\n// <tree encoding for the node(s) that contains the article\n// in tree 2>\n//\n// Chosen article_id 2\n// <tree encoding for the node(s) that contains the article\n// in tree 1>\n// <tree encoding for the node(s) that contains the article\n// in tree 2>\n/***************************************************************/\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\n\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <errno.h>\n\nusing namespace std;\n\n//ofstream artname;\n//bool first = false;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n}\n\nvoid store_tree(string& addr, unordered_map<string, vector<string> >& t){\n ifstream tree_file;\n tree_file.open(addr);\n if(!tree_file){\n cerr<<\"Can't open file [\"<<addr<<\"]\"<<endl;\n exit(0);\n }\n string line = \"\";\n vector<string> parsed;\n while(!tree_file.eof()){\n line = \"\";\n parsed.clear();\n getline(tree_file, line);\n parse(parsed, line);\n if(parsed.size()>1){\n for(int i=1;i<parsed.size();i++){\n \n \n if(t.count(parsed[i])==1){\n t[parsed[i]].push_back(parsed[0]);\n \n }\n else{\n// if(first){\n// artname<<parsed[i]<<\", \"<<parsed[i]<<endl;\n// }\n vector<string> location;\n location.clear();\n location.push_back(parsed[0]);\n t[parsed[i]] = location;\n }\n }\n }\n }\n tree_file.close();\n}\n\n\nint getdir (string dir, vector<string> &files)\n{\n DIR *dp;\n struct dirent *dirp;\n if((dp = opendir(dir.c_str())) == NULL ) {\n cout << \"Error(\" << errno << \") opening \" << dir << endl;\n return errno;\n }\n \n while ((dirp = readdir(dp)) != NULL) {\n if (dirp->d_type == DT_DIR && string(dirp->d_name)!= \".\" && string(dirp->d_name) != \"..\" && string(dirp->d_name) != \".DS_Store\"){\n files.push_back(string(dirp->d_name));\n }\n }\n closedir(dp);\n return 0;\n}\n\n\nvoid getArticleLocations(string& tree_1_addr, string& tree_2_addr, string& output_addr, int& num_art){\n \n \n //store tree structure in a map with format of [article_id, <tree_enc1, tree_enc2,...>]\n unordered_map<string, vector<string> > t1;\n unordered_map<string, vector<string> > t2;\n store_tree(tree_1_addr, t1);\n store_tree(tree_2_addr, t2);\n\n ofstream outfile;\n outfile.open(output_addr);\n \n int tot_art = t1.size();\n int tot_art2 = t2.size();\n \n if(tot_art!=tot_art2){\n \n cerr<<endl<<\"Two trees have different number of unique articles\"<<endl<<endl;\n cerr<<\"Tree 1 size: \"<<tot_art<<endl;\n cerr<<\"Tree 2 size: \"<<tot_art2<<endl;\n // exit(0);\n }\n \n if(num_art>tot_art){\n cerr<<endl<<\"Required number of articles to be sampled is bigger than number of existing articles in the tree. Maximum number of articles (\"<<tot_art<<\") are returned.\"<<endl<<endl;\n num_art = tot_art;\n }\n \n unordered_set<int> used_index;\n string selected_article = \"\";\n unordered_map<string, vector<string> >::iterator random_it;\n unordered_map<string, vector<string> >::iterator it_tree2;\n \n for(int i=0;i<num_art;i++){\n // cout<<i<<endl;\n //randomly generate unique indice to pick articles\n int index = rand()%tot_art;\n while(used_index.count(index)==1){\n index = rand()%tot_art;\n }\n used_index.insert(index);\n \n \n random_it = next(begin(t1), index);\n \n selected_article = random_it->first;\n \n if(t2.count(selected_article)==0){\n cout<<\"can't find article \"<<selected_article<<\" in tree 2\"<<endl;\n i--;\n continue;\n }\n \n outfile<<selected_article<<endl;\n //print out article's position(s) in the tree\n for(int j=0;j<random_it->second.size();j++){\n outfile<<random_it->second[j];\n if(j!=random_it->second.size()-1){\n outfile<<\", \";\n }\n }\n \n outfile<<endl;\n \n \n //print out article's position(s) in the second tree\n it_tree2 = t2.find(selected_article);\n \n \n // cout<<(it_tree2->second).size()<<endl;\n for(int j=0;j<(it_tree2->second).size();j++){\n outfile<<(it_tree2->second)[j];\n if(j!=(it_tree2->second).size()-1){\n outfile<<\", \";\n }\n }\n \n outfile<<endl<<endl;\n }\n outfile.close();\n}\n\nint getTreeNames (string dir, vector<string> &files)\n{\n DIR *dp;\n struct dirent *dirp;\n if((dp = opendir(dir.c_str())) == NULL ) {\n cout << \"Error(\" << errno << \") opening \" << dir << endl;\n return errno;\n }\n \n while ((dirp = readdir(dp)) != NULL) {\n if (string(dirp->d_name)!= \".\" && string(dirp->d_name) != \"..\" && string(dirp->d_name) != \".DS_Store\"){\n string tree_name = string(dirp->d_name);\n string tree = \"\";\n int found = tree_name.find(\".txt\");\n if (found==std::string::npos){\n cerr<<\"cannot locate the name of the tree\"<<endl;\n exit(0);\n }\n else{\n tree = tree_name.substr(0, found);\n }\n\n if (tree!=\"wiki_tree\"){\n files.push_back(tree);\n }\n }\n }\n closedir(dp);\n return 0;\n}\n\nint main(int argc, const char * argv[]) {\n \n \n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Number_of_Articles_to_Sample | Sampled_Arts_Folder | Tree_Folder\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n\n int num_art = stoi(argv[1]);\n string folder_path = argv[2];\n vector<string> subFolder;\n getdir(folder_path, subFolder);\n string tree_folder_addr = argv[3];\n\n vector<string> tree_names;\n getTreeNames(tree_folder_addr, tree_names);\n \n for (int i=0;i<subFolder.size();i++){\n string curr_folder_path = folder_path+\"/\"+subFolder[i];\n for (int j=0;j<tree_names.size();j++){\n //create a folder to hold each comparison result\n string comp_folder_path = curr_folder_path+\"/\"+tree_names[j]+\" vs wiki\";\n if (mkdir(comp_folder_path.c_str(), 0777)!=0 && errno != EEXIST){\n cerr<<\"Failed to create folder \"<<folder_path<<endl;\n exit(0);\n }\n string customized_tree_addr = curr_folder_path+\"/random_\"+tree_names[j]+\".txt\";\n\n string wiki_tree_addr = tree_folder_addr+\"/wiki_tree.txt\";\n \n string output_addr = comp_folder_path+\"/sampled_arts.txt\";\n getArticleLocations(customized_tree_addr, wiki_tree_addr, output_addr, num_art);\n \n }\n \n }\n\n \n return 0;\n \n}\n" }, { "alpha_fraction": 0.5831202268600464, "alphanum_fraction": 0.5959079265594482, "avg_line_length": 21.55769157409668, "blob_id": "560b367ebdac47f8c280bb0a164c6733e12bb4aa", "content_id": "624c9be18626fd2874a0549d07a4af3ac89fd0f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1173, "license_type": "no_license", "max_line_length": 85, "num_lines": 52, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Generate_tree_based_on_edit_size/3_remove_duplicates.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "\n# check against check duplicates again!!!!!!!!!!!!!!!! there're still some error \n\n\nif __name__ == \"__main__\":\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\tseen = set()\n\n\tart_file = open(\"/Users/eve/Desktop/Edit_Edit_Size_Tree/1_unique_combined.txt\", \"w\")\n\n\tline = \"\"\n\ttmp = []\n\n\tused_art = set()\n\twith open(\"/Users/eve/Desktop/Edit_Edit_Size_Tree/BoW_used_articles.txt\") as f:\n\t \n\t\tfor line in f:\n\t\t\tif len(line.strip()) != 0 :\n\t\t\t\tline = line.strip()\n\t\t\t\tused_art.add(line)\n\t\t\t\tnum+=1\n\t\n\tprint \"There are \"+str(num)+\" used articles\"\t\n\tf.close()\n\n\tnum=0\n\tnum_recorded = 0\n\n\t#load already processed article\n\twith open(\"/Users/eve/Desktop/Edit_Edit_Size_Tree/1_combined.txt\") as f:\n\t \n\t\tfor line in f:\n\t\t\tif len(line.strip()) != 0 :\n\t\t\t\tnum+=1\n\t\t\t\tline = line.strip('\\n')\n\t\t\t\ttmp = line.split(\", \")\n\t\t\t\tif tmp[0] in seen:\n\t\t\t\t\tcounter += 1\n\t\t\t\telse:\n\t\t\t\t\tseen.add(tmp[0])\n\t\t\t\t\t# if tmp[0] in used_art:\n\t\t\t\t\tart_file.write(line)\n\t\t\t\t\tart_file.write('\\n')\n\t\t\t\t\tnum_recorded+=1\n\t\t\t\t\t# else:\n\t\t\t\t\t# \tprint(line)\n\n\t\n\tprint \"There are \"+str(num)+\" articles with \"+str(counter)+\" repetitions\"\t\n\n\tprint(str(num-counter))\n\tprint(str(num_recorded))" }, { "alpha_fraction": 0.4765129089355469, "alphanum_fraction": 0.4811680018901825, "avg_line_length": 34.05970001220703, "blob_id": "52aaefe6c93bdef38cdcdcaf740d1d4d761df4ae", "content_id": "41d5a5855d52678ce9ff7c79f9911496aff17ad2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2363, "license_type": "no_license", "max_line_length": 106, "num_lines": 67, "path": "/Helper/getUserId.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetUserId(username):\n url = \"https://en.wikipedia.org/w/api.php?action=query&list=users&format=xml&ususers=\" + str(username)\n subcat = [] \n next = '' \n while True:\n req = urllib2.Request(url+next)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n subcat += re.findall('<user [^>]*>', response) \n cont = re.search('<continue uscontinue=\"([^\"]+)\"', response)\n if not cont: #break the loop if 'continue' element missing\n break\n next = \"&cmcontinue=\" + cont.group(1) \n return subcat\n\n# def GetCateId(cate_name):\n# url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&titles=Category:\" + cate_name\n# subcat = [] \n# found = ''\n# # while True:\n# req = urllib2.Request(url)\n# response = urllib2.urlopen(req)\n# response = response.read() #web request\n# subcat += re.findall('<page [^>]*>', response) \n# # cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n# # if not cont: #break the loop if 'continue' element missing\n# # break \n# if len(subcat)>1:\n# printf(\"\\n\\rGet multiple ids for the category\")\n# return\n# try:\n# found = re.search('pageid=\"(.+?)\"',subcat[0]).group(1)\n# except AttributeError:\n# found = ''\n# printf(\"No pageid is found for the category\")\n# return found \n \n\n\nif __name__ == \"__main__\":\n id_file = open(\"/Users/eve/Desktop/WikiBotId.txt\", \"w\")\n tmp = []\n found = ''\n\n\n with open(\"/Users/eve/Desktop/WikiBot.txt\",'r') as f:\n for line in f:\n line = line.strip('\\n')\n line = line.replace(\" \",\"_\")\n # print(line)\n tmp = []\n tmp = GetUserId(line)\n # print(tmp)\n match = re.search('userid=\"(.+?)\"', tmp[0])\n if(match is None):\n print line\n else:\n found = match.group(1)\n # print(found)\n id_file.write(found)\n id_file.write(\"\\n\")\n\n id_file.close()\n print \"Finished!!!!!Finallyyyyyyyyy\"\n\n\n\n \n\n\n\n\n\n\n" }, { "alpha_fraction": 0.48793935775756836, "alphanum_fraction": 0.4957500696182251, "avg_line_length": 26.37735939025879, "blob_id": "0648519fe42c69106570d3334c30eb168b0f2883", "content_id": "17b8effa197a7fa08e8a2f9e6de85b4e32e3445a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4354, "license_type": "no_license", "max_line_length": 98, "num_lines": 159, "path": "/Desktop/Wiki/Code/7_generate_random_tree_structure/1_generate_random_tree_structure.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// generate_random\n//\n// Created by Eve on 3/9/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n\n/****************************************************************/\n// The code is written for randomly choose an article of a given\n// structure, where the structure (tree enco) and number of\n// articles in each node is the same.\n//\n// [Input format]\n// <Tree.txt>\n// tree_enc_, art_id1, art_id2, ...\n//\n// <Artname.txt>\n// index, article id\n//\n//\n// [Output format]\n// (random tree has articles in their real article ids)\n// Tree encoding, random article 1, random article 2 ...\n//\n/***************************************************************/\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\nusing namespace std;\n#include <time.h> /* time */\n#include <algorithm> // std::random_shuffle\n#include <ctime> // std::time\n#include <cstdlib> // std::rand, std::srand\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 3){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Tree_Address(merged group_art and tree_enco) | Output_Address\"<<endl;\n cout<<\"(e.g ./tree.txt ./Output)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string tree_enco_addr = argv[1];\n string output_addr = argv[2];\n output_addr+=\"/random_tree_structure.txt\";\n \n srand ( unsigned ( std::time(0) ) );\n \n // get all articles in the tree\n vector<string> all_articles;\n unordered_set<string> visited;\n \n string line = \"\";\n vector<string> parsed;\n ifstream tree_file;\n tree_file.open(tree_enco_addr);\n while(!tree_file.eof()){\n getline(tree_file, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n for (int i=1; i<parsed.size();i++){\n if (parsed[i].size()!=0 && parsed[i]!=\" \"){\n if (visited.count(parsed[i])!=0){\n cerr<<\"Duplicated article [\"<<parsed[i]<<\"] found in the tree\"<<endl;\n exit(0);\n }\n visited.insert(parsed[i]);\n all_articles.push_back(parsed[i]);\n }\n }\n \n }\n }\n cout<<\"There are \"<<visited.size()<<\" unique articles in the tree\"<<endl;\n tree_file.close();\n \n \n // randomly permute the index\n vector<int> index_to_insert;\n for (int i=0; i<visited.size(); i++) {\n index_to_insert.push_back(i);\n }\n random_shuffle ( index_to_insert.begin(), index_to_insert.end() );\n\n\n\n\n tree_file.open(tree_enco_addr);\n int num_art_inserted = 0;\n int num_art_for_curr_node = 0;\n \n ofstream outfile;\n outfile.open(output_addr);\n\n int index = 0;\n \n while(!tree_file.eof()){\n getline(tree_file, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n //calculate number of articles in each node\n num_art_for_curr_node = parsed.size()-1;\n outfile<<parsed[0];\n //randomly pick and store n articles in the node\n for(int i=0;i<num_art_for_curr_node;i++){\n index = index_to_insert[num_art_inserted++];\n outfile<<\", \"<<all_articles[index];\n }\n outfile<<endl;\n }\n }\n \n tree_file.close();\n outfile.close();\n\n cout<<\"Randomly permuted \"<<num_art_inserted<<\" articles\"<<endl;\n\n if (num_art_inserted!=visited.size()){\n cerr<<endl<<\"num_art_inserted!=visited.size()\"<<endl;\n\n }\n \n \n \n return 0;\n}\n" }, { "alpha_fraction": 0.47533681988716125, "alphanum_fraction": 0.48335373401641846, "avg_line_length": 29.13087272644043, "blob_id": "69ee0537d9baaef5ad4cd3495fc5848c79c83159", "content_id": "7e9b4f0f375b38b412c629c993dde1d5821ef75b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 8982, "license_type": "no_license", "max_line_length": 111, "num_lines": 298, "path": "/Desktop/Wiki/Code/4_Get_Error_Bar/1_sample_subtrees.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 1_Get_50_Random_Trees\n//\n// Created by Eve on 9/19/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <errno.h>\n#include <time.h>\nusing namespace std;\n#include <algorithm> // std::random_shuffle\n#include <ctime> // std::time\n#include <cstdlib> // std::rand, std::srand\n\nvoid parse(vector<string>& parsed, string& line){\n parsed.clear();\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==','){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else if(line[i]!=' '){\n tmp+=line[i];\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n}\n\n\n\nint getdir (string dir, vector<string> &files)\n{\n DIR *dp;\n struct dirent *dirp;\n if((dp = opendir(dir.c_str())) == NULL ) {\n cout << \"Error(\" << errno << \") opening \" << dir << endl;\n return errno;\n }\n \n while ((dirp = readdir(dp)) != NULL) {\n if (string(dirp->d_name)!= \".\" && string(dirp->d_name) != \"..\" && string(dirp->d_name) != \".DS_Store\"){\n files.push_back(string(dirp->d_name));\n }\n }\n closedir(dp);\n return 0;\n}\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 5){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Note that all trees should have same articles and ids. \"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Tree_Address | Article_id_addr | Output_Address | Number_of_Groups_to_Sample\"<<endl;\n cout<<\"(e.g ./all_trees ./artid.txt ./ 50 )\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string tree_folder_addr = argv[1];\n string artid_addr = argv[2];\n string output_addr = argv[3];\n string num_groups_sample_str = argv[4];\n int num_groups_sample = stoi(num_groups_sample_str);\n \n vector<string> tree_files;\n getdir(tree_folder_addr, tree_files);\n \n \n string line = \"\";\n vector<string> parsed;\n \n //get all trees\n vector< vector<vector<string> > > trees;\n ifstream tree_file;\n \n \n for (int i=0;i<tree_files.size();i++){\n string tree_file_addr = tree_folder_addr+\"/\"+tree_files[i];\n cout<<\"Reading in tree <\"<<tree_files[i]<<\">\"<<endl;\n \n tree_file.open(tree_file_addr);\n vector<vector<string> > tree1;\n tree1.clear();\n while (!tree_file.eof()){\n line = \"\";\n parsed.clear();\n getline(tree_file, line);\n parse(parsed, line);\n if (parsed.size()!=0){\n tree1.push_back(parsed);\n }\n \n }\n trees.push_back(tree1);\n tree_file.close();\n }\n \n cout<<\"Reading in used articles...\"<<endl;\n //get all articles to be sampled\n unordered_set<string> unique_art_set;\n vector<string> unique_art_vec;\n ifstream artid;\n\n artid.open(artid_addr);\n if(!artid){\n cerr<<\"Can't open file \"<<artid_addr<<endl;\n exit(0);\n }\n \n while(!artid.eof()){\n line = \"\";\n parsed.clear();\n getline(artid, line);\n if (line.size()==0) continue;\n parse(parsed, line);\n \n string article = parsed[0];\n if(unique_art_set.count(article)==0){\n unique_art_set.insert(article);\n unique_art_vec.push_back(article);\n }\n else{\n cerr<<\"Found duplicate article <\"<<article<<\">\"<<endl;\n exit(0);\n }\n \n }\n artid.close();\n long num_unique_article = unique_art_vec.size();\n cout<<\"There are in total \"<<num_unique_article<<\" unique articles in the tree\"<<endl;\n \n\n long num_article_per_group = 25000;\n\n if (num_unique_article<num_article_per_group){\n num_article_per_group = num_unique_article*.75;\n }\n cout<<\"We are sampling \"<<num_article_per_group<<\" articles for each group\"<<endl;\n \n \n ofstream used_articles;\n ofstream filtered_tree;\n\n //sample 50 groups of articles\n for (int i=0;i<num_groups_sample;i++){\n\n //create a folder to hold all trees\n string folder_path = output_addr+\"/\"+to_string(i);\n if (mkdir(folder_path.c_str(), 0777)!=0 && errno != EEXIST){\n cerr<<\"Failed to create folder \"<<folder_path<<endl;\n exit(0);\n }\n //create a text file to record used articles for the tree\n string used_articles_addr = folder_path+\"/used_articles.txt\";\n used_articles.open(used_articles_addr);\n\n unordered_set<string> sampled_group;\n srand((int)time(NULL));\n // randomly permute the index\n vector<int> index_to_insert;\n for (int i=0; i<num_unique_article; i++) {\n index_to_insert.push_back(i);\n }\n random_shuffle ( index_to_insert.begin(), index_to_insert.end() );\n\n\n for (int q=0;q<num_article_per_group;q++){\n string sample_article = unique_art_vec[index_to_insert[q]];\n sampled_group.insert(sample_article);\n used_articles<<sample_article<<endl;\n }\n\n used_articles.close();\n \n if (sampled_group.size()!=num_article_per_group){\n cout<<\"++++++++++++++++++++++++++\"<<endl;\n cerr<<\"num_sampled = \"<<num_article_per_group<<endl;\n cerr<<\"sampled_group.size() = \"<<sampled_group.size()<<endl;\n cout<<\"++++++++++++++++++++++++++\"<<endl;\n }\n \n //filter out other articles from the trees\n for (int j=0;j<trees.size();j++){\n \n int ctr = 0;\n int notsampled = 0;\n //for each tree\n string tree_name = output_addr+\"/\"+to_string(i)+\"/\"+tree_files[j];\n filtered_tree.open(tree_name);\n\n for (int k=0;k<trees[j].size();k++){\n // cout<<filtered_tree<<trees[j][k][0]<<endl;\n filtered_tree<<trees[j][k][0];\n for (int q=1;q<trees[j][k].size();q++){\n // cout<<filtered_tree<<trees[j][k][q]<<endl;\n if (sampled_group.count(trees[j][k][q])==1){\n filtered_tree<<\", \"<<trees[j][k][q];\n ctr++;\n }\n else{\n if (trees[j][k][q].length()!=0){\n notsampled++;\n }\n \n }\n }\n filtered_tree<<endl;\n }\n filtered_tree.close();\ncout<<\"here5\"<<endl;\n \n if (ctr!=num_article_per_group){\n cerr<<\"Didn't sample the correct amount of articles for \"<<tree_files[j]<<endl;\n cerr<<\"num_sampled = \"<<num_article_per_group<<endl;\n cerr<<\"ctr = \"<<ctr<<endl;\n cerr<<\"notsampled = \"<<notsampled<<endl;\n cout<<\"-----------------------------------------------\"<<endl;\n// cout<<\"[It's fine if wikitree has more articles because it has duplicates]\"<<endl;\n// exit(0);\n }\ncout<<\"here6\"<<endl;\n }\n \n \n \n }\n\n \n \n \n \n \n// //load in and filter out articles in the bigger tree (wiki tree)\n// ofstream outfile;\n// outfile.open(output_addr);\n//\n// ifstream out_tree_file;\n// tree_file.open(tree_1_addr);\n// if(!tree_file){\n// cerr<<\"Can't open file\"<<endl;\n// exit(0);\n// }\n// line = \"\";\n// parsed.clear();\n//\n// unordered_set<string> unique_art_wiki;\n// while(!tree_file.eof()){\n// line = \"\";\n// parsed.clear();\n// getline(tree_file, line);\n// parse(parsed, line);\n// outfile<<parsed[0];\n// if(parsed.size()>1){\n// for(int i=1;i<parsed.size();i++){\n// //if the article is also in the smaller tree\n// if(unique_art.count(parsed[i])==1){\n// outfile<<\", \"<<parsed[i];\n// unique_art_wiki.insert(parsed[i]);\n// }\n// // else{\n// // cout<<parsed[i]<<endl;\n// // }\n// }\n// }\n// outfile<<endl;\n// }\n// tree_file.close();\n// outfile.close();\n//\n// cout<<\"After filter out articles that are not in the small tree\"<<endl;\n// cout<<\"There are in total \"<<unique_art_wiki.size()<<\" unique articles in the bigger tree\"<<endl;\n//\n \n \n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.4781250059604645, "alphanum_fraction": 0.4900568127632141, "avg_line_length": 24.507246017456055, "blob_id": "eb07bb8124caf479c32aad7d70e570b2f48bbbca", "content_id": "c8db570f0c1547edb37cead519031f747fa13ba3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3521, "license_type": "no_license", "max_line_length": 98, "num_lines": 138, "path": "/Desktop/Wiki/Code/k_group/1_generate_tree_with_k_groups.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// generate_random\n//\n// Created by Eve on 3/9/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n\n/****************************************************************/\n// The code is written for randomly choose an article of a given\n// structure, where the structure (tree enco) and number of\n// articles in each node is the same.\n//\n// [Input format]\n// <Tree.txt>\n// tree_enc_, art_id1, art_id2, ...\n//\n// <Artname.txt>\n// index, article id\n//\n//\n// [Output format]\n// (random tree has articles in their real article ids)\n// Tree encoding, random article 1, random article 2 ...\n//\n/***************************************************************/\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\nusing namespace std;\n#include <time.h> /* time */\n#include <algorithm> // std::random_shuffle\n#include <ctime> // std::time\n#include <cstdlib> // std::rand, std::srand\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\" Output_Address | k | number of articles\"<<endl;\n cout<<\"(e.g ./Output 5 10000)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string k_str = argv[2];\n string output_addr = argv[1];\n output_addr+=\"/tree_with_\"+k_str+\"_groups_1.txt\";\n string output_addr_2 = argv[1];\n output_addr_2+=\"/tree_with_\"+k_str+\"_groups_2.txt\";\n\n string num_art_str = argv[3];\n int num_art = stoi(num_art_str);\n \n int k = stoi(k_str);\n \n srand ( unsigned ( std::time(0) ) );\n \n vector<int> articles;\n // randomly permute the index\n for (int i=0; i<num_art; i++) {\n articles.push_back(i);\n }\n random_shuffle ( articles.begin(), articles.end() );\n\n\n\n ofstream outfile;\n outfile.open(output_addr);\n string tree_encode = \"_0\";\n outfile<<\"_0\"<<endl;\n\n int num_per_group = articles.size()/k;\n for (int i=0;i<k;i++){\n outfile<<tree_encode<<\"_\"<<i;\n if (i==k-1){\n for (int j=i*num_per_group; j<articles.size();j++){\n if (j==articles.size()) break;\n outfile<<\", \"<<articles[j];\n }\n }\n else{\n for (int j=i*num_per_group; j<(i+1)*num_per_group;j++){\n if (j==articles.size()) break;\n outfile<<\", \"<<articles[j];\n }\n }\n \n outfile<<endl;\n }\n\n\n outfile.close();\n\n\n // randomly permute the index\n random_shuffle ( articles.begin(), articles.end() );\n\n outfile.open(output_addr_2);\n tree_encode = \"_0\";\n outfile<<\"_0\"<<endl;\n\n num_per_group = articles.size()/k;\n for (int i=0;i<k;i++){\n outfile<<tree_encode<<\"_\"<<i;\n if (i==k-1){\n for (int j=i*num_per_group; j<articles.size();j++){\n if (j==articles.size()) break;\n outfile<<\", \"<<articles[j];\n }\n }\n else{\n for (int j=i*num_per_group; j<(i+1)*num_per_group;j++){\n if (j==articles.size()) break;\n outfile<<\", \"<<articles[j];\n }\n }\n outfile<<endl;\n }\n\n\n outfile.close();\n \n \n \n return 0;\n}\n" }, { "alpha_fraction": 0.4857228398323059, "alphanum_fraction": 0.493795782327652, "avg_line_length": 27.334745407104492, "blob_id": "f4e603e380cb10514c3fba524810d69211ee360d", "content_id": "e8b83ff8bf4fe6bebab25207fdcfa76c56adc425", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6690, "license_type": "no_license", "max_line_length": 111, "num_lines": 236, "path": "/Desktop/Wiki/Code/5_Get_Random_Tree_Error_Bar/1_create_random_tree.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 1_Get_50_Random_Trees\n//\n// Created by Eve on 9/19/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <errno.h>\n#include <time.h>\nusing namespace std;\n#include <algorithm> // std::random_shuffle\n#include <ctime> // std::time\n#include <cstdlib> // std::rand, std::srand\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n if (tmp.size()!=0 && tmp!=\" \"){\n parsed.push_back(tmp);\n }\n}\n\n\n\nint getdir (string dir, vector<string> &files)\n{\n DIR *dp;\n struct dirent *dirp;\n if((dp = opendir(dir.c_str())) == NULL ) {\n cout << \"Error (\" << errno << \") opening \" << dir << endl;\n return errno;\n }\n \n while ((dirp = readdir(dp)) != NULL) {\n if (string(dirp->d_name)!= \".\" && string(dirp->d_name) != \"..\" && string(dirp->d_name) != \".DS_Store\"){\n string tree_name = string(dirp->d_name);\n if (tree_name!=\"wiki_tree.txt\"){\n files.push_back(tree_name);\n }\n }\n }\n closedir(dp);\n return 0;\n}\n\nvoid generate_random_tree(string& output_addr, string& tree_enco_addr){\n srand ( unsigned ( std::time(0) ) );\n \n // get all articles in the tree\n vector<string> all_articles;\n unordered_set<string> visited;\n \n string line = \"\";\n vector<string> parsed;\n ifstream tree_file;\n tree_file.open(tree_enco_addr);\n while(!tree_file.eof()){\n getline(tree_file, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n for (int i=1; i<parsed.size();i++){\n if (parsed[i].size()!=0 && parsed[i]!=\" \"){\n if (visited.count(parsed[i])!=0){\n cerr<<\"Duplicated article [\"<<parsed[i]<<\"] found in the tree\"<<endl;\n exit(0);\n }\n visited.insert(parsed[i]);\n all_articles.push_back(parsed[i]);\n }\n }\n \n }\n }\n cout<<\"There are \"<<visited.size()<<\" unique articles in the tree\"<<endl;\n tree_file.close();\n \n \n // randomly permute the index\n vector<int> index_to_insert;\n for (int i=0; i<visited.size(); i++) {\n index_to_insert.push_back(i);\n }\n random_shuffle ( index_to_insert.begin(), index_to_insert.end() );\n\n\n\n\n tree_file.open(tree_enco_addr);\n int num_art_inserted = 0;\n int num_art_for_curr_node = 0;\n \n ofstream outfile;\n outfile.open(output_addr);\n\n int index = 0;\n \n while(!tree_file.eof()){\n getline(tree_file, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n //calculate number of articles in each node\n num_art_for_curr_node = parsed.size()-1;\n outfile<<parsed[0];\n //randomly pick and store n articles in the node\n for(int i=0;i<num_art_for_curr_node;i++){\n index = index_to_insert[num_art_inserted++];\n outfile<<\", \"<<all_articles[index];\n }\n outfile<<endl;\n }\n }\n \n tree_file.close();\n outfile.close();\n}\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Note that all trees should have same articles and ids. \"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Tree_Address | Output_Address | Number_of_Groups_to_Sample\"<<endl;\n cout<<\"(e.g ./all_trees ./ 50 )\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string tree_folder_addr = argv[1];\n string output_addr = argv[2];\n string num_groups_sample_str = argv[3];\n int num_groups_sample = stoi(num_groups_sample_str);\n \n vector<string> tree_files;\n getdir(tree_folder_addr, tree_files);\n \n \n //sample 50 groups of articles\n for (int i=0;i<num_groups_sample;i++){\n\n //create a folder to hold all trees\n string folder_path = output_addr+\"/\"+to_string(i);\n if (mkdir(folder_path.c_str(), 0777)!=0 && errno != EEXIST){\n cerr<<\"Failed to create folder \"<<folder_path<<endl;\n exit(0);\n }\n \n \n //filter out other articles from the trees\n for (int j=0;j<tree_files.size();j++){\n //for each tree\n string random_tree_addr = output_addr+\"/\"+to_string(i)+\"/random_\"+tree_files[j];\n string original_tree_addr = tree_folder_addr+\"/\"+tree_files[j];\n generate_random_tree(random_tree_addr, original_tree_addr);\n }\n \n \n \n }\n\n \n \n \n \n \n// //load in and filter out articles in the bigger tree (wiki tree)\n// ofstream outfile;\n// outfile.open(output_addr);\n//\n// ifstream out_tree_file;\n// tree_file.open(tree_1_addr);\n// if(!tree_file){\n// cerr<<\"Can't open file\"<<endl;\n// exit(0);\n// }\n// line = \"\";\n// parsed.clear();\n//\n// unordered_set<string> unique_art_wiki;\n// while(!tree_file.eof()){\n// line = \"\";\n// parsed.clear();\n// getline(tree_file, line);\n// parse(parsed, line);\n// outfile<<parsed[0];\n// if(parsed.size()>1){\n// for(int i=1;i<parsed.size();i++){\n// //if the article is also in the smaller tree\n// if(unique_art.count(parsed[i])==1){\n// outfile<<\", \"<<parsed[i];\n// unique_art_wiki.insert(parsed[i]);\n// }\n// // else{\n// // cout<<parsed[i]<<endl;\n// // }\n// }\n// }\n// outfile<<endl;\n// }\n// tree_file.close();\n// outfile.close();\n//\n// cout<<\"After filter out articles that are not in the small tree\"<<endl;\n// cout<<\"There are in total \"<<unique_art_wiki.size()<<\" unique articles in the bigger tree\"<<endl;\n//\n \n \n return 0;\n}\n\n\n" }, { "alpha_fraction": 0.6547428965568542, "alphanum_fraction": 0.6620888113975525, "avg_line_length": 30.290000915527344, "blob_id": "63d3418369d0adf0af3bd0b09f77813915526b28", "content_id": "b3fbad19f2bb0dc0b4a214de0fa43e9f2b72793c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3131, "license_type": "no_license", "max_line_length": 105, "num_lines": 100, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Generate_LDA_trees/1_get_LDA_words.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "# https://radimrehurek.com/gensim/tut1.html#corpus-formats\n\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',\nlevel=logging.INFO)\nfrom gensim import corpora, models, similarities\n\n# documents = [\"Human machine interface for lab abc computer applications\",\n# \t\t\t \"A survey of user opinion of computer system response time\",\n# \t\t\t \"The EPS user interface management system\",\n# \t\t\t \"System and human system engineering testing of EPS\",\n# \t\t\t \"Relation of user perceived response time to error measurement\",\n# \t\t\t \"The generation of random binary unordered trees\",\n# \t\t\t \"The intersection graph of paths in trees\",\n# \t\t\t \"Graph minors IV Widths of trees and well quasi ordering\",\n# \t\t\t \"Graph minors A survey\"]\n\n# # remove common words and tokenize\n# stoplist = set('for a of the and to in'.split())\n# texts = [[word for word in document.lower().split() if word not in stoplist] for document in documents]\n\n# # remove words that appear only once\n# from collections import defaultdict\n# frequency = defaultdict(int)\n# for text in texts:\n# \tfor token in text:\n# \t\t frequency[token] += 1\n\n# texts = [[token for token in text if frequency[token] > 1] for text in texts]\n\n# from pprint import pprint\n# pprint(texts)\n\n# # map each word onto an integer id\n# dictionary = corpora.Dictionary(texts)\n# dictionary.save('/tmp/deerwester.dict') # store the dictionary, for future reference\n# print(dictionary)\n\n# # check the word id\n# print(dictionary.token2id)\n\n\n# # convert tokenized documents to vectors\n# new_doc = \"Human computer interaction\"\n# new_vec = dictionary.doc2bow(new_doc.lower().split()) # word_id, ctr\n\nw_o_stop_words_addr = '/Users/eve/Desktop/Major_Editor_5/Create_BoW_Tree/1_w_o_stop_words.txt'\nart_topic_addr = '/Users/eve/Desktop/Major_Editor_5/LDA/art_topic.txt'\n\nart_topic = open(art_topic_addr, 'w')\n\nbow = []\ntmp = []\ncurr_id = 0\nartid = []\nfor line in open(w_o_stop_words_addr):\n\tline = line.lower().strip().replace(',', ' ')\n\tif len(line)!=0 and line!=\"************************** new article *************************\":\n\t\ttmp = line.lower().strip().split()\n\t\tbow.append(tmp)\n\t\tartid.append(curr_id)\n\tif line==\"************************** new article *************************\":\n\t\tcurr_id += 1\ndictionary = corpora.Dictionary(bow)\n\n\n\n\n# print(dictionary.token2id)\nclass MyCorpus(object):\n\tdef __iter__(self):\n\t\t\n\t\tfor line in open(w_o_stop_words_addr):\n\t\t\tline = line.lower().strip().replace(',', ' ')\n\n\t\t\tif len(line)!=0 and line!=\"************************** new article *************************\":\n\t\t\t\ttmp = line.lower().strip().split()\n\t\t\t\tyield dictionary.doc2bow(tmp)\n\ncorpus = MyCorpus()\n# for vector in corpus:\n# \tprint(vector)\nprint(\"Finished storing corpus...\")\n\nnum_topics = 1000\n\nlda = models.ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=num_topics, passes=1)\n\n\ndoc_lda = lda[corpus]\n\nprint(\"Printing out topics...\")\n# print out topics overed for each article\narticle_id = 0\nfor article_topics in doc_lda:\n\tart_topic.write(str(artid[article_id]))\n\tfor topic in article_topics:\n\t\tart_topic.write(\", \"+str(topic[0]))\n\tarticle_id += 1\n\tart_topic.write('\\n')\n\n\n" }, { "alpha_fraction": 0.5174973607063293, "alphanum_fraction": 0.5249204635620117, "avg_line_length": 25.742856979370117, "blob_id": "4680369b9e6777b05c1aa7b4c19261e6f724f14f", "content_id": "0b77cf2e664c4195c231120970152012a22c1672", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1886, "license_type": "no_license", "max_line_length": 102, "num_lines": 70, "path": "/Desktop/Wiki/Code/Helper/get_art_id.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetArtId(cate_name):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&titles=:\" + cate_name\n subcat = [] \n found = ''\n # while True:\n req = urllib2.Request(url)\n response = urllib2.urlopen(req)\n response = response.read() #web request\n subcat += re.findall('<page [^>]*>', response) \n # cont = re.search('<continue cmcontinue=\"([^\"]+)\"', response)\n # if not cont: #break the loop if 'continue' element missing\n # break \n try:\n found = re.search('pageid=\"(.+?)\"',subcat[0]).group(1)\n except AttributeError:\n found = ''\n print cate_name\n print (\"No pageid is found for the article\")\n return found \n\n\n\nif __name__ == \"__main__\":\n\n id_file = open(\"/Users/eve/Desktop/article_ids.txt\", \"w\")\n error_file = open(\"/Users/eve/Desktop/article_with_error_ids.txt\", \"w\")\n\n start = 0 #haven't run this category yet\n # start = 0\n counter = start\n\n art_title = []\n\n with open(\"/Users/eve/Desktop/combined.txt\",'r') as f:\n c = 0\n for line in f:\n line = line.strip('\\n')\n if len(line.strip()) != 0 :\n if c >= start:\n art_title.append(line)\n c += 1\n f.close()\n\n\n\n article = []\n artid = \"\"\n \n while art_title:\n artid = GetArtId(art_title[0])\n id_file.write(artid)\n id_file.write('\\n')\n\n if(artid == ''):\n error_file.write(art_title[0])\n error_file.write(', ')\n error_file.write(str(counter)) #record the line number of which the error article exisits \n error_file.write('\\n')\n\n\n art_title.pop(0)\n print counter\n counter += 1\n\n error_file.close()\n id_file.close()\n print \"Finished!!!!!Finallyyyyyyyyy\"\n\n\n\n \n\n\n\n\n\n\n" }, { "alpha_fraction": 0.4919888973236084, "alphanum_fraction": 0.504379391670227, "avg_line_length": 27.029939651489258, "blob_id": "4ffab466c9896faa5cba0d3510c0d0f567f98b1f", "content_id": "aa380226554b15e16fb022a1d9ef9b481bd79d4a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4682, "license_type": "no_license", "max_line_length": 98, "num_lines": 167, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/3_get_word_w_arts.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// get_editor_with_art\n//\n// Created by Eve on 9/19/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n/////////////////////////////////////////////////////////////////////////\n// Code rearrage the parsed revision history //\n// (following article, major word 1, major word 2,... format) //\n// to the following format //\n// word 1, majorly edited article 1, majorly edited article 2, ... //\n/////////////////////////////////////////////////////////////////////////\n\n\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <unordered_set>\nusing namespace std;\n\nint num_art = 0;\nunordered_set<string> all_articles;\n\nvoid parse_info(string& line, unordered_map <string, unordered_set<string> >& info){\n string article;\n vector<string> parsed;\n parsed.clear();\n bool name = false;\n if(line.length() == 0){\n cerr<<\"empty string\"<<endl;\n exit(0);\n }\n string tmp;\n tmp = \"\";\n for (int i=0;i<line.size();i++){\n if (line[i]==','){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else if (line[i]!=' '){\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n\n //go through each word and add the article to the set\n unordered_set<string> unique_article_for_word;\n int appear = 0;\n // go through each word\n for (unsigned int j = 1; j<parsed.size();j++){\n //if the word is aready in the map\n unordered_map <string, unordered_set<string> >::iterator it;\n appear = info.count(parsed[j]);\n if (appear == 1){\n it = info.find(parsed[j]);\n // if the word doesn't have the article in the set\n if(it->second.find(parsed[0])==it->second.end()){\n it->second.insert(parsed[0]);\n }\n }\n // if the editor is not in the map\n else{\n unique_article_for_word.clear();\n unique_article_for_word.insert(parsed[0]);\n info[parsed[j]] = unique_article_for_word;\n }\n }\n \n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 3){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_art_w_major_editor_file | Output_address\"<<endl;\n cout<<\"(e.g ./art_word.txt ./Output)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string output_address = argv[2];\n\n string output_file_address = output_address+\"/3_word_w_art.txt\";\n \n string count_addr = output_address+\"/3_counts.txt\";\n \n \n ofstream outfile, count_file;\n outfile.open (output_file_address);\n count_file.open(count_addr);\n \n \n\n string input_address = argv[1];\n fstream infile;\n infile.open(input_address);\n\n \n \n //use a set to remove duplicate edits of the same article by the same author\n unordered_map <string, unordered_set<string> > info; // [editor name, <art1, art2 ,...>]\n \n \n \n int counter = 0; //current line number\n\n num_art = 0; string line = \"\";\n \n\n \n if(!infile){\n cerr<<\"Can't open the file\"<<endl;\n exit(1);\n }\n \n \n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n if(counter >= 0){\n num_art++;\n parse_info(line, info);\n }\n \n }\n counter++;\n }\n infile.close();\n \n \n\n int num_tf_art = 0;\n //print to a text file\n unordered_map <string, unordered_set<string> >::iterator it2;\n unordered_set<string>::iterator it3;\n for (it2 = info.begin(); it2!=info.end();it2++){\n //skip words that only appears in one article\n if(it2->second.size()<2) continue;\n count_file<<it2->first<<\" \"<<it2->second.size()<<endl;\n //record the td-idf word and articles that contain the word\n outfile<<it2->first<<\", \";\n it3 = it2->second.begin();\n outfile<< *it3;\n it3++;\n\n //record the current article\n all_articles.insert(*it3);\n \n for(; it3 != it2->second.end();it3++){\n outfile<<\", \"<< *it3;\n all_articles.insert(*it3);\n }\n outfile<<endl;;\n }\n \n outfile.close();\n cout<<\"Number of articles with TF-IDF words: \"<<all_articles.size()<<endl;\n cout<<\"Total number of articles: \"<<num_art<<endl;\n \n cout<<\"Completed\"<<endl;\n\n \n return 1;\n}\n" }, { "alpha_fraction": 0.45676499605178833, "alphanum_fraction": 0.46592065691947937, "avg_line_length": 22.68674659729004, "blob_id": "0a1c7bdc42b1ba7fede31a23e5727ebfec863c00", "content_id": "3bc77f9a5b86baa5fe230b9fd7d636e74e35caf1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1966, "license_type": "no_license", "max_line_length": 95, "num_lines": 83, "path": "/Desktop/Wiki/Code/Helper/count_avg_node_size_per_lv.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "// The code is for calculating the node size per lv\n//\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\nusing namespace std;\n\nint parse(string& s, vector<string>& parsed){\n int lv = 0;\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n if(s[i] == '_'){\n lv++;\n }\n \n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n return lv;\n}\n\n\n\nint main(int argc, const char * argv[]) {\n \n cout<<\"MAKE SURE THE INPUT TREE IS FILTERED TREE\"<<endl;\n ifstream input;\n input.open(\"/Volumes/easystore/Wiki/EMNLP/6_Edge_list/filtered_wiki_tree.txt\");\n string line = \"\";\n int counter = 0;\n ofstream outfile;\n outfile.open(\"/Volumes/easystore/Wiki/EMNLP/6_Edge_list/avg_node_size.txt\");\n vector<string> parsed;\n int lv = 1;\n int curr_lv = 0;\n int num_node = 0;\n \n unordered_set<string> arts;\n \n while(!input.eof()){\n getline(input, line);\n if(line.size()!=0){\n parsed.clear();\n curr_lv = parse(line,parsed);\n if(curr_lv!=lv){\n cout<<lv<<\" \"<<arts.size()<<\" \"<<num_node<<\" \"<<1.0*arts.size()/num_node<<endl;\n outfile<<lv<<\" \"<<1.0*arts.size()/num_node<<\" \"<<arts.size()<<endl;\n arts.clear();\n num_node = 0;\n lv = curr_lv;\n }\n num_node++;\n for(int i=0;i<parsed.size();i++){\n if (i==0) continue;\n arts.insert(parsed[i]);\n }\n \n }\n }\n //last one\n outfile<<lv<<\" \"<<arts.size()/num_node<<\" \"<<arts.size()<<endl;\n arts.clear();\n num_node = 0;\n lv = curr_lv;\n \n \n \n \n return 0;\n}\n" }, { "alpha_fraction": 0.6713250279426575, "alphanum_fraction": 0.6868529915809631, "avg_line_length": 21.729412078857422, "blob_id": "67b376c1d915ff26aa541bab8787c2e566b84c8c", "content_id": "2a8fa0dd8dd2ba8ec34d0cf35ca80b056e68adff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1932, "license_type": "no_license", "max_line_length": 91, "num_lines": 85, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Generate_tree_based_on_edit_size/get_LDA_words.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "# https://radimrehurek.com/gensim/tut1.html#corpus-formats\n\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',\nlevel=logging.INFO)\nfrom gensim import corpora, models, similarities\n\n\ned_ed_size_addr = '/Users/eve/Desktop/Edit_Edit_Size_Tree/1_art_ed_ed_size.txt'\nart_topic_addr = '/Users/eve/Desktop/Edit_Edit_Size_Tree/4_art_topic.txt'\n\nart_topic = open(art_topic_addr, 'w')\n\ntry:\n\teditor_ed_size = open(ed_ed_size_addr, 'r+')\nexcept IOError:\n\tprint(\"Failed to open \"+ed_ed_size_addr)\n\nsplit_info = []\ntext = []\ntexts = []\nfor line in editor_ed_size:\n\tif len(line)!=0:\n\t\tsplit_info = line.split(\", \")\n\t\tfor i in range(1, len(split_info), 2):\n\t\t\ttext.append(split_info[i])\n\t\ttexts.append(text)\n\ndictionary = corpora.Dictionary(texts)\neditor_ed_size.close()\n\nrevserse_map = dictionary.token2id\n\n# print(revserse_map[\"227287\"])\n# print(dictionary[108])\n\n# print(dictionary.token2id)\n\n\neditor_ed_size = open(ed_ed_size_addr, 'r+')\ncorpus_vec = []\ndoc_vec = []\ntup = ()\nfor line in editor_ed_size:\n\tif len(line)!=0:\n\t\tsplit_info = line.split(\", \")\n\t\tfor i in range(1, len(split_info), 2):\n\t\t\ttup = (revserse_map[split_info[i]], float(split_info[i+1]))\n\t\t\tdoc_vec.append(tup)\n\t\tcorpus_vec.append(doc_vec)\neditor_ed_size.close()\n\n# print(corpus_vec)\n\nclass MyCorpus(object):\n\tdef __iter__(self):\n\t\tfor vec in corpus_vec:\n\t\t\tyield vec\n\ncorpus = MyCorpus()\n\nprint(\"Finished storing corpus...\\n\\n\")\n\n# print(next(iter(corpus)))\n\n# print(\"\\n\\n\")\n\nnum_topics = 1000\n\nlda = models.ldamodel.LdaModel(corpus, id2word=dictionary, num_topics=num_topics, passes=1)\n\n\ndoc_lda = lda[corpus]\n\nprint(\"Printing out topics...\")\n# print out topics overed for each article\narticle_id = 0\nfor article_topics in doc_lda:\n\tart_topic.write(str(dictionary[article_id]))\n\tfor topic in article_topics:\n\t\tart_topic.write(\", \"+str(topic[0]))\n\tarticle_id += 1\n\tart_topic.write('\\n')\n\nprint(\"Processed \"+str(article_id)+\" articles\")\n" }, { "alpha_fraction": 0.46343013644218445, "alphanum_fraction": 0.47996607422828674, "avg_line_length": 26.418603897094727, "blob_id": "174544685c4d724c002f768ec73db18329be9113", "content_id": "9ad27718df4a82d3309ae7cbd167bded387657d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 4718, "license_type": "no_license", "max_line_length": 116, "num_lines": 172, "path": "/3_Create_Bar_Graph/get_edit_size/4_ed_w_art.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// get_editor_with_art\n//\n// Created by Eve on 9/19/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n/////////////////////////////////////////////////////////////////////////\n// Code rearrage the parsed revision history //\n// (following article, major editor 1, major editor 2,... format) //\n// to the following format //\n// editor 1, majorly edited article 1, majorly edited article 2, ... //\n/////////////////////////////////////////////////////////////////////////\n\n\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <unordered_set>\n#include <map>\nusing namespace std;\n\nint num_art = 0;\nint num_none_ed = 0;\nint min_ed = 0;\n\nvoid parse(string& line, vector<string>& parsed ){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i] == ','){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n if(line[i]!=' '){\n tmp += line[i];\n }\n }\n }\n parsed.push_back(tmp);\n \n}\n\n\nvoid parse_info(string& line, unordered_map <string, map<string, double> >& info){\n string article;\n vector<string> parsed;\n parsed.clear();\n parse(line, parsed);\n \n \n \n //if the format of infile is not right\n if(parsed.size()%2 == 0){\n cerr<<\"format is incorrect\"<<endl;\n exit(0);\n \n }\n \n \n \n //go through each editor and add the article to the set\n map<string, double> tmp_s;\n int appear = 0;\n for (unsigned int j = 1; j<parsed.size();j+=2){\n //record only positive major edits\n if(stod(parsed[j+1])>=0.1){\n //if the editor is aready in the map\n unordered_map <string, map<string, double> >::iterator it;\n \n appear = info.count(parsed[j]);\n if (appear == 1){\n it = info.find(parsed[j]);\n // if the editor doesn't have the article in the set\n if(it->second.find(parsed[0])==it->second.end()){\n (it->second)[parsed[0]] = stod(parsed[j+1]);\n }\n else{\n (it->second)[parsed[0]] += stod(parsed[j+1]);\n }\n }\n // if the editor is not in the map\n else{\n tmp_s.clear();\n tmp_s[parsed[0]] = stod(parsed[j+1]);\n info[parsed[j]] = tmp_s;\n }\n }\n }\n \n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_art_w_major_editor_file | Output_address | category_range_and_output_version\"<<endl;\n// cout<<\"(e.g ./art_w_major_editor_cate_0_to_100000.txt ./Parsed 0_to_100000_2)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n\n \n string output_address = argv[2];\n string cate_range = argv[3];\n string output_file_address = output_address+\"/major_editor_w_art_cate_\"+cate_range+\".txt\";\n \n \n ofstream outfile;\n outfile.open (output_file_address);\n \n \n string input_address = argv[1];\n fstream infile;\n infile.open(input_address);\n \n \n \n //use a set to remove duplicate edits of the same article by the same author\n unordered_map <string, map<string, double> > info; // [editor name, <[art1, edit size], [art2, edit size] ,...>]\n \n int counter = 0; //current line number\n \n string line = \"\";\n \n \n if(!infile){\n cerr<<\"Can't open the file\"<<endl;\n exit(1);\n }\n \n \n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n parse_info(line, info);\n }\n }\n infile.close();\n \n \n \n //print to a text file\n unordered_map <string, map<string, double> >::iterator it2;\n map<string, double>::iterator it3;\n for (it2 = info.begin(); it2!=info.end();it2++){\n it3 = it2->second.begin();\n //if an author edited fewer than 3 edits, disregard him\n if(it2->second.size()<3){\n continue;\n }\n //editor name\n outfile<<it2->first;\n //edited article and size\n \n for(it3 = it2->second.begin(); it3 != it2->second.end();it3++){\n outfile<<\", \"<< it3->first<<\", \"<<it3->second;\n }\n outfile<<endl;\n }\n \n outfile.close();\n \n cout<<\"Completed\"<<endl;\n \n \n return 1;\n}\n\n" }, { "alpha_fraction": 0.5033665299415588, "alphanum_fraction": 0.5161995887756348, "avg_line_length": 29.86323356628418, "blob_id": "0828c40236fd48d5a8919d7553fa957eb3578675", "content_id": "5671fad47a1ad1574782cfba5405b94e0811b4d3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 17378, "license_type": "no_license", "max_line_length": 149, "num_lines": 563, "path": "/Desktop/Wiki/Code/4_Get_Error_Bar/3_find_similarity.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": " //\n// main.cpp\n// find_similarity\n//\n// Created by Eve on 2/4/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <unordered_set>\n#include <algorithm>\n#include <unordered_set>\n#include <math.h>\n#include <thread> \nusing namespace std;\n\n\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <dirent.h>\n#include <errno.h>\n\nunordered_set<string> visited; //global variable: used for repreventing adding repeated articles to the vector\n\nvoid parse(vector<string>& parsed, string& line){\n parsed.clear();\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n}\n\nvoid parse_position(vector<string>& parsed, string& line){\n parsed.clear();\n string tmp = \"\";\n bool start = false;\n for(int i=0;i<line.length();i++){\n if(line[i]=='_'){\n if(!start){\n start = true;\n }\n else{\n parsed.push_back(tmp);\n tmp = \"\";\n }\n }\n else {\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n \n}\n\n// Store the tree in a map in the form of [Key: tree_encoding, Value: <article1, article2...>]\nvoid store_tree(string& addr, unordered_map<string, vector<string> >& t){\n ifstream tree_file;\n tree_file.open(addr);\n if(!tree_file){\n cerr<<\"Can't open file \"<<addr<<endl;\n exit(0);\n }\n string line = \"\";\n vector<string> parsed;\n vector<string> articles;\n\n while(!tree_file.eof()){\n line = \"\";\n parsed.clear();\n getline(tree_file, line);\n parse(parsed, line);\n \n // store tree in a map t with key=tree_encoding, values=articles at the node\n articles.clear();\n t[parsed[0]] = articles;\n \n // populate articles belong to the node to the corresponding tree_encoding\n if(parsed.size()>1){\n for(int i=1;i<parsed.size();i++){\n t[parsed[0]].push_back(parsed[i]);\n }\n }\n }\n tree_file.close();\n}\n\n//get the articles in the node and articles in the children, except for child node \"encountered\"\nvoid get_node_content(string& loc, string& encountered, unordered_map<string, vector<string> >& t, vector<string>& content){\n content.clear();\n queue<string> node_to_visit;\n node_to_visit.push(loc);\n //BFS\n while(!node_to_visit.empty()){\n string curr = node_to_visit.front();\n\n //store articles in the current node (get rid of repetitions)\n if(t.count(curr) == 0) {\n cerr<<\"Cannot locate node \"<<curr<<\" in the tree\"<<endl;\n exit(0);\n }\n unordered_map<string, vector<string> >::iterator it = t.find(curr);\n for(int i=0; i<(it->second).size();i++){\n if(visited.count(it->second[i])==0){\n content.push_back(it->second[i]);\n visited.insert(it->second[i]);\n }\n }\n //get the immediate children nodes of the current node (except for \"encountered\" node)\n int c=0;\n string curr_child = curr+\"_\"+to_string(c);\n while(t.count(curr_child) == 1){\n if(curr_child != encountered){\n node_to_visit.push(curr_child);\n }\n c++;\n curr_child = curr+\"_\"+to_string(c);\n }\n //remove the node\n node_to_visit.pop();\n }\n}\n\nvoid get_path(string& loc, unordered_map<string, vector<string> >& t, vector<vector<string> >& tree_nodes){\n // corner case: the article is contained in the root\n if(loc == \"_0\"){\n cerr<<\"Detected an article in the root\"<<endl;\n exit(0);\n }\n \n // populate first entry: node that contains sampled article\n string encountered_node = \"-1\";\n string current_node = loc;\n // placeholder for retrieving articles in a node\n vector<string> content;\n content.clear();\n\n get_node_content(current_node, encountered_node, t, content);\n tree_nodes.push_back(content);\n \n \n //get its ancestors (except for the root)\n \n vector<string> pos;\n pos.clear();\n parse_position(pos, loc);\n\n int c = pos.size()-1;\n \n while(c!=1){\n \n encountered_node = current_node;\n current_node = \"\";\n for(int i=0;i<c;i++){\n current_node = current_node+ \"_\" +pos[i];\n }\n\n content.clear();\n get_node_content(current_node, encountered_node, t, content);\n tree_nodes.push_back(content);\n \n c--;\n }\n \n}\n\n\nint calculate_node_similarity_score(vector<vector<string> >& p_a, vector<vector<string> >& p_b, vector<float>& curr_score, int a_index, int b_index){\n unordered_set<string> visited;\n\n // error check for matrix\n unordered_set<string> visited_b;\n\n int num_insersection = 0;\n int num_union = 0;\n // populate every article in path a \n for (int i=0;i<=a_index;i++){\n for (int j=0;j<p_a[i].size();j++){\n // skip empty nodes\n if (p_a[i][j].size()==0) continue;\n // new article\n if (visited.count(p_a[i][j])==0){\n visited.insert(p_a[i][j]);\n }\n else{\n cerr<<\"There are duplicates in the path for p_a\"<<endl;\n return -1;\n }\n }\n }\n\n // populate every article in path b \n for (int i=0;i<=b_index;i++){\n for (int j=0;j<p_b[i].size();j++){\n // skip empty nodes\n if (p_b[i][j].size()==0) continue;\n // new article\n if (visited.count(p_b[i][j])==0){\n visited.insert(p_b[i][j]);\n visited_b.insert(p_b[i][j]);\n }\n else{\n if (visited_b.count(p_b[i][j])==1){\n cerr<<\"There are duplicates in the path for b\"<<endl;\n return -1;\n }\n num_insersection++;\n }\n }\n }\n num_union = visited.size();\n\n curr_score[0] = num_insersection;\n curr_score[1] = num_union;\n\n return 1;\n}\n\nvoid output_similarity_matrix (vector<vector<string> >& path_m, vector<vector<string> >& path_n, ofstream& outfile){\n //corner case: the target article is in the wikipedia tree's root, 1-1 match results in 100% match\n if(path_m.size() == 0 || path_n.size() == 0){\n outfile<<1<<endl<<endl;\n return;\n }\n \n //create a similarity matrix\n vector<vector<float> >sim;\n int m = path_m.size()+2; // add two nodes: root node and node that contains only the article \n int n = path_n.size()+2;\n\n // for (int i=0;i<path_m.size();i++){\n // outfile<<\"[\";\n // for (int j=0;j<path_m[i].size();j++){\n // outfile<<path_m[i][j]<<\" \";\n // }\n // outfile<<\"]\";\n // }\n // outfile<<endl;\n\n // for (int i=0;i<path_n.size();i++){\n // outfile<<\"[\";\n // for (int j=0;j<path_n[i].size();j++){\n // outfile<<path_n[i][j]<<\" \";\n // }\n // outfile<<\"]\";\n // }\n // outfile<<endl;\n\n\n vector<float> tmp;\n for(int j=0;j<n;j++){\n tmp.push_back(-1.0);\n }\n for(int i=0;i<m;i++){\n sim.push_back(tmp);\n }\n\n //calculate similarities between two nodes if applicable (to ensure 1-1 match)\n // int index_m = 0;\n // int index_n = 0;\n float score = -1.0;\n int status;\n \n //curr_score[0] = num intersection; curr_score[1] = num_union\n vector<float> curr_score; \n curr_score.push_back(0);\n curr_score.push_back(0);\n\n\n // set scores for root and article node to be 1 \n sim[0][0] = 1;\n sim[m-1][n-1] = 1;\n\n // calculate the score for the rest of the matrix\n for (int i=1; i<m-1;i++){\n for (int j=1; j<n-1;j++){\n // skip invalid matching: top node(s) for smaller path have no matching node\n if (i-1>j-1) continue;\n // skip invalid matching: bottom node(s) for smaller path have no matching node\n if (m-i>n-j) continue;\n \n // calculate similarity score\n status = calculate_node_similarity_score(path_m, path_n, curr_score, path_m.size()-i, path_n.size()-j);\n if (status == -1){\n outfile<<\"Fail\"<<endl;\n cout<<\"Failed to calculate the similarity score\"<<endl;\n exit(0);\n }\n\n score = curr_score[0]*1.0/curr_score[1]; //num same articles/union of articles\n\n if (isnan(score)){\n cerr<<\"Produce NAN\"<<endl;\n cerr<<\"intersection = \"<<curr_score[0]<<\", union = \"<<curr_score[1];\n exit(0);\n }\n sim[i][j] = score;\n \n curr_score[0] = 0;\n curr_score[1] = 0;\n }\n }\n\n \n for(int i=0;i<sim.size();i++){\n for(int j=0;j<sim[i].size();j++){\n outfile<<sim[i][j]<<\" \";\n }\n outfile<<endl;\n }\n outfile<<endl;\n}\n\n\nvoid calculate_path_similarity(vector<string>& t1_loc, vector<string> t2_loc, unordered_map<string, vector<string> >& t1, \n unordered_map<string, vector<string> >& t2, ofstream& outfile){\n // record article ids in each node \n /* \n Note: \n 1. Root is not included since it's empty\n 2. The articles in each node = the recorded articles in the node + all articles in the children of the node\n 3. Repetitive artcles are removed\n 4. similarity_score[0][0] = score for matching the nodes that contain the target article\n 5. similarity_score[m-1][n-1] = score for matching the nodes right below the root for two paths\n */\n\n vector<vector<string> > p1_nodes;\n vector<vector<string> > p2_nodes;\n \n visited.clear();\n get_path(t1_loc[0], t1, p1_nodes);\n \n for (int i=0;i<t2_loc.size();i++){\n p2_nodes.clear();\n visited.clear();\n\n get_path(t2_loc[i], t2, p2_nodes);\n \n //calculate similarity between two path\n //find depth of two paths\n int m = p1_nodes.size();\n int n = p2_nodes.size();\n //ensure we are matching the smaller depth to bigger depth path\n if(m<n){\n output_similarity_matrix(p1_nodes, p2_nodes, outfile);\n }\n else{\n output_similarity_matrix(p2_nodes, p1_nodes, outfile);\n }\n }\n \n}\n\n\nint calculate_and_output_similarity_score(string& tree_1_addr, string& tree_2_addr, string& sampled_art_addr, string& output_addr, int start_index){\n /* ---------------------------------- Store input trees ---------------------------------------*/\n //store tree structure in a map with format of [tree_enc, <art1, art2...>]\n unordered_map<string, vector<string> > t1;\n unordered_map<string, vector<string> > t2;\n store_tree(tree_1_addr, t1);\n store_tree(tree_2_addr, t2);\n cout<<\"Finish storing trees\"<<endl;\n\n\n ofstream outfile;\n outfile.open(output_addr);\n if (!outfile){\n cerr<<\"Can't open \"<<output_addr<<endl;\n return -1;\n }\n \n /* ------------------------------- Extract paths for sampled articles -----------------------------------*/\n ifstream sampled_art;\n sampled_art.open(sampled_art_addr);\n if (!sampled_art){\n cerr<<\"Cannot open \"<<sampled_art_addr<<endl;\n return -1;\n }\n\n\n // get all nodes that contain the current article in tree 1 and tree 2\n vector<string> t1_loc;\n vector<string> t2_loc;\n string line = \"\";\n // counter=0->new article id, counter=1->tree encodings for the current article in tree 1\n // counter=2->tree encodings for the current article in tree 2, counter=3->empty line\n int counter = 0; \n int line_counter = 0;\n int article_counter = 0;\n while(!sampled_art.eof()){\n line = \"\";\n getline(sampled_art, line);\n\n if(line_counter>=start_index) {\n //new article\n if(counter == 0){\n if (line.size()!=0){\n outfile<<\"-----------\"<<line<<\"-----------\"<<endl;\n }\n }\n else if(counter == 1){\n t1_loc.clear();\n parse(t1_loc, line);\n }\n else if(counter == 2){\n t2_loc.clear();\n parse(t2_loc, line);\n }\n //once finish storing all possible locations of the articles in two trees, get the path\n else if(counter == 3){\n counter = -1;\n \n article_counter++;\n // cout<<article_counter<<endl;\n\n // ensure the non-wiki tree does not have duplicated articles\n if (t1_loc.size()!=1 && t2_loc.size()!=1) {\n cerr<<\"There are duplicated articles in the generated tree\"<<endl;\n cerr<<\"t1_loc.size() = \"<<t1_loc.size()<<endl;\n cerr<<\"t2_loc.size() = \"<<t2_loc.size()<<endl;\n return -1;\n }\n //ensure the smaller tree is the first parameter\n if(t1_loc.size()==1){\n calculate_path_similarity(t1_loc, t2_loc, t1, t2, outfile);\n }\n else{\n calculate_path_similarity(t2_loc, t1_loc, t2, t1, outfile);\n }\n }\n \n }\n \n counter++;\n }\n\n // process the last article\n if(counter == 3){\n counter = -1;\n article_counter++;\n // cout<<article_counter<<endl;\n \n // ensure the non-wiki tree does not have duplicated articles\n if (t1_loc.size()!=1 && t2_loc.size()!=1) {\n cerr<<\"There are duplicated articles in the generated tree\"<<endl;\n cerr<<\"t1_loc.size() = \"<<t1_loc.size()<<endl;\n cerr<<\"t2_loc.size() = \"<<t2_loc.size()<<endl;\n return -1;\n }\n //ensure the smaller tree is the first parameter\n if(t1_loc.size()==1){\n calculate_path_similarity(t1_loc, t2_loc, t1, t2, outfile);\n }\n else{\n calculate_path_similarity(t2_loc, t1_loc, t2, t1, outfile);\n }\n }\n\n\n \n sampled_art.close();\n outfile.close();\n\n return 1;\n}\n\nint getTreeNames (string dir, vector<string> &files)\n{\n DIR *dp;\n struct dirent *dirp;\n if((dp = opendir(dir.c_str())) == NULL ) {\n cout << \"Error(\" << errno << \") opening \" << dir << endl;\n return errno;\n }\n \n while ((dirp = readdir(dp)) != NULL) {\n if (string(dirp->d_name)!= \".\" && string(dirp->d_name) != \"..\" && string(dirp->d_name) != \".DS_Store\"){\n string tree_name = string(dirp->d_name);\n string tree = \"\";\n int found = tree_name.find(\".txt\");\n if (found==std::string::npos){\n cerr<<\"cannot locate the name of the tree\"<<endl;\n exit(0);\n }\n else{\n tree = tree_name.substr(0, found);\n }\n\n if (tree!=\"wiki_tree\") {\n files.push_back(tree);\n }\n }\n }\n closedir(dp);\n return 0;\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 5){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Start Folder Number | End folder number (include) | sampled_groups_folder | Tree_folder_addr\"<<endl;\n cout<<\"(e.g 0 5 ./sampled ./all_trees)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n//\n int start_folder = stoi(argv[1]);\n int end_folder = stoi(argv[2]);\n \n string tree_folder_addr = argv[4];\n vector<string> tree_names;\n getTreeNames(tree_folder_addr, tree_names);\n // tree_names.push_back(\"BoW_tree\");\n // tree_names.push_back(\"rand_tree\");\n // tree_names.push_back(\"rev_tree\");\n string folder_path = argv[3];\n vector<string> subFolder;\n// getdir(folder_path, subFolder);\n\n for (int i=start_folder;i<=end_folder;i++){\n subFolder.push_back(to_string(i));\n }\n \n \n for (int i=0;i<subFolder.size();i++){\n string curr_folder_path = folder_path+\"/\"+subFolder[i];\n cout<<\"Getting similarity score for \"<<curr_folder_path<<endl;\n for (int j=0;j<tree_names.size();j++){\n //create a folder to hold each comparison result\n string comp_folder_path = curr_folder_path+\"/\"+tree_names[j]+\" vs wiki\";\n // cout<<comp_folder_path<<endl;\n \n string customized_tree_addr = curr_folder_path+\"/\"+tree_names[j]+\".txt\";\n string wiki_tree_addr = curr_folder_path+\"/wiki_tree.txt\";\n string output_addr = comp_folder_path+\"/reported_similartity.txt\";\n string sampled_file = comp_folder_path+\"/sampled_arts.txt\";\n \n int start_index = 0;\n calculate_and_output_similarity_score(customized_tree_addr, wiki_tree_addr, sampled_file, output_addr, start_index);\n \n }\n \n }\n \n \n \n \n return 0;\n}\n" }, { "alpha_fraction": 0.6710526347160339, "alphanum_fraction": 0.6973684430122375, "avg_line_length": 36.75, "blob_id": "4d990473b9652b45930ff2f8035e645b38c9defa", "content_id": "a132d51d4e230f98939aa0906e3af8f3e81aeb0b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 152, "license_type": "no_license", "max_line_length": 41, "num_lines": 4, "path": "/Desktop/Wiki/Code/7_generate_random_tree_structure/compile.sh", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "g++ 1_generate_random_tree_structure.cpp \ng++ 2_pick_n_location.cpp -o b.out\ng++ 3_find_similarity.cpp -o c.out\ng++ 4_get_tree_similarity.cpp -o d.out\n\n" }, { "alpha_fraction": 0.45639535784721375, "alphanum_fraction": 0.4767441749572754, "avg_line_length": 20.491071701049805, "blob_id": "4f2272280b2dbebc200a2e2d9e88c79230b63fbc", "content_id": "14678f6030d53041e39df5e5ef577f94e9ff4653", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2409, "license_type": "no_license", "max_line_length": 98, "num_lines": 112, "path": "/Desktop/Wiki/combine_major_ed_files.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// combine_two_files_side_by_side\n//\n// Created by Eve on 2/6/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\n\nusing namespace std;\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"file1 | file2 | Output_Address\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n \n string f1_addr = argv[1];\n string f2_addr = argv[2];\n string output_addr = argv[3];\n output_addr+=\"/combined_art_ed.txt\";\n \n \n ifstream f1;\n f1.open(f1_addr);\n ifstream f2;\n f2.open(f2_addr);\n \n \n ofstream outfile;\n outfile.open(output_addr);\n \n if(!outfile){\n cerr<<\"can't open output file\"<<endl;\n exit(0);\n }\n \n //read in file1\n string line;\n string artIndex = \"\";\n int indexOfComma = 0;\n\n\n unordered_set<string> visited;\n\n int dup1 = 0;\n int dup2 = 0;\n\n while(!f1.eof()){\n line = \"\";\n getline(f1, line);\n indexOfComma = line.find(\",\");\n if (indexOfComma!=std::string::npos){\n artIndex = line.substr(0, indexOfComma);\n }\n else{\n artIndex = line;\n }\n \n if (visited.count(artIndex)==0){\n visited.insert(artIndex);\n outfile<<line<<endl;\n }\n else{\n dup1++;\n }\n \n }\n cout<<\"dup1 = \"<<dup1<<endl;\n \n f1.close();\n while(!f2.eof()){\n line = \"\";\n getline(f2, line);\n indexOfComma = line.find(\",\");\n if (indexOfComma!=std::string::npos){\n artIndex = line.substr(0, indexOfComma);\n }\n else{\n artIndex = line;\n }\n \n if (visited.count(artIndex)==0){\n visited.insert(artIndex);\n outfile<<line<<endl;\n }\n else{\n dup2++;\n }\n \n }\n f2.close();\n outfile.close();\n \n\n cout<<\"dup2 = \"<<dup2<<endl;\n cout<<dup1+dup2<<endl;\n return 0;\n}\n\n" }, { "alpha_fraction": 0.4920169413089752, "alphanum_fraction": 0.4991854131221771, "avg_line_length": 28.076190948486328, "blob_id": "e8b6c3f07e360daa5a2a424744d8a08fabe60a92", "content_id": "635bfb63e63b7f731c37ff3ad3a81b5f327ebeb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3069, "license_type": "no_license", "max_line_length": 100, "num_lines": 105, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/1_remove_stop.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "# The code process the articles and removes all the stopwords, non-English words and unicode words. \n#It also tokenize all the words in the file. All the words left are in lower case\n\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom many_stop_words import get_stop_words\nimport string \nimport enchant\n\n\nenglish_dict = enchant.Dict(\"en_US\")\noutput_addr = \"/Users/eve/Desktop/Major_Editor_5/Create_BoW_Tree\"\nfiltered_file_addr = output_addr+\"/1_w_o_stop_words_2.txt\"\nunsaved_uni_addr = output_addr+\"/1_unsaved_unicode_words_2.txt\"\nfiltered_file = open(filtered_file_addr, \"w\")\nunsaved_uni = open(unsaved_uni_addr, \"w\")\n\ncontent_addr = output_addr+\"/0_art_content.txt\"\n\n\nexample_sent = \"\"\nline = \"\"\n\n\nstop_words = list(get_stop_words('en')) #About 900 stopwords\nnltk_words = list(stopwords.words('english')) #About 150 stopwords\nstop_words.extend(nltk_words)\ntmp = []\n\ndef is_ascii(text):\n if isinstance(text, unicode):\n try:\n text.encode('ascii')\n except UnicodeEncodeError:\n return False\n else:\n try:\n text.decode('ascii')\n except UnicodeDecodeError:\n return False\n return True\n\nstart = 0\n\nwith open(content_addr,'r') as f:\n num_art = 0\n c = 0\n\n for line in f:\n line = line.strip()\n\n if(len(line)!=0):\n \tfiltered_sentence = []\n \tif(line == \"************************** New Article *************************\"):\n \t\tfiltered_file.write(\"\\n\\n\")\n \t\tfiltered_file.write(line)\n \t\tfiltered_file.write(\"\\n\\n\")\n \t\tnum_art+=1\n \t\tprint(num_art)\n \telif num_art>=start:\n \t\t# print(line)\n \t\ttmp = []\n \t\tline = line.lower()\n \t\ttmp = line.split(\" \")\n \t\tline = \"\"\n \t\tfor i in tmp:\n \t\t\tif (len(i)==0):\n \t\t\t\tcontinue\n \t\t\tif isinstance(i, unicode) == False:\n \t\t\t\tif english_dict.check(i)==True:\n \t\t\t\t\tif is_ascii(i):\n \t\t\t\t\t\tline = line+i+\" \"\n \t\t\t\t\telse:\n \t\t\t\t\t\tunsaved_uni.write(i)\n \t\t\t\t\t\tunsaved_uni.write(\"\\n\")\n\n \t\t# print line\n \t\tif(len(line)==0):\n \t\t\tcontinue\n\t \texample_sent = line\n\n\t \tword_tokens = word_tokenize(example_sent)\n\n\t \t# filtered_sentence = [w for w in word_tokens if not w in stop_words]\n\t \tfiltered_sentence = []\n\t \tfor w in word_tokens:\n\t \t\tif w not in stop_words:\n\t \t\t\tfiltered_sentence.append(w)\n\n\t \tfor i in filtered_sentence:\n\t \t\tc+=1\n\t \t\tif i not in string.punctuation:\n\t \t\t\ti=i.strip(\"/\")\n\t \t\t\ti=i.strip(\"'\")\n\t \t\t\ti=i.strip(\"=\")\n\t \t\t\ti=i.strip(\"`\")\n\t \t\t\tif len(i)!=0:\n\t \t\t\t\tfiltered_file.write(i)\n\t \t\t\t\tif c!=len(filtered_sentence):\n\t \t\t\t\t\tfiltered_file.write(', ')\n\t \t\tc = 0\n\n\n\t\t\t\nf.close()\n\n\n\n \n\n \n\n \n\n \n\n " }, { "alpha_fraction": 0.5904883742332458, "alphanum_fraction": 0.6029365062713623, "avg_line_length": 29.715686798095703, "blob_id": "1f7031a7e0d7079639b67e668c2f22bfd5ec417a", "content_id": "8b5475247fe0ef3b344d8456318b797a51b270f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3133, "license_type": "no_license", "max_line_length": 173, "num_lines": 102, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/0_get_art_content copy.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetContentSize(title):\n\turl = \"https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=size&format=xml&pageids=\" + title + \"&redirects\"\n\t# next = '' \n\t# while True:\n\t\t# req = urllib2.Request(url+next)\n\treq = urllib2.Request(url)\n\tresponse = urllib2.urlopen(req)\n\tresponse = response.read() #web request \n\tfound = \"\"\n\ttry:\n\t\tfound = re.search('<rev size=\"(.+?)\"', response).group(1)\n\texcept AttributeError:\n\t\tfound = re.findall('missing=\".*\"', response)\n\t\tif (len(found)!=0):\n\t\t\t# print(\"Article \"+title+\"is missing\")\n\t\t\treturn \"-1\"\n\t\telse:\n\t\t\tprint(\"No page size is found for article \"+title+\" and the article is not missing\")\n\t\t\texit()\n\treturn found \n\ndef GetContent(title, outfile):\n\turl = \"https://en.wikipedia.org/w/api.php?format=xml&action=query&prop=extracts&explaintext=1&exlimit=1&pageids=\" + title + \"&redirects\" \n\tnext = '' \n\twhile True:\n\t\treq = urllib2.Request(url+next)\n\t\tresponse = urllib2.urlopen(req)\n\t\tresponse = response.read() #web request \n\t\tcont = re.search('<continue excontinue=\"([^\"]+)\"', response)\n\t\tif not cont: \n\t\t\t# content += response \n\t\t\toutfile.write(response) \n\t\t\tbreak\n\t\tnext = \"&excontinue=\" + cont.group(1) \n\t#return content\n\n\n\nif __name__ == \"__main__\":\n\n\tart = []\n\ttmp = []\n\tstart_index = 0\n\n\tcounter = 0\n\n\toutput_folder = \"/Users/eve/Desktop/Generated_Tree_cutoff_10/BoW_Tree\"\n\n\toutput_addr = output_folder+\"/0_art_content.txt\"\n\tmissing_art_addr = output_folder+\"/0_missing_articles.txt\"\n\tsmall_art_addr = output_folder+\"/0_small_articles.txt\"\n\tvalid_art_addr = output_folder+\"/0_valid_articles.txt\"\n\toutfile = open(output_addr, 'w')\n\tmissing_art = open(missing_art_addr, 'w')\n\tsmall_art = open(small_art_addr, 'w')\n\tvalid_art = open(valid_art_addr, 'w')\n\n\n\tcontent_size = 0\n\tnum_small_art = 0\n\tnum_missing_art = 0\n\tnum_total_art = 0\n\n\n\n\twith open(\"/Users/eve/Desktop/Generated_Tree_cutoff_10/BoW_used_articles.txt\",'r') as f:\n\n\t\tfor line in f:\n\t\t\tcounter = counter+1\n\t\t\tif counter>=start_index:\n\t\t\t\tline = line.strip('\\n')\n\t\t\t\tcontent_size = GetContentSize(line)\n\t\t\t\tif int(content_size) < 100:\n\t\t\t\t\tif int(content_size == \"-1\"):\n\t\t\t\t\t\tprint (\"Article \"+line+\" is missing\")\n\t\t\t\t\t\tnum_missing_art += 1\n\t\t\t\t\t\tmissing_art.write(line)\n\t\t\t\t\t\tmissing_art.write('\\n')\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint (\"Content size for article \"+line+\" is less than 100B\")\n\t\t\t\t\t\tnum_small_art += 1\n\t\t\t\t\t\tsmall_art.write(line)\n\t\t\t\t\t\tvalid_art.write('\\n')\n\t\t\t\telse:\t\n\t\t\t\t\tGetContent(line, outfile)\n\t\t\t\t\tvalid_art.write(line)\n\t\t\t\t\tvalid_art.write('\\n')\n\t\t\t\t\toutfile.write(\"\\r\\n\\r\\n************************** New Article *************************\\r\\n\\r\\n\") #seperate each article\n\t\t\tprint(counter)\n\n\toutfile.close()\n\tmissing_art.close()\n\tsmall_art.close()\n\tvalid_art.close()\n\n\tprint \"Finished!!!!!\"\n\tprint (\"There are \"+str(num_missing_art)+\" articles missing\"+\"\\n\")\n\tprint (\"There are \"+str(num_small_art)+\" articles<100B\"+\"\\n\")\n\tprint (\"There are \"+str(num_small_art+num_missing_art)+\" articles in total\"+\"\\n\")\n" }, { "alpha_fraction": 0.7652495503425598, "alphanum_fraction": 0.776340126991272, "avg_line_length": 66.375, "blob_id": "fb8f5ba94e5080f4677e1d4f439e994d8864b88f", "content_id": "68afb57e67ad5699d90a9111ac973b234359ecc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 541, "license_type": "no_license", "max_line_length": 168, "num_lines": 8, "path": "/Desktop/Wiki/Code/7_generate_random_tree_structure/run.sh", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "Tree_Addr=$1\nOutput_Random_Tree_Addr=$2\nWiki_Addr=$3\nNum_Articles_to_Sample=50\n./a.out $Tree_Addr $Output_Random_Tree_Addr\n./b.out $Output_Random_Tree_Addr/random_tree_structure.txt $Wiki_Addr $Output_Random_Tree_Addr/Random_vs_Wiki $Num_Articles_to_Sample\n./c.out $Output_Random_Tree_Addr/random_tree_structure.txt $Wiki_Addr $Output_Random_Tree_Addr/Random_vs_Wiki/sampled_arts.txt $Output_Random_Tree_Addr/Random_vs_Wiki 0\n./d.out $Output_Random_Tree_Addr/Random_vs_Wiki/reported_similartity.txt $Output_Random_Tree_Addr/Random_vs_Wiki\n\n\n" }, { "alpha_fraction": 0.5633187890052795, "alphanum_fraction": 0.5731440782546997, "avg_line_length": 24.082191467285156, "blob_id": "f349f7f099c397c36e4ae14cfcc2cc68fcbc2e6b", "content_id": "c052daee0a05291e629f2bc28316d0b0d030fe4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1832, "license_type": "no_license", "max_line_length": 96, "num_lines": 73, "path": "/Helper/remove_dup_id_and_names.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "if __name__ == \"__main__\":\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\tseen = set()\n\tindex_to_remove = [] #note that since we use num as a counter, the index starts at 0\n\n\tid_file = open(\"/Users/eve/Desktop/unique_art_id.txt\", \"w\")\n\tname_file = open(\"/Users/eve/Desktop/unique_art_name.txt\", \"w\")\n\n\tline = \"\"\n\n\t# with open(\"/Users/eve/Desktop/combined_artname.txt\") as f:\n\n\t# for line in f:\n\t# \tif len(line.strip()) != 0:\n\t# \t\tnum+=1\n\t# \t line = line.strip('\\n')\n\t# \t if line in seen:\n\t# \t \tcounter += 1\n\t# \t else:\n\t# \t\t\t\tseen.add(line)\n\t# \t\t\t\t# print line\n\t# f.close()\n\t# print \"finish scanning original file\"\n # \tprint counter\n # \tprint num\n\n \t# locate and remove duplicates (store the removed line number to use for removing the artname)\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\n\twith open(\"/Users/eve/Desktop/combined_id.txt\") as f:\n\n\t for line in f:\n\t \tif len(line.strip()) != 0:\n\t \t\tnum+=1\n\t\t line = line.strip('\\n')\n\t\t # print line\n\t\t if line in seen:\n\t\t \tindex_to_remove.append(num)\n\t\t \tcounter += 1\n\t\t else:\n\t\t\t\t\tseen.add(line)\n\t\t\t\t\tid_file.write(line)\n\t\t\t\t\tid_file.write('\\n')\n\n\tprint \"id file processed\"\n\tf.close()\n \tprint counter\n \tprint num\n\n \t# process article name file\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\n\tc = 0\n\twith open(\"/Users/eve/Desktop/combined_name.txt\") as f:\n\t for line in f:\n\t \tif len(line.strip()) != 0:\n\t \t\tnum+=1\n\t\t line = line.strip('\\n')\n\t\t if c<len(index_to_remove) and num == index_to_remove[c]:\n\t\t \tc +=1\n\t\t \tcounter +=1\n\t\t else:\n\t\t\t\t\tname_file.write(line)\n\t\t\t\t\tname_file.write('\\n')\n\n\n\tprint \"name file processed\"\n\tf.close()\n \tprint counter\n \tprint num\n\n" }, { "alpha_fraction": 0.3618951737880707, "alphanum_fraction": 0.3702957034111023, "avg_line_length": 20.402877807617188, "blob_id": "815b67226325087a1fd4f4ac866fac9e659c523e", "content_id": "45123a2b46c2b619977a48955dc1e731934c42e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2977, "license_type": "no_license", "max_line_length": 110, "num_lines": 139, "path": "/Desktop/Wiki/Code/Helper/get_words.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// parse\n//\n// Created by Eve on 11/28/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <fstream>\n#include <stack>\n#include <stdio.h>\n#include <stdlib.h>\n\nusing namespace std;\nbool brackets;\nbool useless;\nbool xml;\n\n\nvoid parse(string& s, ofstream& outfile){\n \n// if(s==\"== See also ==\"||s==\"== References ==\"||s==\"== Sources ==\"||s==\"== External links ==\"){\n// useless = true;\n// return;\n// }\n\n int i=0;\n while(i<s.size()){\n if(xml){\n //remove xml\n if(s[i] == '<'){\n brackets = true;\n }\n if(brackets){\n if (s[i]=='>'){\n brackets = false;\n }\n }\n else{\n //copy the content\n //replace quote\n if(s[i]=='&'){\n if(i+6<s.size()&&s.substr(i,6)==\"&quot;\"){\n outfile<<'\"';\n i=i+6;\n continue;\n }\n }\n \n outfile<<s[i];\n \n }\n }\n \n else{\n //replace quote\n if(s[i]=='&'){\n if(i+6<s.size()&&s.substr(i,6)==\"&quot;\"){\n outfile<<'\"';\n i=i+6;\n continue;\n }\n }\n \n outfile<<s[i];\n \n }\n i++;\n \n }\n \n}\n\n\nint main(int argc, const char * argv[]) {\n ifstream infile;\n ofstream outfile;\n string address = argv[1];\n string o_address = argv[2];\n \n \n\n infile.open(address);\n outfile.open(o_address);\n \n \n \n brackets = false;\n useless = false;\n xml = true;\n int num_art = 0;\n string line = \"\";\n \n \n \n while(!infile.eof()){\n getline(infile, line);\n //skip empty lines\n if(line.empty()){\n continue;\n }\n //veriy if it's a new article\n if(line[0] == '\\r'){\n //if it's \"new art\"\n if(line[1]!='<' && line!=\"\\r\"){\n xml = true;\n brackets = false;\n useless = false;\n num_art+=1;\n cout<<num_art<<endl;\n outfile<<endl<<\"************************** New Article *************************\"<<endl<<endl;\n }\n //if it's xml\n else if(line[1]!='<'){\n parse(line, outfile);\n outfile<<endl;\n xml = false;\n\n }\n }\n\n else if(!useless){\n parse(line, outfile);\n outfile<<endl;\n xml = false;\n \n }\n \n }\n infile.close();\n outfile.close();\n cout<<num_art<<endl;\n cout<<\"Verify if there're more articles than feeded (error may happens for **)\"<<endl;\n \n\n cout<<\"completed\"<<endl;\n return 0;\n}\n\n" }, { "alpha_fraction": 0.47387656569480896, "alphanum_fraction": 0.49133729934692383, "avg_line_length": 29.39917755126953, "blob_id": "21ced86992a01721df1e6ab703664369ae699bb7", "content_id": "4e2d8754a805842789de97fd65c7329f132fe837", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7390, "license_type": "no_license", "max_line_length": 157, "num_lines": 243, "path": "/2_Compare_Tree/Generate_BOW_tree/6_edge_list.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// 7_get_article_weight_pair_new\n//\n// Created by Eve on 10/24/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n//\n// main.cpp\n// 7_get_article_weight_pair\n//\n// Created by Eve on 10/17/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n\n/*********************************************************************************/\n/* The code takes in editors and the articles they did major revisions for. The */\n/* code outputs the edge list for article pairs in the following format: */\n/* [art_weight_pair]: article_decode 1, article_decode 2, weight */\n/* [art_index_name]: article_decode, article_name */\n/*********************************************************************************/\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n\nusing namespace std;\n\n\nint curr_in = -1; //current index of the new inserted article [used in addEdge]\nint num_noEdge = 0;\n\nbool new_art;\nbool store_art1;\nbool store_art2;\nstring art_index1;\nstring art_index2;\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if(s[i+1]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\n//the function assigns an index to represent the article\nint getArtIndex(string& a, unordered_map<string, int>& article_index, ofstream&artname){\n int c = 0; //count the number of appearance of an article in the map\n unordered_map<string, int>::iterator it;\n int in_a = 0; //article index\n c = article_index.count(a);\n //if new article\n if(c == 0){\n// curr_in+=1;\n article_index[a] = stoi(a);\n in_a = stoi(a);\n artname<<in_a<<\", \"<<a<<endl;\n }\n //otherwise, directly get the index of the article\n else if (c == 1){\n it = article_index.find(a);\n in_a = it->second;\n }\n \n return in_a;\n}\n\n\nvoid addEdge(vector<string>& parsed, unordered_map<int, map<int,int> >& weight, unordered_map<string, int>& article_index, ofstream& artname){\n int in_a1 = 0;\n int in_a2 = 0;\n int tmp = 0;\n int c = 0; //counter for article appearances in weight\n unordered_map<int, map<int,int> >::iterator it;\n map<int,int>::iterator it2;\n \n \n \n //skip the first element (author name), take each pair\n for(int i=1;i<parsed.size();i++){\n for(int j = i+1;j<parsed.size();j++){\n in_a1 = getArtIndex(parsed[i], article_index, artname);\n \n in_a2 = getArtIndex(parsed[j], article_index, artname);\n \n// cout<<parsed[i]<<\" \"<<in_a1<<\" \"<<parsed[j]<<\" \"<<in_a2<<endl;\n //swap a1 a2 index to ensure a1 has smaller index (avoid repetition)\n if(in_a1>in_a2){\n tmp = in_a1;\n in_a1 = in_a2;\n in_a2 = tmp;\n }\n c = weight.count(in_a1);\n \n //if new article\n if(c == 0){\n map<int, int> edge;\n edge[in_a2] = 1;\n weight[in_a1] = edge;\n }\n \n //if the article is not in weight\n else{\n it = weight.find(in_a1); //locate article 1\n it2 = (it->second).find(in_a2); //locate article 2 from article 1'a edges\n // if article 2 doesnt have an edge with article 1\n if(it2 == (it->second).end()){\n (it->second)[in_a2] = 1;\n }\n else{\n it2->second+=1;\n }\n }\n }\n \n }\n}\n\n\n\nint main(int argc, const char * argv[]) {\n if(argc < 5){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_major_editor_w_article_file | Output_address | category_range_and_output_version | upper-bound_on_num_art_edited_by_one_ed\"<<endl;\n cout<<\"(e.g ./major_editor_w_art_cate_0_to_100000.txt ./ 0_to_100000_2)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string output_address = argv[2];\n string cate_range = argv[3];\n string edge_list_addr = output_address+\"/art_weight_pair_cate_\"+cate_range+\".txt\";\n string art_index_addr = output_address+\"/art_name_cate_\"+cate_range+\".txt\";\n string num_in = argv[4];\n int art_num_upper_bound = stoi(num_in);\n \n \n //initiate map for storing weight pair\n unordered_map<int, map<int, int> >weight;\n \n //initiate map for storing article_name and its index (for look up)\n unordered_map<string, int> article_index;\n \n //local variables\n vector<string> parsed;\n string line = \"\";\n \n new_art = false;\n store_art1 = false;\n store_art2 = false;\n //********** articles, weight pair *******//\n ofstream art_weight_pair;\n art_weight_pair.open (edge_list_addr);\n\n //********** article index, names *******//\n ofstream art_index_name;\n art_index_name.open (art_index_addr);\n\n //////////////////////////\n // Create edge list //\n //////////////////////////\n ifstream infile;\n infile.open (argv[1]);\n int i = 0;\n\n if(!infile){\n cerr<<\"Can't open infile\"<<endl;\n exit(1);\n }\n int l = 0;\n while(!infile.eof()){\n getline(infile,line);\n l+=1;\n if (!line.empty()){\n if(l %1000 == 0){\n cout<<l<<endl;\n }\n// if(curr_in%100 == 0){\n// cout<<\"\\t\"<<curr_in<<endl;\n// }\n i++;\n parsed.clear();\n parse(line, parsed);\n \n //if the number of artilces edited by an editor is too many, skip the editor\n if((parsed.size()-1) > art_num_upper_bound){\n continue;\n }\n \n addEdge(parsed, weight, article_index, art_index_name);\n \n }\n }\n infile.close();\n\n cout<<\"Finish creating weight pairs\"<<endl;\n \n int real_art_pair_counter = 0;\n //*********** print out art_weight pair ************//\n int num_weight_pair = weight.size(); //not a real number of article pairs\n int c = 0;\n unordered_map<int, map<int,int> >::iterator it;\n map<int,int>::iterator it2;\n for (it = weight.begin();it!=weight.end();it++){\n real_art_pair_counter+= (it->second).size();\n for(it2 = (it->second).begin();it2!=(it->second).end();it2++){\n art_weight_pair<<it->first<<\", \"<<it2->first<<\", \"<<it2->second<<endl;\n }\n c++;\n if(c%10000==0){\n cout<<\"stored \"<<c<<\"/\"<<num_weight_pair<<endl;\n }\n }\n art_weight_pair.close();\n\n cout<<\"Completed\"<<endl;\n \n cout<<\"-------------------------------\"<<endl;\n cout<<\"There are \"<<article_index.size()<<\" articles with at least one edge\"<<endl;\n cout<<\"There are \"<<real_art_pair_counter<<\" weight pairs in total\"<<endl;\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.5065326690673828, "alphanum_fraction": 0.5281407237052917, "avg_line_length": 22.690475463867188, "blob_id": "273fbb77f1f4a721b4beac0e557f635410aff336", "content_id": "435c92823982ae8ef0f906179e8d2041a3d00158", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1990, "license_type": "no_license", "max_line_length": 125, "num_lines": 84, "path": "/Desktop/Wiki/Code/Helper/check_duplicates.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "if __name__ == \"__main__\":\n\tcounter = 0 # num of repetitive elements\n\tnum = 0 # total num of elements\n\tline_num = 0 #inclusing empty lines\n\tseen = set()\n\n\tline = \"\"\n\t# with open(\"/Users/eve/Desktop/Wiki/Life/Opticode_tester/COLING/tree_enc/group_ite_old.txt\",'r') as file:\n\t# \tfor line in file:\n\t# \t\tline_num+=1\n\n\t# \t\tif len(line.strip())!=0: \n\t# \t\t\tnum += 1\n\t# \t\t\tline = line.strip()\n\t# \t\t\t#print \n\t# \t\t\t# if num == 291450:\n\t# \t\t\t# \tprint line\n\t# \t\t\t# \tprint num\n\t# \t\t\t# \tprint line_num\n\t# file.close()\n\n\t# print counter\n\t# print num\n\t# print line_num\n\t# print \"finish one file\"\n\n\n\n\n\n\n\twith open(\"/Volumes/easystore/Wiki/All_Materials_for_Paper/Experiment/3_Art_w_Major_Editors/unique_combined.txt\",'r') as f3:\n\t# with open(\"/Users/eve/Desktop/Wiki/Life/WikiTree/cate_name.txt\",'r') as f3:\n\t\t for line in f3:\n\t\t \tif len(line.strip()) != 0 :\n\t\t \t\tnum+=1\n\t\t\t line = line.strip('\\n')\n\t\t\t \n\t\t\t if line in seen:\n\t\t\t \t# print line\n\t\t\t \tcounter += 1\n\t\t\t else:\n\t\t\t \n\t\t\t seen.add(line)\n\tf3.close()\n\n\tprint \"Number of repetitions: \"\n \tprint counter\n \tprint \"Number of elements: \"\n \tprint num\n \tprint \"finish three file\"\n\n\t# counter = 0\n\t# num = 0\n\t# # seen = set()\n # \t# num = 0\n # \t# with open(\"/Users/eve/Desktop/Wiki/Life/WikiTree/cate_name.txt\",'r') as f2:\n\t# with open(\"/Users/eve/Desktop/Result_for_new_create_tree_code/30_pairs/thresh/tree_enco.txt\",'r') as f2:\n\t# for line in f2:\n\t# \tif len(line.strip()) != 0 :\n\t# \t\tnum+=1\n\t# \t\t# if num == 1000:\n\t# \t\t# \tbreak\n\n\t# \t line = line.strip('\\n')\n\t# \t # if line == \"1926287\":\n\t# \t # \tprint num\n\n\t# \t if line in seen:\n\t# \t \t# print(line)\n\t# \t \t# print num\n\t# \t \tcounter += 1\n\t# \t \t# break\n\t# \t # else:\n\t\t \n\t# \t # seen.add(line)\n\n\t# f2.close()\n\n\t# print \"Number of repetitions: \"\n # \tprint counter\n # \tprint \"Number of elements: \"\n # \tprint num\n # \tprint \"finish two file\"\n" }, { "alpha_fraction": 0.46335211396217346, "alphanum_fraction": 0.4695028066635132, "avg_line_length": 25.71917724609375, "blob_id": "fa5dd0898f3dc44f1173c063ac76d90ce7f29c59", "content_id": "0ed2fb9acbc609fa2d58e00e1a657726cab534d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3902, "license_type": "no_license", "max_line_length": 163, "num_lines": 146, "path": "/Desktop/Wiki/Code/3_Create_Bar_Graph/get_all_categories_in_groups.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "// The code takes in the category tree and a level request. The code goes to the desired level and gets all subcategories and ancestors for the nodes in the level.\n\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <unordered_set>\n\nusing namespace std;\n\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i] == ':'){\n parsed.push_back(tmp);\n tmp = \"\";\n \n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\nvoid parse_group(string& s, vector<int>& decode){\n string tmp=\"\";\n for(int i=0;i<s.size();i++){\n \n if(s[i]=='_'){\n if(tmp.size()==0) continue;\n decode.push_back(stoi(tmp));\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n decode.push_back(stoi(tmp));\n \n \n// for(int i=0;i<decode.size();i++){\n// cout<<decode[i]<<\" \";\n// }\n// cout<<endl;\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Address_for_categories | Output_address | Number_of_level_to_extract \"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n string in_addr = argv[1];\n string output_address = argv[2];\n output_address+=\"/combined_category.txt\";\n string lv_range_str = argv[3];\n int lv_range = stoi(lv_range_str);\n \n //ofstram\n ofstream outfile;\n outfile.open(output_address);\n \n \n //local variables\n vector<string> parsed;\n string line = \"\";\n vector<int> decode;\n \n //read in category file\n ifstream infile;\n infile.open (in_addr);\n \n \n //vector for storing ancestors\n vector <int> ancestors;\n map<string, vector <int> > cate_at_curr_lv;\n \n if(!infile){\n cerr<<\"Can't open infile\"<<endl;\n exit(1);\n }\n \n int line_c = 0;\n while(!infile.eof()){\n line_c++;\n if(line_c%100 == 0){\n cout<<line_c<<endl;\n }\n getline(infile,line);\n if (!line.empty()){\n parsed.clear();\n parse(line, parsed);\n decode.clear();\n parse_group(parsed[0], decode);\n \n //if we haven't reached the level\n if(decode.size()<lv_range){\n ancestors.push_back(stoi(parsed[1]));\n }\n //if the current level is the level we want to examine\n else if(decode.size()==lv_range){\n \n string group_code = parsed[0];\n string article = parsed[1];\n //doesn't exist\n if(cate_at_curr_lv.count(group_code)==0){\n cate_at_curr_lv[group_code] = ancestors;\n \n }\n cate_at_curr_lv[group_code].push_back(stoi(article));\n }\n else{\n string main_group = \"\";\n for(int i=0;i<lv_range;i++){\n main_group = main_group+\"_\"+to_string(decode[i]);\n }\n \n cate_at_curr_lv[main_group].push_back(stoi(parsed[1]));\n }\n }\n }\n infile.close();\n\n \n for(auto it = cate_at_curr_lv.begin();it!=cate_at_curr_lv.end(); it++){\n outfile<<it->first;\n for(int i = 0;i<it->second.size();i++){\n outfile<<\", \"<<it->second[i];\n }\n outfile<<endl;\n }\n \n \n \n cout<<\"There are \"<<cate_at_curr_lv.size()<<\" category groups we are interested in\"<<endl;\n\n return 0;\n}\n\n" }, { "alpha_fraction": 0.4877611994743347, "alphanum_fraction": 0.4994776248931885, "avg_line_length": 27.877155303955078, "blob_id": "51a53baf338cfb18f822680256b010472e9b770f", "content_id": "eaa6c5dd3d0a4a504ab64dc1a7081a992c4b4c4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 13401, "license_type": "no_license", "max_line_length": 220, "num_lines": 464, "path": "/2_Compare_Tree/find_similarity/old_buggy.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": " //\n// main.cpp\n// find_similarity\n//\n// Created by Eve on 2/4/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <algorithm>\n#include <unordered_set>\nusing namespace std;\n\nset<string> visited; //global variable: used for repreventing adding repeated articles to the vector\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n}\n\nvoid parse_position(vector<string>& parsed, string& line){\n string tmp = \"\";\n bool start = false;\n for(int i=0;i<line.length();i++){\n if(line[i]=='_'){\n if(!start){\n start = true;\n }\n else{\n \n parsed.push_back(tmp);\n tmp = \"\";\n }\n }\n else {\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n \n// cout<<\"parsed: \";\n// for(int i=0;i<parsed.size();i++){\n// cout<<\"_\"<<parsed[i];\n// }\n// cout<<endl;\n \n}\n\nvoid store_tree(string& addr, unordered_map<string, vector<string> >& t){\n ifstream tree_file;\n tree_file.open(addr);\n if(!tree_file){\n cerr<<\"Can't open file\"<<endl;\n exit(0);\n }\n string line = \"\";\n vector<string> parsed;\n while(!tree_file.eof()){\n line = \"\";\n parsed.clear();\n getline(tree_file, line);\n parse(parsed, line);\n \n //store key: tree_encoding, values: articles at the node\n vector<string> articles;\n articles.clear();\n t[parsed[0]] = articles;\n// cout<<parsed[0]<<\": \";\n if(parsed.size()>1){\n for(int i=1;i<parsed.size();i++){\n t[parsed[0]].push_back(parsed[i]);\n// cout<<parsed[i]<<\" \";\n }\n }\n// cout<<endl;\n }\n tree_file.close();\n}\n\n//get the articles in the node and articles in the childrens node, except for child node \"except\"\nvoid getNodeContent(string& loc, string& except, unordered_map<string, vector<string> >& t, vector<string>& content){\n// vector<string> content;\n content.clear();\n queue<string> node_to_visit;\n node_to_visit.push(loc);\n //BFS\n while(!node_to_visit.empty()){\n string curr = node_to_visit.front();\n// cout<<\"Node \"<<curr<<\": \";\n \n \n //store articles in the current node (get rid of repetitions)\n if(t.count(curr) == 0) {\n cerr<<\"Cannot locate node \"<<curr<<\" in the tree\"<<endl;\n exit(0);\n }\n unordered_map<string, vector<string> >::iterator it = t.find(curr);\n// cout<<\"articles inside loc \"<<loc<<\": \";\n for(int i=0; i<(it->second).size();i++){\n// cout<<it->second[i]<<\" \";\n if(visited.find(it->second[i])==visited.end()){\n content.push_back(it->second[i]);\n visited.insert(it->second[i]);\n// cout<<it->second[i]<<\" \";\n }\n }\n// cout<<endl;\n //get children nodes (except for \"except)\n int c=0;\n string tmp = curr+\"_\"+to_string(c);\n while(t.count(tmp) == 1){\n if(tmp != except){\n node_to_visit.push(tmp);\n }\n c++;\n tmp = curr+\"_\"+to_string(c);\n }\n //remove the node\n node_to_visit.pop();\n }\n \n// cout<<\"Node \"<<loc<<\": \";\n// for(int i=0;i<content.size();i++){\n// cout<<content[i]<<\" \";\n// }\n// cout<<endl;\n//\n// return content;\n}\n\nvoid get_path(string& loc, unordered_map<string, vector<string> >& t, vector<vector<string> >& tree_nodes){\n //corner case: the article is contained in the root\n if(loc == \"_0\"){\n cout<<\"Detected an article in the root\"<<endl;\n return;\n }\n \n //populate first entry: node that contains sampled article\n string tmp = \"-1\";\n string current_node = loc;\n vector<string> content;\n content.clear();\n getNodeContent(loc, tmp, t, content);\n tree_nodes.push_back(content);\n \n \n //get its ancestors (except for the root)\n vector<string> pos;\n pos.clear();\n parse_position(pos, loc);\n\n int c = pos.size()-1;\n// cout<<\"c = \"<<c<<endl;\n \n while(c!=1){\n \n tmp = current_node;\n current_node = \"\";\n for(int i=0;i<c;i++){\n current_node = current_node+ \"_\" +pos[i];\n }\n// cout<<\"ancestor: \"<<current_node<<endl;\n// cout<<\"except: \"<<tmp<<endl;\n content.clear();\n getNodeContent(current_node, tmp, t, content);\n tree_nodes.push_back(content);\n \n c--;\n }\n \n \n// cout<<\"Tree Nodes: +++++++++++++++++++++\"<<endl;\n// for(int i=0;i<tree_nodes.size();i++){\n// for(int j=0;j<tree_nodes.size();j++){\n// cout<<tree_nodes[i][j]<<\" \";\n// }\n// cout<<endl;\n// }\n// cout<<endl<<endl;\n//\n//\n}\n\nvoid similarity_score(vector<string>& a, vector<string>& b, vector<int>& curr_score){\n //new score = (new number of intersection)/(new number of union) = (prev inter + new inter)/(prev union + (new node size - new inter)\n int intersect_num;\n int added_num;\n// vector<int> ans;\n \n vector<string>::iterator it;\n vector<string> intersect(b.size());\n sort (a.begin(), a.end());\n sort (b.begin(), b.end());\n// cout<<\"here3.1\"<<endl;\n it=set_intersection (a.begin(), a.end(), b.begin(), b.end(), intersect.begin());\n// cout<<\"here3.2\"<<endl;\n intersect.resize(it-intersect.begin());\n// cout<<\"here3.3\"<<endl;\n \n intersect_num = intersect.size();\n if(curr_score[1]==0){\n added_num = b.size()+a.size()-intersect_num;\n }\n else{\n added_num = b.size()-intersect_num;\n }\n \n// cout<<\"here3.4\"<<endl;\n \n curr_score[0] += intersect_num;\n curr_score[1] += added_num;\n \n \n \n}\n\nvoid output_similarity_matrix (vector<vector<string> >& path_m, vector<vector<string> >& path_n, ofstream& outfile){\n //corner case: the node is in the root\n if(path_m.size() == 0 || path_n.size() == 0){\n outfile<<1<<endl<<endl;\n return;\n }\n \n //create a similarity matrix\n vector<vector<float> >sim;\n \n int m = path_m.size();\n int n = path_n.size();\n vector<float> tmp;\n for(int i=0;i<m;i++){\n tmp.clear();\n for(int j=0;j<n;j++){\n tmp.push_back(-1.00);\n }\n sim.push_back(tmp);\n }\n// cout<<\"here\"<<endl;\n \n //calculate similarities between two nodes if applicable (to ensure 1-1 match)\n int index_m = 0;\n int index_n = 0;\n float score = -1.0;\n \n vector<int> curr_score; //curr_score[0] = num inter; curr_score[1] = num_union\n curr_score.push_back(0);\n curr_score.push_back(0);\n\n// cout<<\"m = \"<<m<<\", n = \"<<n<<endl;\n \n for(int i=m-1;i>=0;i--){\n for(int j=n-1-index_m; j>=m-1-index_m; j--){\n// cout<<\"i = \"<<i<<\", j = \"<<j<<endl;\n// cout<<\"m_index = \"<<index_m<<\", n_index = \"<<index_n<<endl;\n similarity_score(path_m[index_m], path_n[index_n], curr_score);\n score = curr_score[0]*1.0/curr_score[1];\n \n sim[i][j] = score;\n \n index_n ++;\n }\n curr_score[0] = 0;\n curr_score[1] = 0;\n index_m ++;\n index_n = index_m;\n }\n \n \n \n \n \n \n// cout<<\"here\"<<endl;\n \n for(int i=0;i<m;i++){\n for(int j=0;j<n;j++){\n outfile<<sim[i][j]<<\" \";\n }\n outfile<<endl;\n }\n outfile<<endl;\n \n}\n\n//void calculate_similarity(vector<string>& t1_loc, vector<string> t2_loc, unordered_map<string, vector<string> >& t1, unordered_map<string, vector<string> >& t2, ofstream& outfile, ofstream& path){\nvoid calculate_similarity(vector<string>& t1_loc, vector<string> t2_loc, unordered_map<string, vector<string> >& t1, unordered_map<string, vector<string> >& t2, ofstream& outfile){\n \n // each entry of the vector indicates the articles in node from the node first contains sampled article to the one belows the root (without repetitions)-->since in our tree we only assign each article to one category\n vector<vector<string> > s_tree_nodes;\n vector<vector<string> > b_tree_nodes;\n \n visited.clear();\n get_path(t1_loc[0], t1, s_tree_nodes);\n \n\n// path<<endl<<\"+++++++++++++ Revision Tree Path +++++++++++++\"<<endl<<endl;\n// path<<\"Getting path for \"<<t1_loc[0]<<endl;\n// for(int i=0;i<s_tree_nodes.size();i++){\n// for(int j=0;j<s_tree_nodes[i].size();j++){\n// path<<s_tree_nodes[i][j]<<\" \";\n// }\n// path<<endl;\n// }\n//\n//\n// path<<endl<<\"+++++++++++++ Wiki Tree Path +++++++++++++\"<<endl<<endl;\n \n for (int i=0;i<t2_loc.size();i++){\n \n// path<<\"Getting path for \"<<t2_loc[i]<<endl;\n b_tree_nodes.clear();\n visited.clear();\n get_path(t2_loc[i], t2, b_tree_nodes);\n \n// for(int i=0;i<b_tree_nodes.size();i++){\n// for(int j=0;j<b_tree_nodes[i].size();j++){\n// path<<b_tree_nodes[i][j]<<\" \";\n// }\n// path<<endl;\n// }\n// if (i!=t2_loc.size()-1){\n// path<<endl<<\"--------------------------------------\"<<endl<<endl;\n// }\n \n \n //calculate similarity between two path\n //find depth of two paths\n int m = s_tree_nodes.size();\n int n = b_tree_nodes.size();\n //ensure we are matching the smaller depth to bigger depth path\n if(m<n){\n output_similarity_matrix(s_tree_nodes, b_tree_nodes, outfile);\n }\n else{\n output_similarity_matrix(b_tree_nodes, s_tree_nodes, outfile);\n }\n \n \n }\n \n \n \n// path<<endl<<\"*****************************\";\n// path<<\"****************************\";\n// path<<endl<<endl;\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 6){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Tree_1_Address | Tree_2_Adress | Selected_Article_Address | Output_Address | Start_index\"<<endl;\n cout<<\"(e.g ./tree_1.txt ./tree_2.txt ./sampled_arts.txt ./ 0)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string tree_1_addr = argv[1];\n string tree_2_addr = argv[2];\n string sampled_file = argv[3];\n string output_addr = argv[4];\n output_addr+=\"/reported_similartity.txt\";\n \n string path_addr = argv[4];\n path_addr+=\"/path.txt\";\n \n string s_in = argv[5];\n int start_index = stoi(s_in);\n if(start_index>1){\n output_addr = argv[4];\n output_addr = output_addr+ \"/reported_similartity_\"+s_in+\".txt\";\n }\n \n //create output file\n ofstream outfile;\n outfile.open(output_addr);\n// ofstream pathfile;\n// pathfile.open(path_addr);\n \n //store tree structure in a map with format of [tree_enc, <art1, art2...>]\n unordered_map<string, vector<string> > t1;\n unordered_map<string, vector<string> > t2;\n store_tree(tree_1_addr, t1);\n store_tree(tree_2_addr, t2);\n cout<<\"Finish storing trees\"<<endl;\n \n //get sampled articles\n ifstream sampled_art;\n sampled_art.open(sampled_file);\n vector<string> t1_loc;\n vector<string> t2_loc;\n string line = \"\";\n int counter = 0;\n int tmp_counter = 0;\n while(!sampled_art.eof()){\n line = \"\";\n getline(sampled_art, line);\n //new article\n if(counter == 0){\n tmp_counter ++;\n cout<<tmp_counter<<endl;\n// pathfile<<\"SAMPLED ARTICLE: \"<<line<<endl;\n if(tmp_counter>=start_index) {\n outfile<<\"-----------\"<<line<<\"-----------\"<<endl;\n }\n }\n if(counter == 1){\n t1_loc.clear();\n parse(t1_loc, line);\n }\n else if(counter == 2){\n t2_loc.clear();\n parse(t2_loc, line);\n }\n //once finish storing all possible locations of the articles in two trees, get the path\n else if(counter == 3){\n counter = -1;\n \n if(tmp_counter>=start_index) {\n //ensure the smaller tree is the first parameter\n if(t1_loc.size()==1){\n \n calculate_similarity(t1_loc, t2_loc, t1, t2, outfile);\n }\n else{\n \n calculate_similarity(t2_loc, t1_loc, t2, t1, outfile);\n }\n }\n }\n \n counter++;\n }\n // process the last group\n //ensure the smaller tree is the first parameter\n if(t1_loc.size()==1){\n calculate_similarity(t1_loc, t2_loc, t1, t2, outfile);\n }\n else{\n calculate_similarity(t2_loc, t1_loc, t2, t1, outfile);\n }\n \n sampled_art.close();\n outfile.close();\n// pathfile.close();\n \n return 0;\n}\n" }, { "alpha_fraction": 0.43671679496765137, "alphanum_fraction": 0.44486215710639954, "avg_line_length": 24.94308853149414, "blob_id": "ece6a66b9f07762cd9145f5421b7d1af664fd803", "content_id": "3a32920517d48e9338faf55acd3ebb70ff9577f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3192, "license_type": "no_license", "max_line_length": 98, "num_lines": 123, "path": "/Desktop/Wiki/Code/Helper/calculate_num_articles_per_lv.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\nusing namespace std;\n\n//ofstream artname;\n//bool first = false;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n if (tmp!=\" \"&&tmp.size()!=0){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n if (tmp!=\" \"&&tmp.size()!=0){\n parsed.push_back(tmp);\n }\n}\n\nint calculate_lv(string& s){\n int lv = 0;\n for (int i=0;i<s.size();i++){\n if (s[i]=='_'){\n lv++;\n }\n }\n return lv;\n}\n\nvoid store_tree(string& addr, unordered_map<string, vector<string> >& t){\n ifstream tree_file;\n tree_file.open(addr);\n if(!tree_file){\n cerr<<\"Can't open file\"<<endl;\n exit(0);\n }\n string line = \"\";\n vector<string> parsed;\n while(!tree_file.eof()){\n line = \"\";\n parsed.clear();\n getline(tree_file, line);\n parse(parsed, line);\n if(parsed.size()>1){\n for(int i=1;i<parsed.size();i++){\n \n \n if(t.count(parsed[i])==1){\n t[parsed[i]].push_back(parsed[0]);\n \n }\n else{\n// if(first){\n// artname<<parsed[i]<<\", \"<<parsed[i]<<endl;\n// }\n vector<string> location;\n location.clear();\n location.push_back(parsed[0]);\n t[parsed[i]] = location;\n }\n }\n }\n }\n tree_file.close();\n}\nint main(int argc, const char * argv[]) {\n if(argc < 2){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Rev_tree_Address\"<<endl;\n cout<<\"(e.g ./rev_tree.txt )\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string tree_1_addr = argv[1];\n \n map<int, int> lv_counter;\n\n ifstream infile;\n infile.open(tree_1_addr);\n string line=\"\";\n vector<string> parsed;\n int total_num_art = 0;\n while(!infile.eof()){\n getline(infile, line);\n if (line!=\"\" && line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n\n string tree_enco = parsed[0];\n int lv = calculate_lv(tree_enco);\n lv_counter[lv]=lv_counter[lv]+parsed.size()-1;\n total_num_art = total_num_art+parsed.size()-1;\n }\n }\n\n int num_art = 0;\n for (auto it=lv_counter.begin();it!=lv_counter.end();it++){\n cout<<it->first<<\" \"<<it->second<<\" \"<<(it->second/total_num_art)*100<<\"%\"<<endl;\n num_art+=it->second;\n }\n\n cout<<\"There are in total \"<<num_art<<\" articles\"<<endl;\n \n return 0;\n \n}\n" }, { "alpha_fraction": 0.4510400891304016, "alphanum_fraction": 0.4637239873409271, "avg_line_length": 23.637500762939453, "blob_id": "2b3fcc5180347fcd5e5ad6e6dbea0bb24f785148", "content_id": "db7006d0d47fef009c9387f6e797f7cf52ea9cc9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1972, "license_type": "no_license", "max_line_length": 135, "num_lines": 80, "path": "/Desktop/Wiki/Code/Helper/count.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// get_editor_with_art\n//\n// Created by Eve on 9/19/17.\n// Copyright © 2017 Eve. All rights reserved.\n//\n\n/////////////////////////////////////////////////////////////////////////\n// Code rearrage the parsed revision history //\n// (following article, major editor 1, major editor 2,... format) //\n// to the following format //\n// editor 1, majorly edited article 1, majorly edited article 2, ... //\n/////////////////////////////////////////////////////////////////////////\n\n\n#include <iostream>\n#include <unordered_map>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <unordered_set>\nusing namespace std;\n\nvoid parse(string& s, vector<string>& parsed){\n string tmp = \"\";\n for(int i=0; i<s.length();i++){\n if(s[i]==','){\n if(s[i+1]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else{\n tmp+=s[i];\n }\n }\n else{\n if(s[i]!= ' '){\n tmp+=s[i];\n }\n }\n }\n parsed.push_back(tmp);\n}\n\nint main(int argc, const char * argv[]) {\n \n string output_address = \"/Users/eve/Desktop/Wiki/Code/1_Generate_Tree/7_create_edge_list/7_get_article_weight_pair_map/output.txt\";\n string input_addr = \"/Volumes/Eve/Wiki/All_Materials_for_Paper/Experiment_for_paper/major_editor_w_art_cate_0_over_1.4M.txt\";\n \n ofstream outfile;\n outfile.open (output_address);\n \n \n fstream infile;\n infile.open(input_addr);\n string line = \"\";\n vector<string> parsed;\n \n while(!infile.eof()){\n getline(infile,line);\n if (!line.empty()){\n parsed.clear();\n parse(line, parsed);\n cout<<parsed[0]<<\" \"<<parsed.size()-1<<endl;\n \n }\n \n }\n infile.close();\n \n \n \n outfile.close();\n \n \n \n \n return 1;\n}\n" }, { "alpha_fraction": 0.47852325439453125, "alphanum_fraction": 0.4873979389667511, "avg_line_length": 23.495651245117188, "blob_id": "ba7a09ba294e308b099c4c2a4bdff184f8c63ca8", "content_id": "bd1650a8cd38ad52fee5311c94adb442ad0f7d08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2818, "license_type": "no_license", "max_line_length": 98, "num_lines": 115, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/combine_tree.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// combine_tree_enc_n_group_art\n//\n// Created by Eve on 2/3/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n// The code reads in 2-3 files\n// combine tree_enc and group_art\n// if group_art is represented by encoded ids, match the id with the actual article id\n\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\nusing namespace std;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else if(line[i]!=',' && line[i]!=':'){\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n}\n\nvoid store_name(string& name_file, unordered_map<int, int>& code_name){\n ifstream artname;\n artname.open(name_file);\n string line = \"\";\n vector<string> parsed;\n while(!artname.eof()){\n getline(artname, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n code_name[stoi(parsed[0])] = stoi(parsed[1]);\n }\n }\n artname.close();\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Tree_Address Name_encoding_file_address Output_Address \"<<endl;\n cout<<\"(e.g ./tree.txt ./art_name_filtered.txt ./ )\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n\n string tree_addr = argv[1];\n string artname_addr = argv[2];\n string output_addr = argv[3];\n output_addr+=\"/tree.txt\";\n \n\n //get tree enc\n ifstream tree;\n tree.open(tree_addr);\n \n //decode file\n ofstream outfile;\n outfile.open(output_addr);\n \n \n string line = \"\";\n vector<string> parsed;\n unordered_map<int, int> code_name;\n store_name(artname_addr, code_name);\n \n \n \n while(!tree.eof()){\n getline(tree, line);\n parsed.clear();\n if(line.size()!=0){\n parse(parsed, line);\n outfile<<parsed[0];\n if(parsed.size()>1){\n //translate encoded id into actual page id\n \n for(int i=1;i<parsed.size();i++){\n parsed[i] = to_string(code_name[stoi(parsed[i])]);\n }\n \n \n for(int i=1;i<parsed.size();i++){\n outfile<<\", \"<<parsed[i];\n }\n }\n outfile<<endl;\n }\n \n\n }\n \n tree.close();\n \n outfile.close();\n \n \n return 0;\n}\n" }, { "alpha_fraction": 0.45893043279647827, "alphanum_fraction": 0.47151345014572144, "avg_line_length": 24.309734344482422, "blob_id": "92c83082e465b2e294a138e20a877910aec8f692", "content_id": "4340be803b529cadb69264ce1bec5f6b675aa65b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2861, "license_type": "no_license", "max_line_length": 98, "num_lines": 113, "path": "/Desktop/Wiki/Code/Helper/calculate_num_articles_to_merge_per_lv.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\nusing namespace std;\n\n//ofstream artname;\n//bool first = false;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n if (tmp!=\" \"&&tmp.size()!=0){\n parsed.push_back(tmp);\n }\n \n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n if (tmp!=\" \"&&tmp.size()!=0){\n parsed.push_back(tmp);\n }\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 3){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"sorted_weight_Address | outputfolder\"<<endl;\n cout<<\"(e.g ./sorted_weight.txt ./)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string weight_addr = argv[1]; //weight, a1, a2\n\n string output_addr = argv[2];\n\n output_addr += \"/ctr.txt\";\n\n ofstream outfile;\n outfile.open(output_addr);\n\n\n unordered_set<string> visited;\n unordered_map<string, int> num_art_merged; //weight, num new articles\n\n vector<string> v;\n\n ifstream infile;\n infile.open(weight_addr);\n string line=\"\";\n vector<string> parsed;\n while(!infile.eof()){\n getline(infile, line);\n if (line!=\"\" && line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n\n if (parsed.size()!=3){\n cerr<<\"parsed.size()!=3\"<<endl;\n cout<<\"[\"<<line<<\"]\"<<endl;\n exit(0);\n }\n\n string weight = parsed[0];\n string a1 = parsed[1];\n string a2 = parsed[2];\n\n if (visited.count(a1)==0){\n num_art_merged[weight] += 1;\n visited.insert(a1);\n v.push_back(a1);\n }\n if (visited.count(a2)==0){\n num_art_merged[weight] += 1;\n visited.insert(a2);\n v.push_back(a2);\n }\n\n }\n }\n\n int num_art = 0;\n for (auto it=num_art_merged.begin();it!=num_art_merged.end();it++){\n cout<<it->first<<\" \"<<it->second<<\" \"<<(it->second*1.0/visited.size())*100<<\"%\"<<endl;\n num_art+=it->second;\n }\n\n sort(v.begin(), v.end());\n for (auto i=0;i<v.size();i++){\n outfile<<v[i]<<endl;\n }\n\n\n outfile.close();\n\n cout<<\"There are in total \"<<num_art<<\" articles\"<<endl;\n cout<<\"There are in total \"<<visited.size()<<\" articles encountered\"<<endl;\n \n return 0;\n \n}\n" }, { "alpha_fraction": 0.7443946003913879, "alphanum_fraction": 0.7612107396125793, "avg_line_length": 39.59090805053711, "blob_id": "9a20d75b3f4e9bc3999def7772b0ff3cadc2513c", "content_id": "8569642aba642f162be6b99475a4f2e23d6137ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 892, "license_type": "no_license", "max_line_length": 116, "num_lines": 22, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/run.sh", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "OUTPUT_FOLDER=$1\nMIN_WEIGHT_TO_CONSIDER=$2\nTOTAL_NUMBER_OF_ART=$3\nMIN_NUM_ART_TO_MERGE=$4\nARTNAME_ADDR=$5\nUSEDART_ADDR=$6\nNUMBER_OF_USED_ART=$7\n\nWORD_W_ART_ADDR=$OUTPUT_FOLDER'/3_word_w_art.txt'\nART_WEIGHT_ADDR=$OUTPUT_FOLDER'/4_art_weight_pair.txt'\nSORTED_WEIGHT_ADDR=$OUTPUT_FOLDER'/5_sorted_weight.txt'\nGroup_Iteration_File=$OUTPUT_FOLDER'/group_ite.txt'\nEncoded_Tree_Addr=$OUTPUT_FOLDER'/tree_enco.txt'\nDecoded_Tree_Addr=$OUTPUT_FOLDER'/7_decoded_tree.txt'\n\n\n./create_edge_list.out $WORD_W_ART_ADDR $OUTPUT_FOLDER 1000 $NUMBER_OF_USED_ART\n./sort_edgelist.out $ART_WEIGHT_ADDR $OUTPUT_FOLDER\n./get_enco.out $SORTED_WEIGHT_ADDR $OUTPUT_FOLDER $MIN_WEIGHT_TO_CONSIDER $TOTAL_NUMBER_OF_ART $MIN_NUM_ART_TO_MERGE\n./create_tree.out $Group_Iteration_File $OUTPUT_FOLDER\n./decode.out $ARTNAME_ADDR $Encoded_Tree_Addr $OUTPUT_FOLDER\n./add_remain.out $USEDART_ADDR $Decoded_Tree_Addr $OUTPUT_FOLDER" }, { "alpha_fraction": 0.5032516121864319, "alphanum_fraction": 0.5112556219100952, "avg_line_length": 35.23636245727539, "blob_id": "fbb1004f0412a4a703287d2a45c39a40df5f4f61", "content_id": "15862fd5d0238147492b0596ac92074a6b290cd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1999, "license_type": "no_license", "max_line_length": 141, "num_lines": 55, "path": "/1_Generate_Tree/3_extract_revision.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n# import eventlet\n\ndef GetRevisions(pageTitle):\n url = \"https://en.wikipedia.org/w/api.php?action=query&format=xml&prop=revisions&rvlimit=500&rvprop=user|userid|size&titles=\" + pageTitle\n\n revisions = [] #list of all accumulated revisions\n next = '' #information for the next request\n while True:\n response = urllib2.urlopen(url + next).read() #web request\n revisions += re.findall('<rev [^>]*>', response) #adds all revisions from the current request to the list\n\n cont = re.search('<continue rvcontinue=\"([^\"]+)\"', response)\n if not cont: #break the loop if 'continue' element missing\n break\n\n next = \"&rvcontinue=\" + cont.group(1) #gets the revision Id from which to start the next request\n\n return revisions;\n\n\nif __name__ == \"__main__\":\n # text_file = open(\"/Users/eve/Desktop/Wiki/Life/revision_history_2.txt\", \"w\")\n text_file = open(\"/home/fangy/Wiki/Life/revision_history.txt\", \"w\")\n # with open(\"/Users/eve/Desktop/Wiki/Life/article.txt\",'r') as f:\n with open(\"/home/fangy/Wiki/Life/article.txt\",'r') as f:\n \tcounter = 0; \n\n for line in f:\n counter = counter+1 \n if counter>=27070:\n # if counter < 3:\n\n\n line = line.strip('\\n')\n line = line.strip('\\t')\n title = line\n\n text_file.write(title)\n text_file.write('\\n')\n\n\n revisions = GetRevisions(title)\n for i in revisions[0:len(revisions)]: #get all revisions\n # print(i)\n text_file.write(i)\n text_file.write('\\n')\n \n revisions = []; \n text_file.write('\\n\\n')\n print(counter)\n print(title)\n\n text_file.close()\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5027104020118713, "alphanum_fraction": 0.512125551700592, "avg_line_length": 26.3828125, "blob_id": "d3529b8cad5bf7feb028e83d941a99b607685cf2", "content_id": "423750340f714dc0d27731b4e5bdcd002b68d7b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3506, "license_type": "no_license", "max_line_length": 98, "num_lines": 128, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/7_combine_group_and_articles.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// combine_tree_enc_n_group_art\n//\n// Created by Eve on 2/3/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n// The code reads in 2-3 files\n// combine tree_enc and group_art\n// if group_art is represented by encoded ids, match the id with the actual article id\n\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\nusing namespace std;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else if(line[i]!=',' && line[i]!=':'){\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n}\n\nvoid store_name(string& name_file, unordered_map<int, int>& code_name){\n ifstream artname;\n artname.open(name_file);\n string line = \"\";\n vector<string> parsed;\n while(!artname.eof()){\n getline(artname, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n code_name[stoi(parsed[0])] = stoi(parsed[1]);\n }\n }\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 4){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Tree_Encode_Address | Group_Art_Address | Output_Address\"<<endl;\n cout<<\"(e.g ./tree_enc.txt ./group_art.txt ./)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n\n string tree_enc_addr = argv[1];\n string group_art_addr = argv[2];\n string output_addr = argv[3];\n output_addr+=\"/7_combined_tree(encoded).txt\";\n \n //store name encoding\n string name_file;\n \n //get tree enc\n ifstream tree_enc;\n tree_enc.open(tree_enc_addr);\n //get group art\n ifstream group_art;\n group_art.open(group_art_addr);\n //combined file\n ofstream outfile;\n outfile.open(output_addr);\n \n \n string enc = \"\";\n string arts = \"\";\n string curr_node = \"\";\n vector<string> parsed;\n while(!tree_enc.eof()){\n enc = \"\";\n arts = \"\";\n getline(tree_enc, enc);\n getline(group_art, arts);\n if (enc.size()==0 && arts.size()==0) continue;\n parsed.clear();\n parse(parsed, enc);\n // error check: no group id for the current node\n if (parsed.size()!=2){\n cerr<<\"No group id for the current node\"<<endl;\n cout<<enc<<endl;\n exit(0);\n }\n outfile<<parsed[0];\n curr_node = parsed[1];\n parsed.clear();\n parse(parsed, arts);\n\n //error check: group id for tree encoding doesn't match with group id for the articles\n if (parsed[0]!=curr_node){\n cerr<<\"Group id for tree encoding doesn't match with group id for the articles\"<<endl;\n cout<<\"curr_node [in tree_enco] = \"<<curr_node<<endl;\n cout<<\"curr_node [in articles] = \"<<parsed[0]<<endl;\n exit(0); \n }\n if(parsed.size()>1){\n for(int i=1;i<parsed.size();i++){\n if (parsed[i].size()!=0 && parsed[i]!=\" \"){\n outfile<<\", \"<<parsed[i];\n }\n }\n }\n outfile<<endl;\n\n }\n \n tree_enc.close();\n group_art.close();\n outfile.close();\n \n \n return 0;\n}\n" }, { "alpha_fraction": 0.7386934757232666, "alphanum_fraction": 0.7554438710212708, "avg_line_length": 53.272727966308594, "blob_id": "5f84a945ffbf39994c93edf5bac3bb5f69e5d28b", "content_id": "a36f816d3fd985a35bb738d9cda5479e265fc710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 597, "license_type": "no_license", "max_line_length": 108, "num_lines": 11, "path": "/Desktop/Wiki/Code/Achieve/Compare_original_tree_to_random_tree/run.sh", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "ALL_TREE_FOLDER=\"/Users/eve/Desktop/Wiki/Code/Compare_original_tree_to_random_tree/Error_Bar/All_Trees\"\nSAMPLED_FOLDER=\"/Users/eve/Desktop/Wiki/Code/Compare_original_tree_to_random_tree/Error_Bar/Random_Version\" \nNUMBER_OF_SAMPLES=\"1\"\nNUMBER_OF_ARTICLES_TO_SAMPLE=\"1000\"\nEND_FOLDER_NUMBER=\"0\"\ng++ 2_pick_n_locate_art.cpp -o b.out\n./b.out $NUMBER_OF_ARTICLES_TO_SAMPLE $SAMPLED_FOLDER $ALL_TREE_FOLDER\ng++ 3_find_similarity.cpp -o c.out\n./c.out 0 $END_FOLDER_NUMBER $SAMPLED_FOLDER $ALL_TREE_FOLDER\ng++ 4_get_tree_similarity.cpp -o d.out\n./d.out $NUMBER_OF_SAMPLES $SAMPLED_FOLDER $ALL_TREE_FOLDER\n" }, { "alpha_fraction": 0.8461538553237915, "alphanum_fraction": 0.8461538553237915, "avg_line_length": 31.5, "blob_id": "8d863dca14ec20641108aa4d25982b8147c20333", "content_id": "0eb3becca93a5a01e627be59998123fce7f4a0bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 65, "license_type": "no_license", "max_line_length": 54, "num_lines": 2, "path": "/README.md", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "# wikicat\nHierarchical clustering on the entire Wikipedia corpus\n" }, { "alpha_fraction": 0.46790409088134766, "alphanum_fraction": 0.48182520270347595, "avg_line_length": 23.85897445678711, "blob_id": "792406949cffb8ba6ee59be0df57613d4143e56b", "content_id": "8dd30954f49450bb4345f08eb162539c570c8a61", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 3880, "license_type": "no_license", "max_line_length": 98, "num_lines": 156, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Archieve/generate_random_tree.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// generate_random\n//\n// Created by Eve on 3/9/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n\n/****************************************************************/\n// The code is written for randomly choose an article of a given\n// structure, where the structure (tree enco) and number of\n// articles in each node is the same.\n//\n// [Input format]\n// <Tree.txt>\n// tree_enc_, art_id1, art_id2, ...\n//\n// <Artname.txt>\n// index, article id\n//\n//\n// [Output format]\n// (random tree has articles in their real article ids)\n// Tree encoding, random article 1, random article 2 ...\n//\n/***************************************************************/\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <unordered_set>\nusing namespace std;\n\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else if(line[i]!=','){\n tmp+=line[i];\n }\n }\n parsed.push_back(tmp);\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 3){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\" Artname_Adress | Output_Address \"<<endl;\n cout<<\"(e.g ./artname.txt ./Output )\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n\n string artname_addr = argv[1];\n string output_addr = argv[2];\n output_addr+=\"/sorted_random_edge_list.txt\";\n \n \n // get all articles in the tree\n vector<string> all_articles;\n set<int> visited;\n \n string line = \"\";\n vector<string> parsed;\n ifstream artname;\n artname.open(artname_addr);\n \n string id_name = argv[2];\n id_name+=\"/artname.txt\";\n ofstream id_file;\n id_file.open(id_name);\n int counter=0;\n \n while(!artname.eof()){\n getline(artname, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n// if(parsed.size()!=2){\n// cerr<<\"parsed.size()!=1\"<<endl;\n// exit (0);\n// }\n// all_articles.push_back(parsed[1]); //store real article ids\n all_articles.push_back(parsed[0]);\n id_file<<counter<<\", \"<<parsed[0]<<endl;;\n counter++;\n }\n }\n artname.close();\n \n ofstream outfile;\n outfile.open(output_addr);\n int num_art = all_articles.size();\n map<int, vector<int>, std::greater<int> > edge_list;\n \n int a1=-1;\n int a2=0;\n int weight=0;\n int num_edges = 0;\n int pairs = 0;\n while(visited.size()!=num_art){\n a1 ++;\n \n \n \n while(visited.count(a2)!=0){\n a2 = rand()%num_art;\n }\n \n if(a1==a2) continue;\n weight = rand()%300+1;\n \n visited.insert(a1);\n visited.insert(a2);\n \n num_edges++;\n \n if(edge_list.count(weight)==0){\n vector<int> tmp;\n tmp.push_back(a1);\n tmp.push_back(a2);\n edge_list[weight] = tmp;\n }\n else{\n edge_list[weight].push_back(a1);\n edge_list[weight].push_back(a2);\n }\n \n }\n cout<<\"randomly generated \"<<num_edges<<\" edges for \"<<num_art<<\" articles\"<<endl;\n \n for(auto i=edge_list.begin();i!=edge_list.end();i++){\n for(int j=0;j<i->second.size();j+=2){\n outfile<<i->first<<\", \"<<i->second[j]<<\", \"<<i->second[j+1]<<endl;\n }\n \n }\n\n outfile.close();\n \n \n \n return 0;\n}\n\n" }, { "alpha_fraction": 0.522895097732544, "alphanum_fraction": 0.5317577719688416, "avg_line_length": 29.81818199157715, "blob_id": "cfe8a96fbcb8c897b0f171edb9dc21bd11ba8371", "content_id": "e77dc4e3a139c726d1ed51521fa70cc8392d669f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 677, "license_type": "no_license", "max_line_length": 95, "num_lines": 22, "path": "/Desktop/Wiki/Code/2_Compare_Tree/Generate_LDA_trees/0_get_LDA_artid.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "w_o_stop_words_addr = '/Users/eve/Desktop/Major_Editor_5/Create_BoW_Tree/1_w_o_stop_words.txt'\nart_topic_addr = '/Users/eve/Desktop/Major_Editor_5/LDA/art_id.txt'\n\nart_id = open(art_topic_addr, 'w')\n\nbow = []\ntmp = []\ncurr_id = 0\nartid = []\nfor line in open(w_o_stop_words_addr):\n\tline = line.lower().strip().replace(',', ' ')\n \tif len(line)!=0 and line!=\"************************** new article *************************\":\n\t tmp = line.lower().strip().split()\n\t bow.append(tmp)\n\t artid.append(curr_id)\n\tif line == \"************************** new article *************************\":\n\t\tcurr_id += 1\n\n\nfor curr_id in artid:\n\tart_id.write(str(curr_id))\n\tart_id.write(\"\\n\")" }, { "alpha_fraction": 0.6603053212165833, "alphanum_fraction": 0.6984732747077942, "avg_line_length": 42.83333206176758, "blob_id": "c331bd18e4054d40ccf8fca2c210fe3841294651", "content_id": "8338fae2774cfbdc1d2483cc1820cd5b868a1431", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 262, "license_type": "no_license", "max_line_length": 47, "num_lines": 6, "path": "/Desktop/Wiki/Code/2_Compare_Tree/generate_bow_tree/compile.sh", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "g++ 4_edge_list.cpp -o create_edge_list.out\ng++ 5_sort_edgelist.cpp -o sort_edgelist.out\ng++ 6_1_get_enco.cpp -o get_enco.out -std=c++11\ng++ 6_2_create_tree.cpp -o create_tree.out\ng++ 8_decode_tree.cpp -o decode.out\ng++ 9_add_remaining_arts.cpp -o add_remain.out" }, { "alpha_fraction": 0.7253333330154419, "alphanum_fraction": 0.7599999904632568, "avg_line_length": 40.66666793823242, "blob_id": "f0810feafeb0c7e7776cf84e6c89718e785a0fe6", "content_id": "d723ef2a2db231b5f0b7dd2f81d24e1e6b97ca6b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 375, "license_type": "no_license", "max_line_length": 74, "num_lines": 9, "path": "/Desktop/Wiki/Code/6_Compare_Any_Two_Trees/run.sh", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "TREE1_ADDR=$1\nTREE2_ADDR=$2\nOUTPUT_ADDR=$3\nNUMBER_OF_ARTICLES_TO_SAMPLE=\"100\"\nSAMPLED_ARTS_ADDR=$OUTPUT_ADDR\"/sampled_arts.txt\"\nSIMILARITY_SCORE_ADDR=$OUTPUT_ADDR\"/reported_similartity.txt\"\n./a.out $TREE1_ADDR $TREE2_ADDR $OUTPUT_ADDR $NUMBER_OF_ARTICLES_TO_SAMPLE\n./b.out $TREE1_ADDR $TREE2_ADDR $SAMPLED_ARTS_ADDR $OUTPUT_ADDR 0\n./c.out $SIMILARITY_SCORE_ADDR $OUTPUT_ADDR\n" }, { "alpha_fraction": 0.48353448510169983, "alphanum_fraction": 0.4962002635002136, "avg_line_length": 28.694690704345703, "blob_id": "9c7abe5614f32eef9e01958b8052cbf8ad9020af", "content_id": "c678a77e7df21dee89f3bf81333d5543aa11c40b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6712, "license_type": "no_license", "max_line_length": 104, "num_lines": 226, "path": "/Desktop/Wiki/Code/7_generate_random_tree_structure/4_get_tree_similarity.cpp", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "//\n// main.cpp\n// get_tree_similarity\n//\n// Created by Eve on 2/6/18.\n// Copyright © 2018 Eve. All rights reserved.\n//\n\n#include <iostream>\n#include <iostream>\n#include <fstream>\n#include <string>\n#include <vector>\n#include <unordered_map>\n#include <map>\n#include <queue>\n#include <set>\n#include <algorithm>\n#include <unordered_set>\n\nfloat max_score = -1.0;\nfloat avg_score = 0.0;\nint path_count = 0;\n\nfloat avg_path_using_max = 0.0;\ndouble avg_path_using_avg = 0.0;\nfloat max_path = -1.0;\nfloat min_path = 1.0;\nint tot_path = 0;\n\n\nusing namespace std;\nvoid parse(vector<string>& parsed, string& line){\n string tmp = \"\";\n //corner case: if the input is an article name\n if(line[1] == '-'){ //use line[1] b/c first char maybe a negative sign\n parsed.push_back(\"-\");\n return;\n }\n for(int i=0;i<line.size();i++){\n if(line[i]==' '){\n parsed.push_back(tmp);\n tmp = \"\";\n }\n else {\n tmp+=line[i];\n }\n }\n if(tmp != \"\"){\n parsed.push_back(tmp);\n }\n}\n\nvoid output_score(vector<vector<float> >& sim_matrix, ofstream& outfile){\n vector<vector<float> > opt_score;\n for(int i=0;i<sim_matrix.size();i++){\n vector<float> tmp;\n for(int j=0;j<sim_matrix[0].size();j++){\n tmp.push_back(0.0);\n }\n opt_score.push_back(tmp);\n }\n //initiate the first row with max running score\n opt_score[0][0] = sim_matrix[0][0];\n for (int i=1;i<sim_matrix[0].size();i++){\n if(opt_score[0][i-1]>sim_matrix[0][i]){\n opt_score[0][i] = opt_score[0][i-1];\n }\n else{\n opt_score[0][i] = sim_matrix[0][i];\n }\n }\n for(int i=1;i<sim_matrix.size();i++){\n for(int j=i;j<sim_matrix[0].size();j++){\n opt_score[i][j] = max(opt_score[i-1][j-1]+sim_matrix[i][j], opt_score[i][j-1]);\n }\n }\n // calculate the optimal similarity score for the path \n float opt = 0.0;\n if (sim_matrix[0].size()!=2){\n // subtract the root and the leaf node\n opt = (opt_score[sim_matrix.size()-1][sim_matrix[0].size()-1]-2)/(sim_matrix[0].size()-2);\n }\n\n \n\n\n\n outfile<<opt<<\" \";\n avg_score += opt;\n path_count += 1;\n if(opt>max_score){max_score = opt;}\n \n \n if(opt>max_path){max_path = opt;}\n if(opt<min_path){min_path = opt;}\n}\n\nint main(int argc, const char * argv[]) {\n if(argc < 3){\n cout<<\"----------------------------------------------------------------\"<<endl;\n cout<<\"Too few arguments. Please provide the information in the following format. \"<<endl;\n cout<<\"Similarity_file Output_file\"<<endl;\n cout<<\"(e.g ./reported_similartity.txt ./)\"<<endl;\n cout<<\"----------------------------------------------------------------\"<<endl;\n return 0;\n }\n \n string sim_addr = argv[1];\n string output_addr = argv[2];\n output_addr+=\"/new_similartity_score.txt\";\n \n string avg_score_addr = argv[2];\n avg_score_addr+=\"/avg_scores.txt\";\n string best_score_addr = argv[2];\n best_score_addr+=\"/best_score.txt\";\n \n //create output file\n ofstream outfile;\n outfile.open(output_addr);\n \n ofstream avg_file;\n avg_file.open(avg_score_addr);\n ofstream best_file;\n best_file.open(best_score_addr);\n \n //get similarity matrix\n ifstream sim_matrix_file;\n sim_matrix_file.open(sim_addr);\n string line = \"\";\n vector<string> parsed;\n vector<vector<float> > sim_matrix;\n vector<float> row;\n sim_matrix.clear();\n bool first_art = true;\n bool reached_limit = false;\n int c=0;\n while(!sim_matrix_file.eof()){\n line = \"\";\n getline(sim_matrix_file, line);\n if(line.size()!=0){\n parsed.clear();\n parse(parsed, line);\n \n //start to analyze the similarity score on a new article\n if(parsed[0]==\"-\"){\n if(!first_art){\n outfile<<endl;\n float avg_score_tmp = avg_score/path_count;\n \n outfile<<\"Average Score: \"<<avg_score_tmp<<endl;\n outfile<<\"Best Score: \"<<max_score<<endl<<endl;\n \n avg_file<<avg_score_tmp<<endl;\n best_file<<max_score<<endl;\n \n avg_path_using_avg = avg_path_using_avg+ avg_score_tmp;\n avg_path_using_max += max_score;\n\n max_score = -1.0;\n avg_score = 0.0;\n path_count = 0;\n }\n c++;\n if(c==100000){\n reached_limit = true;\n }\n first_art = false;\n tot_path+=1;\n outfile<<\"Sampled article\"<<line<<endl;\n outfile<<\"Optimal Score(s): \";\n }\n else{\n row.clear();\n for(int i=0;i<parsed.size();i++){\n if(parsed[i] == \"nan\"){\n cerr<<\"<------- NAN appeared in the similarity score ------>\"<<endl;\n exit(0);\n }\n row.push_back(stof(parsed[i]));\n }\n sim_matrix.push_back(row);\n }\n }\n //if reach the end of one matrix\n else{\n if(sim_matrix.size()!=0){\n output_score(sim_matrix, outfile);\n sim_matrix.clear();\n if(reached_limit==true){\n break;\n }\n \n }\n \n }\n }\n sim_matrix_file.close();\n \n //output last pair\n outfile<<endl;\n float avg_score_tmp = avg_score/path_count;\n \n outfile<<\"Average Score: \"<<avg_score_tmp<<endl;\n outfile<<\"Best Score: \"<<max_score<<endl<<endl;\n avg_file<<avg_score_tmp<<endl;\n best_file<<max_score<<endl;\n \n avg_path_using_avg = avg_path_using_avg+avg_score_tmp;\n avg_path_using_max += max_score;\n \n outfile<<\"-------------------------------------------\"<<endl;\n outfile<<\"Average Score of All Sampled Path (using max_score): \"<<avg_path_using_max/tot_path<<endl;\n outfile<<\"Average Score of All Sampled Path (using avg_score): \"<<avg_path_using_avg/tot_path<<endl;\n cout<<avg_path_using_max/tot_path<<endl;\n cout<<avg_path_using_avg/tot_path<<endl;\n outfile<<\"Maximum Score of All Sampled Path: \"<<max_path<<endl;\n outfile<<\"Minimum Score of All Sampled Path: \"<<min_path<<endl;\n outfile<<\"Analyzed \"<<tot_path<<\" article paths in total\"<<endl;\n outfile.close();\n best_file.close();\n avg_file.close();\n \n return 0;\n\n}\n" }, { "alpha_fraction": 0.5357723832130432, "alphanum_fraction": 0.5471544861793518, "avg_line_length": 15.698630332946777, "blob_id": "3aa61f74bdeb20650338304925494a4fe56a8668", "content_id": "d11c060afda969d184e393cb0d944aee3a686c5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1230, "license_type": "no_license", "max_line_length": 113, "num_lines": 73, "path": "/Desktop/Wiki/Code/3_Create_Bar_Graph/get_art_cate.py", "repo_name": "evefangy/wikicat", "src_encoding": "UTF-8", "text": "import urllib2\nimport re\n\ndef GetCates(art):\n\turl = \"https://en.wikipedia.org/w/api.php?action=query&generator=categories&prop=info&format=xml&pageids=\" + art\n\tcat = [] \n\tnext = '' \n\n\treq = urllib2.Request(url+next)\n\tresponse = urllib2.urlopen(req)\n\tresponse = response.read() #web request\n\tcat += re.findall('<page [^>]*>', response) \n\t\t\t\t \n\t# print cat\n\treturn cat\n\n\t\t\t\t\t\t\t\t\t\n\t\n\n\nif __name__ == \"__main__\":\n\n\tstart = 11426\n \n\tadd = \"/Users/eve/Desktop/art_cates_\"\n\tadd += str(start)\n\tadd += \".txt\"\n\n\n\tout_file = open(add, \"w\")\n\n\n\tarts = []\n\tcates = []\n\ttmp = []\n\tfound = ''\n\tc = 0\n\n\n\n\tcounter = start\n\n\n\twith open(\"/Users/eve/Dropbox/Wiki/two_trees/used_articles.txt\",'r') as f:\n\t\tc = 0\n\t\tfor line in f:\n\t\t\tline = line.strip('\\n')\n\t\t\t\n\t\t\tif c >= start:\n\t\t\t\tarts.append(line)\n\t\t\tc += 1\n\n\t\n\tfor article in arts:\n\t\tprint article\n\n\t\tout_file.write(article)\n\n\t\ttmp = GetCates(article)\n\n\t\tfor i in tmp[0:len(tmp)]:\n\t\t\tfound = re.search('pageid=\"(.+?)\"', i).group(1)\n\t\t\tout_file.write(' ')\n\t\t\tout_file.write(found)\n\n\t\tout_file.write('\\n')\n\t\ttmp = []\n\t\n\t\tcounter += 1\n\t\tprint counter\n\n\tout_file.close()\n\tprint \"Finished!!!!!Finallyyyyyyyyy\"\n\n\n\n\t\n\n\n\n\n\n\n" } ]
81